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