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