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