fa4b80cac588ad328cc3e868c11ed08a48b656db
[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\Localization\LanguageService;
36 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
37 use TYPO3\CMS\Core\Locking\LockFactory;
38 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
39 use TYPO3\CMS\Core\Log\LogManager;
40 use TYPO3\CMS\Core\Page\PageRenderer;
41 use TYPO3\CMS\Core\Resource\StorageRepository;
42 use TYPO3\CMS\Core\Service\DependencyOrderingService;
43 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
44 use TYPO3\CMS\Core\Type\Bitmask\Permission;
45 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
46 use TYPO3\CMS\Core\TypoScript\TemplateService;
47 use TYPO3\CMS\Core\Utility\ArrayUtility;
48 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
49 use TYPO3\CMS\Core\Utility\GeneralUtility;
50 use TYPO3\CMS\Core\Utility\HttpUtility;
51 use TYPO3\CMS\Core\Utility\MathUtility;
52 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
53 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
54 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
55 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
56 use TYPO3\CMS\Frontend\Page\PageGenerator;
57 use TYPO3\CMS\Frontend\Page\PageRepository;
58 use TYPO3\CMS\Frontend\View\AdminPanelView;
59
60 /**
61 * Class for the built TypoScript based frontend. Instantiated in
62 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
63 *
64 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
65 * as the global object TSFE.
66 *
67 * This class has a lot of functions and internal variable which are used from
68 * \TYPO3\CMS\Frontend\Http\RequestHandler
69 *
70 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
71 *
72 * The use of this class should be inspired by the order of function calls as
73 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
74 */
75 class TypoScriptFrontendController implements LoggerAwareInterface
76 {
77 use LoggerAwareTrait;
78
79 /**
80 * The page id (int)
81 * @var string
82 */
83 public $id = '';
84
85 /**
86 * The type (read-only)
87 * @var int
88 */
89 public $type = '';
90
91 /**
92 * The submitted cHash
93 * @var string
94 */
95 public $cHash = '';
96
97 /**
98 * Page will not be cached. Write only TRUE. Never clear value (some other
99 * code might have reasons to set it TRUE).
100 * @var bool
101 */
102 public $no_cache = false;
103
104 /**
105 * The rootLine (all the way to tree root, not only the current site!)
106 * @var array
107 */
108 public $rootLine = '';
109
110 /**
111 * The pagerecord
112 * @var array
113 */
114 public $page = '';
115
116 /**
117 * This will normally point to the same value as id, but can be changed to
118 * point to another page from which content will then be displayed instead.
119 * @var int
120 */
121 public $contentPid = 0;
122
123 /**
124 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
125 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
126 * should be redirected to.
127 *
128 * @var array|null
129 */
130 protected $originalMountPointPage = null;
131
132 /**
133 * Gets set when we are processing a page of type shortcut in the early stages
134 * of the request when we do not know about languages yet, used later in the request
135 * to determine the correct shortcut in case a translation changes the shortcut
136 * target
137 * @var array|null
138 * @see checkTranslatedShortcut()
139 */
140 protected $originalShortcutPage = null;
141
142 /**
143 * sys_page-object, pagefunctions
144 *
145 * @var PageRepository
146 */
147 public $sys_page = '';
148
149 /**
150 * Contains all URL handler instances that are active for the current request.
151 *
152 * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
153 *
154 * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
155 * @see initializeRedirectUrlHandlers()
156 */
157 protected $activeUrlHandlers = [];
158
159 /**
160 * Is set to 1 if a pageNotFound handler could have been called.
161 * @var int
162 */
163 public $pageNotFound = 0;
164
165 /**
166 * Domain start page
167 * @var int
168 */
169 public $domainStartPage = 0;
170
171 /**
172 * Array containing a history of why a requested page was not accessible.
173 * @var array
174 */
175 public $pageAccessFailureHistory = [];
176
177 /**
178 * @var string
179 */
180 public $MP = '';
181
182 /**
183 * This can be set from applications as a way to tag cached versions of a page
184 * and later perform some external cache management, like clearing only a part
185 * of the cache of a page...
186 * @var int
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 * @var int
230 */
231 public $workspacePreview = 0;
232
233 /**
234 * Shows whether logins are allowed in branch
235 * @var bool
236 */
237 public $loginAllowedInBranch = true;
238
239 /**
240 * Shows specific mode (all or groups)
241 * @var string
242 */
243 public $loginAllowedInBranch_mode = '';
244
245 /**
246 * Set to backend user ID to initialize when keyword-based preview is used
247 * @var int
248 */
249 public $ADMCMD_preview_BEUSER_uid = 0;
250
251 /**
252 * Flag indication that preview is active. This is based on the login of a
253 * backend user and whether the backend user has read access to the current
254 * page. A value of 1 means ordinary preview, 2 means preview of a non-live
255 * workspace
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 = 1;
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 $this->getTimeTracker()->push('beUserLogin', '');
1072 $originalFrontendUser = null;
1073 $backendUser = $this->getBackendUser();
1074 if ($this->beUserLogin || $this->doWorkspacePreview()) {
1075 // Backend user preview features:
1076 if ($this->beUserLogin && $backendUser->adminPanel instanceof AdminPanelView) {
1077 $this->fePreview = (int)$backendUser->adminPanel->extGetFeAdminValue('preview');
1078 // If admin panel preview is enabled...
1079 if ($this->fePreview) {
1080 if ($this->fe_user->user) {
1081 $originalFrontendUser = $this->fe_user->user;
1082 }
1083 $this->showHiddenPage = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1084 $this->showHiddenRecords = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1085 // Simulate date
1086 $simTime = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1087 if ($simTime) {
1088 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1089 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1090 }
1091 // simulate user
1092 $simUserGroup = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1093 $this->simUserGroup = $simUserGroup;
1094 if ($simUserGroup) {
1095 if ($this->fe_user->user) {
1096 $this->fe_user->user[$this->fe_user->usergroup_column] = $simUserGroup;
1097 } else {
1098 $this->fe_user->user = [
1099 $this->fe_user->usergroup_column => $simUserGroup
1100 ];
1101 }
1102 }
1103 if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1104 $this->fePreview = 0;
1105 }
1106 }
1107 }
1108 if ($this->id && $this->determineIdIsHiddenPage()) {
1109 // The preview flag is set only if the current page turns out to actually be hidden!
1110 $this->fePreview = 1;
1111 $this->showHiddenPage = true;
1112 }
1113 // The preview flag will be set if a backend user is in an offline workspace
1114 if (
1115 (
1116 $backendUser->user['workspace_preview']
1117 || GeneralUtility::_GP('ADMCMD_view')
1118 || $this->doWorkspacePreview()
1119 )
1120 && (
1121 $this->whichWorkspace() === -1
1122 || $this->whichWorkspace() > 0
1123 )
1124 && !GeneralUtility::_GP('ADMCMD_noBeUser')
1125 ) {
1126 // Will show special preview message.
1127 $this->fePreview = 2;
1128 }
1129 // If the front-end is showing a preview, caching MUST be disabled.
1130 if ($this->fePreview) {
1131 $this->disableCache();
1132 }
1133 }
1134 $this->getTimeTracker()->pull();
1135 // Now, get the id, validate access etc:
1136 $this->fetch_the_id();
1137 // Check if backend user has read access to this page. If not, recalculate the id.
1138 if ($this->beUserLogin && $this->fePreview) {
1139 if (!$backendUser->doesUserHaveAccess($this->page, 1)) {
1140 // Resetting
1141 $this->clear_preview();
1142 $this->fe_user->user = $originalFrontendUser;
1143 // Fetching the id again, now with the preview settings reset.
1144 $this->fetch_the_id();
1145 }
1146 }
1147 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1148 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1149 // Logins are not allowed:
1150 if (!$this->loginAllowedInBranch) {
1151 // Only if there is a login will we run this...
1152 if ($this->isUserOrGroupSet()) {
1153 if ($this->loginAllowedInBranch_mode === 'all') {
1154 // Clear out user and group:
1155 $this->fe_user->hideActiveLogin();
1156 $this->gr_list = '0,-1';
1157 } else {
1158 $this->gr_list = '0,-2';
1159 }
1160 // Fetching the id again, now with the preview settings reset.
1161 $this->fetch_the_id();
1162 }
1163 }
1164 // Final cleaning.
1165 // Make sure it's an integer
1166 $this->id = ($this->contentPid = (int)$this->id);
1167 // Make sure it's an integer
1168 $this->type = (int)$this->type;
1169 // Call post processing function for id determination:
1170 $_params = ['pObj' => &$this];
1171 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1172 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1173 }
1174 }
1175
1176 /**
1177 * Checks if the page is hidden in the active workspace.
1178 * If it is hidden, preview flags will be set.
1179 *
1180 * @return bool
1181 */
1182 protected function determineIdIsHiddenPage()
1183 {
1184 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1185
1186 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1187 ->getQueryBuilderForTable('pages');
1188 $queryBuilder
1189 ->getRestrictions()
1190 ->removeAll()
1191 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1192
1193 $page = $queryBuilder
1194 ->select('uid', 'hidden', 'starttime', 'endtime')
1195 ->from('pages')
1196 ->where(
1197 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1198 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1199 )
1200 ->setMaxResults(1)
1201 ->execute()
1202 ->fetch();
1203
1204 $workspace = $this->whichWorkspace();
1205 if ($workspace !== 0 && $workspace !== false) {
1206 // Fetch overlay of page if in workspace and check if it is hidden
1207 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1208 $pageSelectObject->versioningPreview = true;
1209 $pageSelectObject->init(false);
1210 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1211 $result = $targetPage === -1 || $targetPage === -2;
1212 } else {
1213 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1214 }
1215 return $result;
1216 }
1217
1218 /**
1219 * Resolves the page id and sets up several related properties.
1220 *
1221 * If $this->id is not set at all or is not a plain integer, the method
1222 * does it's best to set the value to an integer. Resolving is based on
1223 * this options:
1224 *
1225 * - Splitting $this->id if it contains an additional type parameter.
1226 * - Getting the id for an alias in $this->id
1227 * - Finding the domain record start page
1228 * - First visible page
1229 * - Relocating the id below the domain record if outside
1230 *
1231 * The following properties may be set up or updated:
1232 *
1233 * - id
1234 * - requestedId
1235 * - type
1236 * - domainStartPage
1237 * - sys_page
1238 * - sys_page->where_groupAccess
1239 * - sys_page->where_hid_del
1240 * - loginUser
1241 * - gr_list
1242 * - no_cache
1243 * - register['SYS_LASTCHANGED']
1244 * - pageNotFound
1245 *
1246 * Via getPageAndRootlineWithDomain()
1247 *
1248 * - rootLine
1249 * - page
1250 * - MP
1251 * - originalShortcutPage
1252 * - originalMountPointPage
1253 * - pageAccessFailureHistory['direct_access']
1254 * - pageNotFound
1255 *
1256 * @todo:
1257 *
1258 * On the first impression the method does to much. This is increased by
1259 * the fact, that is is called repeated times by the method determineId.
1260 * The reasons are manifold.
1261 *
1262 * 1.) The first part, the creation of sys_page, the type and alias
1263 * resolution don't need to be repeated. They could be separated to be
1264 * called only once.
1265 *
1266 * 2.) The user group setup could be done once on a higher level.
1267 *
1268 * 3.) The workflow of the resolution could be elaborated to be less
1269 * tangled. Maybe the check of the page id to be below the domain via the
1270 * root line doesn't need to be done each time, but for the final result
1271 * only.
1272 *
1273 * 4.) The root line does not need to be directly addressed by this class.
1274 * A root line is always related to one page. The rootline could be handled
1275 * indirectly by page objects. Page objects still don't exist.
1276 *
1277 * @throws ServiceUnavailableException
1278 * @access private
1279 */
1280 public function fetch_the_id()
1281 {
1282 $timeTracker = $this->getTimeTracker();
1283 $timeTracker->push('fetch_the_id initialize/', '');
1284 // Initialize the page-select functions.
1285 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1286 $this->sys_page->versioningPreview = $this->fePreview === 2 || (int)$this->workspacePreview || (bool)GeneralUtility::_GP('ADMCMD_view');
1287 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1288 $this->sys_page->init($this->showHiddenPage);
1289 // Set the valid usergroups for FE
1290 $this->initUserGroups();
1291 // Sets sys_page where-clause
1292 $this->setSysPageWhereClause();
1293 // If $this->id is a string, it's an alias
1294 $this->checkAndSetAlias();
1295 // The id and type is set to the integer-value - just to be sure...
1296 $this->id = (int)$this->id;
1297 $this->type = (int)$this->type;
1298 $timeTracker->pull();
1299 // We find the first page belonging to the current domain
1300 $timeTracker->push('fetch_the_id domain/', '');
1301 // The page_id of the current domain
1302 $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1303 if (!$this->id) {
1304 if ($this->domainStartPage) {
1305 // If the id was not previously set, set it to the id of the domain.
1306 $this->id = $this->domainStartPage;
1307 } else {
1308 // Find the first 'visible' page in that domain
1309 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1310 if ($theFirstPage) {
1311 $this->id = $theFirstPage['uid'];
1312 } else {
1313 $message = 'No pages are found on the rootlevel!';
1314 $this->logger->alert($message);
1315 try {
1316 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
1317 $this->sendResponseAndExit($response);
1318 } catch (ServiceUnavailableException $e) {
1319 throw new ServiceUnavailableException($message, 1301648975);
1320 }
1321 }
1322 }
1323 }
1324 $timeTracker->pull();
1325 $timeTracker->push('fetch_the_id rootLine/', '');
1326 // We store the originally requested id
1327 $this->requestedId = $this->id;
1328 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1329 $timeTracker->pull();
1330 // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1331 // Functional tests in workspaces currently
1332 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1333 $pNotFoundMsg = [
1334 1 => 'ID was not an accessible page',
1335 2 => 'Subsection was found and not accessible',
1336 3 => 'ID was outside the domain',
1337 4 => 'The requested page alias does not exist'
1338 ];
1339 $message = $pNotFoundMsg[$this->pageNotFound];
1340 if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1341 $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($message, $this->getPageAccessFailureReasons());
1342 } else {
1343 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1344 }
1345 $this->sendResponseAndExit($response);
1346 }
1347 // Init SYS_LASTCHANGED
1348 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1349 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1350 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1351 }
1352 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1353 $parameters = ['parentObject' => $this];
1354 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1355 }
1356 }
1357
1358 /**
1359 * Loads the page and root line records based on $this->id
1360 *
1361 * A final page and the matching root line are determined and loaded by
1362 * the algorithm defined by this method.
1363 *
1364 * First it loads the initial page from the page repository for $this->id.
1365 * If that can't be loaded directly, it gets the root line for $this->id.
1366 * It walks up the root line towards the root page until the page
1367 * repository can deliver a page record. (The loading restrictions of
1368 * the root line records are more liberal than that of the page record.)
1369 *
1370 * Now the page type is evaluated and handled if necessary. If the page is
1371 * a short cut, it is replaced by the target page. If the page is a mount
1372 * point in overlay mode, the page is replaced by the mounted page.
1373 *
1374 * After this potential replacements are done, the root line is loaded
1375 * (again) for this page record. It walks up the root line up to
1376 * the first viewable record.
1377 *
1378 * (While upon the first accessibility check of the root line it was done
1379 * by loading page by page from the page repository, this time the method
1380 * checkRootlineForIncludeSection() is used to find the most distant
1381 * accessible page within the root line.)
1382 *
1383 * Having found the final page id, the page record and the root line are
1384 * loaded for last time by this method.
1385 *
1386 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1387 * or root lines.
1388 *
1389 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1390 * instead of throwing an exception it's handled by a page unavailable
1391 * handler.
1392 *
1393 * May set or update this properties:
1394 *
1395 * @see TypoScriptFrontendController::$id
1396 * @see TypoScriptFrontendController::$MP
1397 * @see TypoScriptFrontendController::$page
1398 * @see TypoScriptFrontendController::$pageNotFound
1399 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1400 * @see TypoScriptFrontendController::$originalMountPointPage
1401 * @see TypoScriptFrontendController::$originalShortcutPage
1402 *
1403 * @throws ServiceUnavailableException
1404 * @throws PageNotFoundException
1405 * @access private
1406 */
1407 public function getPageAndRootline()
1408 {
1409 $this->resolveTranslatedPageId();
1410 if (empty($this->page)) {
1411 // If no page, we try to find the page before in the rootLine.
1412 // Page is 'not found' in case the id itself was not an accessible page. code 1
1413 $this->pageNotFound = 1;
1414 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1415 if (!empty($this->rootLine)) {
1416 $c = count($this->rootLine) - 1;
1417 while ($c > 0) {
1418 // Add to page access failure history:
1419 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1420 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1421 $c--;
1422 $this->id = $this->rootLine[$c]['uid'];
1423 $this->page = $this->sys_page->getPage($this->id);
1424 if (!empty($this->page)) {
1425 break;
1426 }
1427 }
1428 }
1429 // If still no page...
1430 if (empty($this->page)) {
1431 $message = 'The requested page does not exist!';
1432 $this->logger->error($message);
1433 try {
1434 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1435 $this->sendResponseAndExit($response);
1436 } catch (PageNotFoundException $e) {
1437 throw new PageNotFoundException($message, 1301648780);
1438 }
1439 }
1440 }
1441 // Spacer is not accessible in frontend
1442 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1443 $message = 'The requested page does not exist!';
1444 $this->logger->error($message);
1445 try {
1446 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1447 $this->sendResponseAndExit($response);
1448 } catch (PageNotFoundException $e) {
1449 throw new PageNotFoundException($message, 1301648781);
1450 }
1451 }
1452 // Is the ID a link to another page??
1453 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1454 // 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.
1455 $this->MP = '';
1456 // saving the page so that we can check later - when we know
1457 // about languages - whether we took the correct shortcut or
1458 // whether a translation of the page overwrites the shortcut
1459 // target and we need to follow the new target
1460 $this->originalShortcutPage = $this->page;
1461 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1462 $this->id = $this->page['uid'];
1463 }
1464 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1465 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1466 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1467 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1468 $this->originalMountPointPage = $this->page;
1469 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1470 if (empty($this->page)) {
1471 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1472 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1473 throw new PageNotFoundException($message, 1402043263);
1474 }
1475 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1476 $this->id = $this->page['uid'];
1477 }
1478 // Gets the rootLine
1479 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1480 // If not rootline we're off...
1481 if (empty($this->rootLine)) {
1482 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1483 $this->logger->error($message);
1484 try {
1485 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1486 $this->sendResponseAndExit($response);
1487 } catch (ServiceUnavailableException $e) {
1488 throw new ServiceUnavailableException($message, 1301648167);
1489 }
1490 }
1491 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1492 if ($this->checkRootlineForIncludeSection()) {
1493 if (empty($this->rootLine)) {
1494 $message = 'The requested page was not accessible!';
1495 try {
1496 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1497 $this->sendResponseAndExit($response);
1498 } catch (ServiceUnavailableException $e) {
1499 $this->logger->warning($message);
1500 throw new ServiceUnavailableException($message, 1301648234);
1501 }
1502 } else {
1503 $el = reset($this->rootLine);
1504 $this->id = $el['uid'];
1505 $this->page = $this->sys_page->getPage($this->id);
1506 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1507 }
1508 }
1509 }
1510
1511 /**
1512 * If $this->id contains a translated page record, this needs to be resolved to the default language
1513 * in order for all rootline functionality and access restrictions to be in place further on.
1514 *
1515 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1516 */
1517 protected function resolveTranslatedPageId()
1518 {
1519 $this->page = $this->sys_page->getPage($this->id);
1520 // Accessed a default language page record, nothing to resolve
1521 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1522 return;
1523 }
1524 $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1525 $this->sys_language_content = $this->sys_language_uid;
1526 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1527 $this->id = $this->page['uid'];
1528 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1529 $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1530 }
1531
1532 /**
1533 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1534 *
1535 * @param int $SC The value of the "shortcut" field from the pages record
1536 * @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
1537 * @param int $thisUid The current page UID of the page which is a shortcut
1538 * @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...)
1539 * @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.
1540 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1541 * @throws \RuntimeException
1542 * @throws PageNotFoundException
1543 * @return mixed Returns the page record of the page that the shortcut pointed to.
1544 * @access private
1545 * @see getPageAndRootline()
1546 */
1547 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1548 {
1549 $idArray = GeneralUtility::intExplode(',', $SC);
1550 // Find $page record depending on shortcut mode:
1551 switch ($mode) {
1552 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1553
1554 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1555 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1556 $pO = 0;
1557 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1558 $randval = (int)rand(0, count($pageArray) - 1);
1559 $pO = $randval;
1560 }
1561 $c = 0;
1562 $page = [];
1563 foreach ($pageArray as $pV) {
1564 if ($c === $pO) {
1565 $page = $pV;
1566 break;
1567 }
1568 $c++;
1569 }
1570 if (empty($page)) {
1571 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1572 throw new PageNotFoundException($message, 1301648328);
1573 }
1574 break;
1575 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1576 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1577 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1578 if (empty($page)) {
1579 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1580 throw new PageNotFoundException($message, 1301648358);
1581 }
1582 break;
1583 default:
1584 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1585 if (empty($page)) {
1586 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1587 throw new PageNotFoundException($message, 1301648404);
1588 }
1589 }
1590 // Check if short cut page was a shortcut itself, if so look up recursively:
1591 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1592 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1593 $pageLog[] = $page['uid'];
1594 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1595 } else {
1596 $pageLog[] = $page['uid'];
1597 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1598 $this->logger->error($message);
1599 throw new \RuntimeException($message, 1294587212);
1600 }
1601 }
1602 // Return resulting page:
1603 return $page;
1604 }
1605
1606 /**
1607 * Checks if visibility of the page is blocked upwards in the root line.
1608 *
1609 * If any page in the root line is blocking visibility, true is returend.
1610 *
1611 * All pages from the blocking page downwards are removed from the root
1612 * line, so that the remaning pages can be used to relocate the page up
1613 * to lowest visible page.
1614 *
1615 * The blocking feature of a page must be turned on by setting the page
1616 * record field 'extendToSubpages' to 1.
1617 *
1618 * The following fields are evaluated then:
1619 *
1620 * hidden, starttime, endtime, fe_group
1621 *
1622 * @todo Find a better name, i.e. checkVisibilityByRootLine
1623 * @todo Invert boolean return value. Return true if visible.
1624 *
1625 * @return bool
1626 * @access private
1627 */
1628 public function checkRootlineForIncludeSection(): bool
1629 {
1630 $c = count($this->rootLine);
1631 $removeTheRestFlag = false;
1632 for ($a = 0; $a < $c; $a++) {
1633 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1634 // Add to page access failure history:
1635 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1636 $removeTheRestFlag = true;
1637 }
1638
1639 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1640 // If there is a backend user logged in, check if he has read access to the page:
1641 if ($this->beUserLogin) {
1642 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1643 ->getQueryBuilderForTable('pages');
1644
1645 $queryBuilder
1646 ->getRestrictions()
1647 ->removeAll();
1648
1649 $row = $queryBuilder
1650 ->select('uid')
1651 ->from('pages')
1652 ->where(
1653 $queryBuilder->expr()->eq(
1654 'uid',
1655 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1656 ),
1657 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1658 )
1659 ->execute()
1660 ->fetch();
1661
1662 // versionOL()?
1663 if (!$row) {
1664 // 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...
1665 $removeTheRestFlag = true;
1666 }
1667 } else {
1668 // Don't go here, if there is no backend user logged in.
1669 $removeTheRestFlag = true;
1670 }
1671 }
1672 if ($removeTheRestFlag) {
1673 // Page is 'not found' in case a subsection was found and not accessible, code 2
1674 $this->pageNotFound = 2;
1675 unset($this->rootLine[$a]);
1676 break;
1677 }
1678 }
1679 return $removeTheRestFlag;
1680 }
1681
1682 /**
1683 * Checks page record for enableFields
1684 * Returns TRUE if enableFields does not disable the page record.
1685 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1686 *
1687 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1688 * @param bool $bypassGroupCheck Bypass group-check
1689 * @return bool TRUE, if record is viewable.
1690 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1691 */
1692 public function checkEnableFields($row, $bypassGroupCheck = false)
1693 {
1694 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1695 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1696 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1697 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1698 if ($return === false) {
1699 return false;
1700 }
1701 }
1702 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1703 return true;
1704 }
1705 return false;
1706 }
1707
1708 /**
1709 * Check group access against a page record
1710 *
1711 * @param array $row The page record to evaluate (needs field: fe_group)
1712 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1713 * @return bool TRUE, if group access is granted.
1714 * @access private
1715 */
1716 public function checkPageGroupAccess($row, $groupList = null)
1717 {
1718 if (is_null($groupList)) {
1719 $groupList = $this->gr_list;
1720 }
1721 if (!is_array($groupList)) {
1722 $groupList = explode(',', $groupList);
1723 }
1724 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1725 return count(array_intersect($groupList, $pageGroupList)) > 0;
1726 }
1727
1728 /**
1729 * Checks if the current page of the root line is visible.
1730 *
1731 * If the field extendToSubpages is 0, access is granted,
1732 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1733 *
1734 * @todo Find a better name, i.e. isVisibleRecord()
1735 *
1736 * @param array $row The page record
1737 * @return bool true if visible
1738 * @access private
1739 * @see checkEnableFields()
1740 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1741 * @see checkRootlineForIncludeSection()
1742 */
1743 public function checkPagerecordForIncludeSection(array $row): bool
1744 {
1745 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1746 }
1747
1748 /**
1749 * 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!)
1750 *
1751 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1752 */
1753 public function checkIfLoginAllowedInBranch()
1754 {
1755 // Initialize:
1756 $c = count($this->rootLine);
1757 $loginAllowed = true;
1758 // Traverse root line from root and outwards:
1759 for ($a = 0; $a < $c; $a++) {
1760 // If a value is set for login state:
1761 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1762 // Determine state from value:
1763 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1764 $loginAllowed = false;
1765 $this->loginAllowedInBranch_mode = 'all';
1766 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1767 $loginAllowed = false;
1768 $this->loginAllowedInBranch_mode = 'groups';
1769 } else {
1770 $loginAllowed = true;
1771 }
1772 }
1773 }
1774 return $loginAllowed;
1775 }
1776
1777 /**
1778 * 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
1779 *
1780 * @return array Summary of why page access was not allowed.
1781 */
1782 public function getPageAccessFailureReasons()
1783 {
1784 $output = [];
1785 $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'] : []);
1786 if (!empty($combinedRecords)) {
1787 foreach ($combinedRecords as $k => $pagerec) {
1788 // 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
1789 // 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!
1790 if (!$k || $pagerec['extendToSubpages']) {
1791 if ($pagerec['hidden']) {
1792 $output['hidden'][$pagerec['uid']] = true;
1793 }
1794 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1795 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1796 }
1797 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1798 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1799 }
1800 if (!$this->checkPageGroupAccess($pagerec)) {
1801 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1802 }
1803 }
1804 }
1805 }
1806 return $output;
1807 }
1808
1809 /**
1810 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1811 * If not inside domain, then default to first page in domain.
1812 *
1813 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1814 * @access private
1815 */
1816 public function getPageAndRootlineWithDomain($domainStartPage)
1817 {
1818 $this->getPageAndRootline();
1819 // 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.
1820 if ($domainStartPage && is_array($this->rootLine)) {
1821 $idFound = 0;
1822 foreach ($this->rootLine as $key => $val) {
1823 if ($val['uid'] == $domainStartPage) {
1824 $idFound = 1;
1825 break;
1826 }
1827 }
1828 if (!$idFound) {
1829 // Page is 'not found' in case the id was outside the domain, code 3
1830 $this->pageNotFound = 3;
1831 $this->id = $domainStartPage;
1832 // re-get the page and rootline if the id was not found.
1833 $this->getPageAndRootline();
1834 }
1835 }
1836 }
1837
1838 /**
1839 * Sets sys_page where-clause
1840 *
1841 * @access private
1842 */
1843 public function setSysPageWhereClause()
1844 {
1845 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1846 ->getConnectionForTable('pages')
1847 ->getExpressionBuilder();
1848 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1849 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1850 $expressionBuilder->lt('pages.doktype', 200)
1851 );
1852 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1853 }
1854
1855 /**
1856 * Looking up a domain record based on HTTP_HOST
1857 *
1858 * @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.
1859 * @return int Returns the page id of the page where the domain record was found.
1860 * @access private
1861 */
1862 public function findDomainRecord($recursive = false)
1863 {
1864 if ($recursive) {
1865 $pageUid = 0;
1866 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1867 while (count($host)) {
1868 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1869 if ($pageUid) {
1870 return $pageUid;
1871 }
1872 array_shift($host);
1873 }
1874 return $pageUid;
1875 }
1876 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1877 }
1878
1879 /**
1880 * Page unavailable handler for use in frontend plugins from extensions.
1881 *
1882 * @param string $reason Reason text
1883 * @param string $header HTTP header to send
1884 * @deprecated
1885 */
1886 public function pageUnavailableAndExit($reason = '', $header = '')
1887 {
1888 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1889 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1890 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1891 die;
1892 }
1893
1894 /**
1895 * Page-not-found handler for use in frontend plugins from extensions.
1896 *
1897 * @param string $reason Reason text
1898 * @param string $header HTTP header to send
1899 * @deprecated
1900 */
1901 public function pageNotFoundAndExit($reason = '', $header = '')
1902 {
1903 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1904 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1905 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1906 die;
1907 }
1908
1909 /**
1910 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1911 * and devIPMask must not match the current visitor's IP address.
1912 *
1913 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1914 * @deprecated
1915 */
1916 public function checkPageUnavailableHandler()
1917 {
1918 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1919 if (
1920 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1921 && !GeneralUtility::cmpIP(
1922 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1923 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1924 )
1925 ) {
1926 $checkPageUnavailableHandler = true;
1927 } else {
1928 $checkPageUnavailableHandler = false;
1929 }
1930 return $checkPageUnavailableHandler;
1931 }
1932
1933 /**
1934 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1935 *
1936 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1937 * @param string $header If set, this is passed directly to the PHP function, header()
1938 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1939 * @deprecated
1940 */
1941 public function pageUnavailableHandler($code, $header, $reason)
1942 {
1943 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1944 $this->pageErrorHandler($code, $header, $reason);
1945 }
1946
1947 /**
1948 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1949 *
1950 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1951 * @param string $header If set, this is passed directly to the PHP function, header()
1952 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1953 * @deprecated
1954 */
1955 public function pageNotFoundHandler($code, $header = '', $reason = '')
1956 {
1957 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1958 $this->pageErrorHandler($code, $header, $reason);
1959 }
1960
1961 /**
1962 * Generic error page handler.
1963 * Exits.
1964 *
1965 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1966 * @param string $header If set, this is passed directly to the PHP function, header()
1967 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1968 * @throws \RuntimeException
1969 * @deprecated
1970 */
1971 public function pageErrorHandler($code, $header = '', $reason = '')
1972 {
1973 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1974 // Issue header in any case:
1975 if ($header) {
1976 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1977 foreach ($headerArr as $header) {
1978 header($header);
1979 }
1980 }
1981 // Create response:
1982 // Simply boolean; Just shows TYPO3 error page with reason:
1983 if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1984 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1985 'Page Not Found',
1986 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1987 );
1988 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1989 $funcRef = trim(substr($code, 14));
1990 $params = [
1991 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1992 'reasonText' => $reason,
1993 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1994 ];
1995 try {
1996 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1997 } catch (\Exception $e) {
1998 throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
1999 }
2000 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
2001 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
2002 if (@is_file($readFile)) {
2003 echo str_replace(
2004 [
2005 '###CURRENT_URL###',
2006 '###REASON###'
2007 ],
2008 [
2009 GeneralUtility::getIndpEnv('REQUEST_URI'),
2010 htmlspecialchars($reason)
2011 ],
2012 file_get_contents($readFile)
2013 );
2014 } else {
2015 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2016 }
2017 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
2018 HttpUtility::redirect(substr($code, 9));
2019 } elseif ($code !== '') {
2020 // Check if URL is relative
2021 $url_parts = parse_url($code);
2022 // parse_url could return an array without the key "host", the empty check works better than strict check
2023 if (empty($url_parts['host'])) {
2024 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
2025 if ($code[0] === '/') {
2026 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2027 } else {
2028 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2029 }
2030 $checkBaseTag = false;
2031 } else {
2032 $checkBaseTag = true;
2033 }
2034 // Check recursion
2035 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2036 if ($reason == '') {
2037 $reason = 'Page cannot be found.';
2038 }
2039 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2040 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2041 }
2042 // Prepare headers
2043 $headerArr = [
2044 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2045 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2046 ];
2047 $report = [];
2048 $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2049 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2050 throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2051 }
2052 // Header and content are separated by an empty line
2053 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2054 $content .= CRLF;
2055 if (false === $res) {
2056 // Last chance -- redirect
2057 HttpUtility::redirect($code);
2058 } else {
2059 // Forward these response headers to the client
2060 $forwardHeaders = [
2061 'Content-Type:'
2062 ];
2063 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2064 foreach ($headerArr as $header) {
2065 foreach ($forwardHeaders as $h) {
2066 if (preg_match('/^' . $h . '/', $header)) {
2067 header($header);
2068 }
2069 }
2070 }
2071 // Put <base> if necessary
2072 if ($checkBaseTag) {
2073 // If content already has <base> tag, we do not need to do anything
2074 if (false === stristr($content, '<base ')) {
2075 // Generate href for base tag
2076 $base = $url_parts['scheme'] . '://';
2077 if ($url_parts['user'] != '') {
2078 $base .= $url_parts['user'];
2079 if ($url_parts['pass'] != '') {
2080 $base .= ':' . $url_parts['pass'];
2081 }
2082 $base .= '@';
2083 }
2084 $base .= $url_parts['host'];
2085 // Add path portion skipping possible file name
2086 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2087 // Put it into content (generate also <head> if necessary)
2088 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2089 if (stristr($content, '<head>')) {
2090 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2091 } else {
2092 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2093 }
2094 }
2095 }
2096 // Output the content
2097 echo $content;
2098 }
2099 } else {
2100 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2101 'Page Not Found',
2102 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2103 );
2104 }
2105 die;
2106 }
2107
2108 /**
2109 * Fetches the integer page id for a page alias.
2110 * 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
2111 *
2112 * @access private
2113 */
2114 public function checkAndSetAlias()
2115 {
2116 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2117 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2118 if ($aid) {
2119 $this->id = $aid;
2120 } else {
2121 $this->pageNotFound = 4;
2122 }
2123 }
2124 }
2125
2126 /**
2127 * Merging values into the global $_GET
2128 *
2129 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2130 */
2131 public function mergingWithGetVars($GET_VARS)
2132 {
2133 if (is_array($GET_VARS)) {
2134 // Getting $_GET var, unescaped.
2135 $realGet = GeneralUtility::_GET();
2136 if (!is_array($realGet)) {
2137 $realGet = [];
2138 }
2139 // Merge new values on top:
2140 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2141 // Write values back to $_GET:
2142 GeneralUtility::_GETset($realGet);
2143 // Setting these specifically (like in the init-function):
2144 if (isset($GET_VARS['type'])) {
2145 $this->type = (int)$GET_VARS['type'];
2146 }
2147 if (isset($GET_VARS['cHash'])) {
2148 $this->cHash = $GET_VARS['cHash'];
2149 }
2150 if (isset($GET_VARS['MP'])) {
2151 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2152 }
2153 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2154 $this->set_no_cache('no_cache is requested via GET parameter');
2155 }
2156 }
2157 }
2158
2159 /********************************************
2160 *
2161 * Template and caching related functions.
2162 *
2163 *******************************************/
2164 /**
2165 * Calculates a hash string based on additional parameters in the url.
2166 *
2167 * Calculated hash is stored in $this->cHash_array.
2168 * This is used to cache pages with more parameters than just id and type.
2169 *
2170 * @see reqCHash()
2171 */
2172 public function makeCacheHash()
2173 {
2174 // No need to test anything if caching was already disabled.
2175 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2176 return;
2177 }
2178 $GET = GeneralUtility::_GET();
2179 if ($this->cHash && is_array($GET)) {
2180 // Make sure we use the page uid and not the page alias
2181 $GET['id'] = $this->id;
2182 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2183 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2184 if (!hash_equals($cHash_calc, $this->cHash)) {
2185 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2186 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash comparison failed)');
2187 $this->sendResponseAndExit($response);
2188 } else {
2189 $this->disableCache();
2190 $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);
2191 }
2192 }
2193 } elseif (is_array($GET)) {
2194 // No cHash is set, check if that is correct
2195 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2196 $this->reqCHash();
2197 }
2198 }
2199 }
2200
2201 /**
2202 * Will disable caching if the cHash value was not set.
2203 * 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)
2204 *
2205 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2206 */
2207 public function reqCHash()
2208 {
2209 if (!$this->cHash) {
2210 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2211 if ($this->tempContent) {
2212 $this->clearPageCacheContent();
2213 }
2214 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash empty)');
2215 $this->sendResponseAndExit($response);
2216 } else {
2217 $this->disableCache();
2218 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2219 }
2220 }
2221 }
2222
2223 /**
2224 * Initialize the TypoScript template parser
2225 */
2226 public function initTemplate()
2227 {
2228 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2229 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2230 $this->tmpl->init();
2231 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2232 }
2233
2234 /**
2235 * See if page is in cache and get it if so
2236 * Stores the page content in $this->content if something is found.
2237 *
2238 * @throws \InvalidArgumentException
2239 * @throws \RuntimeException
2240 */
2241 public function getFromCache()
2242 {
2243 // clearing the content-variable, which will hold the pagecontent
2244 $this->content = '';
2245 // Unsetting the lowlevel config
2246 $this->config = [];
2247 $this->cacheContentFlag = false;
2248
2249 if ($this->no_cache) {
2250 return;
2251 }
2252
2253 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2254 if (!is_array($pageSectionCacheContent)) {
2255 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2256 // We use the Registry to store this lock centrally,
2257 // but we protect the access again with a global exclusive lock to avoid race conditions
2258
2259 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2260 //
2261 // from this point on we're the only one working on that page ($key)
2262 //
2263
2264 // query the cache again to see if the page data are there meanwhile
2265 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2266 if (is_array($pageSectionCacheContent)) {
2267 // we have the content, nice that some other process did the work for us already
2268 $this->releaseLock('pagesection');
2269 }
2270 // We keep the lock set, because we are the ones generating the page now
2271 // and filling the cache.
2272 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2273 }
2274
2275 if (is_array($pageSectionCacheContent)) {
2276 // 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.
2277 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2278 // 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.
2279 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2280 ksort($pageSectionCacheContent);
2281 $this->all = $pageSectionCacheContent;
2282 }
2283 unset($pageSectionCacheContent);
2284
2285 // Look for page in cache only if a shift-reload is not sent to the server.
2286 $lockHash = $this->getLockHash();
2287 if (!$this->headerNoCache()) {
2288 if ($this->all) {
2289 // we got page section information
2290 $this->newHash = $this->getHash();
2291 $this->getTimeTracker()->push('Cache Row', '');
2292 $row = $this->getFromCache_queryRow();
2293 if (!is_array($row)) {
2294 // nothing in the cache, we acquire an exclusive lock now
2295
2296 $this->acquireLock('pages', $lockHash);
2297 //
2298 // from this point on we're the only one working on that page ($lockHash)
2299 //
2300
2301 // query the cache again to see if the data are there meanwhile
2302 $row = $this->getFromCache_queryRow();
2303 if (is_array($row)) {
2304 // we have the content, nice that some other process did the work for us
2305 $this->releaseLock('pages');
2306 }
2307 // We keep the lock set, because we are the ones generating the page now
2308 // and filling the cache.
2309 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2310 }
2311 if (is_array($row)) {
2312 // we have data from cache
2313
2314 // Call hook when a page is retrieved from cache:
2315 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2316 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2317 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2318 }
2319 // Fetches the lowlevel config stored with the cached data
2320 $this->config = $row['cache_data'];
2321 // Getting the content
2322 $this->content = $row['content'];
2323 // Flag for temp content
2324 $this->tempContent = $row['temp_content'];
2325 // Setting flag, so we know, that some cached content has been loaded
2326 $this->cacheContentFlag = true;
2327 $this->cacheExpires = $row['expires'];
2328
2329 // Restore page title information, this is needed to generate the page title for
2330 // partially cached pages.
2331 $this->page['title'] = $row['pageTitleInfo']['title'];
2332 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2333 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2334
2335 if (isset($this->config['config']['debug'])) {
2336 $debugCacheTime = (bool)$this->config['config']['debug'];
2337 } else {
2338 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2339 }
2340 if ($debugCacheTime) {
2341 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2342 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2343 $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2344 }
2345 }
2346 $this->getTimeTracker()->pull();
2347
2348 return;
2349 }
2350 }
2351 // the user forced rebuilding the page cache or there was no pagesection information
2352 // get a lock for the page content so other processes will not interrupt the regeneration
2353 $this->acquireLock('pages', $lockHash);
2354 }
2355
2356 /**
2357 * Returning the cached version of page with hash = newHash
2358 *
2359 * @return array Cached row, if any. Otherwise void.
2360 */
2361 public function getFromCache_queryRow()
2362 {
2363 $this->getTimeTracker()->push('Cache Query', '');
2364 $row = $this->pageCache->get($this->newHash);
2365 $this->getTimeTracker()->pull();
2366 return $row;
2367 }
2368
2369 /**
2370 * Detecting if shift-reload has been clicked
2371 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2372 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2373 *
2374 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2375 */
2376 public function headerNoCache()
2377 {
2378 $disableAcquireCacheData = false;
2379 if ($this->beUserLogin) {
2380 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2381 $disableAcquireCacheData = true;
2382 }
2383 }
2384 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2385 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2386 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2387 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2388 }
2389 return $disableAcquireCacheData;
2390 }
2391
2392 /**
2393 * Calculates the cache-hash
2394 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2395 * Used to get and later store the cached data.
2396 *
2397 * @return string MD5 hash of serialized hash base from createHashBase()
2398 * @access private
2399 * @see getFromCache(), getLockHash()
2400 */
2401 public function getHash()
2402 {
2403 return md5($this->createHashBase(false));
2404 }
2405
2406 /**
2407 * Calculates the lock-hash
2408 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2409 *
2410 * @return string MD5 hash
2411 * @access private
2412 * @see getFromCache(), getHash()
2413 */
2414 public function getLockHash()
2415 {
2416 $lockHash = $this->createHashBase(true);
2417 return md5($lockHash);
2418 }
2419
2420 /**
2421 * Calculates the cache-hash (or the lock-hash)
2422 * This hash is unique to the template,
2423 * the variables ->id, ->type, ->gr_list (list of groups),
2424 * ->MP (Mount Points) and cHash array
2425 * Used to get and later store the cached data.
2426 *
2427 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2428 * @return string the serialized hash base
2429 */
2430 protected function createHashBase($createLockHashBase = false)
2431 {
2432 $hashParameters = [
2433 'id' => (int)$this->id,
2434 'type' => (int)$this->type,
2435 'gr_list' => (string)$this->gr_list,
2436 'MP' => (string)$this->MP,
2437 'cHash' => $this->cHash_array,
2438 'domainStartPage' => $this->domainStartPage
2439 ];
2440 // Include the template information if we shouldn't create a lock hash
2441 if (!$createLockHashBase) {
2442 $hashParameters['all'] = $this->all;
2443 }
2444 // Call hook to influence the hash calculation
2445 $_params = [
2446 'hashParameters' => &$hashParameters,
2447 'createLockHashBase' => $createLockHashBase
2448 ];
2449 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2450 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2451 }
2452 return serialize($hashParameters);
2453 }
2454
2455 /**
2456 * Checks if config-array exists already but if not, gets it
2457 *
2458 * @throws ServiceUnavailableException
2459 */
2460 public function getConfigArray()
2461 {
2462 // 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
2463 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2464 $timeTracker = $this->getTimeTracker();
2465 $timeTracker->push('Parse template', '');
2466 // Force parsing, if set?:
2467 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2468 // Start parsing the TS template. Might return cached version.
2469 $this->tmpl->start($this->rootLine);
2470 $timeTracker->pull();
2471 if ($this->tmpl->loaded) {
2472 $timeTracker->push('Setting the config-array', '');
2473 // toplevel - objArrayName
2474 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2475 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2476 if (!is_array($this->pSetup)) {
2477 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2478 $this->logger->alert($message);
2479 try {
2480 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2481 $this->sendResponseAndExit($response);
2482 } catch (ServiceUnavailableException $e) {
2483 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2484 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2485 }
2486 } else {
2487 if (!isset($this->config['config'])) {
2488 $this->config['config'] = [];
2489 }
2490 // Filling the config-array, first with the main "config." part
2491 if (is_array($this->tmpl->setup['config.'])) {
2492 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2493 $this->config['config'] = $this->tmpl->setup['config.'];
2494 }
2495 // override it with the page/type-specific "config."
2496 if (is_array($this->pSetup['config.'])) {
2497 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2498 }
2499 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2500 if ($this->config['config']['typolinkCheckRootline']) {
2501 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2502 }
2503 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2504 if (!isset($this->config['config']['removeDefaultJS'])) {
2505 $this->config['config']['removeDefaultJS'] = 'external';
2506 }
2507 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2508 $this->config['config']['inlineStyle2TempFile'] = 1;
2509 }
2510
2511 if (!isset($this->config['config']['compressJs'])) {
2512 $this->config['config']['compressJs'] = 0;
2513 }
2514 // Processing for the config_array:
2515 $this->config['rootLine'] = $this->tmpl->rootLine;
2516 // Class for render Header and Footer parts
2517 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2518 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2519 if ($file) {
2520 $this->pageRenderer->setTemplateFile($file);
2521 }
2522 }
2523 }
2524 $timeTracker->pull();
2525 } else {
2526 $message = 'No TypoScript template found!';
2527 $this->logger->alert($message);
2528 try {
2529 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2530 $this->sendResponseAndExit($response);
2531 } catch (ServiceUnavailableException $e) {
2532 throw new ServiceUnavailableException($message, 1294587218);
2533 }
2534 }
2535 }
2536
2537 // No cache
2538 // Set $this->no_cache TRUE if the config.no_cache value is set!
2539 if ($this->config['config']['no_cache']) {
2540 $this->set_no_cache('config.no_cache is set');
2541 }
2542 // Merge GET with defaultGetVars
2543 if (!empty($this->config['config']['defaultGetVars.'])) {
2544 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2545 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2546 GeneralUtility::_GETset($modifiedGetVars);
2547 }
2548 // Hook for postProcessing the configuration array
2549 $params = ['config' => &$this->config['config']];
2550 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2551 GeneralUtility::callUserFunction($funcRef, $params, $this);
2552 }
2553 }
2554
2555 /********************************************
2556 *
2557 * Further initialization and data processing
2558 *
2559 *******************************************/
2560
2561 /**
2562 * Setting the language key that will be used by the current page.
2563 * 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.
2564 *
2565 * @access private
2566 */
2567 public function settingLanguage()
2568 {
2569 $_params = [];
2570 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2571 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2572 }
2573
2574 // Initialize charset settings etc.
2575 $languageKey = $this->config['config']['language'] ?? 'default';
2576 $this->lang = $languageKey;
2577 $this->setOutputLanguage($languageKey);
2578
2579 // Rendering charset of HTML page.
2580 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2581 $this->metaCharset = $this->config['config']['metaCharset'];
2582 }
2583
2584 // Get values from TypoScript, if not set before
2585 if ($this->sys_language_uid === 0) {
2586 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2587 }
2588 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2589 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2590 // If sys_language_uid is set to another language than default:
2591 if ($this->sys_language_uid > 0) {
2592 // check whether a shortcut is overwritten by a translated page
2593 // we can only do this now, as this is the place where we get
2594 // to know about translations
2595 $this->checkTranslatedShortcut();
2596 // Request the overlay record for the sys_language_uid:
2597 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2598 if (empty($olRec)) {
2599 // If no OL record exists and a foreign language is asked for...
2600 if ($this->sys_language_uid) {
2601 // If requested translation is not available:
2602 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2603 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language.');
2604 $this->sendResponseAndExit($response);
2605 } else {
2606 switch ((string)$this->sys_language_mode) {
2607 case 'strict':
2608 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (strict).');
2609 $this->sendResponseAndExit($response);
2610 break;
2611 case 'content_fallback':
2612 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2613 // value was found.
2614 $fallBackOrder = GeneralUtility::trimExplode(',', $sys_language_content);
2615 foreach ($fallBackOrder as $orderValue) {
2616 if ($orderValue === '0' || $orderValue === '') {
2617 $this->sys_language_content = 0;
2618 break;
2619 }
2620 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2621 $this->sys_language_content = (int)$orderValue;
2622 break;
2623 }
2624 if ($orderValue === 'pageNotFound') {
2625 // The existing fallbacks have not been found, but instead of continuing
2626 // page rendering with default language, a "page not found" message should be shown
2627 // instead.
2628 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (fallbacks did not apply).');
2629 $this->sendResponseAndExit($response);
2630 }
2631 }
2632 break;
2633 case 'ignore':
2634 $this->sys_language_content = $this->sys_language_uid;
2635 break;
2636 default:
2637 // Default is that everything defaults to the default language...
2638 $this->sys_language_uid = ($this->sys_language_content = 0);
2639 }
2640 }
2641 }
2642 } else {
2643 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2644 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2645 }
2646 }
2647 // Setting sys_language_uid inside sys-page:
2648 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2649 // If default translation is not available:
2650 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2651 $message = 'Page is not available in default language.';
2652 $this->logger->error($message);
2653 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message);
2654 $this->sendResponseAndExit($response);
2655 }
2656 $this->updateRootLinesWithTranslations();
2657
2658 // Finding the ISO code for the currently selected language
2659 // fetched by the sys_language record when not fetching content from the default language
2660 if ($this->sys_language_content > 0) {
2661 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2662 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2663 // avoid versioning overlay to be applied as it generates an SQL error
2664 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2665 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2666 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2667 }
2668 // the DB value is overridden by TypoScript
2669 if (!empty($this->config['config']['sys_language_isocode'])) {
2670 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2671 }
2672 } else {
2673 // fallback to the TypoScript option when rendering with sys_language_uid=0
2674 // also: use "en" by default
2675 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2676 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2677 } else {
2678 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2679 }
2680 }
2681
2682 $_params = [];
2683 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2684 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2685 }
2686 }
2687
2688 /**
2689 * Updating content of the two rootLines IF the language key is set!
2690 */
2691 protected function updateRootLinesWithTranslations()
2692 {
2693 if ($this->sys_language_uid) {
2694 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2695 $this->tmpl->updateRootlineData($this->rootLine);
2696 }
2697 }
2698
2699 /**
2700 * Setting locale for frontend rendering
2701 */
2702 public function settingLocale()
2703 {
2704 // Setting locale
2705 if ($this->config['config']['locale_all']) {
2706 $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2707 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2708 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2709 // @see https://bugs.php.net/bug.php?id=53711
2710 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2711 if ($locale) {
2712 // As str_* methods are locale aware and turkish has no upper case I
2713 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2714 // @see http://bugs.php.net/bug.php?id=35050
2715 if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2716 setlocale(LC_CTYPE, ...$availableLocales);
2717 }
2718 setlocale(LC_MONETARY, ...$availableLocales);
2719 setlocale(LC_TIME, ...$availableLocales);
2720 } else {
2721 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2722 }
2723 }
2724 }
2725
2726 /**
2727 * Checks whether a translated shortcut page has a different shortcut
2728 * target than the original language page.
2729 * If that is the case, things get corrected to follow that alternative
2730 * shortcut
2731 */
2732 protected function checkTranslatedShortcut()
2733 {
2734 if (!is_null($this->originalShortcutPage)) {
2735 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2736 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2737 // the translation of the original shortcut page has a different shortcut target!
2738 // set the correct page and id
2739 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2740 $this->id = ($this->contentPid = $shortcut['uid']);
2741 $this->page = $this->sys_page->getPage($this->id);
2742 // Fix various effects on things like menus f.e.
2743 $this->fetch_the_id();
2744 $this->tmpl->rootLine = array_reverse($this->rootLine);
2745 }
2746 }
2747 }
2748
2749 /**
2750 * Handle data submission
2751 * This is done at this point, because we need the config values
2752 */
2753 public function handleDataSubmission()
2754 {
2755 // Hook for processing data submission to extensions
2756 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2757 $_procObj = GeneralUtility::makeInstance($className);
2758 $_procObj->checkDataSubmission($this);
2759 }
2760 }
2761
2762 /**
2763 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2764 *
2765 * @see $activeRedirectUrlHandlers
2766 */
2767 public function initializeRedirectUrlHandlers()
2768 {
2769 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2770 if (!$urlHandlers) {
2771 return;
2772 }
2773
2774 foreach ($urlHandlers as $identifier => $configuration) {
2775 if (empty($configuration) || !is_array($configuration)) {
2776 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2777 }
2778 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2779 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2780 }
2781 }
2782
2783 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2784
2785 foreach ($orderedHandlers as $configuration) {
2786 /** @var UrlHandlerInterface $urlHandler */
2787 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2788 if ($urlHandler->canHandleCurrentUrl()) {
2789 $this->activeUrlHandlers[] = $urlHandler;
2790 }
2791 }
2792 }
2793
2794 /**
2795 * Loops over all registered URL handlers and lets them process the current URL.
2796 *
2797 * If no handler has stopped the current process (e.g. by redirecting) and a
2798 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2799 *
2800 * @internal Should be called by the FrontendRequestHandler only.
2801 * @return ResponseInterface|null
2802 */
2803 public function redirectToExternalUrl()
2804 {
2805 foreach ($this->activeUrlHandlers as $redirectHandler) {
2806 $response = $redirectHandler->handle();
2807 if ($response instanceof ResponseInterface) {
2808 return $response;
2809 }
2810 }
2811
2812 if (!empty($this->activeUrlHandlers)) {
2813 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2814 }
2815
2816 return null;
2817 }
2818
2819 /**
2820 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2821 * This feature allows sessions to use a GET-parameter instead of a cookie.
2822 *
2823 * @access private
2824 */
2825 public function setUrlIdToken()
2826 {
2827 if ($this->config['config']['ftu']) {
2828 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2829 } else {
2830 $this->getMethodUrlIdToken = '';
2831 }
2832 }
2833
2834 /**
2835 * Calculates and sets the internal linkVars based upon the current
2836 * $_GET parameters and the setting "config.linkVars".
2837 */
2838 public function calculateLinkVars()
2839 {
2840 $this->linkVars = '';
2841 if (empty($this->config['config']['linkVars'])) {
2842 return;
2843 }
2844
2845 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2846
2847 if (empty($linkVars)) {
2848 return;
2849 }
2850 $getData = GeneralUtility::_GET();
2851 foreach ($linkVars as $linkVar) {
2852 $test = $value = '';
2853 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2854 $linkVar = trim($match[1]);
2855 $test = trim($match[2]);
2856 }
2857
2858 $keys = explode('|', $linkVar);
2859 $numberOfLevels = count($keys);
2860 $rootKey = trim($keys[0]);
2861 if (!isset($getData[$rootKey])) {
2862 continue;
2863 }
2864 $value = $getData[$rootKey];
2865 for ($i = 1; $i < $numberOfLevels; $i++) {
2866 $currentKey = trim($keys[$i]);
2867 if (isset($value[$currentKey])) {
2868 $value = $value[$currentKey];
2869 } else {
2870 $value = false;
2871 break;
2872 }
2873 }
2874 if ($value !== false) {
2875 $parameterName = $keys[0];
2876 for ($i = 1; $i < $numberOfLevels; $i++) {
2877 $parameterName .= '[' . $keys[$i] . ']';
2878 }
2879 if (!is_array($value)) {
2880 $temp = rawurlencode($value);
2881 if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2882 // Error: This value was not allowed for this key
2883 continue;
2884 }
2885 $value = '&' . $parameterName . '=' . $temp;
2886 } else {
2887 if ($test !== '' && $test !== 'array') {
2888 // Error: This key must not be an array!
2889 continue;
2890 }
2891 $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2892 }
2893 $this->linkVars .= $value;
2894 }
2895 }
2896 }
2897
2898 /**
2899 * Split the link vars string by "," but not if the "," is inside of braces
2900 *
2901 * @param $string
2902 *
2903 * @return array
2904 */
2905 protected function splitLinkVarsString(string $string): array
2906 {
2907 $tempCommaReplacementString = '###KASPER###';
2908
2909 // replace every "," wrapped in "()" by a "unique" string
2910 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2911 return str_replace(',', $tempCommaReplacementString, $result[0]);
2912 }, $string);
2913
2914 $string = GeneralUtility::trimExplode(',', $string);
2915
2916 // replace all "unique" strings back to ","
2917 return str_replace($tempCommaReplacementString, ',', $string);
2918 }
2919
2920 /**
2921 * Checks if the value defined in "config.linkVars" contains an allowed value.
2922 * Otherwise, return FALSE which means the value will not be added to any links.
2923 *
2924 * @param string $haystack The string in which to find $needle
2925 * @param string $needle The string to find in $haystack
2926 * @return bool Returns TRUE if $needle matches or is found in $haystack
2927 */
2928 protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2929 {
2930 $isAllowed = false;
2931 // Integer
2932 if ($needle === 'int' || $needle === 'integer') {
2933 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2934 $isAllowed = true;
2935 }
2936 } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2937 // Regular expression, only "//" is allowed as delimiter
2938 if (@preg_match($needle, $haystack)) {
2939 $isAllowed = true;
2940 }
2941 } elseif (strstr($needle, '-')) {
2942 // Range
2943 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2944 $range = explode('-', $needle);
2945 if ($range[0] <= $haystack && $range[1] >= $haystack) {
2946 $isAllowed = true;
2947 }
2948 }
2949 } elseif (strstr($needle, '|')) {
2950 // List