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