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