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