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