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