PageLinkBuilder.php 32.6 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\Frontend\Typolink;

20
use Psr\Http\Message\ServerRequestInterface;
21
use Psr\Http\Message\UriInterface;
22
use TYPO3\CMS\Core\Cache\CacheManager;
23
24
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\LanguageAspect;
25
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
26
27
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
28
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
29
use TYPO3\CMS\Core\Exception\Page\RootLineException;
30
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
31
use TYPO3\CMS\Core\Http\Uri;
32
use TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException;
Oliver Hader's avatar
Oliver Hader committed
33
use TYPO3\CMS\Core\Routing\RouterInterface;
34
35
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
36
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
37
use TYPO3\CMS\Core\Site\SiteFinder;
38
39
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
40
use TYPO3\CMS\Core\Utility\RootlineUtility;
41
42
43
44
45
46
47
48
49
use TYPO3\CMS\Frontend\ContentObject\TypolinkModifyLinkConfigForPageLinksHookInterface;

/**
 * Builds a TypoLink to a certain page
 */
class PageLinkBuilder extends AbstractTypolinkBuilder
{
    /**
     * @inheritdoc
50
     * @throws UnableToLinkException
51
52
53
54
     */
    public function build(array &$linkDetails, string $linkText, string $target, array $conf): array
    {
        $tsfe = $this->getTypoScriptFrontendController();
55
56
        if (empty($linkDetails['pageuid']) || $linkDetails['pageuid'] === 'current') {
            // If no id is given
57
58
59
60
61
62
63
64
65
66
67
            $linkDetails['pageuid'] = $tsfe->id;
        }

        // Link to page even if access is missing?
        if (isset($conf['linkAccessRestrictedPages'])) {
            $disableGroupAccessCheck = (bool)$conf['linkAccessRestrictedPages'];
        } else {
            $disableGroupAccessCheck = (bool)$tsfe->config['config']['typolinkLinkAccessRestrictedPages'];
        }

        // Looking up the page record to verify its existence:
68
        $page = $this->resolvePage($linkDetails, $conf, $disableGroupAccessCheck);
69
70
71
72

        if (empty($page)) {
            throw new UnableToLinkException('Page id "' . $linkDetails['typoLinkParameter'] . '" was not found, so "' . $linkText . '" was not linked.', 1490987336, null, $linkText);
        }
73

74
75
76
77
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typolinkProcessing']['typolinkModifyParameterForPageLinks'] ?? [] as $classData) {
            $hookObject = GeneralUtility::makeInstance($classData);
            if (!$hookObject instanceof TypolinkModifyLinkConfigForPageLinksHookInterface) {
                throw new \UnexpectedValueException('$hookObject must implement interface ' . TypolinkModifyLinkConfigForPageLinksHookInterface::class, 1483114905);
78
            }
79
            /** @var TypolinkModifyLinkConfigForPageLinksHookInterface $hookObject */
80
            $conf = $hookObject->modifyPageLinkConfiguration($conf, $linkDetails, $page);
81
82
83
84
85
86
87
88
89
90
91
92
93
        }
        if ($conf['no_cache.']) {
            $conf['no_cache'] = (string)$this->contentObjectRenderer->stdWrap($conf['no_cache'], $conf['no_cache.']);
        }

        $sectionMark = trim(isset($conf['section.']) ? (string)$this->contentObjectRenderer->stdWrap($conf['section'], $conf['section.']) : (string)$conf['section']);
        if ($sectionMark === '' && isset($linkDetails['fragment'])) {
            $sectionMark = $linkDetails['fragment'];
        }
        if ($sectionMark !== '') {
            $sectionMark = '#' . (MathUtility::canBeInterpretedAsInteger($sectionMark) ? 'c' : '') . $sectionMark;
        }
        // Overruling 'type'
94
        $pageType = $linkDetails['pagetype'] ?? '';
95
96
97
98

