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