[BUGFIX] Enable special workspace preview again
[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 * @var int
231 */
232 public $workspacePreview = 0;
233
234 /**
235 * Shows whether logins are allowed in branch
236 * @var bool
237 */
238 public $loginAllowedInBranch = true;
239
240 /**
241 * Shows specific mode (all or groups)
242 * @var string
243 */
244 public $loginAllowedInBranch_mode = '';
245
246 /**
247 * Set to backend user ID to initialize when keyword-based preview is used
248 * @var int
249 */
250 public $ADMCMD_preview_BEUSER_uid = 0;
251
252 /**
253 * Flag indication that preview is active. This is based on the login of a
254 * backend user and whether the backend user has read access to the current
255 * page. A value of 1 means ordinary preview, 2 means preview of a non-live
256 * workspace
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 = 1;
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 $this->getTimeTracker()->push('beUserLogin', '');
1073 $originalFrontendUser = null;
1074 $backendUser = $this->getBackendUser();
1075 if ($this->beUserLogin || $this->doWorkspacePreview()) {
1076 // Backend user preview features:
1077 if ($this->beUserLogin && $backendUser->adminPanel instanceof AdminPanelView) {
1078 $this->fePreview = (int)$backendUser->adminPanel->extGetFeAdminValue('preview');
1079 // If admin panel preview is enabled...
1080 if ($this->fePreview) {
1081 if ($this->fe_user->user) {
1082 $originalFrontendUser = $this->fe_user->user;
1083 }
1084 $this->showHiddenPage = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1085 $this->showHiddenRecords = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1086 // Simulate date
1087 $simTime = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1088 if ($simTime) {
1089 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1090 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1091 }
1092 // simulate user
1093 $simUserGroup = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1094 $this->simUserGroup = $simUserGroup;
1095 if ($simUserGroup) {
1096 if ($this->fe_user->user) {
1097 $this->fe_user->user[$this->fe_user->usergroup_column] = $simUserGroup;
1098 } else {
1099 $this->fe_user->user = [
1100 $this->fe_user->usergroup_column => $simUserGroup
1101 ];
1102 }
1103 }
1104 if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1105 $this->fePreview = 0;
1106 }
1107 }
1108 }
1109 if ($this->id && $this->determineIdIsHiddenPage()) {
1110 // The preview flag is set only if the current page turns out to actually be hidden!
1111 $this->fePreview = 1;
1112 $this->showHiddenPage = true;
1113 }
1114 // The preview flag will be set if a backend user is in an offline workspace
1115 if ($this->whichWorkspace() > 0 && !GeneralUtility::_GP('ADMCMD_noBeUser')) {
1116 // Will show special preview message.
1117 $this->fePreview = 2;
1118 }
1119 // If the front-end is showing a preview, caching MUST be disabled.
1120 if ($this->fePreview) {
1121 $this->disableCache();
1122 }
1123 }
1124 $this->getTimeTracker()->pull();
1125 // Now, get the id, validate access etc:
1126 $this->fetch_the_id();
1127 // Check if backend user has read access to this page. If not, recalculate the id.
1128 if ($this->beUserLogin && $this->fePreview) {
1129 if (!$backendUser->doesUserHaveAccess($this->page, 1)) {
1130 // Resetting
1131 $this->clear_preview();
1132 $this->fe_user->user = $originalFrontendUser;
1133 // Fetching the id again, now with the preview settings reset.
1134 $this->fetch_the_id();
1135 }
1136 }
1137 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1138 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1139 // Logins are not allowed:
1140 if (!$this->loginAllowedInBranch) {
1141 // Only if there is a login will we run this...
1142 if ($this->isUserOrGroupSet()) {
1143 if ($this->loginAllowedInBranch_mode === 'all') {
1144 // Clear out user and group:
1145 $this->fe_user->hideActiveLogin();
1146 $this->gr_list = '0,-1';
1147 } else {
1148 $this->gr_list = '0,-2';
1149 }
1150 // Fetching the id again, now with the preview settings reset.
1151 $this->fetch_the_id();
1152 }
1153 }
1154 // Final cleaning.
1155 // Make sure it's an integer
1156 $this->id = ($this->contentPid = (int)$this->id);
1157 // Make sure it's an integer
1158 $this->type = (int)$this->type;
1159 // Call post processing function for id determination:
1160 $_params = ['pObj' => &$this];
1161 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1162 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1163 }
1164 }
1165
1166 /**
1167 * Checks if the page is hidden in the active workspace.
1168 * If it is hidden, preview flags will be set.
1169 *
1170 * @return bool
1171 */
1172 protected function determineIdIsHiddenPage()
1173 {
1174 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1175
1176 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1177 ->getQueryBuilderForTable('pages');
1178 $queryBuilder
1179 ->getRestrictions()
1180 ->removeAll()
1181 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1182
1183 $page = $queryBuilder
1184 ->select('uid', 'hidden', 'starttime', 'endtime')
1185 ->from('pages')
1186 ->where(
1187 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1188 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1189 )
1190 ->setMaxResults(1)
1191 ->execute()
1192 ->fetch();
1193
1194 if ($this->whichWorkspace() > 0) {
1195 // Fetch overlay of page if in workspace and check if it is hidden
1196 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1197 $pageSelectObject->versioningPreview = true;
1198 $pageSelectObject->init(false);
1199 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1200 $result = $targetPage === -1 || $targetPage === -2;
1201 } else {
1202 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1203 }
1204 return $result;
1205 }
1206
1207 /**
1208 * Resolves the page id and sets up several related properties.
1209 *
1210 * If $this->id is not set at all or is not a plain integer, the method
1211 * does it's best to set the value to an integer. Resolving is based on
1212 * this options:
1213 *
1214 * - Splitting $this->id if it contains an additional type parameter.
1215 * - Getting the id for an alias in $this->id
1216 * - Finding the domain record start page
1217 * - First visible page
1218 * - Relocating the id below the domain record if outside
1219 *
1220 * The following properties may be set up or updated:
1221 *
1222 * - id
1223 * - requestedId
1224 * - type
1225 * - domainStartPage
1226 * - sys_page
1227 * - sys_page->where_groupAccess
1228 * - sys_page->where_hid_del
1229 * - loginUser
1230 * - gr_list
1231 * - no_cache
1232 * - register['SYS_LASTCHANGED']
1233 * - pageNotFound
1234 *
1235 * Via getPageAndRootlineWithDomain()
1236 *
1237 * - rootLine
1238 * - page
1239 * - MP
1240 * - originalShortcutPage
1241 * - originalMountPointPage
1242 * - pageAccessFailureHistory['direct_access']
1243 * - pageNotFound
1244 *
1245 * @todo:
1246 *
1247 * On the first impression the method does to much. This is increased by
1248 * the fact, that is is called repeated times by the method determineId.
1249 * The reasons are manifold.
1250 *
1251 * 1.) The first part, the creation of sys_page, the type and alias
1252 * resolution don't need to be repeated. They could be separated to be
1253 * called only once.
1254 *
1255 * 2.) The user group setup could be done once on a higher level.
1256 *
1257 * 3.) The workflow of the resolution could be elaborated to be less
1258 * tangled. Maybe the check of the page id to be below the domain via the
1259 * root line doesn't need to be done each time, but for the final result
1260 * only.
1261 *
1262 * 4.) The root line does not need to be directly addressed by this class.
1263 * A root line is always related to one page. The rootline could be handled
1264 * indirectly by page objects. Page objects still don't exist.
1265 *
1266 * @throws ServiceUnavailableException
1267 * @access private
1268 */
1269 public function fetch_the_id()
1270 {
1271 $timeTracker = $this->getTimeTracker();
1272 $timeTracker->push('fetch_the_id initialize/', '');
1273 // Initialize the page-select functions.
1274 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1275 $this->sys_page->versioningPreview = $this->fePreview === 2 || (int)$this->workspacePreview || (bool)GeneralUtility::_GP('ADMCMD_view');
1276 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1277 $this->sys_page->init($this->showHiddenPage);
1278 // Set the valid usergroups for FE
1279 $this->initUserGroups();
1280 // Sets sys_page where-clause
1281 $this->setSysPageWhereClause();
1282 // If $this->id is a string, it's an alias
1283 $this->checkAndSetAlias();
1284 // The id and type is set to the integer-value - just to be sure...
1285 $this->id = (int)$this->id;
1286 $this->type = (int)$this->type;
1287 $timeTracker->pull();
1288 // We find the first page belonging to the current domain
1289 $timeTracker->push('fetch_the_id domain/', '');
1290 // The page_id of the current domain
1291 $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1292 if (!$this->id) {
1293 if ($this->domainStartPage) {
1294 // If the id was not previously set, set it to the id of the domain.
1295 $this->id = $this->domainStartPage;
1296 } else {
1297 // Find the first 'visible' page in that domain
1298 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1299 if ($theFirstPage) {
1300 $this->id = $theFirstPage['uid'];
1301 } else {
1302 $message = 'No pages are found on the rootlevel!';
1303 $this->logger->alert($message);
1304 try {
1305 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
1306 $this->sendResponseAndExit($response);
1307 } catch (ServiceUnavailableException $e) {
1308 throw new ServiceUnavailableException($message, 1301648975);
1309 }
1310 }
1311 }
1312 }
1313 $timeTracker->pull();
1314 $timeTracker->push('fetch_the_id rootLine/', '');
1315 // We store the originally requested id
1316 $this->requestedId = $this->id;
1317 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1318 $timeTracker->pull();
1319 // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1320 // Functional tests in workspaces currently
1321 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1322 $pNotFoundMsg = [
1323 1 => 'ID was not an accessible page',
1324 2 => 'Subsection was found and not accessible',
1325 3 => 'ID was outside the domain',
1326 4 => 'The requested page alias does not exist'
1327 ];
1328 $message = $pNotFoundMsg[$this->pageNotFound];
1329 if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1330 $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($message, $this->getPageAccessFailureReasons());
1331 } else {
1332 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1333 }
1334 $this->sendResponseAndExit($response);
1335 }
1336 // Init SYS_LASTCHANGED
1337 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1338 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1339 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1340 }
1341 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1342 $parameters = ['parentObject' => $this];
1343 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1344 }
1345 }
1346
1347 /**
1348 * Loads the page and root line records based on $this->id
1349 *
1350 * A final page and the matching root line are determined and loaded by
1351 * the algorithm defined by this method.
1352 *
1353 * First it loads the initial page from the page repository for $this->id.
1354 * If that can't be loaded directly, it gets the root line for $this->id.
1355 * It walks up the root line towards the root page until the page
1356 * repository can deliver a page record. (The loading restrictions of
1357 * the root line records are more liberal than that of the page record.)
1358 *
1359 * Now the page type is evaluated and handled if necessary. If the page is
1360 * a short cut, it is replaced by the target page. If the page is a mount
1361 * point in overlay mode, the page is replaced by the mounted page.
1362 *
1363 * After this potential replacements are done, the root line is loaded
1364 * (again) for this page record. It walks up the root line up to
1365 * the first viewable record.
1366 *
1367 * (While upon the first accessibility check of the root line it was done
1368 * by loading page by page from the page repository, this time the method
1369 * checkRootlineForIncludeSection() is used to find the most distant
1370 * accessible page within the root line.)
1371 *
1372 * Having found the final page id, the page record and the root line are
1373 * loaded for last time by this method.
1374 *
1375 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1376 * or root lines.
1377 *
1378 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1379 * instead of throwing an exception it's handled by a page unavailable
1380 * handler.
1381 *
1382 * May set or update this properties:
1383 *
1384 * @see TypoScriptFrontendController::$id
1385 * @see TypoScriptFrontendController::$MP
1386 * @see TypoScriptFrontendController::$page
1387 * @see TypoScriptFrontendController::$pageNotFound
1388 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1389 * @see TypoScriptFrontendController::$originalMountPointPage
1390 * @see TypoScriptFrontendController::$originalShortcutPage
1391 *
1392 * @throws ServiceUnavailableException
1393 * @throws PageNotFoundException
1394 * @access private
1395 */
1396 public function getPageAndRootline()
1397 {
1398 $this->resolveTranslatedPageId();
1399 if (empty($this->page)) {
1400 // If no page, we try to find the page before in the rootLine.
1401 // Page is 'not found' in case the id itself was not an accessible page. code 1
1402 $this->pageNotFound = 1;
1403 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1404 if (!empty($this->rootLine)) {
1405 $c = count($this->rootLine) - 1;
1406 while ($c > 0) {
1407 // Add to page access failure history:
1408 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1409 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1410 $c--;
1411 $this->id = $this->rootLine[$c]['uid'];
1412 $this->page = $this->sys_page->getPage($this->id);
1413 if (!empty($this->page)) {
1414 break;
1415 }
1416 }
1417 }
1418 // If still no page...
1419 if (empty($this->page)) {
1420 $message = 'The requested page does not exist!';
1421 $this->logger->error($message);
1422 try {
1423 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1424 $this->sendResponseAndExit($response);
1425 } catch (PageNotFoundException $e) {
1426 throw new PageNotFoundException($message, 1301648780);
1427 }
1428 }
1429 }
1430 // Spacer is not accessible in frontend
1431 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1432 $message = 'The requested page does not exist!';
1433 $this->logger->error($message);
1434 try {
1435 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1436 $this->sendResponseAndExit($response);
1437 } catch (PageNotFoundException $e) {
1438 throw new PageNotFoundException($message, 1301648781);
1439 }
1440 }
1441 // Is the ID a link to another page??
1442 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1443 // 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.
1444 $this->MP = '';
1445 // saving the page so that we can check later - when we know
1446 // about languages - whether we took the correct shortcut or
1447 // whether a translation of the page overwrites the shortcut
1448 // target and we need to follow the new target
1449 $this->originalShortcutPage = $this->page;
1450 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1451 $this->id = $this->page['uid'];
1452 }
1453 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1454 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1455 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1456 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1457 $this->originalMountPointPage = $this->page;
1458 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1459 if (empty($this->page)) {
1460 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1461 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1462 throw new PageNotFoundException($message, 1402043263);
1463 }
1464 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1465 $this->id = $this->page['uid'];
1466 }
1467 // Gets the rootLine
1468 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1469 // If not rootline we're off...
1470 if (empty($this->rootLine)) {
1471 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1472 $this->logger->error($message);
1473 try {
1474 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1475 $this->sendResponseAndExit($response);
1476 } catch (ServiceUnavailableException $e) {
1477 throw new ServiceUnavailableException($message, 1301648167);
1478 }
1479 }
1480 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1481 if ($this->checkRootlineForIncludeSection()) {
1482 if (empty($this->rootLine)) {
1483 $message = 'The requested page was not accessible!';
1484 try {
1485 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1486 $this->sendResponseAndExit($response);
1487 } catch (ServiceUnavailableException $e) {
1488 $this->logger->warning($message);
1489 throw new ServiceUnavailableException($message, 1301648234);
1490 }
1491 } else {
1492 $el = reset($this->rootLine);
1493 $this->id = $el['uid'];
1494 $this->page = $this->sys_page->getPage($this->id);
1495 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1496 }
1497 }
1498 }
1499
1500 /**
1501 * If $this->id contains a translated page record, this needs to be resolved to the default language
1502 * in order for all rootline functionality and access restrictions to be in place further on.
1503 *
1504 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1505 */
1506 protected function resolveTranslatedPageId()
1507 {
1508 $this->page = $this->sys_page->getPage($this->id);
1509 // Accessed a default language page record, nothing to resolve
1510 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1511 return;
1512 }
1513 $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1514 $this->sys_language_content = $this->sys_language_uid;
1515 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1516 $this->id = $this->page['uid'];
1517 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1518 $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1519 }
1520
1521 /**
1522 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1523 *
1524 * @param int $SC The value of the "shortcut" field from the pages record
1525 * @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
1526 * @param int $thisUid The current page UID of the page which is a shortcut
1527 * @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...)
1528 * @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.
1529 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1530 * @throws \RuntimeException
1531 * @throws PageNotFoundException
1532 * @return mixed Returns the page record of the page that the shortcut pointed to.
1533 * @access private
1534 * @see getPageAndRootline()
1535 */
1536 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1537 {
1538 $idArray = GeneralUtility::intExplode(',', $SC);
1539 // Find $page record depending on shortcut mode:
1540 switch ($mode) {
1541 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1542
1543 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1544 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1545 $pO = 0;
1546 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1547 $randval = (int)rand(0, count($pageArray) - 1);
1548 $pO = $randval;
1549 }
1550 $c = 0;
1551 $page = [];
1552 foreach ($pageArray as $pV) {
1553 if ($c === $pO) {
1554 $page = $pV;
1555 break;
1556 }
1557 $c++;
1558 }
1559 if (empty($page)) {
1560 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1561 throw new PageNotFoundException($message, 1301648328);
1562 }
1563 break;
1564 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1565 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1566 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1567 if (empty($page)) {
1568 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1569 throw new PageNotFoundException($message, 1301648358);
1570 }
1571 break;
1572 default:
1573 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1574 if (empty($page)) {
1575 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1576 throw new PageNotFoundException($message, 1301648404);
1577 }
1578 }
1579 // Check if short cut page was a shortcut itself, if so look up recursively:
1580 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1581 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1582 $pageLog[] = $page['uid'];
1583 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1584 } else {
1585 $pageLog[] = $page['uid'];
1586 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1587 $this->logger->error($message);
1588 throw new \RuntimeException($message, 1294587212);
1589 }
1590 }
1591 // Return resulting page:
1592 return $page;
1593 }
1594
1595 /**
1596 * Checks if visibility of the page is blocked upwards in the root line.
1597 *
1598 * If any page in the root line is blocking visibility, true is returend.
1599 *
1600 * All pages from the blocking page downwards are removed from the root
1601 * line, so that the remaning pages can be used to relocate the page up
1602 * to lowest visible page.
1603 *
1604 * The blocking feature of a page must be turned on by setting the page
1605 * record field 'extendToSubpages' to 1.
1606 *
1607 * The following fields are evaluated then:
1608 *
1609 * hidden, starttime, endtime, fe_group
1610 *
1611 * @todo Find a better name, i.e. checkVisibilityByRootLine
1612 * @todo Invert boolean return value. Return true if visible.
1613 *
1614 * @return bool
1615 * @access private
1616 */
1617 public function checkRootlineForIncludeSection(): bool
1618 {
1619 $c = count($this->rootLine);
1620 $removeTheRestFlag = false;
1621 for ($a = 0; $a < $c; $a++) {
1622 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1623 // Add to page access failure history:
1624 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1625 $removeTheRestFlag = true;
1626 }
1627
1628 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1629 // If there is a backend user logged in, check if he has read access to the page:
1630 if ($this->beUserLogin) {
1631 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1632 ->getQueryBuilderForTable('pages');
1633
1634 $queryBuilder
1635 ->getRestrictions()
1636 ->removeAll();
1637
1638 $row = $queryBuilder
1639 ->select('uid')
1640 ->from('pages')
1641 ->where(
1642 $queryBuilder->expr()->eq(
1643 'uid',
1644 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1645 ),
1646 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1647 )
1648 ->execute()
1649 ->fetch();
1650
1651 // versionOL()?
1652 if (!$row) {
1653 // 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...
1654 $removeTheRestFlag = true;
1655 }
1656 } else {
1657 // Don't go here, if there is no backend user logged in.
1658 $removeTheRestFlag = true;
1659 }
1660 }
1661 if ($removeTheRestFlag) {
1662 // Page is 'not found' in case a subsection was found and not accessible, code 2
1663 $this->pageNotFound = 2;
1664 unset($this->rootLine[$a]);
1665 break;
1666 }
1667 }
1668 return $removeTheRestFlag;
1669 }
1670
1671 /**
1672 * Checks page record for enableFields
1673 * Returns TRUE if enableFields does not disable the page record.
1674 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1675 *
1676 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1677 * @param bool $bypassGroupCheck Bypass group-check
1678 * @return bool TRUE, if record is viewable.
1679 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1680 */
1681 public function checkEnableFields($row, $bypassGroupCheck = false)
1682 {
1683 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1684 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1685 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1686 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1687 if ($return === false) {
1688 return false;
1689 }
1690 }
1691 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1692 return true;
1693 }
1694 return false;
1695 }
1696
1697 /**
1698 * Check group access against a page record
1699 *
1700 * @param array $row The page record to evaluate (needs field: fe_group)
1701 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1702 * @return bool TRUE, if group access is granted.
1703 * @access private
1704 */
1705 public function checkPageGroupAccess($row, $groupList = null)
1706 {
1707 if (is_null($groupList)) {
1708 $groupList = $this->gr_list;
1709 }
1710 if (!is_array($groupList)) {
1711 $groupList = explode(',', $groupList);
1712 }
1713 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1714 return count(array_intersect($groupList, $pageGroupList)) > 0;
1715 }
1716
1717 /**
1718 * Checks if the current page of the root line is visible.
1719 *
1720 * If the field extendToSubpages is 0, access is granted,
1721 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1722 *
1723 * @todo Find a better name, i.e. isVisibleRecord()
1724 *
1725 * @param array $row The page record
1726 * @return bool true if visible
1727 * @access private
1728 * @see checkEnableFields()
1729 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1730 * @see checkRootlineForIncludeSection()
1731 */
1732 public function checkPagerecordForIncludeSection(array $row): bool
1733 {
1734 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1735 }
1736
1737 /**
1738 * 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!)
1739 *
1740 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1741 */
1742 public function checkIfLoginAllowedInBranch()
1743 {
1744 // Initialize:
1745 $c = count($this->rootLine);
1746 $loginAllowed = true;
1747 // Traverse root line from root and outwards:
1748 for ($a = 0; $a < $c; $a++) {
1749 // If a value is set for login state:
1750 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1751 // Determine state from value:
1752 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1753 $loginAllowed = false;
1754 $this->loginAllowedInBranch_mode = 'all';
1755 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1756 $loginAllowed = false;
1757 $this->loginAllowedInBranch_mode = 'groups';
1758 } else {
1759 $loginAllowed = true;
1760 }
1761 }
1762 }
1763 return $loginAllowed;
1764 }
1765
1766 /**
1767 * 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
1768 *
1769 * @return array Summary of why page access was not allowed.
1770 */
1771 public function getPageAccessFailureReasons()
1772 {
1773 $output = [];
1774 $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'] : []);
1775 if (!empty($combinedRecords)) {
1776 foreach ($combinedRecords as $k => $pagerec) {
1777 // 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
1778 // 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!
1779 if (!$k || $pagerec['extendToSubpages']) {
1780 if ($pagerec['hidden']) {
1781 $output['hidden'][$pagerec['uid']] = true;
1782 }
1783 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1784 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1785 }
1786 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1787 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1788 }
1789 if (!$this->checkPageGroupAccess($pagerec)) {
1790 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1791 }
1792 }
1793 }
1794 }
1795 return $output;
1796 }
1797
1798 /**
1799 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1800 * If not inside domain, then default to first page in domain.
1801 *
1802 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1803 * @access private
1804 */
1805 public function getPageAndRootlineWithDomain($domainStartPage)
1806 {
1807 $this->getPageAndRootline();
1808 // 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.
1809 if ($domainStartPage && is_array($this->rootLine)) {
1810 $idFound = 0;
1811 foreach ($this->rootLine as $key => $val) {
1812 if ($val['uid'] == $domainStartPage) {
1813 $idFound = 1;
1814 break;
1815 }
1816 }
1817 if (!$idFound) {
1818 // Page is 'not found' in case the id was outside the domain, code 3
1819 $this->pageNotFound = 3;
1820 $this->id = $domainStartPage;
1821 // re-get the page and rootline if the id was not found.
1822 $this->getPageAndRootline();
1823 }
1824 }
1825 }
1826
1827 /**
1828 * Sets sys_page where-clause
1829 *
1830 * @access private
1831 */
1832 public function setSysPageWhereClause()
1833 {
1834 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1835 ->getConnectionForTable('pages')
1836 ->getExpressionBuilder();
1837 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1838 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1839 $expressionBuilder->lt('pages.doktype', 200)
1840 );
1841 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1842 }
1843
1844 /**
1845 * Looking up a domain record based on HTTP_HOST
1846 *
1847 * @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.
1848 * @return int Returns the page id of the page where the domain record was found.
1849 * @access private
1850 */
1851 public function findDomainRecord($recursive = false)
1852 {
1853 if ($recursive) {
1854 $pageUid = 0;
1855 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1856 while (count($host)) {
1857 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1858 if ($pageUid) {
1859 return $pageUid;
1860 }
1861 array_shift($host);
1862 }
1863 return $pageUid;
1864 }
1865 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1866 }
1867
1868 /**
1869 * Page unavailable handler for use in frontend plugins from extensions.
1870 *
1871 * @param string $reason Reason text
1872 * @param string $header HTTP header to send
1873 * @deprecated
1874 */
1875 public function pageUnavailableAndExit($reason = '', $header = '')
1876 {
1877 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1878 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1879 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1880 die;
1881 }
1882
1883 /**
1884 * Page-not-found handler for use in frontend plugins from extensions.
1885 *
1886 * @param string $reason Reason text
1887 * @param string $header HTTP header to send
1888 * @deprecated
1889 */
1890 public function pageNotFoundAndExit($reason = '', $header = '')
1891 {
1892 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1893 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1894 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1895 die;
1896 }
1897
1898 /**
1899 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1900 * and devIPMask must not match the current visitor's IP address.
1901 *
1902 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1903 * @deprecated
1904 */
1905 public function checkPageUnavailableHandler()
1906 {
1907 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1908 if (
1909 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1910 && !GeneralUtility::cmpIP(
1911 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1912 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1913 )
1914 ) {
1915 $checkPageUnavailableHandler = true;
1916 } else {
1917 $checkPageUnavailableHandler = false;
1918 }
1919 return $checkPageUnavailableHandler;
1920 }
1921
1922 /**
1923 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1924 *
1925 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1926 * @param string $header If set, this is passed directly to the PHP function, header()
1927 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1928 * @deprecated
1929 */
1930 public function pageUnavailableHandler($code, $header, $reason)
1931 {
1932 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1933 $this->pageErrorHandler($code, $header, $reason);
1934 }
1935
1936 /**
1937 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1938 *
1939 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1940 * @param string $header If set, this is passed directly to the PHP function, header()
1941 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1942 * @deprecated
1943 */
1944 public function pageNotFoundHandler($code, $header = '', $reason = '')
1945 {
1946 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1947 $this->pageErrorHandler($code, $header, $reason);
1948 }
1949
1950 /**
1951 * Generic error page handler.
1952 * Exits.
1953 *
1954 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1955 * @param string $header If set, this is passed directly to the PHP function, header()
1956 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1957 * @throws \RuntimeException
1958 * @deprecated
1959 */
1960 public function pageErrorHandler($code, $header = '', $reason = '')
1961 {
1962 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1963 // Issue header in any case:
1964 if ($header) {
1965 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1966 foreach ($headerArr as $header) {
1967 header($header);
1968 }
1969 }
1970 // Create response:
1971 // Simply boolean; Just shows TYPO3 error page with reason:
1972 if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1973 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1974 'Page Not Found',
1975 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1976 );
1977 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1978 $funcRef = trim(substr($code, 14));
1979 $params = [
1980 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1981 'reasonText' => $reason,
1982 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1983 ];
1984 try {
1985 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1986 } catch (\Exception $e) {
1987 throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
1988 }
1989 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
1990 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
1991 if (@is_file($readFile)) {
1992 echo str_replace(
1993 [
1994 '###CURRENT_URL###',
1995 '###REASON###'
1996 ],
1997 [
1998 GeneralUtility::getIndpEnv('REQUEST_URI'),
1999 htmlspecialchars($reason)
2000 ],
2001 file_get_contents($readFile)
2002 );
2003 } else {
2004 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2005 }
2006 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
2007 HttpUtility::redirect(substr($code, 9));
2008 } elseif ($code !== '') {
2009 // Check if URL is relative
2010 $url_parts = parse_url($code);
2011 // parse_url could return an array without the key "host", the empty check works better than strict check
2012 if (empty($url_parts['host'])) {
2013 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
2014 if ($code[0] === '/') {
2015 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2016 } else {
2017 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2018 }
2019 $checkBaseTag = false;
2020 } else {
2021 $checkBaseTag = true;
2022 }
2023 // Check recursion
2024 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2025 if ($reason == '') {
2026 $reason = 'Page cannot be found.';
2027 }
2028 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2029 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2030 }
2031 // Prepare headers
2032 $headerArr = [
2033 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2034 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2035 ];
2036 $report = [];
2037 $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2038 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2039 throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2040 }
2041 // Header and content are separated by an empty line
2042 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2043 $content .= CRLF;
2044 if (false === $res) {
2045 // Last chance -- redirect
2046 HttpUtility::redirect($code);
2047 } else {
2048 // Forward these response headers to the client
2049 $forwardHeaders = [
2050 'Content-Type:'
2051 ];
2052 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2053 foreach ($headerArr as $header) {
2054 foreach ($forwardHeaders as $h) {
2055 if (preg_match('/^' . $h . '/', $header)) {
2056 header($header);
2057 }
2058 }
2059 }
2060 // Put <base> if necessary
2061 if ($checkBaseTag) {
2062 // If content already has <base> tag, we do not need to do anything
2063 if (false === stristr($content, '<base ')) {
2064 // Generate href for base tag
2065 $base = $url_parts['scheme'] . '://';
2066 if ($url_parts['user'] != '') {
2067 $base .= $url_parts['user'];
2068 if ($url_parts['pass'] != '') {
2069 $base .= ':' . $url_parts['pass'];
2070 }
2071 $base .= '@';
2072 }
2073 $base .= $url_parts['host'];
2074 // Add path portion skipping possible file name
2075 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2076 // Put it into content (generate also <head> if necessary)
2077 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2078 if (stristr($content, '<head>')) {
2079 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2080 } else {
2081 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2082 }
2083 }
2084 }
2085 // Output the content
2086 echo $content;
2087 }
2088 } else {
2089 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2090 'Page Not Found',
2091 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2092 );
2093 }
2094 die;
2095 }
2096
2097 /**
2098 * Fetches the integer page id for a page alias.
2099 * 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
2100 *
2101 * @access private
2102 */
2103 public function checkAndSetAlias()
2104 {
2105 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2106 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2107 if ($aid) {
2108 $this->id = $aid;
2109 } else {
2110 $this->pageNotFound = 4;
2111 }
2112 }
2113 }
2114
2115 /**
2116 * Merging values into the global $_GET
2117 *
2118 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2119 */
2120 public function mergingWithGetVars($GET_VARS)
2121 {
2122 if (is_array($GET_VARS)) {
2123 // Getting $_GET var, unescaped.
2124 $realGet = GeneralUtility::_GET();
2125 if (!is_array($realGet)) {
2126 $realGet = [];
2127 }
2128 // Merge new values on top:
2129 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2130 // Write values back to $_GET:
2131 GeneralUtility::_GETset($realGet);
2132 // Setting these specifically (like in the init-function):
2133 if (isset($GET_VARS['type'])) {
2134 $this->type = (int)$GET_VARS['type'];
2135 }
2136 if (isset($GET_VARS['cHash'])) {
2137 $this->cHash = $GET_VARS['cHash'];
2138 }
2139 if (isset($GET_VARS['MP'])) {
2140 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2141 }
2142 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2143 $this->set_no_cache('no_cache is requested via GET parameter');
2144 }
2145 }
2146 }
2147
2148 /********************************************
2149 *
2150 * Template and caching related functions.
2151 *
2152 *******************************************/
2153 /**
2154 * Calculates a hash string based on additional parameters in the url.
2155 *
2156 * Calculated hash is stored in $this->cHash_array.
2157 * This is used to cache pages with more parameters than just id and type.
2158 *
2159 * @see reqCHash()
2160 */
2161 public function makeCacheHash()
2162 {
2163 // No need to test anything if caching was already disabled.
2164 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2165 return;
2166 }
2167 $GET = GeneralUtility::_GET();
2168 if ($this->cHash && is_array($GET)) {
2169 // Make sure we use the page uid and not the page alias
2170 $GET['id'] = $this->id;
2171 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2172 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2173 if (!hash_equals($cHash_calc, $this->cHash)) {
2174 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2175 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash comparison failed)');
2176 $this->sendResponseAndExit($response);
2177 } else {
2178 $this->disableCache();
2179 $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);
2180 }
2181 }
2182 } elseif (is_array($GET)) {
2183 // No cHash is set, check if that is correct
2184 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2185 $this->reqCHash();
2186 }
2187 }
2188 }
2189
2190 /**
2191 * Will disable caching if the cHash value was not set.
2192 * 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)
2193 *
2194 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2195 */
2196 public function reqCHash()
2197 {
2198 if (!$this->cHash) {
2199 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2200 if ($this->tempContent) {
2201 $this->clearPageCacheContent();
2202 }
2203 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash empty)');
2204 $this->sendResponseAndExit($response);
2205 } else {
2206 $this->disableCache();
2207 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2208 }
2209 }
2210 }
2211
2212 /**
2213 * Initialize the TypoScript template parser
2214 */
2215 public function initTemplate()
2216 {
2217 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2218 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2219 $this->tmpl->init();
2220 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2221 }
2222
2223 /**
2224 * See if page is in cache and get it if so
2225 * Stores the page content in $this->content if something is found.
2226 *
2227 * @throws \InvalidArgumentException
2228 * @throws \RuntimeException
2229 */
2230 public function getFromCache()
2231 {
2232 // clearing the content-variable, which will hold the pagecontent
2233 $this->content = '';
2234 // Unsetting the lowlevel config
2235 $this->config = [];
2236 $this->cacheContentFlag = false;
2237
2238 if ($this->no_cache) {
2239 return;
2240 }
2241
2242 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2243 if (!is_array($pageSectionCacheContent)) {
2244 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2245 // We use the Registry to store this lock centrally,
2246 // but we protect the access again with a global exclusive lock to avoid race conditions
2247
2248 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2249 //
2250 // from this point on we're the only one working on that page ($key)
2251 //
2252
2253 // query the cache again to see if the page data are there meanwhile
2254 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2255 if (is_array($pageSectionCacheContent)) {
2256 // we have the content, nice that some other process did the work for us already
2257 $this->releaseLock('pagesection');
2258 }
2259 // We keep the lock set, because we are the ones generating the page now
2260 // and filling the cache.
2261 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2262 }
2263
2264 if (is_array($pageSectionCacheContent)) {
2265 // 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.
2266 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2267 // 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.
2268 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2269 ksort($pageSectionCacheContent);
2270 $this->all = $pageSectionCacheContent;
2271 }
2272 unset($pageSectionCacheContent);
2273
2274 // Look for page in cache only if a shift-reload is not sent to the server.
2275 $lockHash = $this->getLockHash();
2276 if (!$this->headerNoCache()) {
2277 if ($this->all) {
2278 // we got page section information
2279 $this->newHash = $this->getHash();
2280 $this->getTimeTracker()->push('Cache Row', '');
2281 $row = $this->getFromCache_queryRow();
2282 if (!is_array($row)) {
2283 // nothing in the cache, we acquire an exclusive lock now
2284
2285 $this->acquireLock('pages', $lockHash);
2286 //
2287 // from this point on we're the only one working on that page ($lockHash)
2288 //
2289
2290 // query the cache again to see if the data are there meanwhile
2291 $row = $this->getFromCache_queryRow();
2292 if (is_array($row)) {
2293 // we have the content, nice that some other process did the work for us
2294 $this->releaseLock('pages');
2295 }
2296 // We keep the lock set, because we are the ones generating the page now
2297 // and filling the cache.
2298 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2299 }
2300 if (is_array($row)) {
2301 // we have data from cache
2302
2303 // Call hook when a page is retrieved from cache:
2304 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2305 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2306 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2307 }
2308 // Fetches the lowlevel config stored with the cached data
2309 $this->config = $row['cache_data'];
2310 // Getting the content
2311 $this->content = $row['content'];
2312 // Flag for temp content
2313 $this->tempContent = $row['temp_content'];
2314 // Setting flag, so we know, that some cached content has been loaded
2315 $this->cacheContentFlag = true;
2316 $this->cacheExpires = $row['expires'];
2317
2318 // Restore page title information, this is needed to generate the page title for
2319 // partially cached pages.
2320 $this->page['title'] = $row['pageTitleInfo']['title'];
2321 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2322 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2323
2324 if (isset($this->config['config']['debug'])) {
2325 $debugCacheTime = (bool)$this->config['config']['debug'];
2326 } else {
2327 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2328 }
2329 if ($debugCacheTime) {
2330 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2331 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2332 $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2333 }
2334 }
2335 $this->getTimeTracker()->pull();
2336
2337 return;
2338 }
2339 }
2340 // the user forced rebuilding the page cache or there was no pagesection information
2341 // get a lock for the page content so other processes will not interrupt the regeneration
2342 $this->acquireLock('pages', $lockHash);
2343 }
2344
2345 /**
2346 * Returning the cached version of page with hash = newHash
2347 *
2348 * @return array Cached row, if any. Otherwise void.
2349 */
2350 public function getFromCache_queryRow()
2351 {
2352 $this->getTimeTracker()->push('Cache Query', '');
2353 $row = $this->pageCache->get($this->newHash);
2354 $this->getTimeTracker()->pull();
2355 return $row;
2356 }
2357
2358 /**
2359 * Detecting if shift-reload has been clicked
2360 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2361 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2362 *
2363 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2364 */
2365 public function headerNoCache()
2366 {
2367 $disableAcquireCacheData = false;
2368 if ($this->beUserLogin) {
2369 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2370 $disableAcquireCacheData = true;
2371 }
2372 }
2373 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2374 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2375 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2376 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2377 }
2378 return $disableAcquireCacheData;
2379 }
2380
2381 /**
2382 * Calculates the cache-hash
2383 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2384 * Used to get and later store the cached data.
2385 *
2386 * @return string MD5 hash of serialized hash base from createHashBase()
2387 * @access private
2388 * @see getFromCache(), getLockHash()
2389 */
2390 public function getHash()
2391 {
2392 return md5($this->createHashBase(false));
2393 }
2394
2395 /**
2396 * Calculates the lock-hash
2397 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2398 *
2399 * @return string MD5 hash
2400 * @access private
2401 * @see getFromCache(), getHash()
2402 */
2403 public function getLockHash()
2404 {
2405 $lockHash = $this->createHashBase(true);
2406 return md5($lockHash);
2407 }
2408
2409 /**
2410 * Calculates the cache-hash (or the lock-hash)
2411 * This hash is unique to the template,
2412 * the variables ->id, ->type, ->gr_list (list of groups),
2413 * ->MP (Mount Points) and cHash array
2414 * Used to get and later store the cached data.
2415 *
2416 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2417 * @return string the serialized hash base
2418 */
2419 protected function createHashBase($createLockHashBase = false)
2420 {
2421 $hashParameters = [
2422 'id' => (int)$this->id,
2423 'type' => (int)$this->type,
2424 'gr_list' => (string)$this->gr_list,
2425 'MP' => (string)$this->MP,
2426 'cHash' => $this->cHash_array,
2427 'domainStartPage' => $this->domainStartPage
2428 ];
2429 // Include the template information if we shouldn't create a lock hash
2430 if (!$createLockHashBase) {
2431 $hashParameters['all'] = $this->all;
2432 }
2433 // Call hook to influence the hash calculation
2434 $_params = [
2435 'hashParameters' => &$hashParameters,
2436 'createLockHashBase' => $createLockHashBase
2437 ];
2438 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2439 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2440 }
2441 return serialize($hashParameters);
2442 }
2443
2444 /**
2445 * Checks if config-array exists already but if not, gets it
2446 *
2447 * @throws ServiceUnavailableException
2448 */
2449 public function getConfigArray()
2450 {
2451 // 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
2452 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2453 $timeTracker = $this->getTimeTracker();
2454 $timeTracker->push('Parse template', '');
2455 // Force parsing, if set?:
2456 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2457 // Start parsing the TS template. Might return cached version.
2458 $this->tmpl->start($this->rootLine);
2459 $timeTracker->pull();
2460 if ($this->tmpl->loaded) {
2461 $timeTracker->push('Setting the config-array', '');
2462 // toplevel - objArrayName
2463 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2464 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2465 if (!is_array($this->pSetup)) {
2466 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2467 $this->logger->alert($message);
2468 try {
2469 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2470 $this->sendResponseAndExit($response);
2471 } catch (ServiceUnavailableException $e) {
2472 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2473 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2474 }
2475 } else {
2476 if (!isset($this->config['config'])) {
2477 $this->config['config'] = [];
2478 }
2479 // Filling the config-array, first with the main "config." part
2480 if (is_array($this->tmpl->setup['config.'])) {
2481 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2482 $this->config['config'] = $this->tmpl->setup['config.'];
2483 }
2484 // override it with the page/type-specific "config."
2485 if (is_array($this->pSetup['config.'])) {
2486 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2487 }
2488 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2489 if ($this->config['config']['typolinkCheckRootline']) {
2490 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2491 }
2492 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2493 if (!isset($this->config['config']['removeDefaultJS'])) {
2494 $this->config['config']['removeDefaultJS'] = 'external';
2495 }
2496 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2497 $this->config['config']['inlineStyle2TempFile'] = 1;
2498 }
2499
2500 if (!isset($this->config['config']['compressJs'])) {
2501 $this->config['config']['compressJs'] = 0;
2502 }
2503 // Processing for the config_array:
2504 $this->config['rootLine'] = $this->tmpl->rootLine;
2505 // Class for render Header and Footer parts
2506 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2507 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2508 if ($file) {
2509 $this->pageRenderer->setTemplateFile($file);
2510 }
2511 }
2512 }
2513 $timeTracker->pull();
2514 } else {
2515 $message = 'No TypoScript template found!';
2516 $this->logger->alert($message);
2517 try {
2518 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2519 $this->sendResponseAndExit($response);
2520 } catch (ServiceUnavailableException $e) {
2521 throw new ServiceUnavailableException($message, 1294587218);
2522 }
2523 }
2524 }
2525
2526 // No cache
2527 // Set $this->no_cache TRUE if the config.no_cache value is set!
2528 if ($this->config['config']['no_cache']) {
2529 $this->set_no_cache('config.no_cache is set');
2530 }
2531 // Merge GET with defaultGetVars
2532 if (!empty($this->config['config']['defaultGetVars.'])) {
2533 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2534 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2535 GeneralUtility::_GETset($modifiedGetVars);
2536 }
2537 // Hook for postProcessing the configuration array
2538 $params = ['config' => &$this->config['config']];
2539 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2540 GeneralUtility::callUserFunction($funcRef, $params, $this);
2541 }
2542 }
2543
2544 /********************************************
2545 *
2546 * Further initialization and data processing
2547 *
2548 *******************************************/
2549
2550 /**
2551 * Setting the language key that will be used by the current page.
2552 * 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.
2553 *
2554 * @access private
2555 */
2556 public function settingLanguage()
2557 {
2558 $_params = [];
2559 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2560 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2561 }
2562
2563 // Initialize charset settings etc.
2564 $languageKey = $this->config['config']['language'] ?? 'default';
2565 $this->lang = $languageKey;
2566 $this->setOutputLanguage($languageKey);
2567
2568 // Rendering charset of HTML page.
2569 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2570 $this->metaCharset = $this->config['config']['metaCharset'];
2571 }
2572
2573 // Get values from TypoScript, if not set before
2574 if ($this->sys_language_uid === 0) {
2575 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2576 }
2577 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2578 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2579 // If sys_language_uid is set to another language than default:
2580 if ($this->sys_language_uid > 0) {
2581 // check whether a shortcut is overwritten by a translated page
2582 // we can only do this now, as this is the place where we get
2583 // to know about translations
2584 $this->checkTranslatedShortcut();
2585 // Request the overlay record for the sys_language_uid:
2586 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2587 if (empty($olRec)) {
2588 // If no OL record exists and a foreign language is asked for...
2589 if ($this->sys_language_uid) {
2590 // If requested translation is not available:
2591 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2592 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language.');
2593 $this->sendResponseAndExit($response);
2594 } else {
2595 switch ((string)$this->sys_language_mode) {
2596 case 'strict':
2597 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (strict).');
2598 $this->sendResponseAndExit($response);
2599 break;
2600 case 'content_fallback':
2601 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2602 // value was found.
2603 $fallBackOrder = GeneralUtility::trimExplode(',', $sys_language_content);
2604 foreach ($fallBackOrder as $orderValue) {
2605 if ($orderValue === '0' || $orderValue === '') {
2606 $this->sys_language_content = 0;
2607 break;
2608 }
2609 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2610 $this->sys_language_content = (int)$orderValue;
2611 break;
2612 }
2613 if ($orderValue === 'pageNotFound') {
2614 // The existing fallbacks have not been found, but instead of continuing
2615 // page rendering with default language, a "page not found" message should be shown
2616 // instead.
2617 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (fallbacks did not apply).');
2618 $this->sendResponseAndExit($response);
2619 }
2620 }
2621 break;
2622 case 'ignore':
2623 $this->sys_language_content = $this->sys_language_uid;
2624 break;
2625 default:
2626 // Default is that everything defaults to the default language...
2627 $this->sys_language_uid = ($this->sys_language_content = 0);
2628 }
2629 }
2630 }
2631 } else {
2632 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2633 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2634 }
2635 }
2636 // Setting sys_language_uid inside sys-page:
2637 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2638 // If default translation is not available:
2639 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2640 $message = 'Page is not available in default language.';
2641 $this->logger->error($message);
2642 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message);
2643 $this->sendResponseAndExit($response);
2644 }
2645 $this->updateRootLinesWithTranslations();
2646
2647 // Finding the ISO code for the currently selected language
2648 // fetched by the sys_language record when not fetching content from the default language
2649 if ($this->sys_language_content > 0) {
2650 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2651 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2652 // avoid versioning overlay to be applied as it generates an SQL error
2653 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2654 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2655 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2656 }
2657 // the DB value is overridden by TypoScript
2658 if (!empty($this->config['config']['sys_language_isocode'])) {
2659 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2660 }
2661 } else {
2662 // fallback to the TypoScript option when rendering with sys_language_uid=0
2663 // also: use "en" by default
2664 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2665 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2666 } else {
2667 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2668 }
2669 }
2670
2671 $_params = [];
2672 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2673 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2674 }
2675 }
2676
2677 /**
2678 * Updating content of the two rootLines IF the language key is set!
2679 */
2680 protected function updateRootLinesWithTranslations()
2681 {
2682 if ($this->sys_language_uid) {
2683 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2684 $this->tmpl->updateRootlineData($this->rootLine);
2685 }
2686 }
2687
2688 /**
2689 * Setting locale for frontend rendering
2690 */
2691 public function settingLocale()
2692 {
2693 // Setting locale
2694 if ($this->config['config']['locale_all']) {
2695 $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2696 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2697 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2698 // @see https://bugs.php.net/bug.php?id=53711
2699 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2700 if ($locale) {
2701 // As str_* methods are locale aware and turkish has no upper case I
2702 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2703 // @see http://bugs.php.net/bug.php?id=35050
2704 if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2705 setlocale(LC_CTYPE, ...$availableLocales);
2706 }
2707 setlocale(LC_MONETARY, ...$availableLocales);
2708 setlocale(LC_TIME, ...$availableLocales);
2709 } else {
2710 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2711 }
2712 }
2713 }
2714
2715 /**
2716 * Checks whether a translated shortcut page has a different shortcut
2717 * target than the original language page.
2718 * If that is the case, things get corrected to follow that alternative
2719 * shortcut
2720 */
2721 protected function checkTranslatedShortcut()
2722 {
2723 if (!is_null($this->originalShortcutPage)) {
2724 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2725 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2726 // the translation of the original shortcut page has a different shortcut target!
2727 // set the correct page and id
2728 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2729 $this->id = ($this->contentPid = $shortcut['uid']);
2730 $this->page = $this->sys_page->getPage($this->id);
2731 // Fix various effects on things like menus f.e.
2732 $this->fetch_the_id();
2733 $this->tmpl->rootLine = array_reverse($this->rootLine);
2734 }
2735 }
2736 }
2737
2738 /**
2739 * Handle data submission
2740 * This is done at this point, because we need the config values
2741 */
2742 public function handleDataSubmission()
2743 {
2744 // Hook for processing data submission to extensions
2745 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2746 $_procObj = GeneralUtility::makeInstance($className);
2747 $_procObj->checkDataSubmission($this);
2748 }
2749 }
2750
2751 /**
2752 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2753 *
2754 * @see $activeRedirectUrlHandlers
2755 */
2756 public function initializeRedirectUrlHandlers()
2757 {
2758 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2759 if (!$urlHandlers) {
2760 return;
2761 }
2762
2763 foreach ($urlHandlers as $identifier => $configuration) {
2764 if (empty($configuration) || !is_array($configuration)) {
2765 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2766 }
2767 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2768 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2769 }
2770 }
2771
2772 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2773
2774 foreach ($orderedHandlers as $configuration) {
2775 /** @var UrlHandlerInterface $urlHandler */
2776 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2777 if ($urlHandler->canHandleCurrentUrl()) {
2778 $this->activeUrlHandlers[] = $urlHandler;
2779 }
2780 }
2781 }
2782
2783 /**
2784 * Loops over all registered URL handlers and lets them process the current URL.
2785 *
2786 * If no handler has stopped the current process (e.g. by redirecting) and a
2787 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2788 *
2789 * @internal Should be called by the FrontendRequestHandler only.
2790 * @return ResponseInterface|null
2791 */
2792 public function redirectToExternalUrl()
2793 {
2794 foreach ($this->activeUrlHandlers as $redirectHandler) {
2795 $response = $redirectHandler->handle();
2796 if ($response instanceof ResponseInterface) {
2797 return $response;
2798 }
2799 }
2800
2801 if (!empty($this->activeUrlHandlers)) {
2802 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2803 }
2804
2805 return null;
2806 }
2807
2808 /**
2809 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2810 * This feature allows sessions to use a GET-parameter instead of a cookie.
2811 *
2812 * @access private
2813 */
2814 public function setUrlIdToken()
2815 {
2816 if ($this->config['config']['ftu']) {
2817 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2818 } else {
2819 $this->getMethodUrlIdToken = '';
2820 }
2821 }
2822
2823 /**
2824 * Calculates and sets the internal linkVars based upon the current
2825 * $_GET parameters and the setting "config.linkVars".
2826 */
2827 public function calculateLinkVars()
2828 {
2829 $this->linkVars = '';
2830 if (empty($this->config['config']['linkVars'])) {
2831 return;
2832 }
2833
2834 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2835
2836 if (empty($linkVars)) {
2837 return;
2838 }
2839 $getData = GeneralUtility::_GET();
2840 foreach ($linkVars as $linkVar) {
2841 $test = $value = '';
2842 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2843 $linkVar = trim($match[1]);
2844 $test = trim($match[2]);
2845 }
2846
2847 $keys = explode('|', $linkVar);
2848 $numberOfLevels = count($keys);
2849 $rootKey = trim($keys[0]);
2850 if (!isset($getData[$rootKey])) {
2851 continue;
2852 }
2853 $value = $getData[$rootKey];
2854 for ($i = 1; $i < $numberOfLevels; $i++) {
2855 $currentKey = trim($keys[$i]);
2856 if (isset($value[$currentKey])) {
2857 $value = $value[$currentKey];
2858 } else {
2859 $value = false;
2860 break;
2861 }
2862 }
2863 if ($value !== false) {
2864 $parameterName = $keys[0];
2865 for ($i = 1; $i < $numberOfLevels; $i++) {
2866 $parameterName .= '[' . $keys[$i] . ']';
2867 }
2868 if (!is_array($value)) {
2869 $temp = rawurlencode($value);
2870 if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2871 // Error: This value was not allowed for this key
2872 continue;
2873 }
2874 $value = '&' . $parameterName . '=' . $temp;
2875 } else {
2876 if ($test !== '' && $test !== 'array') {
2877 // Error: This key must not be an array!
2878 continue;
2879 }
2880 $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2881 }
2882 $this->linkVars .= $value;
2883 }
2884 }
2885 }
2886
2887 /**
2888 * Split the link vars string by "," but not if the "," is inside of braces
2889 *
2890 * @param $string
2891 *
2892 * @return array
2893 */
2894 protected function splitLinkVarsString(string $string): array
2895 {
2896 $tempCommaReplacementString = '###KASPER###';
2897
2898 // replace every "," wrapped in "()" by a "unique" string
2899 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2900 return str_replace(',', $tempCommaReplacementString, $result[0]);
2901 }, $string);
2902
2903 $string = GeneralUtility::trimExplode(',', $string);
2904
2905 // replace all "unique" strings back to ","
2906 return str_replace($tempCommaReplacementString, ',', $string);
2907 }
2908
2909 /**
2910 * Checks if the value defined in "config.linkVars" contains an allowed value.
2911 * Otherwise, return FALSE which means the value will not be added to any links.
2912 *
2913 * @param string $haystack The string in which to find $needle
2914 * @param string $needle The string to find in $haystack
2915 * @return bool Returns TRUE if $needle matches or is found in $haystack
2916 */
2917 protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2918 {
2919 $isAllowed = false;
2920 // Integer
2921 if ($needle === 'int' || $needle === 'integer') {
2922 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2923 $isAllowed = true;
2924 }
2925 } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2926 // Regular expression, only "//" is allowed as delimiter
2927 if (@preg_match($needle, $haystack)) {