590d8f28a52926f9664d5fb86bebf7a5b1905571
[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 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1614 $this->id = $this->page['uid'];
1615 }
1616 // Gets the rootLine
1617 try {
1618 $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1619 } catch (RootLineException $e) {
1620 $this->rootLine = [];
1621 }
1622 // If not rootline we're off...
1623 if (empty($this->rootLine)) {
1624 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1625 $this->logger->error($message);
1626 try {
1627 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1628 $GLOBALS['TYPO3_REQUEST'],
1629 $message,
1630 $this->getPageAccessFailureReasons(PageAccessFailureReasons::ROOTLINE_BROKEN)
1631 );
1632 throw new ImmediateResponseException($response, 1533931350);
1633 } catch (ServiceUnavailableException $e) {
1634 throw new ServiceUnavailableException($message, 1301648167);
1635 }
1636 }
1637 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1638 if ($this->checkRootlineForIncludeSection()) {
1639 if (empty($this->rootLine)) {
1640 $message = 'The requested page was not accessible!';
1641 try {
1642 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1643 $GLOBALS['TYPO3_REQUEST'],
1644 $message,
1645 $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_GENERAL)
1646 );
1647 throw new ImmediateResponseException($response, 1533931351);
1648 } catch (ServiceUnavailableException $e) {
1649 $this->logger->warning($message);
1650 throw new ServiceUnavailableException($message, 1301648234);
1651 }
1652 } else {
1653 $el = reset($this->rootLine);
1654 $this->id = $el['uid'];
1655 $this->page = $this->sys_page->getPage($this->id);
1656 try {
1657 $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1658 } catch (RootLineException $e) {
1659 $this->rootLine = [];
1660 }
1661 }
1662 }
1663 }
1664
1665 /**
1666 * If $this->id contains a translated page record, this needs to be resolved to the default language
1667 * in order for all rootline functionality and access restrictions to be in place further on.
1668 *
1669 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1670 */
1671 protected function resolveTranslatedPageId()
1672 {
1673 $this->page = $this->sys_page->getPage($this->id);
1674 // Accessed a default language page record, nothing to resolve
1675 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1676 return;
1677 }
1678 $languageId = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1679 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1680 $this->context->setAspect('language', GeneralUtility::makeInstance(LanguageAspect::class, $languageId));
1681 $this->id = $this->page['uid'];
1682 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1683 if (!$this->getCurrentSiteLanguage()) {
1684 $_GET['L'] = $languageId;
1685 $GLOBALS['HTTP_GET_VARS']['L'] = $languageId;
1686 }
1687 }
1688
1689 /**
1690 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value).
1691 *
1692 * @param int $SC The value of the "shortcut" field from the pages record
1693 * @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
1694 * @param int $thisUid The current page UID of the page which is a shortcut
1695 * @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...)
1696 * @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.
1697 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1698 * @throws \RuntimeException
1699 * @throws ShortcutTargetPageNotFoundException
1700 * @return mixed Returns the page record of the page that the shortcut pointed to.
1701 * @internal
1702 * @see getPageAndRootline()
1703 * @deprecated As this method conceptually belongs to PageRepository, it is moved in PageRepository, and will be removed in TYPO3 v10.0.
1704 */
1705 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1706 {
1707 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);
1708 return $this->sys_page->getPageShortcut($SC, $mode, $thisUid, $itera, $pageLog, $disableGroupCheck);
1709 }
1710
1711 /**
1712 * Checks if visibility of the page is blocked upwards in the root line.
1713 *
1714 * If any page in the root line is blocking visibility, true is returend.
1715 *
1716 * All pages from the blocking page downwards are removed from the root
1717 * line, so that the remaining pages can be used to relocate the page up
1718 * to lowest visible page.
1719 *
1720 * The blocking feature of a page must be turned on by setting the page
1721 * record field 'extendToSubpages' to 1 in case of hidden, starttime,
1722 * endtime or fe_group restrictions.
1723 *
1724 * Additionally this method checks for backend user sections in root line
1725 * and if found evaluates if a backend user is logged in and has access.
1726 *
1727 * Recyclers are also checked and trigger page not found if found in root
1728 * line.
1729 *
1730 * @todo Find a better name, i.e. checkVisibilityByRootLine
1731 * @todo Invert boolean return value. Return true if visible.
1732 *
1733 * @return bool
1734 */
1735 protected function checkRootlineForIncludeSection(): bool
1736 {
1737 $c = count($this->rootLine);
1738 $removeTheRestFlag = false;
1739 for ($a = 0; $a < $c; $a++) {
1740 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1741 // Add to page access failure history:
1742 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1743 $removeTheRestFlag = true;
1744 }
1745
1746 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1747 // If there is a backend user logged in, check if he has read access to the page:
1748 if ($this->isBackendUserLoggedIn()) {
1749 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1750 ->getQueryBuilderForTable('pages');
1751
1752 $queryBuilder
1753 ->getRestrictions()
1754 ->removeAll();
1755
1756 $row = $queryBuilder
1757 ->select('uid')
1758 ->from('pages')
1759 ->where(
1760 $queryBuilder->expr()->eq(
1761 'uid',
1762 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1763 ),
1764 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1765 )
1766 ->execute()
1767 ->fetch();
1768
1769 // versionOL()?
1770 if (!$row) {
1771 // 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...
1772 $removeTheRestFlag = true;
1773 }
1774 } else {
1775 // Don't go here, if there is no backend user logged in.
1776 $removeTheRestFlag = true;
1777 }
1778 } elseif ((int)$this->rootLine[$a]['doktype'] === PageRepository::DOKTYPE_RECYCLER) {
1779 // page is in a recycler
1780 $removeTheRestFlag = true;
1781 }
1782 if ($removeTheRestFlag) {
1783 // Page is 'not found' in case a subsection was found and not accessible, code 2
1784 $this->pageNotFound = 2;
1785 unset($this->rootLine[$a]);
1786 }
1787 }
1788 return $removeTheRestFlag;
1789 }
1790
1791 /**
1792 * Checks page record for enableFields
1793 * Returns TRUE if enableFields does not disable the page record.
1794 * Takes notice of the includeHiddenPages visibility aspect flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1795 *
1796 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1797 * @param bool $bypassGroupCheck Bypass group-check
1798 * @return bool TRUE, if record is viewable.
1799 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1800 */
1801 public function checkEnableFields($row, $bypassGroupCheck = false)
1802 {
1803 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1804 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1805 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1806 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1807 if ($return === false) {
1808 return false;
1809 }
1810 }
1811 if ((!$row['hidden'] || $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages', false))
1812 && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME']
1813 && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME'])
1814 && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1815 return true;
1816 }
1817 return false;
1818 }
1819
1820 /**
1821 * Check group access against a page record
1822 *
1823 * @param array $row The page record to evaluate (needs field: fe_group)
1824 * @return bool TRUE, if group access is granted.
1825 * @internal
1826 */
1827 public function checkPageGroupAccess($row)
1828 {
1829 /** @var UserAspect $userAspect */
1830 $userAspect = $this->context->getAspect('frontend.user');
1831 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1832 return count(array_intersect($userAspect->getGroupIds(), $pageGroupList)) > 0;
1833 }
1834
1835 /**
1836 * Checks if the current page of the root line is visible.
1837 *
1838 * If the field extendToSubpages is 0, access is granted,
1839 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1840 *
1841 * @todo Find a better name, i.e. isVisibleRecord()
1842 *
1843 * @param array $row The page record
1844 * @return bool true if visible
1845 * @internal
1846 * @see checkEnableFields()
1847 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1848 * @see checkRootlineForIncludeSection()
1849 */
1850 public function checkPagerecordForIncludeSection(array $row): bool
1851 {
1852 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1853 }
1854
1855 /**
1856 * 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!)
1857 *
1858 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1859 */
1860 public function checkIfLoginAllowedInBranch()
1861 {
1862 // Initialize:
1863 $c = count($this->rootLine);
1864 $loginAllowed = true;
1865 // Traverse root line from root and outwards:
1866 for ($a = 0; $a < $c; $a++) {
1867 // If a value is set for login state:
1868 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1869 // Determine state from value:
1870 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1871 $loginAllowed = false;
1872 $this->loginAllowedInBranch_mode = 'all';
1873 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1874 $loginAllowed = false;
1875 $this->loginAllowedInBranch_mode = 'groups';
1876 } else {
1877 $loginAllowed = true;
1878 }
1879 }
1880 }
1881 return $loginAllowed;
1882 }
1883
1884 /**
1885 * 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
1886 *
1887 * @param string $failureReasonCode the error code to be attached (optional), see PageAccessFailureReasons list for details
1888 * @return array Summary of why page access was not allowed.
1889 */
1890 public function getPageAccessFailureReasons(string $failureReasonCode = null)
1891 {
1892 $output = [];
1893 if ($failureReasonCode) {
1894 $output['code'] = $failureReasonCode;
1895 }
1896 $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'] : []);
1897 if (!empty($combinedRecords)) {
1898 foreach ($combinedRecords as $k => $pagerec) {
1899 // 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
1900 // 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!
1901 if (!$k || $pagerec['extendToSubpages']) {
1902 if ($pagerec['hidden']) {
1903 $output['hidden'][$pagerec['uid']] = true;
1904 }
1905 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1906 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1907 }
1908 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1909 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1910 }
1911 if (!$this->checkPageGroupAccess($pagerec)) {
1912 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1913 }
1914 }
1915 }
1916 }
1917 return $output;
1918 }
1919
1920 /**
1921 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1922 * If not inside domain, then default to first page in domain.
1923 *
1924 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1925 * @internal
1926 */
1927 public function getPageAndRootlineWithDomain($domainStartPage)
1928 {
1929 $this->getPageAndRootline();
1930 // 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.
1931 if ($domainStartPage && is_array($this->rootLine)) {
1932 $idFound = false;
1933 foreach ($this->rootLine as $key => $val) {
1934 if ($val['uid'] == $domainStartPage) {
1935 $idFound = true;
1936 break;
1937 }
1938 }
1939 if (!$idFound) {
1940 // Page is 'not found' in case the id was outside the domain, code 3
1941 $this->pageNotFound = 3;
1942 $this->id = $domainStartPage;
1943 // re-get the page and rootline if the id was not found.
1944 $this->getPageAndRootline();
1945 }
1946 }
1947 }
1948
1949 /**
1950 * Page unavailable handler for use in frontend plugins from extensions.
1951 *
1952 * @param string $reason Reason text
1953 * @param string $header HTTP header to send
1954 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1955 */
1956 public function pageUnavailableAndExit($reason = '', $header = '')
1957 {
1958 trigger_error('$TSFE->pageUnavailableAndExit() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1959 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1960 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1961 die;
1962 }
1963
1964 /**
1965 * Page-not-found handler for use in frontend plugins from extensions.
1966 *
1967 * @param string $reason Reason text
1968 * @param string $header HTTP header to send
1969 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1970 */
1971 public function pageNotFoundAndExit($reason = '', $header = '')
1972 {
1973 trigger_error('$TSFE->pageNotFoundAndExit() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1974 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1975 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1976 die;
1977 }
1978
1979 /**
1980 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1981 * and devIPMask must not match the current visitor's IP address.
1982 *
1983 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1984 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1985 */
1986 public function checkPageUnavailableHandler()
1987 {
1988 trigger_error('$TSFE->checkPageUnavailableHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1989 if (
1990 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1991 && !GeneralUtility::cmpIP(
1992 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1993 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1994 )
1995 ) {
1996 $checkPageUnavailableHandler = true;
1997 } else {
1998 $checkPageUnavailableHandler = false;
1999 }
2000 return $checkPageUnavailableHandler;
2001 }
2002
2003 /**
2004 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
2005 *
2006 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
2007 * @param string $header If set, this is passed directly to the PHP function, header()
2008 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2009 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2010 */
2011 public function pageUnavailableHandler($code, $header, $reason)
2012 {
2013 trigger_error('$TSFE->pageUnavailableHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
2014 $this->pageErrorHandler($code, $header, $reason);
2015 }
2016
2017 /**
2018 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
2019 *
2020 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
2021 * @param string $header If set, this is passed directly to the PHP function, header()
2022 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2023 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2024 */
2025 public function pageNotFoundHandler($code, $header = '', $reason = '')
2026 {
2027 trigger_error('$TSFE->pageNotFoundHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
2028 $this->pageErrorHandler($code, $header, $reason);
2029 }
2030
2031 /**
2032 * Generic error page handler.
2033 * Exits.
2034 *
2035 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
2036 * @param string $header If set, this is passed directly to the PHP function, header()
2037 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2038 * @throws \RuntimeException
2039 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2040 */
2041 public function pageErrorHandler($code, $header = '', $reason = '')
2042 {
2043 trigger_error('$TSFE->pageErrorHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
2044 // Issue header in any case:
2045 if ($header) {
2046 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2047 foreach ($headerArr as $header) {
2048 header($header);
2049 }
2050 }
2051 // Create response:
2052 // Simply boolean; Just shows TYPO3 error page with reason:
2053 if (strtolower($code) === 'true' || (string)$code === '1' || is_bool($code)) {
2054 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2055 'Page Not Found',
2056 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
2057 );
2058 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
2059 $funcRef = trim(substr($code, 14));
2060 $params = [
2061 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
2062 'reasonText' => $reason,
2063 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
2064 ];
2065 try {
2066 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
2067 } catch (\Exception $e) {
2068 throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
2069 }
2070 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
2071 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
2072 if (@is_file($readFile)) {
2073 echo str_replace(
2074 [
2075 '###CURRENT_URL###',
2076 '###REASON###'
2077 ],
2078 [
2079 GeneralUtility::getIndpEnv('REQUEST_URI'),
2080 htmlspecialchars($reason)
2081 ],
2082 file_get_contents($readFile)
2083 );
2084 } else {
2085 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2086 }
2087 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
2088 HttpUtility::redirect(substr($code, 9));
2089 } elseif ($code !== '') {
2090 // Check if URL is relative
2091 $url_parts = parse_url($code);
2092 // parse_url could return an array without the key "host", the empty check works better than strict check
2093 if (empty($url_parts['host'])) {
2094 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
2095 if ($code[0] === '/') {
2096 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2097 } else {
2098 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2099 }
2100 $checkBaseTag = false;
2101 } else {
2102 $checkBaseTag = true;
2103 }
2104 // Check recursion
2105 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2106 if ($reason == '') {
2107 $reason = 'Page cannot be found.';
2108 }
2109 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2110 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2111 }
2112 // Prepare headers
2113 $headerArr = [
2114 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2115 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2116 ];
2117 $report = [];
2118 $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2119 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2120 throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2121 }
2122 // Header and content are separated by an empty line
2123 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2124 $content .= CRLF;
2125 if (false === $res) {
2126 // Last chance -- redirect
2127 HttpUtility::redirect($code);
2128 } else {
2129 // Forward these response headers to the client
2130 $forwardHeaders = [
2131 'Content-Type:'
2132 ];
2133 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2134 foreach ($headerArr as $header) {
2135 foreach ($forwardHeaders as $h) {
2136 if (preg_match('/^' . $h . '/', $header)) {
2137 header($header);
2138 }
2139 }
2140 }
2141 // Put <base> if necessary
2142 if ($checkBaseTag) {
2143 // If content already has <base> tag, we do not need to do anything
2144 if (false === stristr($content, '<base ')) {
2145 // Generate href for base tag
2146 $base = $url_parts['scheme'] . '://';
2147 if ($url_parts['user'] != '') {
2148 $base .= $url_parts['user'];
2149 if ($url_parts['pass'] != '') {
2150 $base .= ':' . $url_parts['pass'];
2151 }
2152 $base .= '@';
2153 }
2154 $base .= $url_parts['host'];
2155 // Add path portion skipping possible file name
2156 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2157 // Put it into content (generate also <head> if necessary)
2158 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2159 if (stristr($content, '<head>')) {
2160 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2161 } else {
2162 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2163 }
2164 }
2165 }
2166 // Output the content
2167 echo $content;
2168 }
2169 } else {
2170 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2171 'Page Not Found',
2172 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2173 );
2174 }
2175 die;
2176 }
2177
2178 /**
2179 * Fetches the integer page id for a page alias.
2180 * 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
2181 */
2182 protected function checkAndSetAlias()
2183 {
2184 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2185 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2186 if ($aid) {
2187 $this->id = $aid;
2188 } else {
2189 $this->pageNotFound = 4;
2190 }
2191 }
2192 }
2193
2194 /**
2195 * Merging values into the global $_GET
2196 *
2197 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2198 * @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.
2199 */
2200 protected function mergingWithGetVars($GET_VARS)
2201 {
2202 if (is_array($GET_VARS)) {
2203 // Getting $_GET var, unescaped.
2204 $realGet = GeneralUtility::_GET();
2205 if (!is_array($realGet)) {
2206 $realGet = [];
2207 }
2208 // Merge new values on top:
2209 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2210 // Write values back to $_GET
2211 $_GET = $realGet;
2212 $GLOBALS['HTTP_GET_VARS'] = $realGet;
2213 // Setting these specifically (like in the init-function):
2214 if (isset($GET_VARS['type'])) {
2215 $this->type = (int)$GET_VARS['type'];
2216 }
2217 if (isset($GET_VARS['cHash'])) {
2218 $this->cHash = $GET_VARS['cHash'];
2219 }
2220 if (isset($GET_VARS['MP'])) {
2221 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2222 }
2223 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2224 $this->set_no_cache('no_cache is requested via GET parameter');
2225 }
2226 }
2227 }
2228
2229 /********************************************
2230 *
2231 * Template and caching related functions.
2232 *
2233 *******************************************/
2234 /**
2235 * Calculates a hash string based on additional parameters in the url.
2236 *
2237 * Calculated hash is stored in $this->cHash_array.
2238 * This is used to cache pages with more parameters than just id and type.
2239 *
2240 * @see reqCHash()
2241 * @deprecated since TYPO3 v9.5, will be removed in TYPO3 v10.0. This validation is done in the PageParameterValidator PSR-15 middleware.
2242 */
2243 public function makeCacheHash()
2244 {
2245 trigger_error('$TSFE->makeCacheHash() will be removed in TYPO3 v10.0, as this is now handled in the PSR-15 middleware.', E_USER_DEPRECATED);
2246 // No need to test anything if caching was already disabled.
2247 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2248 return;
2249 }
2250 $GET = GeneralUtility::_GET();
2251 if ($this->cHash && is_array($GET)) {
2252 // Make sure we use the page uid and not the page alias
2253 $GET['id'] = $this->id;
2254 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2255 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2256 if (!hash_equals($cHash_calc, $this->cHash)) {
2257 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2258 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2259 $GLOBALS['TYPO3_REQUEST'],
2260 'Request parameters could not be validated (&cHash comparison failed)',
2261 ['code' => PageAccessFailureReasons::CACHEHASH_COMPARISON_FAILED]
2262 );
2263 throw new ImmediateResponseException($response, 1533931352);
2264 }
2265 $this->disableCache();
2266 $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);
2267 }
2268 } elseif (is_array($GET)) {
2269 // No cHash is set, check if that is correct
2270 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2271 $this->reqCHash();
2272 }
2273 }
2274 }
2275
2276 /**
2277 * Will disable caching if the cHash value was not set when having dynamic arguments in GET query parameters.
2278 * 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)
2279 *
2280 * @see \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2281 */
2282 public function reqCHash()
2283 {
2284 $skip = $this->pageArguments !== null && empty($this->pageArguments->getDynamicArguments());
2285 if ($this->cHash || $skip) {
2286 return;
2287 }
2288 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2289 if ($this->tempContent) {
2290 $this->clearPageCacheContent();
2291 }
2292 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2293 $GLOBALS['TYPO3_REQUEST'],
2294 'Request parameters could not be validated (&cHash empty)',
2295 ['code' => PageAccessFailureReasons::CACHEHASH_EMPTY]
2296 );
2297 throw new ImmediateResponseException($response, 1533931354);
2298 }
2299 $this->disableCache();
2300 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2301 }
2302
2303 /**
2304 * @param PageArguments $pageArguments
2305 * @internal
2306 */
2307 public function setPageArguments(PageArguments $pageArguments)
2308 {
2309 $this->pageArguments = $pageArguments;
2310 }
2311
2312 /**
2313 * Initialize the TypoScript template parser
2314 * @deprecated since TYPO3 v9.4 will be removed in TYPO3 v10.0. Either instantiate $TSFE->tmpl yourself, if really necessary.
2315 */
2316 public function initTemplate()
2317 {
2318 trigger_error('$TSFE->initTemplate() will be removed in TYPO3 v10.0. Instantiating TemplateService is done implicitly on usage within $TSFE directly.', E_USER_DEPRECATED);
2319 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context);
2320 }
2321
2322 /**
2323 * See if page is in cache and get it if so
2324 * Stores the page content in $this->content if something is found.
2325 *
2326 * @throws \InvalidArgumentException
2327 * @throws \RuntimeException
2328 */
2329 public function getFromCache()
2330 {
2331 // clearing the content-variable, which will hold the pagecontent
2332 $this->content = '';
2333 // Unsetting the lowlevel config
2334 $this->config = [];
2335 $this->cacheContentFlag = false;
2336
2337 if ($this->no_cache) {
2338 return;
2339 }
2340
2341 if (!($this->tmpl instanceof TemplateService)) {
2342 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context);
2343 }
2344
2345 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2346 if (!is_array($pageSectionCacheContent)) {
2347 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2348 // We use the Registry to store this lock centrally,
2349 // but we protect the access again with a global exclusive lock to avoid race conditions
2350
2351 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2352 //
2353 // from this point on we're the only one working on that page ($key)
2354 //
2355
2356 // query the cache again to see if the page data are there meanwhile
2357 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2358 if (is_array($pageSectionCacheContent)) {
2359 // we have the content, nice that some other process did the work for us already
2360 $this->releaseLock('pagesection');
2361 }
2362 // We keep the lock set, because we are the ones generating the page now
2363 // and filling the cache.
2364 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2365 }
2366
2367 if (is_array($pageSectionCacheContent)) {
2368 // 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.
2369 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2370 // 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.
2371 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2372 ksort($pageSectionCacheContent);
2373 $this->all = $pageSectionCacheContent;
2374 }
2375 unset($pageSectionCacheContent);
2376
2377 // Look for page in cache only if a shift-reload is not sent to the server.
2378 $lockHash = $this->getLockHash();
2379 if (!$this->headerNoCache()) {
2380 if ($this->all) {
2381 // we got page section information
2382 $this->newHash = $this->getHash();
2383 $this->getTimeTracker()->push('Cache Row');
2384 $row = $this->getFromCache_queryRow();
2385 if (!is_array($row)) {
2386 // nothing in the cache, we acquire an exclusive lock now
2387
2388 $this->acquireLock('pages', $lockHash);
2389 //
2390 // from this point on we're the only one working on that page ($lockHash)
2391 //
2392
2393 // query the cache again to see if the data are there meanwhile
2394 $row = $this->getFromCache_queryRow();
2395 if (is_array($row)) {
2396 // we have the content, nice that some other process did the work for us
2397 $this->releaseLock('pages');
2398 }
2399 // We keep the lock set, because we are the ones generating the page now
2400 // and filling the cache.
2401 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2402 }
2403 if (is_array($row)) {
2404 // we have data from cache
2405
2406 // Call hook when a page is retrieved from cache:
2407 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2408 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2409 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2410 }
2411 // Fetches the lowlevel config stored with the cached data
2412 $this->config = $row['cache_data'];
2413 // Getting the content
2414 $this->content = $row['content'];
2415 // Flag for temp content
2416 $this->tempContent = $row['temp_content'];
2417 // Setting flag, so we know, that some cached content has been loaded
2418 $this->cacheContentFlag = true;
2419 $this->cacheExpires = $row['expires'];
2420
2421 // Restore page title information, this is needed to generate the page title for
2422 // partially cached pages.
2423 $this->page['title'] = $row['pageTitleInfo']['title'];
2424 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2425 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2426
2427 if (isset($this->config['config']['debug'])) {
2428 $debugCacheTime = (bool)$this->config['config']['debug'];
2429 } else {
2430 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2431 }
2432 if ($debugCacheTime) {
2433 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2434 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2435 $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $row['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $row['expires']) . ' -->';
2436 }
2437 }
2438 $this->getTimeTracker()->pull();
2439
2440 return;
2441 }
2442 }
2443 // the user forced rebuilding the page cache or there was no pagesection information
2444 // get a lock for the page content so other processes will not interrupt the regeneration
2445 $this->acquireLock('pages', $lockHash);
2446 }
2447
2448 /**
2449 * Returning the cached version of page with hash = newHash
2450 *
2451 * @return array Cached row, if any. Otherwise void.
2452 */
2453 public function getFromCache_queryRow()
2454 {
2455 $this->getTimeTracker()->push('Cache Query');
2456 $row = $this->pageCache->get($this->newHash);
2457 $this->getTimeTracker()->pull();
2458 return $row;
2459 }
2460
2461 /**
2462 * Detecting if shift-reload has been clicked
2463 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2464 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2465 *
2466 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2467 */
2468 public function headerNoCache()
2469 {
2470 $disableAcquireCacheData = false;
2471 if ($this->isBackendUserLoggedIn()) {
2472 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2473 $disableAcquireCacheData = true;
2474 }
2475 }
2476 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2477 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2478 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2479 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2480 }
2481 return $disableAcquireCacheData;
2482 }
2483
2484 /**
2485 * Calculates the cache-hash
2486 * This hash is unique to the template, the variables ->id, ->type, list of fe user groups, ->MP (Mount Points) and cHash array
2487 * Used to get and later store the cached data.
2488 *
2489 * @return string MD5 hash of serialized hash base from createHashBase()
2490 * @see getFromCache(), getLockHash()
2491 */
2492 protected function getHash()
2493 {
2494 return md5($this->createHashBase(false));
2495 }
2496
2497 /**
2498 * Calculates the lock-hash
2499 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2500 *
2501 * @return string MD5 hash
2502 * @see getFromCache(), getHash()
2503 */
2504 protected function getLockHash()
2505 {
2506 $lockHash = $this->createHashBase(true);
2507 return md5($lockHash);
2508 }
2509
2510 /**
2511 * Calculates the cache-hash (or the lock-hash)
2512 * This hash is unique to the template,
2513 * the variables ->id, ->type, list of frontend user groups,
2514 * ->MP (Mount Points) and cHash array
2515 * Used to get and later store the cached data.
2516 *
2517 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2518 * @return string the serialized hash base
2519 */
2520 protected function createHashBase($createLockHashBase = false)
2521 {
2522 // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
2523 // is not cached properly as we don't have any language-specific conditions anymore
2524 $siteBase = $this->getCurrentSiteLanguage() ? (string)$this->getCurrentSiteLanguage()->getBase() : '';
2525
2526 // Fetch the list of user groups
2527 /** @var UserAspect $userAspect */
2528 $userAspect = $this->context->getAspect('frontend.user');
2529 $hashParameters = [
2530 'id' => (int)$this->id,
2531 'type' => (int)$this->type,
2532 'gr_list' => (string)implode(',', $userAspect->getGroupIds()),
2533 'MP' => (string)$this->MP,
2534 'siteBase' => $siteBase,
2535 // cHash_array includes dynamic route arguments (if route was resolved)
2536 'cHash' => $this->cHash_array,
2537 // additional variation trigger for static routes
2538 'staticRouteArguments' => $this->pageArguments !== null ? $this->pageArguments->getStaticArguments() : null,
2539 'domainStartPage' => $this->domainStartPage
2540 ];
2541 // Include the template information if we shouldn't create a lock hash
2542 if (!$createLockHashBase) {
2543 $hashParameters['all'] = $this->all;
2544 }
2545 // Call hook to influence the hash calculation
2546 $_params = [
2547 'hashParameters' => &$hashParameters,
2548 'createLockHashBase' => $createLockHashBase
2549 ];
2550 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2551 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2552 }
2553 return serialize($hashParameters);
2554 }
2555
2556 /**
2557 * Checks if config-array exists already but if not, gets it
2558 *
2559 * @throws ServiceUnavailableException
2560 */
2561 public function getConfigArray()
2562 {
2563 if (!($this->tmpl instanceof TemplateService)) {
2564 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context);
2565 }
2566
2567 // 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
2568 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2569 $timeTracker = $this->getTimeTracker();
2570 $timeTracker->push('Parse template');
2571 // Force parsing, if set?:
2572 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2573 // Start parsing the TS template. Might return cached version.
2574 $this->tmpl->start($this->rootLine);
2575 $timeTracker->pull();
2576 if ($this->tmpl->loaded) {
2577 $timeTracker->push('Setting the config-array');
2578 // toplevel - objArrayName
2579 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2580 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2581 if (!is_array($this->pSetup)) {
2582 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2583 $this->logger->alert($message);
2584 try {
2585 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
2586 $GLOBALS['TYPO3_REQUEST'],
2587 $message,
2588 ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_CONFIGURED]
2589 );
2590 throw new ImmediateResponseException($response, 1533931374);
2591 } catch (ServiceUnavailableException $e) {
2592 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2593 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2594 }
2595 } else {
2596 if (!isset($this->config['config'])) {
2597 $this->config['config'] = [];
2598 }
2599 // Filling the config-array, first with the main "config." part
2600 if (is_array($this->tmpl->setup['config.'])) {
2601 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2602 $this->config['config'] = $this->tmpl->setup['config.'];
2603 }
2604 // override it with the page/type-specific "config."
2605 if (is_array($this->pSetup['config.'])) {
2606 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2607 }
2608 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10.0
2609 if ($this->config['config']['typolinkCheckRootline']) {
2610 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2611 }
2612 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2613 if (!isset($this->config['config']['removeDefaultJS'])) {
2614 $this->config['config']['removeDefaultJS'] = 'external';
2615 }
2616 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2617 $this->config['config']['inlineStyle2TempFile'] = 1;
2618 }
2619
2620 if (!isset($this->config['config']['compressJs'])) {
2621 $this->config['config']['compressJs'] = 0;
2622 }
2623 // Processing for the config_array:
2624 $this->config['rootLine'] = $this->tmpl->rootLine;
2625 // Class for render Header and Footer parts
2626 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2627 try {
2628 $file = GeneralUtility::makeInstance(FilePathSanitizer::class)
2629 ->sanitize((string)$this->pSetup['pageHeaderFooterTemplateFile']);
2630 $this->pageRenderer->setTemplateFile($file);
2631 } catch (\TYPO3\CMS\Core\Resource\Exception $e) {
2632 // do nothing
2633 }
2634 }
2635 }
2636 $timeTracker->pull();
2637 } else {
2638 $message = 'No TypoScript template found!';
2639 $this->logger->alert($message);
2640 try {
2641 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
2642 $GLOBALS['TYPO3_REQUEST'],
2643 $message,
2644 ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_FOUND]
2645 );
2646 throw new ImmediateResponseException($response, 1533931380);
2647 } catch (ServiceUnavailableException $e) {
2648 throw new ServiceUnavailableException($message, 1294587218);
2649 }
2650 }
2651 }
2652
2653 // No cache
2654 // Set $this->no_cache TRUE if the config.no_cache value is set!
2655 if ($this->config['config']['no_cache']) {
2656 $this->set_no_cache('config.no_cache is set');
2657 }
2658 // Merge GET with defaultGetVars
2659 // Please note that this code will get removed in TYPO3 v10.0 as it is done in the PSR-15 middleware.
2660 if (!empty($this->config['config']['defaultGetVars.'])) {
2661 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2662 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2663 $_GET = $modifiedGetVars;
2664 $GLOBALS['HTTP_GET_VARS'] = $modifiedGetVars;
2665 }
2666
2667 // Auto-configure settings when a site is configured
2668 if ($this->getCurrentSiteLanguage()) {
2669 $this->config['config']['absRefPrefix'] = $this->config['config']['absRefPrefix'] ?? 'auto';
2670 }
2671
2672 $this->setUrlIdToken();
2673
2674 // Hook for postProcessing the configuration array
2675 $params = ['config' => &$this->config['config']];
2676 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2677 GeneralUtility::callUserFunction($funcRef, $params, $this);
2678 }
2679 }
2680
2681 /********************************************
2682 *
2683 * Further initialization and data processing
2684 *
2685 *******************************************/
2686
2687 /**
2688 * Setting the language key that will be used by the current page.
2689 * 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.
2690 *
2691 * @internal
2692 */
2693 public function settingLanguage()
2694 {
2695 $_params = [];
2696 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2697 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2698 }
2699
2700 $siteLanguage = $this->getCurrentSiteLanguage();
2701
2702 // Initialize charset settings etc.
2703 if ($siteLanguage) {
2704 $languageKey = $siteLanguage->getTypo3Language();
2705 } else {
2706 $languageKey = $this->config['config']['language'] ?? 'default';
2707 }
2708 $this->lang = $languageKey;
2709 $this->setOutputLanguage($languageKey);
2710
2711 // Rendering charset of HTML page.
2712 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2713 $this->metaCharset = $this->config['config']['metaCharset'];
2714 }
2715
2716 // Get values from site language
2717 if ($siteLanguage) {
2718 $languageAspect = LanguageAspectFactory::createFromSiteLanguage($siteLanguage);
2719 } else {
2720 $languageAspect = LanguageAspectFactory::createFromTypoScript($this->config['config'] ?? []);
2721 }
2722
2723 $languageId = $languageAspect->getId();
2724 $languageContentId = $languageAspect->getContentId();
2725
2726 // If sys_language_uid is set to another language than default:
2727 if ($languageAspect->getId() > 0) {
2728 // check whether a shortcut is overwritten by a translated page
2729 // we can only do this now, as this is the place where we get
2730 // to know about translations
2731 $this->checkTranslatedShortcut($languageAspect->getId());
2732 // Request the overlay record for the sys_language_uid:
2733 $olRec = $this->sys_page->getPageOverlay($this->id, $languageAspect->getId());
2734 if (empty($olRec)) {
2735 // If requested translation is not available:
2736 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2737 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2738 $GLOBALS['TYPO3_REQUEST'],
2739 'Page is not available in the requested language.',
2740 ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE]
2741 );
2742 throw new ImmediateResponseException($response, 1533931388);
2743 }
2744 switch ((string)$languageAspect->getLegacyLanguageMode()) {
2745 case 'strict':
2746 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2747 $GLOBALS['TYPO3_REQUEST'],
2748 'Page is not available in the requested language (strict).',
2749 ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE_STRICT_MODE]
2750 );
2751 throw new ImmediateResponseException($response, 1533931395);
2752 break;
2753 case 'fallback':
2754 case 'content_fallback':
2755 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2756 // value was found.
2757 foreach ($languageAspect->getFallbackChain() ?? [] as $orderValue) {
2758 if ($orderValue === '0' || $orderValue === 0 || $orderValue === '') {
2759 $languageContentId = 0;
2760 break;
2761 }
2762 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2763 $languageContentId = (int)$orderValue;
2764 break;
2765 }
2766 if ($orderValue === 'pageNotFound') {
2767 // The existing fallbacks have not been found, but instead of continuing
2768 // page rendering with default language, a "page not found" message should be shown
2769 // instead.
2770 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2771 $GLOBALS['TYPO3_REQUEST'],
2772 'Page is not available in the requested language (fallbacks did not apply).',
2773 ['code' => PageAccessFailureReasons::LANGUAGE_AND_FALLBACKS_NOT_AVAILABLE]
2774 );
2775 throw new ImmediateResponseException($response, 1533931402);
2776 }
2777 }
2778 break;
2779 case 'ignore':
2780 $languageContentId = $languageAspect->getId();
2781 break;
2782 default:
2783 // Default is that everything defaults to the default language...
2784 $languageId = ($languageContentId = 0);
2785 }
2786 } else {
2787 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2788 $this->page = $this->sys_page->getPageOverlay($this->page, $languageAspect->getId());
2789 }
2790
2791 // Define the language aspect again now
2792 $languageAspect = GeneralUtility::makeInstance(
2793 LanguageAspect::class,
2794 $languageId,
2795 $languageContentId,
2796 $languageAspect->getOverlayType(),
2797 $languageAspect->getFallbackChain()
2798 );
2799 }
2800
2801 // Set the language aspect
2802 $this->context->setAspect('language', $languageAspect);
2803
2804 // Setting sys_language_uid inside sys-page by creating a new page repository
2805 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
2806 // If default translation is not available:
2807 if ((!$languageAspect->getContentId() || !$languageAspect->getId())
2808 && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'] ?? 0)
2809 ) {
2810 $message = 'Page is not available in default language.';
2811 $this->logger->error($message);
2812 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2813 $GLOBALS['TYPO3_REQUEST'],
2814 $message,
2815 ['code' => PageAccessFailureReasons::LANGUAGE_DEFAULT_NOT_AVAILABLE]
2816 );
2817 throw new ImmediateResponseException($response, 1533931423);
2818 }
2819
2820 if ($languageAspect->getId() > 0) {
2821 $this->updateRootLinesWithTranslations();
2822 }
2823
2824 // Finding the ISO code for the currently selected language
2825 // fetched by the sys_language record when not fetching content from the default language
2826 if ($siteLanguage = $this->getCurrentSiteLanguage()) {
2827 $this->sys_language_isocode = $siteLanguage->getTwoLetterIsoCode();
2828 } elseif ($languageAspect->getContentId() > 0) {
2829 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2830 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2831 // avoid versioning overlay to be applied as it generates an SQL error
2832 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $languageAspect->getContentId(), 'language_isocode,static_lang_isocode');
2833 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2834 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2835 }
2836 // the DB value is overridden by TypoScript
2837 if (!empty($this->config['config']['sys_language_isocode'])) {
2838 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2839 }
2840 } else {
2841 // fallback to the TypoScript option when rendering with sys_language_uid=0
2842 // also: use "en" by default
2843 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2844 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2845 } else {
2846 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2847 }
2848 }
2849
2850 $_params = [];
2851 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2852 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2853 }
2854 }
2855
2856 /**
2857 * Updating content of the two rootLines IF the language key is set!
2858 */
2859 protected function updateRootLinesWithTranslations()
2860 {
2861 try {
2862 $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
2863 } catch (RootLineException $e) {
2864 $this->rootLine = [];
2865 }
2866 $this->tmpl->updateRootlineData($this->rootLine);
2867 }
2868
2869 /**
2870 * Setting locale for frontend rendering
2871 */
2872 public function settingLocale()
2873 {
2874 // Setting locale
2875 $locale = $this->config['config']['locale_all'];
2876 $siteLanguage = $this->getCurrentSiteLanguage();
2877 if ($siteLanguage) {
2878 $locale = $siteLanguage->getLocale();
2879 }
2880 if ($locale) {
2881 $availableLocales = GeneralUtility::trimExplode(',', $locale, true);
2882 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2883 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2884 // @see https://bugs.php.net/bug.php?id=53711
2885 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2886 if ($locale) {
2887 // As str_* methods are locale aware and turkish has no upper case I
2888 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2889 // @see http://bugs.php.net/bug.php?id=35050
2890 if (strpos($locale, 'tr') !== 0) {
2891 setlocale(LC_CTYPE, ...$availableLocales);
2892 }
2893 setlocale(LC_MONETARY, ...$availableLocales);
2894 setlocale(LC_TIME, ...$availableLocales);
2895 } else {
2896 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($locale) . '" not found.', 3);
2897 }
2898 }
2899 }
2900
2901 /**
2902 * Checks whether a translated shortcut page has a different shortcut
2903 * target than the original language page.
2904 * If that is the case, things get corrected to follow that alternative
2905 * shortcut
2906 * @param int $languageId
2907 */
2908 protected function checkTranslatedShortcut(int $languageId)
2909 {
2910 if (!is_null($this->originalShortcutPage)) {
2911 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $languageId);
2912 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2913 // the translation of the original shortcut page has a different shortcut target!
2914 // set the correct page and id
2915 $shortcut = $this->sys_page->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2916 $this->id = ($this->contentPid = $shortcut['uid']);
2917 $this->page = $this->sys_page->getPage($this->id);
2918 // Fix various effects on things like menus f.e.
2919 $this->fetch_the_id();
2920 $this->tmpl->rootLine = array_reverse($this->rootLine);
2921 }
2922 }
2923 }
2924
2925 /**
2926 * Handle data submission
2927 * This is done at this point, because we need the config values
2928 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2929 */
2930 public function handleDataSubmission()
2931 {
2932 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);
2933 // Hook for processing data submission to extensions
2934 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2935 $_procObj = GeneralUtility::makeInstance($className);
2936 $_procObj->checkDataSubmission($this);
2937 }
2938 }
2939
2940 /**
2941 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2942 *
2943 * @param bool $calledFromCore if set to true, no deprecation warning will be triggered
2944 * @see $activeRedirectUrlHandlers
2945 * @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.
2946 */
2947 public function initializeRedirectUrlHandlers($calledFromCore = false)
2948 {
2949 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2950 if (!$urlHandlers) {
2951 if (!$calledFromCore) {
2952 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);
2953 }
2954 return;
2955 }