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