        if (isset($linkDetails['parameters'])) {
            $conf['additionalParams'] .= '&' . ltrim($linkDetails['parameters'], '&');
        }
99
        // MountPoints, look for closest MPvar:
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        $MPvarAcc = [];
        if (!$tsfe->config['config']['MP_disableTypolinkClosestMPvalue']) {
            $temp_MP = $this->getClosestMountPointValueForPage($page['uid']);
            if ($temp_MP) {
                $MPvarAcc['closest'] = $temp_MP;
            }
        }
        // Look for overlay Mount Point:
        $mount_info = $tsfe->sys_page->getMountPointInfo($page['uid'], $page);
        if (is_array($mount_info) && $mount_info['overlay']) {
            $page = $tsfe->sys_page->getPage($mount_info['mount_pid'], $disableGroupAccessCheck);
            if (empty($page)) {
                throw new UnableToLinkException('Mount point "' . $mount_info['mount_pid'] . '" was not available, so "' . $linkText . '" was not linked.', 1490987337, null, $linkText);
            }
            $MPvarAcc['re-map'] = $mount_info['MPvar'];
        }
        // Query Params:
        $addQueryParams = $conf['addQueryString'] ? $this->contentObjectRenderer->getQueryArguments($conf['addQueryString.']) : '';
        $addQueryParams .= isset($conf['additionalParams.']) ? trim((string)$this->contentObjectRenderer->stdWrap($conf['additionalParams'], $conf['additionalParams.'])) : trim((string)$conf['additionalParams']);
        if ($addQueryParams === '&' || $addQueryParams[0] !== '&') {
            $addQueryParams = '';
        }
        // Mount pages are always local and never link to another domain
        if (!empty($MPvarAcc)) {
            // Add "&MP" var:
            $addQueryParams .= '&MP=' . rawurlencode(implode(',', $MPvarAcc));
126
        } elseif (strpos($addQueryParams, '&MP=') === false) {
127
128
129
130
            // We do not come here if additionalParams had '&MP='. This happens when typoLink is called from
            // menu. Mount points always work in the content of the current domain and we must not change
            // domain if MP variables exist.
            // If we link across domains and page is free type shortcut, we must resolve the shortcut first!
131
            if ((int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
                && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
            ) {
                // Save in case of broken destination or endless loop
                $page2 = $page;
                // Same as in RealURL, seems enough
                $maxLoopCount = 20;
                while ($maxLoopCount
                    && is_array($page)
                    && (int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
                    && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
                ) {
                    $page = $tsfe->sys_page->getPage($page['shortcut'], $disableGroupAccessCheck);
                    $maxLoopCount--;
                }
                if (empty($page) || $maxLoopCount === 0) {
                    // We revert if shortcut is broken or maximum number of loops is exceeded (indicates endless loop)
                    $page = $page2;
                }
            }
        }
152

153
154
        if (isset($conf['useCacheHash'])) {
            // This option will be removed in TYPO3 v11.0.
155
            trigger_error('Setting typolink.useCacheHash has no effect anymore. Remove the option in all your TypoScript code and Fluid templates.', E_USER_DEPRECATED);
156
        }
157

158
159
160
161
162
163
164
165
166
167
168
169
170
171
        // get config.linkVars and prepend them before the actual GET parameters
        $queryParameters = [];
        parse_str($addQueryParams, $queryParameters);
        if ($tsfe->linkVars) {
            $globalQueryParameters = [];
            parse_str($tsfe->linkVars, $globalQueryParameters);
            $queryParameters = array_replace_recursive($globalQueryParameters, $queryParameters);
        }
        // Disable "?id=", for pages with no site configuration, this is added later-on anyway
        unset($queryParameters['id']);

        // Override language property if not being set already
        if (isset($queryParameters['L']) && !isset($conf['language'])) {
            $conf['language'] = (int)$queryParameters['L'];
172
            unset($queryParameters['L']);
173
174
        }

175
176
        // Check if the target page has a site configuration
        try {
177
            $siteOfTargetPage = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId((int)$page['uid'], null, $queryParameters['MP'] ?? '');
178
179
            $currentSite = $this->getCurrentSite();
        } catch (SiteNotFoundException $e) {
180
            // Usually happens in tests, as sites with configuration should be available everywhere.
181
182
183
            $siteOfTargetPage = null;
            $currentSite = null;
        }
184

185
        // Link to a page that has a site configuration
186
        if ($siteOfTargetPage !== null) {
187
188
189
190
191
            try {
                $siteLanguageOfTargetPage = $this->getSiteLanguageOfTargetPage($siteOfTargetPage, (string)($conf['language'] ?? 'current'));
            } catch (UnableToLinkException $e) {
                throw new UnableToLinkException($e->getMessage(), $e->getCode(), $e, $linkText);
            }
192
193
194
195
196
197
198
199
200
201
202
            $languageAspect = LanguageAspectFactory::createFromSiteLanguage($siteLanguageOfTargetPage);

            // Now overlay the page in the target language, in order to have valid title attributes etc.
            if ($siteLanguageOfTargetPage->getLanguageId() > 0) {
                $context = clone GeneralUtility::makeInstance(Context::class);
                $context->setAspect('language', $languageAspect);
                $pageRepository = GeneralUtility::makeInstance(PageRepository::class, $context);
                $page = $pageRepository->getPageOverlay($page);
            }
            // Check if the target page can be access depending on l18n_cfg
            if (!$tsfe->sys_page->isPageSuitableForLanguage($page, $languageAspect)) {
203
                if ($siteLanguageOfTargetPage->getLanguageId() === 0 && GeneralUtility::hideIfDefaultLanguage($page['l18n_cfg'])) {
204
205
                    throw new UnableToLinkException('Default language of page  "' . $linkDetails['typoLinkParameter'] . '" is hidden, so "' . $linkText . '" was not linked.', 1551621985, null, $linkText);
                }
206
207
208
209
210
                // If the requested language is not the default language and the page has no overlay for this language
                // generating a link would cause a 404 error when using this like if one of those conditions apply:
                //  - The page is set to be hidden if it is not translated (evaluated in TSFE)
                //  - The site configuration has a "strict" fallback set (evaluated in the Router - very early)
                if ($siteLanguageOfTargetPage->getLanguageId() > 0 && !isset($page['_PAGES_OVERLAY']) && (GeneralUtility::hideIfNotTranslated($page['l18n_cfg']) || $siteLanguageOfTargetPage->getFallbackType() === 'strict')) {
211
212
213
214
                    throw new UnableToLinkException('Fallback to default language of page "' . $linkDetails['typoLinkParameter'] . '" is disabled, so "' . $linkText . '" was not linked.', 1551621996, null, $linkText);
                }
            }

215
216
217
218
219
            if ($pageType) {
                $queryParameters['type'] = (int)$pageType;
            }

            $treatAsExternalLink = true;
220
221
222
223
224
225
226
227
228
229
            // External links are resolved via calling Typolink again (could be anything, really)
            if ((int)$page['doktype'] === PageRepository::DOKTYPE_LINK) {
                $conf['parameter'] = $page['url'];
                unset($conf['parameter.']);
                $this->contentObjectRenderer->typoLink($linkText, $conf);
                $target = $this->contentObjectRenderer->lastTypoLinkTarget;
                $url = $this->contentObjectRenderer->lastTypoLinkUrl;
                if (empty($url)) {
                    throw new UnableToLinkException('Link to external page "' . $page['uid'] . '" does not have a proper target URL, so "' . $linkText . '" was not linked.', 1551621999, null, $linkText);
                }
230
            } else {
231
232
233
234
                // Generate the URL
                $url = $this->generateUrlForPageWithSiteConfiguration($page, $siteOfTargetPage, $queryParameters, $sectionMark, $conf);
                // no scheme => always not external
                if (!$url->getScheme() || !$url->getHost()) {
235
                    $treatAsExternalLink = false;
236
237
238
                } else {
                    // URL has a scheme, possibly because someone requested a full URL. So now lets check if the URL
                    // is on the same site pagetree. If this is the case, we'll treat it as internal
239
240
                    // @todo: currently this does not check if the target page is a mounted page in a different site,
                    // so it is treating this as an absolute URL, which is wrong
241
242
243
                    if ($currentSite instanceof Site && $currentSite->getRootPageId() === $siteOfTargetPage->getRootPageId()) {
                        $treatAsExternalLink = false;
                    }
244
                }
245
                $url = (string)$url;
246
247
248
249
250
251
252
253
254
255
            }
            if ($treatAsExternalLink) {
                $target = $target ?: $this->resolveTargetAttribute($conf, 'extTarget', false, $tsfe->extTarget);
            } else {
                $target = (isset($page['target']) && trim($page['target'])) ? $page['target'] : $target;
                if (empty($target)) {
                    $target = $this->resolveTargetAttribute($conf, 'target', true, $tsfe->intTarget);
                }
            }
        } else {
256
            throw new UnableToLinkException('Could not link to page with ID: ' . $page['uid'], 1546887172, null, $linkText);
257
258
        }

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        // If link is to an access restricted page which should be redirected, then find new URL:
        if (empty($conf['linkAccessRestrictedPages'])
            && $tsfe->config['config']['typolinkLinkAccessRestrictedPages']
            && $tsfe->config['config']['typolinkLinkAccessRestrictedPages'] !== 'NONE'
            && !$tsfe->checkPageGroupAccess($page)
        ) {
            $thePage = $tsfe->sys_page->getPage($tsfe->config['config']['typolinkLinkAccessRestrictedPages']);
            $addParams = str_replace(
                [
                    '###RETURN_URL###',
                    '###PAGE_ID###'
                ],
                [
                    rawurlencode($url),
                    $page['uid']
                ],
                $tsfe->config['config']['typolinkLinkAccessRestrictedPages_addParams']
            );
            $url = $this->contentObjectRenderer->getTypoLink_URL($thePage['uid'] . ($pageType ? ',' . $pageType : ''), $addParams, $target);
            $url = $this->forceAbsoluteUrl($url, $conf);
        }

        // Setting title if blank value to link
        $linkText = $this->parseFallbackLinkTextIfLinkTextIsEmpty($linkText, $page['title']);
        return [$url, $linkText, $target];
    }

286
287
288
289
290
291
292
293
294
295
    /**
     * Resolves page and if a translated page was found, resolves that to it
     * language parent, adjusts `$linkDetails['pageuid']` (for hook processing)
     * and modifies `$configuration['language']` (for language URL generation).
     *
     * @param array $linkDetails
     * @param array $configuration
     * @param bool $disableGroupAccessCheck
     * @return array
     */
296
    protected function resolvePage(array &$linkDetails, array &$configuration, bool $disableGroupAccessCheck): array
297
    {
298
299
300
        $pageRepository = $this->buildPageRepository();
        // Looking up the page record to verify its existence
        // This is used when a page to a translated page is executed directly.
301
302
303
304
305
306
307
308
309
310
        $page = $pageRepository->getPage($linkDetails['pageuid'], $disableGroupAccessCheck);

        if (empty($page) || !is_array($page)) {
            return [];
        }

        $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'] ?? null;
        $languageParentField = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'] ?? null;
        $language = (int)($page[$languageField] ?? 0);

311
312
        // The page that should be linked is actually a default-language page, nothing to do here.
        if ($language === 0 || empty($page[$languageParentField])) {
313
314
315
            return $page;
        }

316
        // Let's fetch the default-language page now
317
318
319
320
321
322
323
324
        $languageParentPage = $pageRepository->getPage(
            $page[$languageParentField],
            $disableGroupAccessCheck
        );
        if (empty($languageParentPage)) {
            return $page;
        }

325
        // Set the "pageuid" to the default-language page ID.
326
327
328
329
330
        $linkDetails['pageuid'] = (int)$languageParentPage['uid'];
        $configuration['language'] = $language;
        return $languageParentPage;
    }

331
    /**
332
     * Fetches the requested language of a site that the link should be built for
333
334
     *
     * @param Site $siteOfTargetPage
335
336
     * @param string $targetLanguageId "current" or the languageId
     * @return SiteLanguage
337
338
     * @throws UnableToLinkException
     */
339
    protected function getSiteLanguageOfTargetPage(Site $siteOfTargetPage, string $targetLanguageId): SiteLanguage
340
341
342
343
344
    {
        $currentSite = $this->getCurrentSite();
        $currentSiteLanguage = $this->getCurrentSiteLanguage();
        // Happens when currently on a pseudo-site configuration
        // We assume to use the default language then
345
        if ($currentSite && !($currentSiteLanguage instanceof SiteLanguage)) {
346
347
348
349
350
351
352
353
354
355
356
357
358
            $currentSiteLanguage = $currentSite->getDefaultLanguage();
        }

        if ($targetLanguageId === 'current') {
            $targetLanguageId = $currentSiteLanguage ? $currentSiteLanguage->getLanguageId() : 0;
        } else {
            $targetLanguageId = (int)$targetLanguageId;
        }
        try {
            $siteLanguageOfTargetPage = $siteOfTargetPage->getLanguageById($targetLanguageId);
        } catch (\InvalidArgumentException $e) {
            throw new UnableToLinkException('The target page does not have a language with ID ' . $targetLanguageId . ' configured in its site configuration.', 1535477406);
        }
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        return $siteLanguageOfTargetPage;
    }

    /**
     * Create a UriInterface object when linking to a page with a site configuration
     *
     * @param array $page
     * @param Site $siteOfTargetPage
     * @param array $queryParameters
     * @param string $fragment
     * @param array $conf
     * @return UriInterface
     * @throws UnableToLinkException
     */
    protected function generateUrlForPageWithSiteConfiguration(array $page, Site $siteOfTargetPage, array $queryParameters, string $fragment, array $conf): UriInterface
    {
        $currentSite = $this->getCurrentSite();
        $currentSiteLanguage = $this->getCurrentSiteLanguage();
        // Happens when currently on a pseudo-site configuration
        // We assume to use the default language then
        if ($currentSite && !($currentSiteLanguage instanceof SiteLanguage)) {
            $currentSiteLanguage = $currentSite->getDefaultLanguage();
        }

        $siteLanguageOfTargetPage = $this->getSiteLanguageOfTargetPage($siteOfTargetPage, (string)($conf['language'] ?? 'current'));
384
385
386
387
388

        // By default, it is assumed to ab an internal link or current domain's linking scheme should be used
        // Use the config option to override this.
        $useAbsoluteUrl = $conf['forceAbsoluteUrl'] ?? false;
        // Check if the current page equal to the site of the target page, now only set the absolute URL
389
390
391
392
393
        // Always generate absolute URLs if no current site is set
        if (
            !$currentSite
            || $currentSite->getRootPageId() !== $siteOfTargetPage->getRootPageId()
            || $siteLanguageOfTargetPage->getBase()->getHost() !== $currentSiteLanguage->getBase()->getHost()) {
394
395
396
397
            $useAbsoluteUrl = true;
        }

        $targetPageId = (int)($page['l10n_parent'] > 0 ? $page['l10n_parent'] : $page['uid']);
Oliver Hader's avatar
Oliver Hader committed
398
        $queryParameters['_language'] = $siteLanguageOfTargetPage;
399
400
401
402
403

        if ($conf['no_cache']) {
            $queryParameters['no_cache'] = 1;
        }

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
        if ($fragment
            && $useAbsoluteUrl === false
            && $currentSiteLanguage === $siteLanguageOfTargetPage
            && $targetPageId === (int)$GLOBALS['TSFE']->id
            && (empty($conf['addQueryString']) || !isset($conf['addQueryString.']))
            && !$GLOBALS['TSFE']->config['config']['baseURL']
            && count($queryParameters) === 1 // _language is always set
            ) {
            $uri = (new Uri())->withFragment($fragment);
        } else {
            try {
                $uri = $siteOfTargetPage->getRouter()->generateUri(
                    $targetPageId,
                    $queryParameters,
                    $fragment,
                    $useAbsoluteUrl ? RouterInterface::ABSOLUTE_URL : RouterInterface::ABSOLUTE_PATH
                );
            } catch (InvalidRouteArgumentsException $e) {
                throw new UnableToLinkException('The target page could not be linked. Error: ' . $e->getMessage(), 1535472406);
            }
            // Override scheme, but only if the site does not define a scheme yet AND the site defines a domain/host
            if ($useAbsoluteUrl && !$uri->getScheme() && $uri->getHost()) {
                $scheme = $conf['forceAbsoluteUrl.']['scheme'] ?? 'https';
                $uri = $uri->withScheme($scheme);
            }
429
        }
430

431
432
433
434
        return $uri;
    }

    /**
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
     * The function will do its best to find a MP value that will keep the page id inside the current Mount Point rootline if any.
     *
     * @param int $pageId page id
     * @return string MP value, prefixed with &MP= (depending on $raw)
     */
    protected function getClosestMountPointValueForPage($pageId)
    {
        $tsfe = $this->getTypoScriptFrontendController();
        if (empty($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) || !$tsfe->MP) {
            return '';
        }
        // Same page as current.
        if ((int)$tsfe->id === (int)$pageId) {
            return $tsfe->MP;
        }

Benni Mack's avatar
Benni Mack committed
451
        // Find closest mount point
452
        // Gets rootline of linked-to page
453
        try {
454
455
            $tCR_rootline = GeneralUtility::makeInstance(RootlineUtility::class, $pageId)->get();
        } catch (RootLineException $e) {
456
457
            $tCR_rootline = [];
        }
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
        $inverseTmplRootline = array_reverse($tsfe->tmpl->rootLine);
        $rl_mpArray = [];
        $startMPaccu = false;
        // Traverse root line of link uid and inside of that the REAL root line of current position.
        foreach ($tCR_rootline as $tCR_data) {
            foreach ($inverseTmplRootline as $rlKey => $invTmplRLRec) {
                // Force accumulating when in overlay mode: Links to this page have to stay within the current branch
                if ($invTmplRLRec['_MOUNT_OL'] && (int)$tCR_data['uid'] === (int)$invTmplRLRec['uid']) {
                    $startMPaccu = true;
                }
                // Accumulate MP data:
                if ($startMPaccu && $invTmplRLRec['_MP_PARAM']) {
                    $rl_mpArray[] = $invTmplRLRec['_MP_PARAM'];
                }
                // If two PIDs matches and this is NOT the site root, start accumulation of MP data (on the next level):
473
                // (The check for site root is done so links to branches outside the site but sharing the site roots PID
474
475
476
477
478
479
480
481
482
483
484
485
                // is NOT detected as within the branch!)
                if ((int)$tCR_data['pid'] === (int)$invTmplRLRec['pid'] && count($inverseTmplRootline) !== $rlKey + 1) {
                    $startMPaccu = true;
                }
            }
            if ($startMPaccu) {
                // Good enough...
                break;
            }
        }
        return !empty($rl_mpArray) ? implode(',', array_reverse($rl_mpArray)) : '';
    }
486
487
488
489
490
491
492
493
494
495
496
497
498

    /**
     * Initializes the automatically created mountPointMap coming from the "config.MP_mapRootPoints" setting
     * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
     *
     * Previously located within TemplateService::getFromMPmap()
     *
     * @param int $pageId Page id to return MPvar value for.
     * @return string
     */
    public function getMountPointParameterFromRootPointMaps(int $pageId)
    {
        // Create map if not found already
499
        $config = $this->getTypoScriptFrontendController()->config;
500
        $mountPointMap = $this->initializeMountPointMap(
501
502
            !empty($config['config']['MP_defaults']) ? $config['config']['MP_defaults'] : null,
            !empty($config['config']['MP_mapRootPoints']) ? $config['config']['MP_mapRootPoints'] : null
503
504
505
        );

        // Finding MP var for Page ID:
506
        if (!empty($mountPointMap[$pageId])) {
507
508
509
510
511
512
513
514
515
516
517
518
519
520
            return implode(',', $mountPointMap[$pageId]);
        }
        return '';
    }

    /**
     * Create mount point map, based on TypoScript config.MP_mapRootPoints and config.MP_defaults.
     *
     * @param string $defaultMountPoints a string as defined in config.MP_defaults
     * @param string|null $mapRootPointList a string as defined in config.MP_mapRootPoints
     * @return array
     */
    protected function initializeMountPointMap(string $defaultMountPoints = null, string $mapRootPointList = null): array
    {
521
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
522
        $mountPointMap = $runtimeCache->get('pageLinkBuilderMountPointMap') ?: [];
523
524
525
526
527
528
        if (!empty($mountPointMap) || (empty($mapRootPointList) && empty($defaultMountPoints))) {
            return $mountPointMap;
        }
        if ($defaultMountPoints) {
            $defaultMountPoints = GeneralUtility::trimExplode('|', $defaultMountPoints, true);
            foreach ($defaultMountPoints as $temp_p) {
529
                [$temp_idP, $temp_MPp] = explode(':', $temp_p, 2);
530
531
532
533
534
535
536
537
538
539
540
541
542
543
                $temp_ids = GeneralUtility::intExplode(',', $temp_idP);
                foreach ($temp_ids as $temp_id) {
                    $mountPointMap[$temp_id] = trim($temp_MPp);
                }
            }
        }

        $rootPoints = GeneralUtility::trimExplode(',', strtolower($mapRootPointList), true);
        // Traverse rootpoints
        foreach ($rootPoints as $p) {
            $initMParray = [];
            if ($p === 'root') {
                $rootPage = $this->getTypoScriptFrontendController()->tmpl->rootLine[0];
                $p = $rootPage['uid'];
544
545
                if ($rootPage['_MOUNT_OL'] && $rootPage['_MP_PARAM']) {
                    $initMParray[] = $rootPage['_MP_PARAM'];
546
547
                }
            }
548
            $this->populateMountPointMapForPageRecursively($mountPointMap, (int)$p, $initMParray);
549
        }
550
        $runtimeCache->set('pageLinkBuilderMountPointMap', $mountPointMap);
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
        return $mountPointMap;
    }

    /**
     * Creating mountPointMap for a certain ID root point.
     * Previously called TemplateService->initMPmap_create()
     *
     * @param array $mountPointMap the exiting mount point map
     * @param int $id Root id from which to start map creation.
     * @param array $MP_array MP_array passed from root page.
     * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
     * @see getMountPointParameterFromRootPointMaps()
     */
    protected function populateMountPointMapForPageRecursively(array &$mountPointMap, int $id, $MP_array = [], $level = 0)
    {
        if ($id <= 0) {
            return;
        }
        // First level, check id
        if (!$level) {
            // Find mount point if any:
            $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
            // Overlay mode:
            if (is_array($mount_info) && $mount_info['overlay']) {
                $MP_array[] = $mount_info['MPvar'];
                $id = $mount_info['mount_pid'];
            }
            // Set mapping information for this level:
            $mountPointMap[$id] = $MP_array;
            // Normal mode:
            if (is_array($mount_info) && !$mount_info['overlay']) {
                $MP_array[] = $mount_info['MPvar'];
                $id = $mount_info['mount_pid'];
            }
        }
        if ($id && $level < 20) {
            $nextLevelAcc = [];
            // Select and traverse current level pages:
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
            $queryResult = $queryBuilder
594
                ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
                ->from('pages')
                ->where(
                    $queryBuilder->expr()->eq(
                        'pid',
                        $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
                    ),
                    $queryBuilder->expr()->neq(
                        'doktype',
                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
                    ),
                    $queryBuilder->expr()->neq(
                        'doktype',
                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
                    )
                )->execute();
            while ($row = $queryResult->fetch()) {
                // Find mount point if any:
612
                $next_id = (int)$row['uid'];
613
614
615
616
617
                $next_MP_array = $MP_array;
                $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
                // Overlay mode:
                if (is_array($mount_info) && $mount_info['overlay']) {
                    $next_MP_array[] = $mount_info['MPvar'];
618
                    $next_id = (int)$mount_info['mount_pid'];
619
620
621
622
623
624
625
                }
                if (!isset($mountPointMap[$next_id])) {
                    // Set mapping information for this level:
                    $mountPointMap[$next_id] = $next_MP_array;
                    // Normal mode:
                    if (is_array($mount_info) && !$mount_info['overlay']) {
                        $next_MP_array[] = $mount_info['MPvar'];
626
                        $next_id = (int)$mount_info['mount_pid'];
627
628
629
630
631
632
633
634
635
636
637
638
                    }
                    // Register recursive call
                    // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
                    $nextLevelAcc[] = [$next_id, $next_MP_array];
                }
            }
            // Call recursively, if any:
            foreach ($nextLevelAcc as $pSet) {
                $this->populateMountPointMapForPageRecursively($mountPointMap, $pSet[0], $pSet[1], $level + 1);
            }
        }
    }
639
640
641
642
643
644
645
646
647
648
649
650
651

    /**
     * Check if we have a site object in the current request. if null, this usually means that
     * this class was called from CLI context.
     *
     * @return SiteInterface|null
     */
    protected function getCurrentSite(): ?SiteInterface
    {
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
            return $GLOBALS['TYPO3_REQUEST']->getAttribute('site', null);
        }
        if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TSFE']->id) && $GLOBALS['TSFE']->id > 0) {
652
            $finder = GeneralUtility::makeInstance(SiteFinder::class);
653
            try {
654
                $site = $finder->getSiteByPageId((int)$GLOBALS['TSFE']->id);
655
656
657
658
            } catch (SiteNotFoundException $e) {
                $site = null;
            }
            return $site;
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
        }
        return null;
    }

    /**
     * If the current request has a site language, this means that the SiteResolver has detected a
     * page with a site configuration and a selected language, so let's choose that one.
     *
     * @return SiteLanguage|null
     */
    protected function getCurrentSiteLanguage(): ?SiteLanguage
    {
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
            return $GLOBALS['TYPO3_REQUEST']->getAttribute('language', null);
        }
        return null;
    }
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696

    /**
     * Builds PageRepository instance without depending on global context, e.g.
     * not automatically overlaying records based on current request language.
     *
     * @return PageRepository
     */
    protected function buildPageRepository(): PageRepository
    {
        // clone global context object (singleton)
        $context = clone GeneralUtility::makeInstance(Context::class);
        $context->setAspect(
            'language',
            GeneralUtility::makeInstance(LanguageAspect::class)
        );
        $pageRepository = GeneralUtility::makeInstance(
            PageRepository::class,
            $context
        );
        return $pageRepository;
    }
697
}