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