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