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