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