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