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