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