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