[BUGFIX] Do not try to resolve a path to t3lib
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Controller / TypoScriptFrontendController.php
1 <?php
2 namespace TYPO3\CMS\Frontend\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
18 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
19 use TYPO3\CMS\Core\Cache\CacheManager;
20 use TYPO3\CMS\Core\Charset\CharsetConverter;
21 use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
22 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
23 use TYPO3\CMS\Core\Localization\Locales;
24 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
25 use TYPO3\CMS\Core\Locking\Locker;
26 use TYPO3\CMS\Core\Messaging\ErrorpageMessage;
27 use TYPO3\CMS\Core\Page\PageRenderer;
28 use TYPO3\CMS\Core\Resource\StorageRepository;
29 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
30 use TYPO3\CMS\Core\TypoScript\TemplateService;
31 use TYPO3\CMS\Core\Utility\ArrayUtility;
32 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
33 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
34 use TYPO3\CMS\Core\Locking\LockFactory;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Core\Utility\HttpUtility;
37 use TYPO3\CMS\Core\Utility\MathUtility;
38 use TYPO3\CMS\Core\Utility\StringUtility;
39 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
40 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
41 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
42 use TYPO3\CMS\Frontend\Page\PageGenerator;
43 use TYPO3\CMS\Frontend\Page\PageRepository;
44 use TYPO3\CMS\Frontend\View\AdminPanelView;
45
46 /**
47 * Class for the built TypoScript based frontend. Instantiated in
48 * index_ts.php script as the global object TSFE.
49 *
50 * Main frontend class, instantiated in the index_ts.php script as the global
51 * object TSFE.
52 *
53 * This class has a lot of functions and internal variable which are used from
54 * index_ts.php.
55 *
56 * The class is instantiated as $GLOBALS['TSFE'] in index_ts.php.
57 *
58 * The use of this class should be inspired by the order of function calls as
59 * found in index_ts.php.
60 *
61 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
62 */
63 class TypoScriptFrontendController {
64
65 /**
66 * The page id (int)
67 * @var string
68 */
69 public $id = '';
70
71 /**
72 * The type (read-only)
73 * @var int
74 */
75 public $type = '';
76
77 /**
78 * The submitted cHash
79 * @var string
80 */
81 public $cHash = '';
82
83 /**
84 * Page will not be cached. Write only TRUE. Never clear value (some other
85 * code might have reasons to set it TRUE).
86 * @var bool
87 */
88 public $no_cache = FALSE;
89
90 /**
91 * The rootLine (all the way to tree root, not only the current site!)
92 * @var array
93 */
94 public $rootLine = '';
95
96 /**
97 * The pagerecord
98 * @var array
99 */
100 public $page = '';
101
102 /**
103 * This will normally point to the same value as id, but can be changed to
104 * point to another page from which content will then be displayed instead.
105 * @var int
106 */
107 public $contentPid = 0;
108
109 /**
110 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
111 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
112 * should be redirected to.
113 *
114 * @var array|NULL
115 */
116 protected $originalMountPointPage = NULL;
117
118 /**
119 * Gets set when we are processing a page of type shortcut in the early stages
120 * opf init.php when we do not know about languages yet, used later in init.php
121 * to determine the correct shortcut in case a translation changes the shortcut
122 * target
123 * @var array|NULL
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;
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 // Call post processing function for constructor:
892 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
893 $_params = array('pObj' => &$this);
894 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
895 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
896 }
897 }
898 $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
899 $this->initCaches();
900 }
901
902 /**
903 * @param string $contentType
904 * @internal Should only be used by TYPO3 core for now
905 */
906 public function setContentType($contentType) {
907 $this->contentType = $contentType;
908 }
909
910 /**
911 * Connect to SQL database. May exit after outputting an error message
912 * or some JavaScript redirecting to the install tool.
913 *
914 * @throws \RuntimeException
915 * @throws ServiceUnavailableException
916 * @return void
917 */
918 public function connectToDB() {
919 try {
920 $GLOBALS['TYPO3_DB']->connectDB();
921 } catch (\RuntimeException $exception) {
922 switch ($exception->getCode()) {
923 case 1270853883:
924 // Cannot connect to current database
925 $message = 'Cannot connect to the configured database "' . TYPO3_db . '"';
926 if ($this->checkPageUnavailableHandler()) {
927 $this->pageUnavailableAndExit($message);
928 } else {
929 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
930 throw new ServiceUnavailableException($message, 1301648782);
931 }
932 break;
933 case 1270853884:
934 // Username / password not accepted
935 $message = 'The current username, password or host was not accepted when' . ' the connection to the database was attempted to be established!';
936 if ($this->checkPageUnavailableHandler()) {
937 $this->pageUnavailableAndExit($message);
938 } else {
939 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
940 throw new ServiceUnavailableException('Database Error: ' . $message, 1301648945);
941 }
942 break;
943 default:
944 throw $exception;
945 }
946 }
947 // Call post processing function for DB connection:
948 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'])) {
949 $_params = array('pObj' => &$this);
950 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef) {
951 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
952 }
953 }
954 }
955
956 /**
957 * Looks up the value of $this->RDCT in the database and if it is
958 * found to be associated with a redirect URL then the redirection
959 * is carried out with a 'Location:' header
960 * May exit after sending a location-header.
961 *
962 * @return void
963 */
964 public function sendRedirect() {
965 if ($this->RDCT) {
966 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->RDCT, 'cache_md5params'));
967 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
968 $this->updateMD5paramsRecord($this->RDCT);
969 header('Location: ' . $row['params']);
970 die;
971 }
972 }
973 }
974
975 /**
976 * Gets instance of PageRenderer
977 *
978 * @return PageRenderer
979 */
980 public function getPageRenderer() {
981 if (!isset($this->pageRenderer)) {
982 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
983 $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
984 $this->pageRenderer->setBackPath(TYPO3_mainDir);
985 }
986 return $this->pageRenderer;
987 }
988
989 /**
990 * This is needed for USER_INT processing
991 *
992 * @param PageRenderer $pageRenderer
993 */
994 protected function setPageRenderer(PageRenderer $pageRenderer) {
995 $this->pageRenderer = $pageRenderer;
996 }
997
998 /********************************************
999 *
1000 * Initializing, resolving page id
1001 *
1002 ********************************************/
1003 /**
1004 * Initializes the caching system.
1005 *
1006 * @return void
1007 */
1008 protected function initCaches() {
1009 $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
1010 }
1011
1012 /**
1013 * Initializes the front-end login user.
1014 *
1015 * @return void
1016 */
1017 public function initFEuser() {
1018 $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
1019 $this->fe_user->lockIP = $this->TYPO3_CONF_VARS['FE']['lockIP'];
1020 $this->fe_user->checkPid = $this->TYPO3_CONF_VARS['FE']['checkFeUserPid'];
1021 $this->fe_user->lifetime = (int)$this->TYPO3_CONF_VARS['FE']['lifetime'];
1022 // List of pid's acceptable
1023 $pid = GeneralUtility::_GP('pid');
1024 $this->fe_user->checkPid_value = $pid ? $GLOBALS['TYPO3_DB']->cleanIntList($pid) : 0;
1025 // Check if a session is transferred:
1026 if (GeneralUtility::_GP('FE_SESSION_KEY')) {
1027 $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
1028 // If the session key hash check is OK:
1029 if (md5(($fe_sParts[0] . '/' . $this->TYPO3_CONF_VARS['SYS']['encryptionKey'])) === (string)$fe_sParts[1]) {
1030 $cookieName = FrontendUserAuthentication::getCookieName();
1031 $_COOKIE[$cookieName] = $fe_sParts[0];
1032 if (isset($_SERVER['HTTP_COOKIE'])) {
1033 // See http://forge.typo3.org/issues/27740
1034 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
1035 }
1036 $this->fe_user->forceSetCookie = 1;
1037 $this->fe_user->dontSetCookie = FALSE;
1038 unset($cookieName);
1039 }
1040 }
1041 $this->fe_user->start();
1042 $this->fe_user->unpack_uc('');
1043 // Gets session data
1044 $this->fe_user->fetchSessionData();
1045 $recs = GeneralUtility::_GP('recs');
1046 // If any record registration is submitted, register the record.
1047 if (is_array($recs)) {
1048 $this->fe_user->record_registration($recs, $this->TYPO3_CONF_VARS['FE']['maxSessionDataSize']);
1049 }
1050 // Call hook for possible manipulation of frontend user object
1051 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'])) {
1052 $_params = array('pObj' => &$this);
1053 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef) {
1054 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1055 }
1056 }
1057 // For every 60 seconds the is_online timestamp is updated.
1058 if (is_array($this->fe_user->user) && $this->fe_user->user['uid'] && $this->fe_user->user['is_online'] < $GLOBALS['EXEC_TIME'] - 60) {
1059 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('fe_users', 'uid=' . (int)$this->fe_user->user['uid'], array('is_online' => $GLOBALS['EXEC_TIME']));
1060 }
1061 }
1062
1063 /**
1064 * Initializes the front-end user groups.
1065 * Sets ->loginUser and ->gr_list based on front-end user status.
1066 *
1067 * @return void
1068 */
1069 public function initUserGroups() {
1070 // This affects the hidden-flag selecting the fe_groups for the user!
1071 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
1072 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
1073 $this->fe_user->fetchGroupData();
1074 if (is_array($this->fe_user->user) && count($this->fe_user->groupData['uid'])) {
1075 // global flag!
1076 $this->loginUser = TRUE;
1077 // 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!
1078 $this->gr_list = '0,-2';
1079 $gr_array = $this->fe_user->groupData['uid'];
1080 } else {
1081 $this->loginUser = FALSE;
1082 // 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!
1083 $this->gr_list = '0,-1';
1084 if ($this->loginAllowedInBranch) {
1085 // 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.
1086 $gr_array = $this->fe_user->groupData['uid'];
1087 } else {
1088 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
1089 $gr_array = array();
1090 }
1091 }
1092 // Clean up.
1093 // Make unique...
1094 $gr_array = array_unique($gr_array);
1095 // sort
1096 sort($gr_array);
1097 if (count($gr_array) && !$this->loginAllowedInBranch_mode) {
1098 $this->gr_list .= ',' . implode(',', $gr_array);
1099 }
1100 if ($this->fe_user->writeDevLog) {
1101 GeneralUtility::devLog('Valid usergroups for TSFE: ' . $this->gr_list, __CLASS__);
1102 }
1103 }
1104
1105 /**
1106 * Checking if a user is logged in or a group constellation different from "0,-1"
1107 *
1108 * @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!)
1109 */
1110 public function isUserOrGroupSet() {
1111 return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
1112 }
1113
1114 /**
1115 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
1116 *
1117 * Two options:
1118 * 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)
1119 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
1120 *
1121 * @return void
1122 */
1123 public function checkAlternativeIdMethods() {
1124 $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
1125 // Call post processing function for custom URL methods.
1126 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
1127 $_params = array('pObj' => &$this);
1128 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef) {
1129 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Clears the preview-flags, sets sim_exec_time to current time.
1136 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
1137 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
1138 *
1139 * @return void
1140 */
1141 public function clear_preview() {
1142 $this->showHiddenPage = FALSE;
1143 $this->showHiddenRecords = FALSE;
1144 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1145 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1146 $this->fePreview = 0;
1147 }
1148
1149 /**
1150 * Checks if a backend user is logged in
1151 *
1152 * @return bool whether a backend user is logged in
1153 */
1154 public function isBackendUserLoggedIn() {
1155 return (bool)$this->beUserLogin;
1156 }
1157
1158 /**
1159 * Creates the backend user object and returns it.
1160 *
1161 * @return FrontendBackendUserAuthentication the backend user object
1162 */
1163 public function initializeBackendUser() {
1164 // PRE BE_USER HOOK
1165 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'])) {
1166 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] as $_funcRef) {
1167 $_params = array();
1168 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1169 }
1170 }
1171 /** @var $BE_USER FrontendBackendUserAuthentication */
1172 $BE_USER = NULL;
1173 // If the backend cookie is set,
1174 // we proceed and check if a backend user is logged in.
1175 if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1176 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(TRUE);
1177 $GLOBALS['TT']->push('Back End user initialized', '');
1178 // @todo validate the comment below: is this necessary? if so,
1179 // formfield_status should be set to "" in \TYPO3\CMS\Backend\FrontendBackendUserAuthentication
1180 // which is a subclass of \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1181 // ----
1182 // the value this->formfield_status is set to empty in order to
1183 // disable login-attempts to the backend account through this script
1184 // New backend user object
1185 $BE_USER = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1186 $BE_USER->lockIP = $this->TYPO3_CONF_VARS['BE']['lockIP'];
1187 // Object is initialized
1188 $BE_USER->start();
1189 $BE_USER->unpack_uc('');
1190 if (!empty($BE_USER->user['uid'])) {
1191 $BE_USER->fetchGroupData();
1192 $this->beUserLogin = TRUE;
1193 }
1194 // Unset the user initialization.
1195 if (!$BE_USER->checkLockToIP() || !$BE_USER->checkBackendAccessSettingsFromInitPhp() || empty($BE_USER->user['uid'])) {
1196 $BE_USER = NULL;
1197 $this->beUserLogin = FALSE;
1198 }
1199 $GLOBALS['TT']->pull();
1200 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(TRUE);
1201 }
1202 // POST BE_USER HOOK
1203 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'])) {
1204 $_params = array(
1205 'BE_USER' => &$BE_USER
1206 );
1207 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] as $_funcRef) {
1208 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1209 }
1210 }
1211 return $BE_USER;
1212 }
1213
1214 /**
1215 * Determines the id and evaluates any preview settings
1216 * 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.
1217 *
1218 * @return void
1219 */
1220 public function determineId() {
1221 // Call pre processing function for id determination
1222 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'])) {
1223 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] as $functionReference) {
1224 $parameters = array('parentObject' => $this);
1225 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1226 }
1227 }
1228 // Getting ARG-v values if some
1229 $this->setIDfromArgV();
1230 // If there is a Backend login we are going to check for any preview settings:
1231 $GLOBALS['TT']->push('beUserLogin', '');
1232 $originalFrontendUser = NULL;
1233 if ($this->beUserLogin || $this->doWorkspacePreview()) {
1234 // Backend user preview features:
1235 if ($this->beUserLogin && $GLOBALS['BE_USER']->adminPanel instanceof AdminPanelView) {
1236 $this->fePreview = (bool)$GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview');
1237 // If admin panel preview is enabled...
1238 if ($this->fePreview) {
1239 if ($this->fe_user->user) {
1240 $originalFrontendUser = $this->fe_user->user;
1241 }
1242 $this->showHiddenPage = (bool)$GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1243 $this->showHiddenRecords = (bool)$GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1244 // Simulate date
1245 $simTime = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1246 if ($simTime) {
1247 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1248 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1249 }
1250 // simulate user
1251 $simUserGroup = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1252 $this->simUserGroup = $simUserGroup;
1253 if ($simUserGroup) {
1254 if ($this->fe_user->user) {
1255 $this->fe_user->user[$this->fe_user->usergroup_column] = $simUserGroup;
1256 } else {
1257 $this->fe_user->user = array(
1258 $this->fe_user->usergroup_column => $simUserGroup
1259 );
1260 }
1261 }
1262 if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1263 $this->fePreview = 0;
1264 }
1265 }
1266 }
1267 if ($this->id) {
1268 if ($this->determineIdIsHiddenPage()) {
1269 // The preview flag is set only if the current page turns out to actually be hidden!
1270 $this->fePreview = 1;
1271 $this->showHiddenPage = TRUE;
1272 }
1273 // For Live workspace: Check root line for proper connection to tree root (done because of possible preview of page / branch versions)
1274 if (!$this->fePreview && $this->whichWorkspace() === 0) {
1275 // Initialize the page-select functions to check rootline:
1276 $temp_sys_page = GeneralUtility::makeInstance(PageRepository::class);
1277 $temp_sys_page->init($this->showHiddenPage);
1278 // If root line contained NO records and ->error_getRootLine_failPid tells us that it was because of a pid=-1 (indicating a "version" record)...:
1279 if (!count($temp_sys_page->getRootLine($this->id, $this->MP)) && $temp_sys_page->error_getRootLine_failPid == -1) {
1280 // Setting versioningPreview flag and try again:
1281 $temp_sys_page->versioningPreview = TRUE;
1282 if (count($temp_sys_page->getRootLine($this->id, $this->MP))) {
1283 // 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.
1284 $this->fePreview = 1;
1285 }
1286 }
1287 }
1288 }
1289 // The preview flag will be set if a backend user is in an offline workspace
1290 if (
1291 (
1292 $GLOBALS['BE_USER']->user['workspace_preview']
1293 || GeneralUtility::_GP('ADMCMD_view')
1294 || $this->doWorkspacePreview()
1295 )
1296 && (
1297 $this->whichWorkspace() === -1
1298 || $this->whichWorkspace() > 0
1299 )
1300 && !GeneralUtility::_GP('ADMCMD_noBeUser')
1301 ) {
1302 // Will show special preview message.
1303 $this->fePreview = 2;
1304 }
1305 // If the front-end is showing a preview, caching MUST be disabled.
1306 if ($this->fePreview) {
1307 $this->disableCache();
1308 }
1309 }
1310 $GLOBALS['TT']->pull();
1311 // Now, get the id, validate access etc:
1312 $this->fetch_the_id();
1313 // Check if backend user has read access to this page. If not, recalculate the id.
1314 if ($this->beUserLogin && $this->fePreview) {
1315 if (!$GLOBALS['BE_USER']->doesUserHaveAccess($this->page, 1)) {
1316 // Resetting
1317 $this->clear_preview();
1318 $this->fe_user->user = $originalFrontendUser;
1319 // Fetching the id again, now with the preview settings reset.
1320 $this->fetch_the_id();
1321 }
1322 }
1323 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1324 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1325 // Logins are not allowed:
1326 if (!$this->loginAllowedInBranch) {
1327 // Only if there is a login will we run this...
1328 if ($this->isUserOrGroupSet()) {
1329 if ($this->loginAllowedInBranch_mode == 'all') {
1330 // Clear out user and group:
1331 $this->fe_user->hideActiveLogin();
1332 $this->gr_list = '0,-1';
1333 } else {
1334 $this->gr_list = '0,-2';
1335 }
1336 // Fetching the id again, now with the preview settings reset.
1337 $this->fetch_the_id();
1338 }
1339 }
1340 // Final cleaning.
1341 // Make sure it's an integer
1342 $this->id = ($this->contentPid = (int)$this->id);
1343 // Make sure it's an integer
1344 $this->type = (int)$this->type;
1345 // Call post processing function for id determination:
1346 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
1347 $_params = array('pObj' => &$this);
1348 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef) {
1349 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1350 }
1351 }
1352 }
1353
1354 /**
1355 * Checks if the page is hidden in the active workspace.
1356 * If it is hidden, preview flags will be set.
1357 *
1358 * @return bool
1359 */
1360 protected function determineIdIsHiddenPage() {
1361 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1362 $pageSelectCondition = $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, 'pages');
1363 $page = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('uid,hidden,starttime,endtime', 'pages', $pageSelectCondition . ' AND pid>=0 AND deleted=0');
1364 $workspace = $this->whichWorkspace();
1365 if ($workspace !== 0 && $workspace !== FALSE) {
1366 // Fetch overlay of page if in workspace and check if it is hidden
1367 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1368 $pageSelectObject->versioningPreview = TRUE;
1369 $pageSelectObject->init(FALSE);
1370 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1371 $result = $targetPage === -1 || $targetPage === -2;
1372 } else {
1373 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1374 }
1375 return $result;
1376 }
1377
1378 /**
1379 * Get The Page ID
1380 * This gets the id of the page, checks if the page is in the domain and if the page is accessible
1381 * Sets variables such as $this->sys_page, $this->loginUser, $this->gr_list, $this->id, $this->type, $this->domainStartPage
1382 *
1383 * @throws ServiceUnavailableException
1384 * @return void
1385 * @access private
1386 */
1387 public function fetch_the_id() {
1388 $GLOBALS['TT']->push('fetch_the_id initialize/', '');
1389 // Initialize the page-select functions.
1390 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1391 $this->sys_page->versioningPreview = $this->fePreview === 2 || (int)$this->workspacePreview || (bool)GeneralUtility::_GP('ADMCMD_view');
1392 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1393 $this->sys_page->init($this->showHiddenPage);
1394 // Set the valid usergroups for FE
1395 $this->initUserGroups();
1396 // Sets sys_page where-clause
1397 $this->setSysPageWhereClause();
1398 // Splitting $this->id by a period (.).
1399 // First part is 'id' and second part (if exists) will overrule the &type param
1400 $idParts = explode('.', $this->id, 2);
1401 $this->id = $idParts[0];
1402 if (isset($idParts[1])) {
1403 $this->type = $idParts[1];
1404 }
1405
1406 // If $this->id is a string, it's an alias
1407 $this->checkAndSetAlias();
1408 // The id and type is set to the integer-value - just to be sure...
1409 $this->id = (int)$this->id;
1410 $this->type = (int)$this->type;
1411 $GLOBALS['TT']->pull();
1412 // We find the first page belonging to the current domain
1413 $GLOBALS['TT']->push('fetch_the_id domain/', '');
1414 // The page_id of the current domain
1415 $this->domainStartPage = $this->findDomainRecord($this->TYPO3_CONF_VARS['SYS']['recursiveDomainSearch']);
1416 if (!$this->id) {
1417 if ($this->domainStartPage) {
1418 // If the id was not previously set, set it to the id of the domain.
1419 $this->id = $this->domainStartPage;
1420 } else {
1421 // Find the first 'visible' page in that domain
1422 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1423 if ($theFirstPage) {
1424 $this->id = $theFirstPage['uid'];
1425 } else {
1426 $message = 'No pages are found on the rootlevel!';
1427 if ($this->checkPageUnavailableHandler()) {
1428 $this->pageUnavailableAndExit($message);
1429 } else {
1430 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1431 throw new ServiceUnavailableException($message, 1301648975);
1432 }
1433 }
1434 }
1435 }
1436 $GLOBALS['TT']->pull();
1437 $GLOBALS['TT']->push('fetch_the_id rootLine/', '');
1438 // We store the originally requested id
1439 $this->requestedId = $this->id;
1440 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1441 $GLOBALS['TT']->pull();
1442 if ($this->pageNotFound && $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
1443 $pNotFoundMsg = array(
1444 1 => 'ID was not an accessible page',
1445 2 => 'Subsection was found and not accessible',
1446 3 => 'ID was outside the domain',
1447 4 => 'The requested page alias does not exist'
1448 );
1449 $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound]);
1450 }
1451 if ($this->page['url_scheme'] > 0) {
1452 $newUrl = '';
1453 $requestUrlScheme = parse_url(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'), PHP_URL_SCHEME);
1454 if ((int)$this->page['url_scheme'] === HttpUtility::SCHEME_HTTP && $requestUrlScheme == 'https') {
1455 $newUrl = 'http://' . substr(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'), 8);
1456 } elseif ((int)$this->page['url_scheme'] === HttpUtility::SCHEME_HTTPS && $requestUrlScheme == 'http') {
1457 $newUrl = 'https://' . substr(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'), 7);
1458 }
1459 if ($newUrl !== '') {
1460 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
1461 $headerCode = HttpUtility::HTTP_STATUS_303;
1462 } else {
1463 $headerCode = HttpUtility::HTTP_STATUS_301;
1464 }
1465 HttpUtility::redirect($newUrl, $headerCode);
1466 }
1467 }
1468 // Set no_cache if set
1469 if ($this->page['no_cache']) {
1470 $this->set_no_cache('no_cache is set in page properties');
1471 }
1472 // Init SYS_LASTCHANGED
1473 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1474 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1475 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1476 }
1477 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'])) {
1478 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] as $functionReference) {
1479 $parameters = array('parentObject' => $this);
1480 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1481 }
1482 }
1483 }
1484
1485 /**
1486 * Gets the page and rootline arrays based on the id, $this->id
1487 *
1488 * If the id does not correspond to a proper page, the 'previous' valid page in the rootline is found
1489 * If the page is a shortcut (doktype=4), the ->id is loaded with that id
1490 *
1491 * 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.
1492 *
1493 * Sets or manipulates internal variables such as: $this->id, $this->page, $this->rootLine, $this->MP, $this->pageNotFound
1494 *
1495 * @throws ServiceUnavailableException
1496 * @throws PageNotFoundException
1497 * @return void
1498 * @access private
1499 */
1500 public function getPageAndRootline() {
1501 $this->page = $this->sys_page->getPage($this->id);
1502 if (!count($this->page)) {
1503 // If no page, we try to find the page before in the rootLine.
1504 // Page is 'not found' in case the id itself was not an accessible page. code 1
1505 $this->pageNotFound = 1;
1506 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1507 if (count($this->rootLine)) {
1508 $c = count($this->rootLine) - 1;
1509 while ($c > 0) {
1510 // Add to page access failure history:
1511 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1512 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1513 $c--;
1514 $this->id = $this->rootLine[$c]['uid'];
1515 $this->page = $this->sys_page->getPage($this->id);
1516 if (count($this->page)) {
1517 break;
1518 }
1519 }
1520 }
1521 // If still no page...
1522 if (!count($this->page)) {
1523 $message = 'The requested page does not exist!';
1524 if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
1525 $this->pageNotFoundAndExit($message);
1526 } else {
1527 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1528 throw new PageNotFoundException($message, 1301648780);
1529 }
1530 }
1531 }
1532 // Spacer is not accessible in frontend
1533 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1534 $message = 'The requested page does not exist!';
1535 if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
1536 $this->pageNotFoundAndExit($message);
1537 } else {
1538 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1539 throw new PageNotFoundException($message, 1301648781);
1540 }
1541 }
1542 // Is the ID a link to another page??
1543 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1544 // 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.
1545 $this->MP = '';
1546 // saving the page so that we can check later - when we know
1547 // about languages - whether we took the correct shortcut or
1548 // whether a translation of the page overwrites the shortcut
1549 // target and we need to follow the new target
1550 $this->originalShortcutPage = $this->page;
1551 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1552 $this->id = $this->page['uid'];
1553 }
1554 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1555 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1556 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1557 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1558 $this->originalMountPointPage = $this->page;
1559 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1560 if (empty($this->page)) {
1561 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1562 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1563 throw new PageNotFoundException($message, 1402043263);
1564 }
1565 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1566 $this->id = $this->page['uid'];
1567 }
1568 // Gets the rootLine
1569 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1570 // If not rootline we're off...
1571 if (!count($this->rootLine)) {
1572 $ws = $this->whichWorkspace();
1573 if ($this->sys_page->error_getRootLine_failPid == -1 && $ws) {
1574 $this->sys_page->versioningPreview = TRUE;
1575 $this->versioningWorkspaceId = $ws;
1576 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1577 }
1578 if (!count($this->rootLine)) {
1579 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1580 if ($this->checkPageUnavailableHandler()) {
1581 $this->pageUnavailableAndExit($message);
1582 } else {
1583 $rootline = '(' . $this->sys_page->error_getRootLine . ')';
1584 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1585 throw new ServiceUnavailableException($message . '<br /><br />' . $rootline, 1301648167);
1586 }
1587 }
1588 $this->fePreview = 1;
1589 }
1590 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1591 if ($this->checkRootlineForIncludeSection()) {
1592 if (!count($this->rootLine)) {
1593 $message = 'The requested page was not accessible!';
1594 if ($this->checkPageUnavailableHandler()) {
1595 $this->pageUnavailableAndExit($message);
1596 } else {
1597 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1598 throw new ServiceUnavailableException($message, 1301648234);
1599 }
1600 } else {
1601 $el = reset($this->rootLine);
1602 $this->id = $el['uid'];
1603 $this->page = $this->sys_page->getPage($this->id);
1604 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1605 }
1606 }
1607 }
1608
1609 /**
1610 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1611 *
1612 * @param int $SC The value of the "shortcut" field from the pages record
1613 * @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
1614 * @param int $thisUid The current page UID of the page which is a shortcut
1615 * @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...)
1616 * @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.
1617 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1618 * @throws \RuntimeException
1619 * @throws PageNotFoundException
1620 * @return mixed Returns the page record of the page that the shortcut pointed to.
1621 * @access private
1622 * @see getPageAndRootline()
1623 */
1624 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = array(), $disableGroupCheck = FALSE) {
1625 $idArray = GeneralUtility::intExplode(',', $SC);
1626 // Find $page record depending on shortcut mode:
1627 switch ($mode) {
1628 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1629
1630 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1631 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1632 $pO = 0;
1633 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && count($pageArray)) {
1634 $randval = (int)rand(0, count($pageArray) - 1);
1635 $pO = $randval;
1636 }
1637 $c = 0;
1638 foreach ($pageArray as $pV) {
1639 if ($c == $pO) {
1640 $page = $pV;
1641 break;
1642 }
1643 $c++;
1644 }
1645 if (count($page) == 0) {
1646 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1647 throw new PageNotFoundException($message, 1301648328);
1648 }
1649 break;
1650 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1651 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1652 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1653 if (count($page) == 0) {
1654 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1655 throw new PageNotFoundException($message, 1301648358);
1656 }
1657 break;
1658 default:
1659 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1660 if (count($page) == 0) {
1661 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1662 throw new PageNotFoundException($message, 1301648404);
1663 }
1664 }
1665 // Check if short cut page was a shortcut itself, if so look up recursively:
1666 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1667 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1668 $pageLog[] = $page['uid'];
1669 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1670 } else {
1671 $pageLog[] = $page['uid'];
1672 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1673 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
1674 throw new \RuntimeException($message, 1294587212);
1675 }
1676 }
1677 // Return resulting page:
1678 return $page;
1679 }
1680
1681 /**
1682 * Checks the current rootline for defined sections.
1683 *
1684 * @return bool
1685 * @access private
1686 */
1687 public function checkRootlineForIncludeSection() {
1688 $c = count($this->rootLine);
1689 $removeTheRestFlag = 0;
1690 for ($a = 0; $a < $c; $a++) {
1691 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1692 // Add to page access failure history:
1693 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1694 $removeTheRestFlag = 1;
1695 }
1696 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1697 // If there is a backend user logged in, check if he has read access to the page:
1698 if ($this->beUserLogin) {
1699 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid=' . (int)$this->id . ' AND ' . $GLOBALS['BE_USER']->getPagePermsClause(1));
1700 // versionOL()?
1701 list($isPage) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
1702 if (!$isPage) {
1703 // 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...
1704 $removeTheRestFlag = 1;
1705 }
1706 } else {
1707 // Dont go here, if there is no backend user logged in.
1708 $removeTheRestFlag = 1;
1709 }
1710 }
1711 if ($removeTheRestFlag) {
1712 // Page is 'not found' in case a subsection was found and not accessible, code 2
1713 $this->pageNotFound = 2;
1714 unset($this->rootLine[$a]);
1715 }
1716 }
1717 return $removeTheRestFlag;
1718 }
1719
1720 /**
1721 * Checks page record for enableFields
1722 * Returns TRUE if enableFields does not disable the page record.
1723 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1724 *
1725 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1726 * @param bool $bypassGroupCheck Bypass group-check
1727 * @return bool TRUE, if record is viewable.
1728 * @see TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1729 */
1730 public function checkEnableFields($row, $bypassGroupCheck = FALSE) {
1731 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'])) {
1732 $_params = array('pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck);
1733 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] as $_funcRef) {
1734 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1735 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1736 if ($return === FALSE) {
1737 return FALSE;
1738 }
1739 }
1740 }
1741 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1742 return TRUE;
1743 }
1744 }
1745
1746 /**
1747 * Check group access against a page record
1748 *
1749 * @param array $row The page record to evaluate (needs field: fe_group)
1750 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1751 * @return bool TRUE, if group access is granted.
1752 * @access private
1753 */
1754 public function checkPageGroupAccess($row, $groupList = NULL) {
1755 if (is_null($groupList)) {
1756 $groupList = $this->gr_list;
1757 }
1758 if (!is_array($groupList)) {
1759 $groupList = explode(',', $groupList);
1760 }
1761 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1762 return count(array_intersect($groupList, $pageGroupList)) > 0;
1763 }
1764
1765 /**
1766 * Checks page record for include section
1767 *
1768 * @param array $row The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
1769 * @return bool Returns TRUE if either extendToSubpages is not checked or if the enableFields does not disable the page record.
1770 * @access private
1771 * @see checkEnableFields(), TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer::getTreeList(), checkRootlineForIncludeSection()
1772 */
1773 public function checkPagerecordForIncludeSection($row) {
1774 return !$row['extendToSubpages'] || $this->checkEnableFields($row) ? 1 : 0;
1775 }
1776
1777 /**
1778 * 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!)
1779 *
1780 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1781 */
1782 public function checkIfLoginAllowedInBranch() {
1783 // Initialize:
1784 $c = count($this->rootLine);
1785 $disable = FALSE;
1786 // Traverse root line from root and outwards:
1787 for ($a = 0; $a < $c; $a++) {
1788 // If a value is set for login state:
1789 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1790 // Determine state from value:
1791 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1792 $disable = TRUE;
1793 $this->loginAllowedInBranch_mode = 'all';
1794 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1795 $disable = TRUE;
1796 $this->loginAllowedInBranch_mode = 'groups';
1797 } else {
1798 $disable = FALSE;
1799 }
1800 }
1801 }
1802 return !$disable;
1803 }
1804
1805 /**
1806 * 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
1807 *
1808 * @return array Summary of why page access was not allowed.
1809 */
1810 public function getPageAccessFailureReasons() {
1811 $output = array();
1812 $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());
1813 if (count($combinedRecords)) {
1814 foreach ($combinedRecords as $k => $pagerec) {
1815 // 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
1816 // 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!
1817 if (!$k || $pagerec['extendToSubpages']) {
1818 if ($pagerec['hidden']) {
1819 $output['hidden'][$pagerec['uid']] = TRUE;
1820 }
1821 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1822 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1823 }
1824 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1825 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1826 }
1827 if (!$this->checkPageGroupAccess($pagerec)) {
1828 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1829 }
1830 }
1831 }
1832 }
1833 return $output;
1834 }
1835
1836 /**
1837 * This checks if there are ARGV-parameters in the QUERY_STRING and if so, those are used for the id
1838 * $this->id must be 'FALSE' in order for any processing to happen in here
1839 * If an id/alias value is extracted from the QUERY_STRING it is set in $this->id
1840 *
1841 * @return void
1842 * @access private
1843 */
1844 public function setIDfromArgV() {
1845 if (!$this->id) {
1846 list($theAlias) = explode('&', GeneralUtility::getIndpEnv('QUERY_STRING'));
1847 $theAlias = trim($theAlias);
1848 $this->id = $theAlias != '' && strpos($theAlias, '=') === FALSE ? $theAlias : 0;
1849 }
1850 }
1851
1852 /**
1853 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1854 * If not inside domain, then default to first page in domain.
1855 *
1856 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1857 * @return void
1858 * @access private
1859 */
1860 public function getPageAndRootlineWithDomain($domainStartPage) {
1861 $this->getPageAndRootline();
1862 // 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.
1863 if ($domainStartPage && is_array($this->rootLine)) {
1864 $idFound = 0;
1865 foreach ($this->rootLine as $key => $val) {
1866 if ($val['uid'] == $domainStartPage) {
1867 $idFound = 1;
1868 break;
1869 }
1870 }
1871 if (!$idFound) {
1872 // Page is 'not found' in case the id was outside the domain, code 3
1873 $this->pageNotFound = 3;
1874 $this->id = $domainStartPage;
1875 // re-get the page and rootline if the id was not found.
1876 $this->getPageAndRootline();
1877 }
1878 }
1879 }
1880
1881 /**
1882 * Sets sys_page where-clause
1883 *
1884 * @return void
1885 * @access private
1886 */
1887 public function setSysPageWhereClause() {
1888 $this->sys_page->where_hid_del .= ' AND pages.doktype<200';
1889 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1890 }
1891
1892 /**
1893 * Looking up a domain record based on HTTP_HOST
1894 *
1895 * @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.
1896 * @return int Returns the page id of the page where the domain record was found.
1897 * @access private
1898 */
1899 public function findDomainRecord($recursive = FALSE) {
1900 if ($recursive) {
1901 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1902 while (count($host)) {
1903 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1904 if ($pageUid) {
1905 return $pageUid;
1906 } else {
1907 array_shift($host);
1908 }
1909 }
1910 return $pageUid;
1911 } else {
1912 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1913 }
1914 }
1915
1916 /**
1917 * Page unavailable handler for use in frontend plugins from extensions.
1918 *
1919 * @param string $reason Reason text
1920 * @param string $header HTTP header to send
1921 * @return void Function exits.
1922 */
1923 public function pageUnavailableAndExit($reason = '', $header = '') {
1924 $header = $header ?: $this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling_statheader'];
1925 $this->pageUnavailableHandler($this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling'], $header, $reason);
1926 die;
1927 }
1928
1929 /**
1930 * Page-not-found handler for use in frontend plugins from extensions.
1931 *
1932 * @param string $reason Reason text
1933 * @param string $header HTTP header to send
1934 * @return void Function exits.
1935 */
1936 public function pageNotFoundAndExit($reason = '', $header = '') {
1937 $header = $header ?: $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling_statheader'];
1938 $this->pageNotFoundHandler($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'], $header, $reason);
1939 die;
1940 }
1941
1942 /**
1943 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1944 * and devIPMask must not match the current visitor's IP address.
1945 *
1946 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1947 */
1948 public function checkPageUnavailableHandler() {
1949 if (
1950 $this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling']
1951 && !GeneralUtility::cmpIP(
1952 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1953 $this->TYPO3_CONF_VARS['SYS']['devIPmask']
1954 )
1955 ) {
1956 $checkPageUnavailableHandler = TRUE;
1957 } else {
1958 $checkPageUnavailableHandler = FALSE;
1959 }
1960 return $checkPageUnavailableHandler;
1961 }
1962
1963 /**
1964 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1965 *
1966 * @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.
1967 * @param string $header If set, this is passed directly to the PHP function, header()
1968 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1969 * @return void (The function exits!)
1970 */
1971 public function pageUnavailableHandler($code, $header, $reason) {
1972 $this->pageErrorHandler($code, $header, $reason);
1973 }
1974
1975 /**
1976 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1977 *
1978 * @param mixed $code Which type of handling; If a true PHP-boolean or TRUE then a \TYPO3\CMS\Core\Messaging\ErrorpageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
1979 * @param string $header If set, this is passed directly to the PHP function, header()
1980 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1981 * @return void (The function exits!)
1982 */
1983 public function pageNotFoundHandler($code, $header = '', $reason = '') {
1984 $this->pageErrorHandler($code, $header, $reason);
1985 }
1986
1987 /**
1988 * Generic error page handler.
1989 * Exits.
1990 *
1991 * @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.
1992 * @param string $header If set, this is passed directly to the PHP function, header()
1993 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1994 * @throws \RuntimeException
1995 * @return void (The function exits!)
1996 */
1997 public function pageErrorHandler($code, $header = '', $reason = '') {
1998 // Issue header in any case:
1999 if ($header) {
2000 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2001 foreach ($headerArr as $header) {
2002 header($header);
2003 }
2004 }
2005 // Create response:
2006 // Simply boolean; Just shows TYPO3 error page with reason:
2007 if (gettype($code) == 'boolean' || (string)$code === '1') {
2008 $title = 'Page Not Found';
2009 $message = 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . htmlspecialchars($reason) : '');
2010 $messagePage = GeneralUtility::makeInstance(ErrorpageMessage::class, $message, $title);
2011 $messagePage->output();
2012 die;
2013 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
2014 $funcRef = trim(substr($code, 14));
2015 $params = array(
2016 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
2017 'reasonText' => $reason,
2018 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
2019 );
2020 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
2021 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
2022 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
2023 if (@is_file($readFile)) {
2024 echo str_replace(
2025 array(
2026 '###CURRENT_URL###',
2027 '###REASON###'
2028 ),
2029 array(
2030 GeneralUtility::getIndpEnv('REQUEST_URI'),
2031 htmlspecialchars($reason)
2032 ),
2033 GeneralUtility::getUrl($readFile)
2034 );
2035 } else {
2036 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2037 }
2038 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
2039 HttpUtility::redirect(substr($code, 9));
2040 } elseif ($code !== '') {
2041 // Check if URL is relative
2042 $url_parts = parse_url($code);
2043 if ($url_parts['host'] == '') {
2044 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
2045 if ($code[0] === '/') {
2046 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2047 } else {
2048 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2049 }
2050 $checkBaseTag = FALSE;
2051 } else {
2052 $checkBaseTag = TRUE;
2053 }
2054 // Check recursion
2055 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2056 if ($reason == '') {
2057 $reason = 'Page cannot be found.';
2058 }
2059 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2060 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2061 }
2062 // Prepare headers
2063 $headerArr = array(
2064 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2065 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2066 );
2067 $res = GeneralUtility::getUrl($code, 1, $headerArr);
2068 // Header and content are separated by an empty line
2069 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2070 $content .= CRLF;
2071 if (FALSE === $res) {
2072 // Last chance -- redirect
2073 HttpUtility::redirect($code);
2074 } else {
2075 // Forward these response headers to the client
2076 $forwardHeaders = array(
2077 'Content-Type:'
2078 );
2079 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2080 foreach ($headerArr as $header) {
2081 foreach ($forwardHeaders as $h) {
2082 if (preg_match('/^' . $h . '/', $header)) {
2083 header($header);
2084 }
2085 }
2086 }
2087 // Put <base> if necesary
2088 if ($checkBaseTag) {
2089 // If content already has <base> tag, we do not need to do anything
2090 if (FALSE === stristr($content, '<base ')) {
2091 // Generate href for base tag
2092 $base = $url_parts['scheme'] . '://';
2093 if ($url_parts['user'] != '') {
2094 $base .= $url_parts['user'];
2095 if ($url_parts['pass'] != '') {
2096 $base .= ':' . $url_parts['pass'];
2097 }
2098 $base .= '@';
2099 }
2100 $base .= $url_parts['host'];
2101 // Add path portion skipping possible file name
2102 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2103 // Put it into content (generate also <head> if necessary)
2104 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2105 if (stristr($content, '<head>')) {
2106 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2107 } else {
2108 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2109 }
2110 }
2111 }
2112 // Output the content
2113 echo $content;
2114 }
2115 } else {
2116 $title = 'Page Not Found';
2117 $message = $reason ? 'Reason: ' . htmlspecialchars($reason) : 'Page cannot be found.';
2118 $messagePage = GeneralUtility::makeInstance(ErrorpageMessage::class, $message, $title);
2119 $messagePage->output();
2120 }
2121 die;
2122 }
2123
2124 /**
2125 * Fetches the integer page id for a page alias.
2126 * 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
2127 *
2128 * @return void
2129 * @access private
2130 */
2131 public function checkAndSetAlias() {
2132 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2133 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2134 if ($aid) {
2135 $this->id = $aid;
2136 } else {
2137 $this->pageNotFound = 4;
2138 }
2139 }
2140 }
2141
2142 /**
2143 * Merging values into the global $_GET
2144 *
2145 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2146 * @return void
2147 */
2148 public function mergingWithGetVars($GET_VARS) {
2149 if (is_array($GET_VARS)) {
2150 // Getting $_GET var, unescaped.
2151 $realGet = GeneralUtility::_GET();
2152 if (!is_array($realGet)) {
2153 $realGet = array();
2154 }
2155 // Merge new values on top:
2156 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2157 // Write values back to $_GET:
2158 GeneralUtility::_GETset($realGet);
2159 // Setting these specifically (like in the init-function):
2160 if (isset($GET_VARS['type'])) {
2161 $this->type = (int)$GET_VARS['type'];
2162 }
2163 if (isset($GET_VARS['cHash'])) {
2164 $this->cHash = $GET_VARS['cHash'];
2165 }
2166 if (isset($GET_VARS['jumpurl'])) {
2167 $this->jumpurl = $GET_VARS['jumpurl'];
2168 }
2169 if (isset($GET_VARS['MP'])) {
2170 $this->MP = $this->TYPO3_CONF_VARS['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2171 }
2172 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2173 $this->set_no_cache('no_cache is requested via GET parameter');
2174 }
2175 }
2176 }
2177
2178 /********************************************
2179 *
2180 * Template and caching related functions.
2181 *
2182 *******************************************/
2183 /**
2184 * Calculates a hash string based on additional parameters in the url.
2185 *
2186 * Calculated hash is stored in $this->cHash_array.
2187 * This is used to cache pages with more parameters than just id and type.
2188 *
2189 * @return void
2190 * @see reqCHash()
2191 */
2192 public function makeCacheHash() {
2193 // No need to test anything if caching was already disabled.
2194 if ($this->no_cache && !$this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
2195 return;
2196 }
2197 $GET = GeneralUtility::_GET();
2198 if ($this->cHash && is_array($GET)) {
2199 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2200 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2201 if ($cHash_calc != $this->cHash) {
2202 if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
2203 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
2204 } else {
2205 $this->disableCache();
2206 $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);
2207 }
2208 }
2209 } elseif (is_array($GET)) {
2210 // No cHash is set, check if that is correct
2211 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2212 $this->reqCHash();
2213 }
2214 }
2215 }
2216
2217 /**
2218 * Will disable caching if the cHash value was not set.
2219 * 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)
2220 *
2221 * @return void
2222 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2223 */
2224 public function reqCHash() {
2225 if (!$this->cHash) {
2226 if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
2227 if ($this->tempContent) {
2228 $this->clearPageCacheContent();
2229 }
2230 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
2231 } else {
2232 $this->disableCache();
2233 $GLOBALS['TT']->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2234 }
2235 }
2236 }
2237
2238 /**
2239 * Initialize the TypoScript template parser
2240 *
2241 * @return void
2242 */
2243 public function initTemplate() {
2244 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2245 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2246 $this->tmpl->init();
2247 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2248 }
2249
2250 /**
2251 * See if page is in cache and get it if so
2252 * Stores the page content in $this->content if something is found.
2253 *
2254 * @throws \InvalidArgumentException
2255 * @throws \RuntimeException
2256 */
2257 public function getFromCache() {
2258 // clearing the content-variable, which will hold the pagecontent
2259 $this->content = '';
2260 // Unsetting the lowlevel config
2261 unset($this->config);
2262 $this->cacheContentFlag = FALSE;
2263
2264 if ($this->no_cache) {
2265 return;
2266 }
2267
2268 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2269 if (!is_array($pageSectionCacheContent)) {
2270 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2271 // We use the Registry to store this lock centrally,
2272 // but we protect the access again with a global exclusive lock to avoid race conditions
2273
2274 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2275 //
2276 // from this point on we're the only one working on that page ($key)
2277 //
2278
2279 // query the cache again to see if the page data are there meanwhile
2280 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2281 if (is_array($pageSectionCacheContent)) {
2282 // we have the content, nice that some other process did the work for us already
2283 $this->releaseLock('pagesection');
2284 } else {
2285 // We keep the lock set, because we are the ones generating the page now
2286 // and filling the cache.
2287 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2288 }
2289 }
2290
2291 if (is_array($pageSectionCacheContent)) {
2292 // 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.
2293 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2294 // 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.
2295 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2296 ksort($pageSectionCacheContent);
2297 $this->all = $pageSectionCacheContent;
2298 }
2299 unset($pageSectionCacheContent);
2300
2301 // Look for page in cache only if a shift-reload is not sent to the server.
2302 $lockHash = $this->getLockHash();
2303 if (!$this->headerNoCache()) {
2304 if ($this->all) {
2305 // we got page section information
2306 $this->newHash = $this->getHash();
2307 $GLOBALS['TT']->push('Cache Row', '');
2308 $row = $this->getFromCache_queryRow();
2309 if (!is_array($row)) {
2310 // nothing in the cache, we acquire an exclusive lock now
2311
2312 $this->acquireLock('pages', $lockHash);
2313 //
2314 // from this point on we're the only one working on that page ($lockHash)
2315 //
2316
2317 // query the cache again to see if the data are there meanwhile
2318 $row = $this->getFromCache_queryRow();
2319 if (is_array($row)) {
2320 // we have the content, nice that some other process did the work for us
2321 $this->releaseLock('pages');
2322 } else {
2323 // We keep the lock set, because we are the ones generating the page now
2324 // and filling the cache.
2325 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2326 }
2327 }
2328 if (is_array($row)) {
2329 // we have data from cache
2330
2331 // Call hook when a page is retrieved from cache:
2332 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'])) {
2333 $_params = array('pObj' => &$this, 'cache_pages_row' => &$row);
2334 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] as $_funcRef) {
2335 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2336 }
2337 }
2338 // Fetches the lowlevel config stored with the cached data
2339 $this->config = $row['cache_data'];
2340 // Getting the content
2341 $this->content = $row['content'];
2342 // Flag for temp content
2343 $this->tempContent = $row['temp_content'];
2344 // Setting flag, so we know, that some cached content has been loaded
2345 $this->cacheContentFlag = TRUE;
2346 $this->cacheExpires = $row['expires'];
2347
2348 // Restore page title information, this is needed to generate the page title for
2349 // partially cached pages.
2350 $this->page['title'] = $row['pageTitleInfo']['title'];
2351 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2352 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2353
2354 if (isset($this->config['config']['debug'])) {
2355 $debugCacheTime = (bool)$this->config['config']['debug'];
2356 } else {
2357 $debugCacheTime = !empty($this->TYPO3_CONF_VARS['FE']['debug']);
2358 }
2359 if ($debugCacheTime) {
2360 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2361 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2362 $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . Date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2363 }
2364 }
2365 $GLOBALS['TT']->pull();
2366
2367 return;
2368 }
2369 }
2370 // the user forced rebuilding the page cache or there was no pagesection information
2371 // get a lock for the page content so other processes will not interrupt the regeneration
2372 $this->acquireLock('pages', $lockHash);
2373 }
2374
2375 /**
2376 * Returning the cached version of page with hash = newHash
2377 *
2378 * @return array Cached row, if any. Otherwise void.
2379 */
2380 public function getFromCache_queryRow() {
2381 $GLOBALS['TT']->push('Cache Query', '');
2382 $row = $this->pageCache->get($this->newHash);
2383 $GLOBALS['TT']->pull();
2384 return $row;
2385 }
2386
2387 /**
2388 * Detecting if shift-reload has been clicked
2389 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2390 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2391 *
2392 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2393 */
2394 public function headerNoCache() {
2395 $disableAcquireCacheData = FALSE;
2396 if ($this->beUserLogin) {
2397 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2398 $disableAcquireCacheData = TRUE;
2399 }
2400 }
2401 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2402 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'])) {
2403 $_params = array('pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData);
2404 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] as $_funcRef) {
2405 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2406 }
2407 }
2408 return $disableAcquireCacheData;
2409 }
2410
2411 /**
2412 * Calculates the cache-hash
2413 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2414 * Used to get and later store the cached data.
2415 *
2416 * @return string MD5 hash of serialized hash base from createHashBase()
2417 * @access private
2418 * @see getFromCache(), getLockHash()
2419 */
2420 public function getHash() {
2421 return md5($this->createHashBase(FALSE));
2422 }
2423
2424 /**
2425 * Calculates the lock-hash
2426 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2427 *
2428 * @return string MD5 hash
2429 * @access private
2430 * @see getFromCache(), getHash()
2431 */
2432 public function getLockHash() {
2433 $lockHash = $this->createHashBase(TRUE);
2434 return md5($lockHash);
2435 }
2436
2437 /**
2438 * Calculates the cache-hash (or the lock-hash)
2439 * This hash is unique to the template,
2440 * the variables ->id, ->type, ->gr_list (list of groups),
2441 * ->MP (Mount Points) and cHash array
2442 * Used to get and later store the cached data.
2443 *
2444 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2445 * @return string the serialized hash base
2446 */
2447 protected function createHashBase($createLockHashBase = FALSE) {
2448 $hashParameters = array(
2449 'id' => (int)$this->id,
2450 'type' => (int)$this->type,
2451 'gr_list' => (string)$this->gr_list,
2452 'MP' => (string)$this->MP,
2453 'cHash' => $this->cHash_array,
2454 'domainStartPage' => $this->domainStartPage
2455 );
2456 // Include the template information if we shouldn't create a lock hash
2457 if (!$createLockHashBase) {
2458 $hashParameters['all'] = $this->all;
2459 }
2460 // Call hook to influence the hash calculation
2461 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'])) {
2462 $_params = array(
2463 'hashParameters' => &$hashParameters,
2464 'createLockHashBase' => $createLockHashBase
2465 );
2466 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] as $_funcRef) {
2467 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2468 }
2469 }
2470 return serialize($hashParameters);
2471 }
2472
2473 /**
2474 * Checks if config-array exists already but if not, gets it
2475 *
2476 * @throws ServiceUnavailableException
2477 * @return void
2478 */
2479 public function getConfigArray() {
2480 $setStatPageName = FALSE;
2481 // 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
2482 if (!is_array($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2483 $GLOBALS['TT']->push('Parse template', '');
2484 // Force parsing, if set?:
2485 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2486 // Start parsing the TS template. Might return cached version.
2487 $this->tmpl->start($this->rootLine);
2488 $GLOBALS['TT']->pull();
2489 if ($this->tmpl->loaded) {
2490 $GLOBALS['TT']->push('Setting the config-array', '');
2491 // toplevel - objArrayName
2492 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2493 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2494 if (!is_array($this->pSetup)) {
2495 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2496 if ($this->checkPageUnavailableHandler()) {
2497 $this->pageUnavailableAndExit($message);
2498 } else {
2499 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2500 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2501 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2502 }
2503 } else {
2504 $this->config['config'] = array();
2505 // Filling the config-array, first with the main "config." part
2506 if (is_array($this->tmpl->setup['config.'])) {
2507 $this->config['config'] = $this->tmpl->setup['config.'];
2508 }
2509 // override it with the page/type-specific "config."
2510 if (is_array($this->pSetup['config.'])) {
2511 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2512 }
2513 if ($this->config['config']['typolinkEnableLinksAcrossDomains']) {
2514 $this->config['config']['typolinkCheckRootline'] = TRUE;
2515 }
2516 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2517 if (!isset($this->config['config']['removeDefaultJS'])) {
2518 $this->config['config']['removeDefaultJS'] = 'external';
2519 }
2520 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2521 $this->config['config']['inlineStyle2TempFile'] = 1;
2522 }
2523
2524 if (!isset($this->config['config']['compressJs'])) {
2525 $this->config['config']['compressJs'] = 0;
2526 }
2527 // Processing for the config_array:
2528 $this->config['rootLine'] = $this->tmpl->rootLine;
2529 $this->config['mainScript'] = trim($this->config['config']['mainScript']) ?: 'index.php';
2530 // Class for render Header and Footer parts
2531 $template = '';
2532 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2533 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2534 if ($file) {
2535 $this->getPageRenderer()->setTemplateFile($file);
2536 }
2537 }
2538 }
2539 $GLOBALS['TT']->pull();
2540 } else {
2541 if ($this->checkPageUnavailableHandler()) {
2542 $this->pageUnavailableAndExit('No TypoScript template found!');
2543 } else {
2544 $message = 'No TypoScript template found!';
2545 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2546 throw new ServiceUnavailableException($message, 1294587218);
2547 }
2548 }
2549 }
2550
2551 // No cache
2552 // Set $this->no_cache TRUE if the config.no_cache value is set!
2553 if ($this->config['config']['no_cache']) {
2554 $this->set_no_cache('config.no_cache is set');
2555 }
2556 // Merge GET with defaultGetVars
2557 if (!empty($this->config['config']['defaultGetVars.'])) {
2558 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2559 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2560 GeneralUtility::_GETset($modifiedGetVars);
2561 }
2562 // Hook for postProcessing the configuration array
2563 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'])) {
2564 $params = array('config' => &$this->config['config']);
2565 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] as $funcRef) {
2566 GeneralUtility::callUserFunction($funcRef, $params, $this);
2567 }
2568 }
2569 }
2570
2571 /********************************************
2572 *
2573 * Further initialization and data processing
2574 * (jumpurl/submission of forms)
2575 *
2576 *******************************************/
2577
2578 /**
2579 * Setting the language key that will be used by the current page.
2580 * 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.
2581 *
2582 * @return void
2583 * @access private
2584 */
2585 public function settingLanguage() {
2586 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'])) {
2587 $_params = array();
2588 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] as $_funcRef) {
2589 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2590 }
2591 }
2592
2593 // Initialize charset settings etc.
2594 $this->initLLvars();
2595
2596 // Get values from TypoScript:
2597 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2598 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2599 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2600 // If sys_language_uid is set to another language than default:
2601 if ($this->sys_language_uid > 0) {
2602 // check whether a shortcut is overwritten by a translated page
2603 // we can only do this now, as this is the place where we get
2604 // to know about translations
2605 $this->checkTranslatedShortcut();
2606 // Request the overlay record for the sys_language_uid:
2607 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2608 if (!count($olRec)) {
2609 // If no OL record exists and a foreign language is asked for...
2610 if ($this->sys_language_uid) {
2611 // If requested translation is not available:
2612 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2613 $this->pageNotFoundAndExit('Page is not available in the requested language.');
2614 } else {
2615 switch ((string)$this->sys_language_mode) {
2616 case 'strict':
2617 $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
2618 break;
2619 case 'content_fallback':
2620 $fallBackOrder = GeneralUtility::intExplode(',', $sys_language_content);
2621 foreach ($fallBackOrder as $orderValue) {
2622 if ((string)$orderValue === '0' || count($this->sys_page->getPageOverlay($this->id, $orderValue))) {
2623 $this->sys_language_content = $orderValue;
2624 // Setting content uid (but leaving the sys_language_uid)
2625 break;
2626 }
2627 }
2628 break;
2629 case 'ignore':
2630 $this->sys_language_content = $this->sys_language_uid;
2631 break;
2632 default:
2633 // Default is that everything defaults to the default language...
2634 $this->sys_language_uid = ($this->sys_language_content = 0);
2635 }
2636 }
2637 }
2638 } else {
2639 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2640 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2641 }
2642 }
2643 // Setting sys_language_uid inside sys-page:
2644 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2645 // If default translation is not available:
2646 if ((!$this->sys_language_uid || !$this->sys_language_content) && $this->page['l18n_cfg'] & 1) {
2647 $message = 'Page is not available in default language.';
2648 GeneralUtility::sysLog($message, 'cms', GeneralUtility::SYSLOG_SEVERITY_ERROR);
2649 $this->pageNotFoundAndExit($message);
2650 }
2651 $this->updateRootLinesWithTranslations();
2652
2653 // Finding the ISO code for the currently selected language
2654 // fetched by the sys_language record when not fetching content from the default language
2655 if ($this->sys_language_content > 0) {
2656 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2657 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2658 // avoid versioning overlay to be applied as it generates an SQL error
2659 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode', TRUE);
2660 if (is_array($sys_language_row)) {
2661 if (!empty($sys_language_row['language_isocode'])) {
2662 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2663 } elseif ($sys_language_row['static_lang_isocode'] && ExtensionManagementUtility::isLoaded('static_info_tables')) {
2664 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.');
2665 $stLrow = $this->sys_page->getRawRecord('static_languages', $sys_language_row['static_lang_isocode'], 'lg_iso_2', TRUE);
2666 $this->sys_language_isocode = $stLrow['lg_iso_2'];
2667 }
2668 }
2669 // the DB value is overriden by TypoScript
2670 if (!empty($this->config['config']['sys_language_isocode'])) {
2671 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2672 }
2673 } else {
2674 // fallback to the TypoScript option when rendering with sys_language_uid=0
2675 // also: use "en" by default
2676 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2677 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2678 } else {
2679 $this->sys_language_isocode = $this->lang != 'default' ? $this->lang : 'en';
2680 }
2681 }
2682
2683
2684 // Setting softMergeIfNotBlank:
2685 $table_fields = GeneralUtility::trimExplode(',', $this->config['config']['sys_language_softMergeIfNotBlank'], TRUE);
2686 foreach ($table_fields as $TF) {
2687 list($tN, $fN) = explode(':', $TF);
2688 $GLOBALS['TCA'][$tN]['columns'][$fN]['l10n_mode'] = 'mergeIfNotBlank';
2689 }
2690 // Setting softExclude:
2691 $table_fields = GeneralUtility::trimExplode(',', $this->config['config']['sys_language_softExclude'], TRUE);
2692 foreach ($table_fields as $TF) {
2693 list($tN, $fN) = explode(':', $TF);
2694 $GLOBALS['TCA'][$tN]['columns'][$fN]['l10n_mode'] = 'exclude';
2695 }
2696 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'])) {
2697 $_params = array();
2698 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] as $_funcRef) {
2699 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2700 }
2701 }
2702 }
2703
2704 /**
2705 * Updating content of the two rootLines IF the language key is set!
2706 */
2707 protected function updateRootLinesWithTranslations() {
2708 if ($this->sys_language_uid) {
2709 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2710 $this->tmpl->updateRootlineData($this->rootLine);
2711 }
2712 }
2713
2714 /**
2715 * Setting locale for frontend rendering
2716 *
2717 * @return void
2718 */
2719 public function settingLocale() {
2720 // Setting locale
2721 if ($this->config['config']['locale_all']) {
2722 // There's a problem that PHP parses float values in scripts wrong if the
2723 // locale LC_NUMERIC is set to something with a comma as decimal point
2724 // Do we set all except LC_NUMERIC
2725 $locale = setlocale(LC_COLLATE, $this->config['config']['locale_all']);
2726 if ($locale) {
2727 setlocale(LC_CTYPE, $this->config['config']['locale_all']);
2728 setlocale(LC_MONETARY, $this->config['config']['locale_all']);
2729 setlocale(LC_TIME, $this->config['config']['locale_all']);
2730 $this->localeCharset = $this->csConvObj->get_locale_charset($this->config['config']['locale_all']);
2731 } else {
2732 $GLOBALS['TT']->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2733 }
2734 }
2735 }
2736
2737 /**
2738 * Checks whether a translated shortcut page has a different shortcut
2739 * target than the original language page.
2740 * If that is the case, things get corrected to follow that alternative
2741 * shortcut
2742 *
2743 * @return void
2744 * @author Ingo Renner <ingo@typo3.org>
2745 */
2746 protected function checkTranslatedShortcut() {
2747 if (!is_null($this->originalShortcutPage)) {
2748 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2749 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2750 // the translation of the original shortcut page has a different shortcut target!
2751 // set the correct page and id
2752 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2753 $this->id = ($this->contentPid = $shortcut['uid']);
2754 $this->page = $this->sys_page->getPage($this->id);
2755 // Fix various effects on things like menus f.e.
2756 $this->fetch_the_id();
2757 $this->tmpl->rootLine = array_reverse($this->rootLine);
2758 }
2759 }
2760 }
2761
2762 /**
2763 * Handle data submission
2764 * This is done at this point, because we need the config values
2765 *
2766 * @return void
2767 */
2768 public function handleDataSubmission() {
2769 // Hook for processing data submission to extensions
2770 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'])) {
2771 foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $_classRef) {
2772 $_procObj = GeneralUtility::getUserObj($_classRef);
2773 $_procObj->checkDataSubmission($this);
2774 }
2775 }
2776 }
2777
2778 /**
2779 * Checks if a formmail submission can be sent as email, also used for JumpURLs
2780 * should be removed once JumpURL is handled outside TypoScriptFrontendController
2781 *
2782 * @param string $locationData The input from $_POST['locationData']
2783 * @return void|int
2784 */
2785 protected function locDataCheck($locationData) {
2786 $locData = explode(':', $locationData);
2787 if (!$locData[1] || $this->sys_page->checkRecord($locData[1], $locData[2], 1)) {
2788 // $locData[1] -check means that a record is checked only if the locationData has a value for a record else than the page.
2789 if (count($this->sys_page->getPage($locData[0]))) {
2790 return 1;
2791 } else {
2792 $GLOBALS['TT']->setTSlogMessage('LocationData Error: The page pointed to by location data (' . $locationData . ') was not accessible.', 2);
2793 }
2794 } else {
2795 $GLOBALS['TT']->setTSlogMessage('LocationData Error: Location data (' . $locationData . ') record pointed to was not accessible.', 2);
2796 }
2797 }
2798
2799 /**
2800 * Sets the jumpurl for page type "External URL"
2801 *
2802 * @return void
2803 */
2804 public function setExternalJumpUrl() {
2805 if ($extUrl = $this->sys_page->getExtURL($this->page, $this->config['config']['disablePageExternalUrl'])) {
2806 $this->jumpurl = $extUrl;
2807 GeneralUtility::_GETset(GeneralUtility::hmac($this->jumpurl, 'jumpurl'), 'juHash');
2808 }
2809 }
2810
2811 /**
2812 * Check the jumpUrl referer if required
2813 *
2814 * @return void
2815 */
2816 public function checkJumpUrlReferer() {
2817 if ($this->jumpurl !== '' && !$this->TYPO3_CONF_VARS['SYS']['doNotCheckReferer']) {
2818 $referer = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
2819 if (isset($referer['host']) && !($referer['host'] == GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'))) {
2820 unset($this->jumpurl);
2821 }
2822 }
2823 }
2824
2825 /**
2826 * Sends a header "Location" to jumpUrl, if jumpurl is set.
2827 * Will exit if a location header is sent (for instance if jumpUrl was triggered)
2828 *
2829 * "jumpUrl" is a concept where external links are redirected from the index_ts.php script, which first logs the URL.
2830 *
2831 * @throws \Exception
2832 * @return void
2833 */
2834 public function jumpUrl() {
2835 if ($this->jumpurl) {
2836 if (GeneralUtility::_GP('juSecure')) {
2837 $locationData = (string)GeneralUtility::_GP('locationData');
2838 // Need a type cast here because mimeType is optional!
2839 $mimeType = (string)GeneralUtility::_GP('mimeType');
2840 $hArr = array(
2841 $this->jumpurl,
2842 $locationData,
2843 $mimeType
2844 );
2845 $calcJuHash <