5b0ecdce6aedfb5f4ed21316086d4f9895645207
[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 TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
19 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20 use TYPO3\CMS\Core\Cache\CacheManager;
21 use TYPO3\CMS\Core\Charset\CharsetConverter;
22 use TYPO3\CMS\Core\Controller\ErrorPageController;
23 use TYPO3\CMS\Core\Database\ConnectionPool;
24 use TYPO3\CMS\Core\Database\Query\QueryHelper;
25 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
26 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
28 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
29 use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
30 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
31 use TYPO3\CMS\Core\Localization\Locales;
32 use TYPO3\CMS\Core\Localization\LocalizationFactory;
33 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
34 use TYPO3\CMS\Core\Locking\LockFactory;
35 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
36 use TYPO3\CMS\Core\Page\PageRenderer;
37 use TYPO3\CMS\Core\Resource\StorageRepository;
38 use TYPO3\CMS\Core\Service\DependencyOrderingService;
39 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
40 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
41 use TYPO3\CMS\Core\TypoScript\TemplateService;
42 use TYPO3\CMS\Core\Utility\ArrayUtility;
43 use TYPO3\CMS\Core\Utility\GeneralUtility;
44 use TYPO3\CMS\Core\Utility\HttpUtility;
45 use TYPO3\CMS\Core\Utility\MathUtility;
46 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
47 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
48 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
49 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
50 use TYPO3\CMS\Frontend\Page\PageGenerator;
51 use TYPO3\CMS\Frontend\Page\PageRepository;
52 use TYPO3\CMS\Frontend\View\AdminPanelView;
53
54 /**
55 * Class for the built TypoScript based frontend. Instantiated in
56 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
57 *
58 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
59 * as the global object TSFE.
60 *
61 * This class has a lot of functions and internal variable which are used from
62 * \TYPO3\CMS\Frontend\Http\RequestHandler
63 *
64 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
65 *
66 * The use of this class should be inspired by the order of function calls as
67 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
68 */
69 class TypoScriptFrontendController
70 {
71 /**
72 * The page id (int)
73 * @var string
74 */
75 public $id = '';
76
77 /**
78 * The type (read-only)
79 * @var int
80 */
81 public $type = '';
82
83 /**
84 * The submitted cHash
85 * @var string
86 */
87 public $cHash = '';
88
89 /**
90 * Page will not be cached. Write only TRUE. Never clear value (some other
91 * code might have reasons to set it TRUE).
92 * @var bool
93 */
94 public $no_cache = false;
95
96 /**
97 * The rootLine (all the way to tree root, not only the current site!)
98 * @var array
99 */
100 public $rootLine = '';
101
102 /**
103 * The pagerecord
104 * @var array
105 */
106 public $page = '';
107
108 /**
109 * This will normally point to the same value as id, but can be changed to
110 * point to another page from which content will then be displayed instead.
111 * @var int
112 */
113 public $contentPid = 0;
114
115 /**
116 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
117 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
118 * should be redirected to.
119 *
120 * @var array|NULL
121 */
122 protected $originalMountPointPage = null;
123
124 /**
125 * Gets set when we are processing a page of type shortcut in the early stages
126 * of the request when we do not know about languages yet, used later in the request
127 * to determine the correct shortcut in case a translation changes the shortcut
128 * target
129 * @var array|NULL
130 * @see checkTranslatedShortcut()
131 */
132 protected $originalShortcutPage = null;
133
134 /**
135 * sys_page-object, pagefunctions
136 *
137 * @var PageRepository
138 */
139 public $sys_page = '';
140
141 /**
142 * Contains all URL handler instances that are active for the current request.
143 *
144 * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
145 *
146 * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
147 * @see initializeRedirectUrlHandlers()
148 */
149 protected $activeUrlHandlers = [];
150
151 /**
152 * Is set to 1 if a pageNotFound handler could have been called.
153 * @var int
154 */
155 public $pageNotFound = 0;
156
157 /**
158 * Domain start page
159 * @var int
160 */
161 public $domainStartPage = 0;
162
163 /**
164 * Array containing a history of why a requested page was not accessible.
165 * @var array
166 */
167 public $pageAccessFailureHistory = [];
168
169 /**
170 * @var string
171 */
172 public $MP = '';
173
174 /**
175 * @var string
176 */
177 public $RDCT = '';
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 * @param string $RDCT The value of GeneralUtility::_GP('RDCT')
800 * @see \TYPO3\CMS\Frontend\Http\RequestHandler
801 */
802 public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '', $RDCT = '')
803 {
804 // Setting some variables:
805 $this->id = $id;
806 $this->type = $type;
807 if ($no_cache) {
808 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
809 $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
810 $this->getTimeTracker()->setTSlogMessage($warning, 2);
811 } else {
812 $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL') . '"';
813 $this->disableCache();
814 }
815 GeneralUtility::sysLog($warning, 'cms', GeneralUtility::SYSLOG_SEVERITY_WARNING);
816 }
817 $this->cHash = $cHash;
818 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? (string)$MP : '';
819 $this->RDCT = $RDCT;
820 $this->uniqueString = md5(microtime());
821 $this->initPageRenderer();
822 // Call post processing function for constructor:
823 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
824 $_params = ['pObj' => &$this];
825 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
826 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
827 }
828 }
829 $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
830 $this->initCaches();
831 }
832
833 /**
834 * Initializes the page renderer object
835 */
836 protected function initPageRenderer()
837 {
838 if ($this->pageRenderer !== null) {
839 return;
840 }
841 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
842 $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
843 }
844
845 /**
846 * @param string $contentType
847 * @internal Should only be used by TYPO3 core for now
848 */
849 public function setContentType($contentType)
850 {
851 $this->contentType = $contentType;
852 }
853
854 /**
855 * Connect to SQL database. May exit after outputting an error message
856 * or some JavaScript redirecting to the install tool.
857 *
858 * @throws \RuntimeException
859 * @throws ServiceUnavailableException
860 */
861 public function connectToDB()
862 {
863 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
864 try {
865 $connection->connect();
866 } catch (ConnectionException $exception) {
867 // Cannot connect to current database
868 $message = 'Cannot connect to the configured database "' . $connection->getDatabase() . '"';
869 if ($this->checkPageUnavailableHandler()) {
870 $this->pageUnavailableAndExit($message);
871 } else {
872 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
873 throw new ServiceUnavailableException($message, 1301648782);
874 }
875 }
876 // Call post processing function for DB connection:
877 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'])) {
878 $_params = ['pObj' => &$this];
879 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef) {
880 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
881 }
882 }
883 }
884
885 /**
886 * Looks up the value of $this->RDCT in the database and if it is
887 * found to be associated with a redirect URL then the redirection
888 * is carried out with a 'Location:' header
889 * May exit after sending a location-header.
890 */
891 public function sendRedirect()
892 {
893 if ($this->RDCT) {
894 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
895 ->getQueryBuilderForTable('cache_md5params');
896
897 $row = $queryBuilder
898 ->select('params')
899 ->from('cache_md5params')
900 ->where(
901 $queryBuilder->expr()->eq(
902 'md5hash',
903 $queryBuilder->createNamedParameter($this->RDCT, \PDO::PARAM_STR)
904 )
905 )
906 ->execute()
907 ->fetch();
908
909 if ($row) {
910 $this->updateMD5paramsRecord($this->RDCT);
911 header('Location: ' . $row['params']);
912 die;
913 }
914 }
915 }
916
917 /********************************************
918 *
919 * Initializing, resolving page id
920 *
921 ********************************************/
922 /**
923 * Initializes the caching system.
924 */
925 protected function initCaches()
926 {
927 $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
928 }
929
930 /**
931 * Initializes the front-end login user.
932 */
933 public function initFEuser()
934 {
935 $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
936 // List of pid's acceptable
937 $pid = GeneralUtility::_GP('pid');
938 $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
939 // Check if a session is transferred:
940 if (GeneralUtility::_GP('FE_SESSION_KEY')) {
941 $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
942 // If the session key hash check is OK:
943 if (md5(($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) === (string)$fe_sParts[1]) {
944 $cookieName = FrontendUserAuthentication::getCookieName();
945 $_COOKIE[$cookieName] = $fe_sParts[0];
946 if (isset($_SERVER['HTTP_COOKIE'])) {
947 // See http://forge.typo3.org/issues/27740
948 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
949 }
950 $this->fe_user->forceSetCookie = 1;
951 $this->fe_user->dontSetCookie = false;
952 unset($cookieName);
953 }
954 }
955 $this->fe_user->start();
956 $this->fe_user->unpack_uc();
957
958 // Call hook for possible manipulation of frontend user object
959 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'])) {
960 $_params = ['pObj' => &$this];
961 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef) {
962 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
963 }
964 }
965 // For every 60 seconds the is_online timestamp is updated.
966 if (is_array($this->fe_user->user) && $this->fe_user->user['uid'] && $this->fe_user->user['is_online'] < $GLOBALS['EXEC_TIME'] - 60) {
967 $dbConnection = GeneralUtility::makeInstance(ConnectionPool::class)
968 ->getConnectionForTable('fe_users');
969 $dbConnection->update(
970 'fe_users',
971 [
972 'is_online' => $GLOBALS['EXEC_TIME']
973 ],
974 [
975 'uid' => (int)$this->fe_user->user['uid']
976 ]
977 );
978 }
979 }
980
981 /**
982 * Initializes the front-end user groups.
983 * Sets ->loginUser and ->gr_list based on front-end user status.
984 */
985 public function initUserGroups()
986 {
987 // This affects the hidden-flag selecting the fe_groups for the user!
988 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
989 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
990 $this->fe_user->fetchGroupData();
991 if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
992 // global flag!
993 $this->loginUser = true;
994 // 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!
995 $this->gr_list = '0,-2';
996 $gr_array = $this->fe_user->groupData['uid'];
997 } else {
998 $this->loginUser = false;
999 // 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!
1000 $this->gr_list = '0,-1';
1001 if ($this->loginAllowedInBranch) {
1002 // 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.
1003 $gr_array = $this->fe_user->groupData['uid'];
1004 } else {
1005 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
1006 $gr_array = [];
1007 }
1008 }
1009 // Clean up.
1010 // Make unique...
1011 $gr_array = array_unique($gr_array);
1012 // sort
1013 sort($gr_array);
1014 if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
1015 $this->gr_list .= ',' . implode(',', $gr_array);
1016 }
1017 if ($this->fe_user->writeDevLog) {
1018 GeneralUtility::devLog('Valid usergroups for TSFE: ' . $this->gr_list, __CLASS__);
1019 }
1020 }
1021
1022 /**
1023 * Checking if a user is logged in or a group constellation different from "0,-1"
1024 *
1025 * @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!)
1026 */
1027 public function isUserOrGroupSet()
1028 {
1029 return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
1030 }
1031
1032 /**
1033 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
1034 *
1035 * Two options:
1036 * 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)
1037 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
1038 */
1039 public function checkAlternativeIdMethods()
1040 {
1041 $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
1042 // Call post processing function for custom URL methods.
1043 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
1044 $_params = ['pObj' => &$this];
1045 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef) {
1046 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1047 }
1048 }
1049 }
1050
1051 /**
1052 * Clears the preview-flags, sets sim_exec_time to current time.
1053 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
1054 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
1055 */
1056 public function clear_preview()
1057 {
1058 $this->showHiddenPage = false;
1059 $this->showHiddenRecords = false;
1060 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1061 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1062 $this->fePreview = 0;
1063 }
1064
1065 /**
1066 * Checks if a backend user is logged in
1067 *
1068 * @return bool whether a backend user is logged in
1069 */
1070 public function isBackendUserLoggedIn()
1071 {
1072 return (bool)$this->beUserLogin;
1073 }
1074
1075 /**
1076 * Creates the backend user object and returns it.
1077 *
1078 * @return FrontendBackendUserAuthentication the backend user object
1079 */
1080 public function initializeBackendUser()
1081 {
1082 // PRE BE_USER HOOK
1083 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'])) {
1084 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] as $_funcRef) {
1085 $_params = [];
1086 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1087 }
1088 }
1089 $backendUserObject = null;
1090 // If the backend cookie is set,
1091 // we proceed and check if a backend user is logged in.
1092 if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1093 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1094 $this->getTimeTracker()->push('Back End user initialized', '');
1095 $this->beUserLogin = false;
1096 // New backend user object
1097 $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1098 $backendUserObject->start();
1099 $backendUserObject->unpack_uc();
1100 if (!empty($backendUserObject->user['uid'])) {
1101 $backendUserObject->fetchGroupData();
1102 }
1103 // Unset the user initialization if any setting / restriction applies
1104 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1105 $backendUserObject = null;
1106 } elseif (!empty($backendUserObject->user['uid'])) {
1107 // If the user is active now, let the controller know
1108 $this->beUserLogin = true;
1109 } else {
1110 $backendUserObject = null;
1111 }
1112 $this->getTimeTracker()->pull();
1113 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1114 }
1115 // POST BE_USER HOOK
1116 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'])) {
1117 $_params = [
1118 'BE_USER' => &$backendUserObject
1119 ];
1120 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] as $_funcRef) {
1121 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1122 }
1123 }
1124 return $backendUserObject;
1125 }
1126
1127 /**
1128 * Determines the id and evaluates any preview settings
1129 * Basically this function is about determining whether a backend user is logged in,
1130 * if he has read access to the page and if he's previewing the page.
1131 * That all determines which id to show and how to initialize the id.
1132 */
1133 public function determineId()
1134 {
1135 // Call pre processing function for id determination
1136 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'])) {
1137 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] as $functionReference) {
1138 $parameters = ['parentObject' => $this];
1139 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1140 }
1141 }
1142 // If there is a Backend login we are going to check for any preview settings:
1143 $this->getTimeTracker()->push('beUserLogin', '');
1144 $originalFrontendUser = null;
1145 $backendUser = $this->getBackendUser();
1146 if ($this->beUserLogin || $this->doWorkspacePreview()) {
1147 // Backend user preview features:
1148 if ($this->beUserLogin && $backendUser->adminPanel instanceof AdminPanelView) {
1149 $this->fePreview = (int)$backendUser->adminPanel->extGetFeAdminValue('preview');
1150 // If admin panel preview is enabled...
1151 if ($this->fePreview) {
1152 if ($this->fe_user->user) {
1153 $originalFrontendUser = $this->fe_user->user;
1154 }
1155 $this->showHiddenPage = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1156 $this->showHiddenRecords = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1157 // Simulate date
1158 $simTime = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1159 if ($simTime) {
1160 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1161 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1162 }
1163 // simulate user
1164 $simUserGroup = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1165 $this->simUserGroup = $simUserGroup;
1166 if ($simUserGroup) {
1167 if ($this->fe_user->user) {
1168 $this->fe_user->user[$this->fe_user->usergroup_column] = $simUserGroup;
1169 } else {
1170 $this->fe_user->user = [
1171 $this->fe_user->usergroup_column => $simUserGroup
1172 ];
1173 }
1174 }
1175 if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1176 $this->fePreview = 0;
1177 }
1178 }
1179 }
1180 if ($this->id && $this->determineIdIsHiddenPage()) {
1181 // The preview flag is set only if the current page turns out to actually be hidden!
1182 $this->fePreview = 1;
1183 $this->showHiddenPage = true;
1184 }
1185 // The preview flag will be set if a backend user is in an offline workspace
1186 if (
1187 (
1188 $backendUser->user['workspace_preview']
1189 || GeneralUtility::_GP('ADMCMD_view')
1190 || $this->doWorkspacePreview()
1191 )
1192 && (
1193 $this->whichWorkspace() === -1
1194 || $this->whichWorkspace() > 0
1195 )
1196 && !GeneralUtility::_GP('ADMCMD_noBeUser')
1197 ) {
1198 // Will show special preview message.
1199 $this->fePreview = 2;
1200 }
1201 // If the front-end is showing a preview, caching MUST be disabled.
1202 if ($this->fePreview) {
1203 $this->disableCache();
1204 }
1205 }
1206 $this->getTimeTracker()->pull();
1207 // Now, get the id, validate access etc:
1208 $this->fetch_the_id();
1209 // Check if backend user has read access to this page. If not, recalculate the id.
1210 if ($this->beUserLogin && $this->fePreview) {
1211 if (!$backendUser->doesUserHaveAccess($this->page, 1)) {
1212 // Resetting
1213 $this->clear_preview();
1214 $this->fe_user->user = $originalFrontendUser;
1215 // Fetching the id again, now with the preview settings reset.
1216 $this->fetch_the_id();
1217 }
1218 }
1219 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1220 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1221 // Logins are not allowed:
1222 if (!$this->loginAllowedInBranch) {
1223 // Only if there is a login will we run this...
1224 if ($this->isUserOrGroupSet()) {
1225 if ($this->loginAllowedInBranch_mode === 'all') {
1226 // Clear out user and group:
1227 $this->fe_user->hideActiveLogin();
1228 $this->gr_list = '0,-1';
1229 } else {
1230 $this->gr_list = '0,-2';
1231 }
1232 // Fetching the id again, now with the preview settings reset.
1233 $this->fetch_the_id();
1234 }
1235 }
1236 // Final cleaning.
1237 // Make sure it's an integer
1238 $this->id = ($this->contentPid = (int)$this->id);
1239 // Make sure it's an integer
1240 $this->type = (int)$this->type;
1241 // Call post processing function for id determination:
1242 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
1243 $_params = ['pObj' => &$this];
1244 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef) {
1245 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1246 }
1247 }
1248 }
1249
1250 /**
1251 * Checks if the page is hidden in the active workspace.
1252 * If it is hidden, preview flags will be set.
1253 *
1254 * @return bool
1255 */
1256 protected function determineIdIsHiddenPage()
1257 {
1258 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1259
1260 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1261 ->getQueryBuilderForTable('pages');
1262 $queryBuilder
1263 ->getRestrictions()
1264 ->removeAll()
1265 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1266
1267 $page = $queryBuilder
1268 ->select('uid', 'hidden', 'starttime', 'endtime')
1269 ->from('pages')
1270 ->where(
1271 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1272 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1273 )
1274 ->setMaxResults(1)
1275 ->execute()
1276 ->fetch();
1277
1278 $workspace = $this->whichWorkspace();
1279 if ($workspace !== 0 && $workspace !== false) {
1280 // Fetch overlay of page if in workspace and check if it is hidden
1281 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1282 $pageSelectObject->versioningPreview = true;
1283 $pageSelectObject->init(false);
1284 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1285 $result = $targetPage === -1 || $targetPage === -2;
1286 } else {
1287 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1288 }
1289 return $result;
1290 }
1291
1292 /**
1293 * Get The Page ID
1294 * This gets the id of the page, checks if the page is in the domain and if the page is accessible
1295 * Sets variables such as $this->sys_page, $this->loginUser, $this->gr_list, $this->id, $this->type, $this->domainStartPage
1296 *
1297 * @throws ServiceUnavailableException
1298 * @access private
1299 */
1300 public function fetch_the_id()
1301 {
1302 $timeTracker = $this->getTimeTracker();
1303 $timeTracker->push('fetch_the_id initialize/', '');
1304 // Initialize the page-select functions.
1305 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1306 $this->sys_page->versioningPreview = $this->fePreview === 2 || (int)$this->workspacePreview || (bool)GeneralUtility::_GP('ADMCMD_view');
1307 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1308 $this->sys_page->init($this->showHiddenPage);
1309 // Set the valid usergroups for FE
1310 $this->initUserGroups();
1311 // Sets sys_page where-clause
1312 $this->setSysPageWhereClause();
1313 // Splitting $this->id by a period (.).
1314 // First part is 'id' and second part (if exists) will overrule the &type param
1315 $idParts = explode('.', $this->id, 2);
1316 $this->id = $idParts[0];
1317 if (isset($idParts[1])) {
1318 $this->type = $idParts[1];
1319 }
1320
1321 // If $this->id is a string, it's an alias
1322 $this->checkAndSetAlias();
1323 // The id and type is set to the integer-value - just to be sure...
1324 $this->id = (int)$this->id;
1325 $this->type = (int)$this->type;
1326 $timeTracker->pull();
1327 // We find the first page belonging to the current domain
1328 $timeTracker->push('fetch_the_id domain/', '');
1329 // The page_id of the current domain
1330 $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1331 if (!$this->id) {
1332 if ($this->domainStartPage) {
1333 // If the id was not previously set, set it to the id of the domain.
1334 $this->id = $this->domainStartPage;
1335 } else {
1336 // Find the first 'visible' page in that domain
1337 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1338 if ($theFirstPage) {
1339 $this->id = $theFirstPage['uid'];
1340 } else {
1341 $message = 'No pages are found on the rootlevel!';
1342 if ($this->checkPageUnavailableHandler()) {
1343 $this->pageUnavailableAndExit($message);
1344 } else {
1345 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1346 throw new ServiceUnavailableException($message, 1301648975);
1347 }
1348 }
1349 }
1350 }
1351 $timeTracker->pull();
1352 $timeTracker->push('fetch_the_id rootLine/', '');
1353 // We store the originally requested id
1354 $this->requestedId = $this->id;
1355 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1356 $timeTracker->pull();
1357 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1358 $pNotFoundMsg = [
1359 1 => 'ID was not an accessible page',
1360 2 => 'Subsection was found and not accessible',
1361 3 => 'ID was outside the domain',
1362 4 => 'The requested page alias does not exist'
1363 ];
1364 $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound]);
1365 }
1366 // Set no_cache if set
1367 if ($this->page['no_cache']) {
1368 $this->set_no_cache('no_cache is set in page properties');
1369 }
1370 // Init SYS_LASTCHANGED
1371 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1372 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1373 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1374 }
1375 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'])) {
1376 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] as $functionReference) {
1377 $parameters = ['parentObject' => $this];
1378 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1379 }
1380 }
1381 }
1382
1383 /**
1384 * Loads the page and root line records based on $this->id
1385 *
1386 * A final page and the matching root line are determined and loaded by
1387 * the algorithm defined by this method.
1388 *
1389 * First it loads the initial page from the page repository for $this->id.
1390 * If that can't be loaded directly, it gets the root line for $this->id.
1391 * It walks up the root line towards the root page until the page
1392 * repository can deliver a page record. (The loading restrictions of
1393 * the root line records are more liberal than that of the page record.)
1394 *
1395 * Now the page type is evaluated and handled if necessary. If the page is
1396 * a short cut, it is replaced by the target page. If the page is a mount
1397 * point in overlay mode, the page is replaced by the mounted page.
1398 *
1399 * After this potential replacements are done, the root line is loaded
1400 * (again) for this page record. It walks up the root line up to
1401 * the first viewable record.
1402 *
1403 * (While upon the first accessibility check of the root line it was done
1404 * by loading page by page from the page repository, this time the method
1405 * checkRootlineForIncludeSection() is used to find the most distant
1406 * accessible page within the root line.)
1407 *
1408 * Having found the final page id, the page record and the root line are
1409 * loaded for last time by this method.
1410 *
1411 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1412 * or root lines.
1413 *
1414 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1415 * instead of throwing an exception it's handled by a page unavailable
1416 * handler.
1417 *
1418 * May set or update this properties:
1419 *
1420 * @see TypoScriptFrontendController::$id
1421 * @see TypoScriptFrontendController::$MP
1422 * @see TypoScriptFrontendController::$page
1423 * @see TypoScriptFrontendController::$pageNotFound
1424 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1425 * @see TypoScriptFrontendController::$originalMountPointPage
1426 * @see TypoScriptFrontendController::$originalShortcutPage
1427 *
1428 * @throws ServiceUnavailableException
1429 * @throws PageNotFoundException
1430 * @access private
1431 */
1432 public function getPageAndRootline()
1433 {
1434 $this->page = $this->sys_page->getPage($this->id);
1435 if (empty($this->page)) {
1436 // If no page, we try to find the page before in the rootLine.
1437 // Page is 'not found' in case the id itself was not an accessible page. code 1
1438 $this->pageNotFound = 1;
1439 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1440 if (!empty($this->rootLine)) {
1441 $c = count($this->rootLine) - 1;
1442 while ($c > 0) {
1443 // Add to page access failure history:
1444 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1445 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1446 $c--;
1447 $this->id = $this->rootLine[$c]['uid'];
1448 $this->page = $this->sys_page->getPage($this->id);
1449 if (!empty($this->page)) {
1450 break;
1451 }
1452 }
1453 }
1454 // If still no page...
1455 if (empty($this->page)) {
1456 $message = 'The requested page does not exist!';
1457 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1458 $this->pageNotFoundAndExit($message);
1459 } else {
1460 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1461 throw new PageNotFoundException($message, 1301648780);
1462 }
1463 }
1464 }
1465 // Spacer is not accessible in frontend
1466 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1467 $message = 'The requested page does not exist!';
1468 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1469 $this->pageNotFoundAndExit($message);
1470 } else {
1471 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1472 throw new PageNotFoundException($message, 1301648781);
1473 }
1474 }
1475 // Is the ID a link to another page??
1476 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1477 // 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.
1478 $this->MP = '';
1479 // saving the page so that we can check later - when we know
1480 // about languages - whether we took the correct shortcut or
1481 // whether a translation of the page overwrites the shortcut
1482 // target and we need to follow the new target
1483 $this->originalShortcutPage = $this->page;
1484 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1485 $this->id = $this->page['uid'];
1486 }
1487 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1488 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1489 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1490 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1491 $this->originalMountPointPage = $this->page;
1492 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1493 if (empty($this->page)) {
1494 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1495 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1496 throw new PageNotFoundException($message, 1402043263);
1497 }
1498 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1499 $this->id = $this->page['uid'];
1500 }
1501 // Gets the rootLine
1502 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1503 // If not rootline we're off...
1504 if (empty($this->rootLine)) {
1505 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1506 if ($this->checkPageUnavailableHandler()) {
1507 $this->pageUnavailableAndExit($message);
1508 } else {
1509 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1510 throw new ServiceUnavailableException($message, 1301648167);
1511 }
1512 }
1513 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1514 if ($this->checkRootlineForIncludeSection()) {
1515 if (empty($this->rootLine)) {
1516 $message = 'The requested page was not accessible!';
1517 if ($this->checkPageUnavailableHandler()) {
1518 $this->pageUnavailableAndExit($message);
1519 } else {
1520 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1521 throw new ServiceUnavailableException($message, 1301648234);
1522 }
1523 } else {
1524 $el = reset($this->rootLine);
1525 $this->id = $el['uid'];
1526 $this->page = $this->sys_page->getPage($this->id);
1527 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1528 }
1529 }
1530 }
1531
1532 /**
1533 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1534 *
1535 * @param int $SC The value of the "shortcut" field from the pages record
1536 * @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
1537 * @param int $thisUid The current page UID of the page which is a shortcut
1538 * @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...)
1539 * @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.
1540 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1541 * @throws \RuntimeException
1542 * @throws PageNotFoundException
1543 * @return mixed Returns the page record of the page that the shortcut pointed to.
1544 * @access private
1545 * @see getPageAndRootline()
1546 */
1547 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1548 {
1549 $idArray = GeneralUtility::intExplode(',', $SC);
1550 // Find $page record depending on shortcut mode:
1551 switch ($mode) {
1552 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1553
1554 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1555 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1556 $pO = 0;
1557 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1558 $randval = (int)rand(0, count($pageArray) - 1);
1559 $pO = $randval;
1560 }
1561 $c = 0;
1562 $page = [];
1563 foreach ($pageArray as $pV) {
1564 if ($c === $pO) {
1565 $page = $pV;
1566 break;
1567 }
1568 $c++;
1569 }
1570 if (empty($page)) {
1571 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1572 throw new PageNotFoundException($message, 1301648328);
1573 }
1574 break;
1575 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1576 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1577 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1578 if (empty($page)) {
1579 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1580 throw new PageNotFoundException($message, 1301648358);
1581 }
1582 break;
1583 default:
1584 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1585 if (empty($page)) {
1586 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1587 throw new PageNotFoundException($message, 1301648404);
1588 }
1589 }
1590 // Check if short cut page was a shortcut itself, if so look up recursively:
1591 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1592 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1593 $pageLog[] = $page['uid'];
1594 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1595 } else {
1596 $pageLog[] = $page['uid'];
1597 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1598 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1599 throw new \RuntimeException($message, 1294587212);
1600 }
1601 }
1602 // Return resulting page:
1603 return $page;
1604 }
1605
1606 /**
1607 * Checks the current rootline for defined sections.
1608 *
1609 * @return bool
1610 * @access private
1611 */
1612 public function checkRootlineForIncludeSection()
1613 {
1614 $c = count($this->rootLine);
1615 $removeTheRestFlag = 0;
1616 for ($a = 0; $a < $c; $a++) {
1617 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1618 // Add to page access failure history:
1619 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1620 $removeTheRestFlag = 1;
1621 }
1622
1623 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1624 // If there is a backend user logged in, check if he has read access to the page:
1625 if ($this->beUserLogin) {
1626 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1627 ->getQueryBuilderForTable('pages');
1628
1629 $queryBuilder
1630 ->getRestrictions()
1631 ->removeAll();
1632
1633 $row = $queryBuilder
1634 ->select('uid')
1635 ->from('pages')
1636 ->where(
1637 $queryBuilder->expr()->eq(
1638 'uid',
1639 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1640 ),
1641 $this->getBackendUser()->getPagePermsClause(1)
1642 )
1643 ->execute()
1644 ->fetch();
1645
1646 // versionOL()?
1647 if (!$row) {
1648 // 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...
1649 $removeTheRestFlag = 1;
1650 }
1651 } else {
1652 // Don't go here, if there is no backend user logged in.
1653 $removeTheRestFlag = 1;
1654 }
1655 }
1656 if ($removeTheRestFlag) {
1657 // Page is 'not found' in case a subsection was found and not accessible, code 2
1658 $this->pageNotFound = 2;
1659 unset($this->rootLine[$a]);
1660 }
1661 }
1662 return $removeTheRestFlag;
1663 }
1664
1665 /**
1666 * Checks page record for enableFields
1667 * Returns TRUE if enableFields does not disable the page record.
1668 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1669 *
1670 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1671 * @param bool $bypassGroupCheck Bypass group-check
1672 * @return bool TRUE, if record is viewable.
1673 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1674 */
1675 public function checkEnableFields($row, $bypassGroupCheck = false)
1676 {
1677 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'])) {
1678 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1679 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] as $_funcRef) {
1680 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1681 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1682 if ($return === false) {
1683 return false;
1684 }
1685 }
1686 }
1687 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1688 return true;
1689 }
1690 return false;
1691 }
1692
1693 /**
1694 * Check group access against a page record
1695 *
1696 * @param array $row The page record to evaluate (needs field: fe_group)
1697 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1698 * @return bool TRUE, if group access is granted.
1699 * @access private
1700 */
1701 public function checkPageGroupAccess($row, $groupList = null)
1702 {
1703 if (is_null($groupList)) {
1704 $groupList = $this->gr_list;
1705 }
1706 if (!is_array($groupList)) {
1707 $groupList = explode(',', $groupList);
1708 }
1709 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1710 return count(array_intersect($groupList, $pageGroupList)) > 0;
1711 }
1712
1713 /**
1714 * Checks page record for include section
1715 *
1716 * @param array $row The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
1717 * @return bool Returns TRUE if either extendToSubpages is not checked or if the enableFields does not disable the page record.
1718 * @access private
1719 * @see checkEnableFields(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkRootlineForIncludeSection()
1720 */
1721 public function checkPagerecordForIncludeSection($row)
1722 {
1723 return !$row['extendToSubpages'] || $this->checkEnableFields($row) ? 1 : 0;
1724 }
1725
1726 /**
1727 * 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!)
1728 *
1729 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1730 */
1731 public function checkIfLoginAllowedInBranch()
1732 {
1733 // Initialize:
1734 $c = count($this->rootLine);
1735 $loginAllowed = true;
1736 // Traverse root line from root and outwards:
1737 for ($a = 0; $a < $c; $a++) {
1738 // If a value is set for login state:
1739 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1740 // Determine state from value:
1741 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1742 $loginAllowed = false;
1743 $this->loginAllowedInBranch_mode = 'all';
1744 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1745 $loginAllowed = false;
1746 $this->loginAllowedInBranch_mode = 'groups';
1747 } else {
1748 $loginAllowed = true;
1749 }
1750 }
1751 }
1752 return $loginAllowed;
1753 }
1754
1755 /**
1756 * 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
1757 *
1758 * @return array Summary of why page access was not allowed.
1759 */
1760 public function getPageAccessFailureReasons()
1761 {
1762 $output = [];
1763 $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'] : []);
1764 if (!empty($combinedRecords)) {
1765 foreach ($combinedRecords as $k => $pagerec) {
1766 // 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
1767 // 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!
1768 if (!$k || $pagerec['extendToSubpages']) {
1769 if ($pagerec['hidden']) {
1770 $output['hidden'][$pagerec['uid']] = true;
1771 }
1772 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1773 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1774 }
1775 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1776 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1777 }
1778 if (!$this->checkPageGroupAccess($pagerec)) {
1779 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1780 }
1781 }
1782 }
1783 }
1784 return $output;
1785 }
1786
1787 /**
1788 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1789 * If not inside domain, then default to first page in domain.
1790 *
1791 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1792 * @access private
1793 */
1794 public function getPageAndRootlineWithDomain($domainStartPage)
1795 {
1796 $this->getPageAndRootline();
1797 // 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.
1798 if ($domainStartPage && is_array($this->rootLine)) {
1799 $idFound = 0;
1800 foreach ($this->rootLine as $key => $val) {
1801 if ($val['uid'] == $domainStartPage) {
1802 $idFound = 1;
1803 break;
1804 }
1805 }
1806 if (!$idFound) {
1807 // Page is 'not found' in case the id was outside the domain, code 3
1808 $this->pageNotFound = 3;
1809 $this->id = $domainStartPage;
1810 // re-get the page and rootline if the id was not found.
1811 $this->getPageAndRootline();
1812 }
1813 }
1814 }
1815
1816 /**
1817 * Sets sys_page where-clause
1818 *
1819 * @access private
1820 */
1821 public function setSysPageWhereClause()
1822 {
1823 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1824 ->getConnectionForTable('pages')
1825 ->getExpressionBuilder();
1826 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1827 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1828 $expressionBuilder->lt('pages.doktype', 200)
1829 );
1830 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1831 }
1832
1833 /**
1834 * Looking up a domain record based on HTTP_HOST
1835 *
1836 * @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.
1837 * @return int Returns the page id of the page where the domain record was found.
1838 * @access private
1839 */
1840 public function findDomainRecord($recursive = false)
1841 {
1842 if ($recursive) {
1843 $pageUid = 0;
1844 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1845 while (count($host)) {
1846 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1847 if ($pageUid) {
1848 return $pageUid;
1849 } else {
1850 array_shift($host);
1851 }
1852 }
1853 return $pageUid;
1854 } else {
1855 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1856 }
1857 }
1858
1859 /**
1860 * Page unavailable handler for use in frontend plugins from extensions.
1861 *
1862 * @param string $reason Reason text
1863 * @param string $header HTTP header to send
1864 */
1865 public function pageUnavailableAndExit($reason = '', $header = '')
1866 {
1867 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1868 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1869 die;
1870 }
1871
1872 /**
1873 * Page-not-found handler for use in frontend plugins from extensions.
1874 *
1875 * @param string $reason Reason text
1876 * @param string $header HTTP header to send
1877 */
1878 public function pageNotFoundAndExit($reason = '', $header = '')
1879 {
1880 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1881 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1882 die;
1883 }
1884
1885 /**
1886 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1887 * and devIPMask must not match the current visitor's IP address.
1888 *
1889 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1890 */
1891 public function checkPageUnavailableHandler()
1892 {
1893 if (
1894 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1895 && !GeneralUtility::cmpIP(
1896 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1897 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1898 )
1899 ) {
1900 $checkPageUnavailableHandler = true;
1901 } else {
1902 $checkPageUnavailableHandler = false;
1903 }
1904 return $checkPageUnavailableHandler;
1905 }
1906
1907 /**
1908 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1909 *
1910 * @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.
1911 * @param string $header If set, this is passed directly to the PHP function, header()
1912 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1913 */
1914 public function pageUnavailableHandler($code, $header, $reason)
1915 {
1916 $this->pageErrorHandler($code, $header, $reason);
1917 }
1918
1919 /**
1920 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1921 *
1922 * @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.
1923 * @param string $header If set, this is passed directly to the PHP function, header()
1924 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1925 */
1926 public function pageNotFoundHandler($code, $header = '', $reason = '')
1927 {
1928 $this->pageErrorHandler($code, $header, $reason);
1929 }
1930
1931 /**
1932 * Generic error page handler.
1933 * Exits.
1934 *
1935 * @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.
1936 * @param string $header If set, this is passed directly to the PHP function, header()
1937 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1938 * @throws \RuntimeException
1939 */
1940 public function pageErrorHandler($code, $header = '', $reason = '')
1941 {
1942 // Issue header in any case:
1943 if ($header) {
1944 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1945 foreach ($headerArr as $header) {
1946 header($header);
1947 }
1948 }
1949 // Create response:
1950 // Simply boolean; Just shows TYPO3 error page with reason:
1951 if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1952 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1953 'Page Not Found',
1954 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1955 );
1956 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1957 $funcRef = trim(substr($code, 14));
1958 $params = [
1959 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1960 'reasonText' => $reason,
1961 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1962 ];
1963 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1964 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
1965 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
1966 if (@is_file($readFile)) {
1967 echo str_replace(
1968 [
1969 '###CURRENT_URL###',
1970 '###REASON###'
1971 ],
1972 [
1973 GeneralUtility::getIndpEnv('REQUEST_URI'),
1974 htmlspecialchars($reason)
1975 ],
1976 file_get_contents($readFile)
1977 );
1978 } else {
1979 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
1980 }
1981 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
1982 HttpUtility::redirect(substr($code, 9));
1983 } elseif ($code !== '') {
1984 // Check if URL is relative
1985 $url_parts = parse_url($code);
1986 // parse_url could return an array without the key "host", the empty check works better than strict check
1987 if (empty($url_parts['host'])) {
1988 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1989 if ($code[0] === '/') {
1990 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
1991 } else {
1992 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
1993 }
1994 $checkBaseTag = false;
1995 } else {
1996 $checkBaseTag = true;
1997 }
1998 // Check recursion
1999 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2000 if ($reason == '') {
2001 $reason = 'Page cannot be found.';
2002 }
2003 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2004 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2005 }
2006 // Prepare headers
2007 $headerArr = [
2008 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2009 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2010 ];
2011 $res = GeneralUtility::getUrl($code, 1, $headerArr);
2012 // Header and content are separated by an empty line
2013 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2014 $content .= CRLF;
2015 if (false === $res) {
2016 // Last chance -- redirect
2017 HttpUtility::redirect($code);
2018 } else {
2019 // Forward these response headers to the client
2020 $forwardHeaders = [
2021 'Content-Type:'
2022 ];
2023 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2024 foreach ($headerArr as $header) {
2025 foreach ($forwardHeaders as $h) {
2026 if (preg_match('/^' . $h . '/', $header)) {
2027 header($header);
2028 }
2029 }
2030 }
2031 // Put <base> if necessary
2032 if ($checkBaseTag) {
2033 // If content already has <base> tag, we do not need to do anything
2034 if (false === stristr($content, '<base ')) {
2035 // Generate href for base tag
2036 $base = $url_parts['scheme'] . '://';
2037 if ($url_parts['user'] != '') {
2038 $base .= $url_parts['user'];
2039 if ($url_parts['pass'] != '') {
2040 $base .= ':' . $url_parts['pass'];
2041 }
2042 $base .= '@';
2043 }
2044 $base .= $url_parts['host'];
2045 // Add path portion skipping possible file name
2046 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2047 // Put it into content (generate also <head> if necessary)
2048 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2049 if (stristr($content, '<head>')) {
2050 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2051 } else {
2052 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2053 }
2054 }
2055 }
2056 // Output the content
2057 echo $content;
2058 }
2059 } else {
2060 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2061 'Page Not Found',
2062 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2063 );
2064 }
2065 die;
2066 }
2067
2068 /**
2069 * Fetches the integer page id for a page alias.
2070 * 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
2071 *
2072 * @access private
2073 */
2074 public function checkAndSetAlias()
2075 {
2076 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2077 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2078 if ($aid) {
2079 $this->id = $aid;
2080 } else {
2081 $this->pageNotFound = 4;
2082 }
2083 }
2084 }
2085
2086 /**
2087 * Merging values into the global $_GET
2088 *
2089 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2090 */
2091 public function mergingWithGetVars($GET_VARS)
2092 {
2093 if (is_array($GET_VARS)) {
2094 // Getting $_GET var, unescaped.
2095 $realGet = GeneralUtility::_GET();
2096 if (!is_array($realGet)) {
2097 $realGet = [];
2098 }
2099 // Merge new values on top:
2100 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2101 // Write values back to $_GET:
2102 GeneralUtility::_GETset($realGet);
2103 // Setting these specifically (like in the init-function):
2104 if (isset($GET_VARS['type'])) {
2105 $this->type = (int)$GET_VARS['type'];
2106 }
2107 if (isset($GET_VARS['cHash'])) {
2108 $this->cHash = $GET_VARS['cHash'];
2109 }
2110 if (isset($GET_VARS['MP'])) {
2111 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2112 }
2113 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2114 $this->set_no_cache('no_cache is requested via GET parameter');
2115 }
2116 }
2117 }
2118
2119 /********************************************
2120 *
2121 * Template and caching related functions.
2122 *
2123 *******************************************/
2124 /**
2125 * Calculates a hash string based on additional parameters in the url.
2126 *
2127 * Calculated hash is stored in $this->cHash_array.
2128 * This is used to cache pages with more parameters than just id and type.
2129 *
2130 * @see reqCHash()
2131 */
2132 public function makeCacheHash()
2133 {
2134 // No need to test anything if caching was already disabled.
2135 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2136 return;
2137 }
2138 $GET = GeneralUtility::_GET();
2139 if ($this->cHash && is_array($GET)) {
2140 // Make sure we use the page uid and not the page alias
2141 $GET['id'] = $this->id;
2142 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2143 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2144 if ($cHash_calc != $this->cHash) {
2145 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2146 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
2147 } else {
2148 $this->disableCache();
2149 $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);
2150 }
2151 }
2152 } elseif (is_array($GET)) {
2153 // No cHash is set, check if that is correct
2154 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2155 $this->reqCHash();
2156 }
2157 }
2158 }
2159
2160 /**
2161 * Will disable caching if the cHash value was not set.
2162 * 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)
2163 *
2164 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2165 */
2166 public function reqCHash()
2167 {
2168 if (!$this->cHash) {
2169 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2170 if ($this->tempContent) {
2171 $this->clearPageCacheContent();
2172 }
2173 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
2174 } else {
2175 $this->disableCache();
2176 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2177 }
2178 }
2179 }
2180
2181 /**
2182 * Initialize the TypoScript template parser
2183 */
2184 public function initTemplate()
2185 {
2186 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2187 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2188 $this->tmpl->init();
2189 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2190 }
2191
2192 /**
2193 * See if page is in cache and get it if so
2194 * Stores the page content in $this->content if something is found.
2195 *
2196 * @throws \InvalidArgumentException
2197 * @throws \RuntimeException
2198 */
2199 public function getFromCache()
2200 {
2201 // clearing the content-variable, which will hold the pagecontent
2202 $this->content = '';
2203 // Unsetting the lowlevel config
2204 $this->config = [];
2205 $this->cacheContentFlag = false;
2206
2207 if ($this->no_cache) {
2208 return;
2209 }
2210
2211 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2212 if (!is_array($pageSectionCacheContent)) {
2213 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2214 // We use the Registry to store this lock centrally,
2215 // but we protect the access again with a global exclusive lock to avoid race conditions
2216
2217 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2218 //
2219 // from this point on we're the only one working on that page ($key)
2220 //
2221
2222 // query the cache again to see if the page data are there meanwhile
2223 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2224 if (is_array($pageSectionCacheContent)) {
2225 // we have the content, nice that some other process did the work for us already
2226 $this->releaseLock('pagesection');
2227 } else {
2228 // We keep the lock set, because we are the ones generating the page now
2229 // and filling the cache.
2230 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2231 }
2232 }
2233
2234 if (is_array($pageSectionCacheContent)) {
2235 // 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.
2236 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2237 // 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.
2238 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2239 ksort($pageSectionCacheContent);
2240 $this->all = $pageSectionCacheContent;
2241 }
2242 unset($pageSectionCacheContent);
2243
2244 // Look for page in cache only if a shift-reload is not sent to the server.
2245 $lockHash = $this->getLockHash();
2246 if (!$this->headerNoCache()) {
2247 if ($this->all) {
2248 // we got page section information
2249 $this->newHash = $this->getHash();
2250 $this->getTimeTracker()->push('Cache Row', '');
2251 $row = $this->getFromCache_queryRow();
2252 if (!is_array($row)) {
2253 // nothing in the cache, we acquire an exclusive lock now
2254
2255 $this->acquireLock('pages', $lockHash);
2256 //
2257 // from this point on we're the only one working on that page ($lockHash)
2258 //
2259
2260 // query the cache again to see if the data are there meanwhile
2261 $row = $this->getFromCache_queryRow();
2262 if (is_array($row)) {
2263 // we have the content, nice that some other process did the work for us
2264 $this->releaseLock('pages');
2265 } else {
2266 // We keep the lock set, because we are the ones generating the page now
2267 // and filling the cache.
2268 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2269 }
2270 }
2271 if (is_array($row)) {
2272 // we have data from cache
2273
2274 // Call hook when a page is retrieved from cache:
2275 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'])) {
2276 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2277 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] as $_funcRef) {
2278 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2279 }
2280 }
2281 // Fetches the lowlevel config stored with the cached data
2282 $this->config = $row['cache_data'];
2283 // Getting the content
2284 $this->content = $row['content'];
2285 // Flag for temp content
2286 $this->tempContent = $row['temp_content'];
2287 // Setting flag, so we know, that some cached content has been loaded
2288 $this->cacheContentFlag = true;
2289 $this->cacheExpires = $row['expires'];
2290
2291 // Restore page title information, this is needed to generate the page title for
2292 // partially cached pages.
2293 $this->page['title'] = $row['pageTitleInfo']['title'];
2294 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2295 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2296
2297 if (isset($this->config['config']['debug'])) {
2298 $debugCacheTime = (bool)$this->config['config']['debug'];
2299 } else {
2300 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2301 }
2302 if ($debugCacheTime) {
2303 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2304 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2305 $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2306 }
2307 }
2308 $this->getTimeTracker()->pull();
2309
2310 return;
2311 }
2312 }
2313 // the user forced rebuilding the page cache or there was no pagesection information
2314 // get a lock for the page content so other processes will not interrupt the regeneration
2315 $this->acquireLock('pages', $lockHash);
2316 }
2317
2318 /**
2319 * Returning the cached version of page with hash = newHash
2320 *
2321 * @return array Cached row, if any. Otherwise void.
2322 */
2323 public function getFromCache_queryRow()
2324 {
2325 $this->getTimeTracker()->push('Cache Query', '');
2326 $row = $this->pageCache->get($this->newHash);
2327 $this->getTimeTracker()->pull();
2328 return $row;
2329 }
2330
2331 /**
2332 * Detecting if shift-reload has been clicked
2333 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2334 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2335 *
2336 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2337 */
2338 public function headerNoCache()
2339 {
2340 $disableAcquireCacheData = false;
2341 if ($this->beUserLogin) {
2342 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2343 $disableAcquireCacheData = true;
2344 }
2345 }
2346 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2347 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'])) {
2348 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2349 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] as $_funcRef) {
2350 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2351 }
2352 }
2353 return $disableAcquireCacheData;
2354 }
2355
2356 /**
2357 * Calculates the cache-hash
2358 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2359 * Used to get and later store the cached data.
2360 *
2361 * @return string MD5 hash of serialized hash base from createHashBase()
2362 * @access private
2363 * @see getFromCache(), getLockHash()
2364 */
2365 public function getHash()
2366 {
2367 return md5($this->createHashBase(false));
2368 }
2369
2370 /**
2371 * Calculates the lock-hash
2372 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2373 *
2374 * @return string MD5 hash
2375 * @access private
2376 * @see getFromCache(), getHash()
2377 */
2378 public function getLockHash()
2379 {
2380 $lockHash = $this->createHashBase(true);
2381 return md5($lockHash);
2382 }
2383
2384 /**
2385 * Calculates the cache-hash (or the lock-hash)
2386 * This hash is unique to the template,
2387 * the variables ->id, ->type, ->gr_list (list of groups),
2388 * ->MP (Mount Points) and cHash array
2389 * Used to get and later store the cached data.
2390 *
2391 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2392 * @return string the serialized hash base
2393 */
2394 protected function createHashBase($createLockHashBase = false)
2395 {
2396 $hashParameters = [
2397 'id' => (int)$this->id,
2398 'type' => (int)$this->type,
2399 'gr_list' => (string)$this->gr_list,
2400 'MP' => (string)$this->MP,
2401 'cHash' => $this->cHash_array,
2402 'domainStartPage' => $this->domainStartPage
2403 ];
2404 // Include the template information if we shouldn't create a lock hash
2405 if (!$createLockHashBase) {
2406 $hashParameters['all'] = $this->all;
2407 }
2408 // Call hook to influence the hash calculation
2409 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'])) {
2410 $_params = [
2411 'hashParameters' => &$hashParameters,
2412 'createLockHashBase' => $createLockHashBase
2413 ];
2414 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] as $_funcRef) {
2415 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2416 }
2417 }
2418 return serialize($hashParameters);
2419 }
2420
2421 /**
2422 * Checks if config-array exists already but if not, gets it
2423 *
2424 * @throws ServiceUnavailableException
2425 */
2426 public function getConfigArray()
2427 {
2428 // 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
2429 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2430 $timeTracker = $this->getTimeTracker();
2431 $timeTracker->push('Parse template', '');
2432 // Force parsing, if set?:
2433 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2434 // Start parsing the TS template. Might return cached version.
2435 $this->tmpl->start($this->rootLine);
2436 $timeTracker->pull();
2437 if ($this->tmpl->loaded) {
2438 $timeTracker->push('Setting the config-array', '');
2439 // toplevel - objArrayName
2440 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2441 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2442 if (!is_array($this->pSetup)) {
2443 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2444 if ($this->checkPageUnavailableHandler()) {
2445 $this->pageUnavailableAndExit($message);
2446 } else {
2447 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2448 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2449 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2450 }
2451 } else {
2452 if (!isset($this->config['config'])) {
2453 $this->config['config'] = [];
2454 }
2455 // Filling the config-array, first with the main "config." part
2456 if (is_array($this->tmpl->setup['config.'])) {
2457 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2458 $this->config['config'] = $this->tmpl->setup['config.'];
2459 }
2460 // override it with the page/type-specific "config."
2461 if (is_array($this->pSetup['config.'])) {
2462 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2463 }
2464 if ($this->config['config']['typolinkEnableLinksAcrossDomains']) {
2465 $this->config['config']['typolinkCheckRootline'] = true;
2466 }
2467 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2468 if (!isset($this->config['config']['removeDefaultJS'])) {
2469 $this->config['config']['removeDefaultJS'] = 'external';
2470 }
2471 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2472 $this->config['config']['inlineStyle2TempFile'] = 1;
2473 }
2474
2475 if (!isset($this->config['config']['compressJs'])) {
2476 $this->config['config']['compressJs'] = 0;
2477 }
2478 // Processing for the config_array:
2479 $this->config['rootLine'] = $this->tmpl->rootLine;
2480 // Class for render Header and Footer parts
2481 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2482 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2483 if ($file) {
2484 $this->pageRenderer->setTemplateFile($file);
2485 }
2486 }
2487 }
2488 $timeTracker->pull();
2489 } else {
2490 if ($this->checkPageUnavailableHandler()) {
2491 $this->pageUnavailableAndExit('No TypoScript template found!');
2492 } else {
2493 $message = 'No TypoScript template found!';
2494 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2495 throw new ServiceUnavailableException($message, 1294587218);
2496 }
2497 }
2498 }
2499
2500 // No cache
2501 // Set $this->no_cache TRUE if the config.no_cache value is set!
2502 if ($this->config['config']['no_cache']) {
2503 $this->set_no_cache('config.no_cache is set');
2504 }
2505 // Merge GET with defaultGetVars
2506 if (!empty($this->config['config']['defaultGetVars.'])) {
2507 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2508 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2509 GeneralUtility::_GETset($modifiedGetVars);
2510 }
2511 // Hook for postProcessing the configuration array
2512 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'])) {
2513 $params = ['config' => &$this->config['config']];
2514 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] as $funcRef) {
2515 GeneralUtility::callUserFunction($funcRef, $params, $this);
2516 }
2517 }
2518 }
2519
2520 /********************************************
2521 *
2522 * Further initialization and data processing
2523 *
2524 *******************************************/
2525
2526 /**
2527 * Setting the language key that will be used by the current page.
2528 * 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.
2529 *
2530 * @access private
2531 */
2532 public function settingLanguage()
2533 {
2534 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'])) {
2535 $_params = [];
2536 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] as $_funcRef) {
2537 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2538 }
2539 }
2540
2541 // Initialize charset settings etc.
2542 $this->initLLvars();
2543
2544 // Get values from TypoScript:
2545 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2546 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2547 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2548 // If sys_language_uid is set to another language than default:
2549 if ($this->sys_language_uid > 0) {
2550 // check whether a shortcut is overwritten by a translated page
2551 // we can only do this now, as this is the place where we get
2552 // to know about translations
2553 $this->checkTranslatedShortcut();
2554 // Request the overlay record for the sys_language_uid:
2555 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2556 if (empty($olRec)) {
2557 // If no OL record exists and a foreign language is asked for...
2558 if ($this->sys_language_uid) {
2559 // If requested translation is not available:
2560 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2561 $this->pageNotFoundAndExit('Page is not available in the requested language.');
2562 } else {
2563 switch ((string)$this->sys_language_mode) {
2564 case 'strict':
2565 $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
2566 break;
2567 case 'content_fallback':
2568 $fallBackOrder = GeneralUtility::intExplode(',', $sys_language_content);
2569 foreach ($fallBackOrder as $orderValue) {
2570 if ((string)$orderValue === '0' || !empty($this->sys_page->getPageOverlay($this->id, $orderValue))) {
2571 $this->sys_language_content = $orderValue;
2572 // Setting content uid (but leaving the sys_language_uid)
2573 break;
2574 }
2575 }
2576 break;
2577 case 'ignore':
2578 $this->sys_language_content = $this->sys_language_uid;
2579 break;
2580 default:
2581 // Default is that everything defaults to the default language...
2582 $this->sys_language_uid = ($this->sys_language_content = 0);
2583 }
2584 }
2585 }
2586 } else {
2587 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2588 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2589 }
2590 }
2591 // Setting sys_language_uid inside sys-page:
2592 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2593 // If default translation is not available:
2594 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2595 $message = 'Page is not available in default language.';
2596 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2597 $this->pageNotFoundAndExit($message);
2598 }
2599 $this->updateRootLinesWithTranslations();
2600
2601 // Finding the ISO code for the currently selected language
2602 // fetched by the sys_language record when not fetching content from the default language
2603 if ($this->sys_language_content > 0) {
2604 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2605 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2606 // avoid versioning overlay to be applied as it generates an SQL error
2607 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2608 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2609 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2610 }
2611 // the DB value is overridden by TypoScript
2612 if (!empty($this->config['config']['sys_language_isocode'])) {
2613 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2614 }
2615 } else {
2616 // fallback to the TypoScript option when rendering with sys_language_uid=0
2617 // also: use "en" by default
2618 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2619 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2620 } else {
2621 $this->sys_language_isocode = $this->lang !== 'default' ? $this->lang : 'en';
2622 }
2623 }
2624
2625 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'])) {
2626 $_params = [];
2627 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] as $_funcRef) {
2628 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2629 }
2630 }
2631 }
2632
2633 /**
2634 * Updating content of the two rootLines IF the language key is set!
2635 */
2636 protected function updateRootLinesWithTranslations()
2637 {
2638 if ($this->sys_language_uid) {
2639 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2640 $this->tmpl->updateRootlineData($this->rootLine);
2641 }
2642 }
2643
2644 /**
2645 * Setting locale for frontend rendering
2646 */
2647 public function settingLocale()
2648 {
2649 // Setting locale
2650 if ($this->config['config']['locale_all']) {
2651 $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2652 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2653 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2654 // @see https://bugs.php.net/bug.php?id=53711
2655 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2656 if ($locale) {
2657 // As str_* methods are locale aware and turkish has no upper case I
2658 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2659 // @see http://bugs.php.net/bug.php?id=35050
2660 if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2661 setlocale(LC_CTYPE, ...$availableLocales);
2662 }
2663 setlocale(LC_MONETARY, ...$availableLocales);
2664 setlocale(LC_TIME, ...$availableLocales);
2665 } else {
2666 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2667 }
2668 }
2669 }
2670
2671 /**
2672 * Checks whether a translated shortcut page has a different shortcut
2673 * target than the original language page.
2674 * If that is the case, things get corrected to follow that alternative
2675 * shortcut
2676 */
2677 protected function checkTranslatedShortcut()
2678 {
2679 if (!is_null($this->originalShortcutPage)) {
2680 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2681 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2682 // the translation of the original shortcut page has a different shortcut target!
2683 // set the correct page and id
2684 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2685 $this->id = ($this->contentPid = $shortcut['uid']);
2686 $this->page = $this->sys_page->getPage($this->id);
2687 // Fix various effects on things like menus f.e.
2688 $this->fetch_the_id();
2689 $this->tmpl->rootLine = array_reverse($this->rootLine);
2690 }
2691 }
2692 }
2693
2694 /**
2695 * Handle data submission
2696 * This is done at this point, because we need the config values
2697 */
2698 public function handleDataSubmission()
2699 {
2700 // Hook for processing data submission to extensions
2701 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'])) {
2702 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $className) {
2703 $_procObj = GeneralUtility::makeInstance($className);
2704 $_procObj->checkDataSubmission($this);
2705 }
2706 }
2707 }
2708
2709 /**
2710 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2711 *
2712 * @see $activeRedirectUrlHandlers
2713 */
2714 public function initializeRedirectUrlHandlers()
2715 {
2716 if (
2717 empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'])
2718 || !is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'])
2719 ) {
2720 return;
2721 }
2722
2723 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'];
2724 foreach ($urlHandlers as $identifier => $configuration) {
2725 if (empty($configuration) || !is_array($configuration)) {
2726 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2727 }
2728 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2729 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2730 }
2731 }
2732
2733 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2734
2735 foreach ($orderedHandlers as $configuration) {
2736 /** @var UrlHandlerInterface $urlHandler */
2737 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2738 if ($urlHandler->canHandleCurrentUrl()) {
2739 $this->activeUrlHandlers[] = $urlHandler;
2740 }
2741 }
2742 }
2743
2744 /**
2745 * Loops over all registered URL handlers and lets them process the current URL.
2746 *
2747 * If no handler has stopped the current process (e.g. by redirecting) and a
2748 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2749 *
2750 * @internal Should be called by the FrontendRequestHandler only.
2751 */
2752 public function redirectToExternalUrl()
2753 {
2754 foreach ($this->activeUrlHandlers as $redirectHandler) {
2755 $redirectHandler->handle();
2756 }
2757
2758 if (!empty($this->activeUrlHandlers)) {
2759 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2760 }
2761 }
2762
2763 /**
2764 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2765 * This feature allows sessions to use a GET-parameter instead of a cookie.
2766 *
2767 * @access private
2768 */
2769 public function setUrlIdToken()
2770 {
2771 if ($this->config['config']['ftu']) {
2772 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2773 } else {
2774 $this->getMethodUrlIdToken = '';
2775 }
2776 }
2777
2778 /**
2779 * Calculates and sets the internal linkVars based upon the current
2780 * $_GET parameters and the setting "config.linkVars".
2781 */
2782 public function calculateLinkVars()
2783 {
2784 $this->linkVars = '';
2785 if (empty($this->config['config']['linkVars'])) {
2786 return;
2787 }
2788
2789 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2790
2791 if (empty($linkVars)) {
2792 return;
2793 }
2794 $getData = GeneralUtility::_GET();
2795 foreach ($linkVars as $linkVar) {
2796 $test = ($value = '');
2797 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2798 $linkVar = trim($match[1]);
2799 $test = trim($match[2]);
2800 }
2801 if ($linkVar === '' || !isset($getData[$linkVar])) {
2802 continue;
2803 }
2804 if (!is_array($getData[$linkVar])) {
2805 $temp = rawurlencode($getData[$linkVar]);
2806 if ($test !== '' && !PageGenerator::isAllowedLinkVarValue($temp, $test)) {
2807 // Error: This value was not allowed for this key
2808 continue;
2809 }
2810 $value = '&' . $linkVar . '=' . $temp;
2811 } else {
2812 if ($test !== '' && $test !== 'array') {
2813 // Error: This key must not be an array!
2814 continue;
2815 }
2816 $value = GeneralUtility::implodeArrayForUrl($linkVar, $getData[$linkVar]);
2817 }
2818 $this->linkVars .= $value;
2819 }
2820 }
2821
2822 /**
2823 * Split the link vars string by "," but not if the "," is inside of braces
2824 *
2825 * @param $string
2826 *
2827 * @return array
2828 */
2829 protected function splitLinkVarsString(string $string): array
2830 {
2831 $tempCommaReplacementString = '###KASPER###';
2832
2833 // replace every "," wrapped in "()" by a "unique" string
2834 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2835 return str_replace(',', $tempCommaReplacementString, $result[0]);
2836 }, $string);
2837
2838 $string = GeneralUtility::trimExplode(',', $string);
2839
2840 // replace all "unique" strings back to ","
2841 return str_replace($tempCommaReplacementString, ',', $string);
2842 }
2843
2844 /**
2845 * Redirect to target page if the current page is an overlaid mountpoint.
2846 *
2847 * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2848 * and is accessed directly, the user will be redirected to the mountpoint context.
2849 */
2850 public function checkPageForMountpointRedirect()
2851 {
2852 if (!empty($this->originalMountPointPage) && $this->originalMountPointPage['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
2853 $this->redirectToCurrentPage();
2854 }
2855 }
2856
2857 /**
2858 * Redirect to target page, if the current page is a Shortcut.
2859 *
2860 * If the current page is of type shortcut and accessed directly via its URL, this function redirects to the
2861 * Shortcut target using a Location header.
2862 */
2863 public function checkPageForShortcutRedirect()
2864 {
2865 if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2866 $this->redirectToCurrentPage();
2867 }
2868 }
2869
2870 /**
2871 * Builds a typolink to the current page, appends the type paremeter if required
2872 * and redirects the user to the generated URL using a Location header.
2873 */
2874 protected function redirectToCurrentPage()
2875 {
2876 $this->calculateLinkVars();
2877 // Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
2878 /** @var $cObj ContentObjectRenderer */
2879 $cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
2880 $parameter = $this->page['uid'];
2881 $type = GeneralUtility::_GET('type');
2882 if ($type && MathUtility::canBeInterpretedAsInteger($type)) {
2883 $parameter .= ',' . $type;
2884 }
2885 $redirectUrl = $cObj->typoLink_URL(['parameter' => $parameter, 'addQueryString' => true,
2886 'addQueryString.' => ['exclude' => 'id']]);
2887
2888 // Prevent redirection loop
2889 if (!empty($redirectUrl)) {
2890 // redirect and exit
2891 HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_307);
2892 }
2893 }
2894
2895 /********************************************
2896 *
2897 * Page generation; cache handling
2898 *
2899 *******************************************/
2900 /**
2901 * Returns TRUE if the page should be generated.
2902 * That is if no URL handler is active and the cacheContentFlag is not set.
2903 *
2904 * @return bool
2905 */
2906 public function isGeneratePage()
2907 {
2908 return !$this->cacheContentFlag && empty($this->activeUrlHandlers);
2909 }
2910
2911 /**
2912 * Temp cache content
2913 * 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.
2914 */
2915 public function tempPageCacheContent()
2916 {
2917 $this->tempContent = false;
2918 if (!$this->no_cache) {
2919 $seconds = 30;
2920 $title = htmlspecialchars($this->tmpl->printTitle($this->page['title']));
2921 $request_uri = htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI'));
2922 $stdMsg = '