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