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