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