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