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