[TASK] Streamline page language linking
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Typolink / PageLinkBuilder.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Frontend\Typolink;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use Psr\Http\Message\ServerRequestInterface;
19 use Psr\Http\Message\UriInterface;
20 use TYPO3\CMS\Core\Cache\CacheManager;
21 use TYPO3\CMS\Core\Database\ConnectionPool;
22 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
23 use TYPO3\CMS\Core\Exception\Page\RootLineException;
24 use TYPO3\CMS\Core\Exception\SiteNotFoundException;
25 use TYPO3\CMS\Core\Routing\PageUriBuilder;
26 use TYPO3\CMS\Core\Routing\SiteMatcher;
27 use TYPO3\CMS\Core\Site\Entity\Site;
28 use TYPO3\CMS\Core\Site\Entity\SiteInterface;
29 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31 use TYPO3\CMS\Core\Utility\MathUtility;
32 use TYPO3\CMS\Core\Utility\RootlineUtility;
33 use TYPO3\CMS\Frontend\Compatibility\LegacyDomainResolver;
34 use TYPO3\CMS\Frontend\ContentObject\TypolinkModifyLinkConfigForPageLinksHookInterface;
35 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
36 use TYPO3\CMS\Frontend\Page\PageRepository;
37
38 /**
39 * Builds a TypoLink to a certain page
40 */
41 class PageLinkBuilder extends AbstractTypolinkBuilder
42 {
43 /**
44 * @inheritdoc
45 */
46 public function build(array &$linkDetails, string $linkText, string $target, array $conf): array
47 {
48 $tsfe = $this->getTypoScriptFrontendController();
49 // Checking if the id-parameter is an alias.
50 if (!empty($linkDetails['pagealias'])) {
51 $linkDetails['pageuid'] = $tsfe->sys_page->getPageIdFromAlias($linkDetails['pagealias']);
52 } elseif (empty($linkDetails['pageuid']) || $linkDetails['pageuid'] === 'current') {
53 // If no id or alias is given
54 $linkDetails['pageuid'] = $tsfe->id;
55 }
56
57 // Link to page even if access is missing?
58 if (isset($conf['linkAccessRestrictedPages'])) {
59 $disableGroupAccessCheck = (bool)$conf['linkAccessRestrictedPages'];
60 } else {
61 $disableGroupAccessCheck = (bool)$tsfe->config['config']['typolinkLinkAccessRestrictedPages'];
62 }
63
64 // Looking up the page record to verify its existence:
65 $page = $this->resolvePage($tsfe->sys_page, $linkDetails, $conf, $disableGroupAccessCheck);
66
67 if (empty($page)) {
68 throw new UnableToLinkException('Page id "' . $linkDetails['typoLinkParameter'] . '" was not found, so "' . $linkText . '" was not linked.', 1490987336, null, $linkText);
69 }
70
71 $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'] ?? null;
72 $language = (int)($page[$languageField] ?? 0);
73 if ($language === 0 && GeneralUtility::hideIfDefaultLanguage($page['l18n_cfg'])) {
74 throw new UnableToLinkException('Default language of page "' . $linkDetails['typoLinkParameter'] . '" is hidden, so "' . $linkText . '" was not linked.', 1529527301, null, $linkText);
75 }
76 if ($language > 0 && !isset($page['_PAGES_OVERLAY']) && GeneralUtility::hideIfNotTranslated($page['l18n_cfg'])) {
77 throw new UnableToLinkException('Fallback to default language of page "' . $linkDetails['typoLinkParameter'] . '" is disabled, so "' . $linkText . '" was not linked.', 1529527488, null, $linkText);
78 }
79
80 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typolinkProcessing']['typolinkModifyParameterForPageLinks'] ?? [] as $classData) {
81 $hookObject = GeneralUtility::makeInstance($classData);
82 if (!$hookObject instanceof TypolinkModifyLinkConfigForPageLinksHookInterface) {
83 throw new \UnexpectedValueException('$hookObject must implement interface ' . TypolinkModifyLinkConfigForPageLinksHookInterface::class, 1483114905);
84 }
85 /** @var $hookObject TypolinkModifyLinkConfigForPageLinksHookInterface */
86 $conf = $hookObject->modifyPageLinkConfiguration($conf, $linkDetails, $page);
87 }
88 $enableLinksAcrossDomains = $tsfe->config['config']['typolinkEnableLinksAcrossDomains'];
89 if ($conf['no_cache.']) {
90 $conf['no_cache'] = (string)$this->contentObjectRenderer->stdWrap($conf['no_cache'], $conf['no_cache.']);
91 }
92
93 $sectionMark = trim(isset($conf['section.']) ? (string)$this->contentObjectRenderer->stdWrap($conf['section'], $conf['section.']) : (string)$conf['section']);
94 if ($sectionMark === '' && isset($linkDetails['fragment'])) {
95 $sectionMark = $linkDetails['fragment'];
96 }
97 if ($sectionMark !== '') {
98 $sectionMark = '#' . (MathUtility::canBeInterpretedAsInteger($sectionMark) ? 'c' : '') . $sectionMark;
99 }
100 // Overruling 'type'
101 $pageType = $linkDetails['pagetype'] ?? '';
102
103 if (isset($linkDetails['parameters'])) {
104 $conf['additionalParams'] .= '&' . ltrim($linkDetails['parameters'], '&');
105 }
106 // MointPoints, look for closest MPvar:
107 $MPvarAcc = [];
108 if (!$tsfe->config['config']['MP_disableTypolinkClosestMPvalue']) {
109 $temp_MP = $this->getClosestMountPointValueForPage($page['uid']);
110 if ($temp_MP) {
111 $MPvarAcc['closest'] = $temp_MP;
112 }
113 }
114 // Look for overlay Mount Point:
115 $mount_info = $tsfe->sys_page->getMountPointInfo($page['uid'], $page);
116 if (is_array($mount_info) && $mount_info['overlay']) {
117 $page = $tsfe->sys_page->getPage($mount_info['mount_pid'], $disableGroupAccessCheck);
118 if (empty($page)) {
119 throw new UnableToLinkException('Mount point "' . $mount_info['mount_pid'] . '" was not available, so "' . $linkText . '" was not linked.', 1490987337, null, $linkText);
120 }
121 $MPvarAcc['re-map'] = $mount_info['MPvar'];
122 }
123 // Query Params:
124 $addQueryParams = $conf['addQueryString'] ? $this->contentObjectRenderer->getQueryArguments($conf['addQueryString.']) : '';
125 $addQueryParams .= isset($conf['additionalParams.']) ? trim((string)$this->contentObjectRenderer->stdWrap($conf['additionalParams'], $conf['additionalParams.'])) : trim((string)$conf['additionalParams']);
126 if ($addQueryParams === '&' || $addQueryParams[0] !== '&') {
127 $addQueryParams = '';
128 }
129 // Mount pages are always local and never link to another domain
130 if (!empty($MPvarAcc)) {
131 // Add "&MP" var:
132 $addQueryParams .= '&MP=' . rawurlencode(implode(',', $MPvarAcc));
133 } elseif (strpos($addQueryParams, '&MP=') === false) {
134 // We do not come here if additionalParams had '&MP='. This happens when typoLink is called from
135 // menu. Mount points always work in the content of the current domain and we must not change
136 // domain if MP variables exist.
137 // If we link across domains and page is free type shortcut, we must resolve the shortcut first!
138 // If we do not do it, TYPO3 will fail to (1) link proper page in RealURL/CoolURI because
139 // they return relative links and (2) show proper page if no RealURL/CoolURI exists when link is clicked
140 if ($enableLinksAcrossDomains
141 && (int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
142 && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
143 ) {
144 // Save in case of broken destination or endless loop
145 $page2 = $page;
146 // Same as in RealURL, seems enough
147 $maxLoopCount = 20;
148 while ($maxLoopCount
149 && is_array($page)
150 && (int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
151 && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
152 ) {
153 $page = $tsfe->sys_page->getPage($page['shortcut'], $disableGroupAccessCheck);
154 $maxLoopCount--;
155 }
156 if (empty($page) || $maxLoopCount === 0) {
157 // We revert if shortcut is broken or maximum number of loops is exceeded (indicates endless loop)
158 $page = $page2;
159 }
160 }
161 }
162 if ($conf['useCacheHash']) {
163 $params = $tsfe->linkVars . $addQueryParams . '&id=' . $page['uid'];
164 if (trim($params, '& ') !== '') {
165 $cHash = GeneralUtility::makeInstance(CacheHashCalculator::class)->generateForParameters($params);
166 $addQueryParams .= $cHash ? '&cHash=' . $cHash : '';
167 }
168 unset($params);
169 }
170
171 // Check if the target page has a site configuration
172 try {
173 $siteOfTargetPage = GeneralUtility::makeInstance(SiteMatcher::class)->matchByPageId((int)$page['uid']);
174 $currentSite = $this->getCurrentSite();
175 } catch (SiteNotFoundException $e) {
176 // Usually happens in tests, as Pseudo Sites should be available everywhere.
177 $siteOfTargetPage = null;
178 $currentSite = null;
179 }
180 // Link to a page that has a site configuration
181 if ($siteOfTargetPage instanceof Site) {
182 $queryParameters = [];
183 parse_str($addQueryParams, $queryParameters);
184 unset($queryParameters['id'], $queryParameters['L']);
185 if ($pageType) {
186 $queryParameters['type'] = (int)$pageType;
187 }
188
189 // Generate the URL
190 $url = $this->generateUrlForPageWithSiteConfiguration($page, $siteOfTargetPage, $queryParameters, $sectionMark, $conf);
191
192 $treatAsExternalLink = true;
193 // no scheme => always not external
194 if (!$url->getScheme() || !$url->getHost()) {
195 $treatAsExternalLink = false;
196 } else {
197 // URL has a scheme, possibly because someone requested a full URL. So now lets check if the URL
198 // is on the same site pagetree. If this is the case, we'll treat it as internal
199 if ($currentSite instanceof Site && $currentSite->getRootPageId() === $siteOfTargetPage->getRootPageId()) {
200 $treatAsExternalLink = false;
201 }
202 }
203
204 $url = (string)$url;
205 if ($treatAsExternalLink) {
206 $target = $target ?: $this->resolveTargetAttribute($conf, 'extTarget', false, $tsfe->extTarget);
207 } else {
208 $target = (isset($page['target']) && trim($page['target'])) ? $page['target'] : $target;
209 if (empty($target)) {
210 $target = $this->resolveTargetAttribute($conf, 'target', true, $tsfe->intTarget);
211 }
212 }
213 } else {
214 list($url, $target) = $this->generateUrlForPageWithoutSiteConfiguration($page, $addQueryParams, $conf, $pageType, $sectionMark, $target, $MPvarAcc);
215 }
216
217 // If link is to an access restricted page which should be redirected, then find new URL:
218 if (empty($conf['linkAccessRestrictedPages'])
219 && $tsfe->config['config']['typolinkLinkAccessRestrictedPages']
220 && $tsfe->config['config']['typolinkLinkAccessRestrictedPages'] !== 'NONE'
221 && !$tsfe->checkPageGroupAccess($page)
222 ) {
223 $thePage = $tsfe->sys_page->getPage($tsfe->config['config']['typolinkLinkAccessRestrictedPages']);
224 $addParams = str_replace(
225 [
226 '###RETURN_URL###',
227 '###PAGE_ID###'
228 ],
229 [
230 rawurlencode($url),
231 $page['uid']
232 ],
233 $tsfe->config['config']['typolinkLinkAccessRestrictedPages_addParams']
234 );
235 $url = $this->contentObjectRenderer->getTypoLink_URL($thePage['uid'] . ($pageType ? ',' . $pageType : ''), $addParams, $target);
236 $url = $this->forceAbsoluteUrl($url, $conf);
237 $this->contentObjectRenderer->lastTypoLinkLD['totalUrl'] = $url;
238 }
239
240 // Setting title if blank value to link
241 $linkText = $this->parseFallbackLinkTextIfLinkTextIsEmpty($linkText, $page['title']);
242 return [$url, $linkText, $target];
243 }
244
245 /**
246 * Resolves page and if a translated page was found, resolves that to it
247 * language parent, adjusts `$linkDetails['pageuid']` (for hook processing)
248 * and modifies `$configuration['language']` (for language URL generation).
249 *
250 * @param PageRepository $pageRepository
251 * @param array $linkDetails
252 * @param array $configuration
253 * @param bool $disableGroupAccessCheck
254 * @return array
255 */
256 protected function resolvePage(PageRepository $pageRepository, array &$linkDetails, array &$configuration, bool $disableGroupAccessCheck): array
257 {
258 // Looking up the page record to verify its existence:
259 $page = $pageRepository->getPage($linkDetails['pageuid'], $disableGroupAccessCheck);
260
261 if (empty($page) || !is_array($page)) {
262 return [];
263 }
264
265 $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'] ?? null;
266 $languageParentField = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'] ?? null;
267 $language = (int)($page[$languageField] ?? 0);
268
269 if ($language <= 0 || empty($page[$languageParentField])) {
270 return $page;
271 }
272
273 $languageParentPage = $pageRepository->getPage(
274 $page[$languageParentField],
275 $disableGroupAccessCheck
276 );
277 if (empty($languageParentPage)) {
278 return $page;
279 }
280
281 $linkDetails['pageuid'] = (int)$languageParentPage['uid'];
282 $configuration['language'] = $language;
283 return $languageParentPage;
284 }
285
286 /**
287 * Create a UriInterface object when linking to a page with a site configuration
288 *
289 * @param array $page
290 * @param Site $siteOfTargetPage
291 * @param array $queryParameters
292 * @param string $fragment
293 * @param array $conf
294 * @return UriInterface
295 * @throws UnableToLinkException
296 */
297 protected function generateUrlForPageWithSiteConfiguration(array $page, Site $siteOfTargetPage, array $queryParameters, string $fragment, array $conf): UriInterface
298 {
299 $currentSite = $this->getCurrentSite();
300 $currentSiteLanguage = $this->getCurrentSiteLanguage();
301 // Happens when currently on a pseudo-site configuration
302 // We assume to use the default language then
303 if (!($currentSiteLanguage instanceof SiteLanguage)) {
304 $currentSiteLanguage = $currentSite->getDefaultLanguage();
305 }
306
307 $targetLanguageId = $conf['language'] ?? 'current';
308 if ($targetLanguageId === 'current') {
309 $targetLanguageId = $currentSiteLanguage ? $currentSiteLanguage->getLanguageId() : 0;
310 } else {
311 $targetLanguageId = (int)$targetLanguageId;
312 }
313 try {
314 $siteLanguageOfTargetPage = $siteOfTargetPage->getLanguageById($targetLanguageId);
315 } catch (\InvalidArgumentException $e) {
316 throw new UnableToLinkException('The target page does not have a language with ID ' . $targetLanguageId . ' configured in its site configuration.', 1535477406);
317 }
318
319 // By default, it is assumed to ab an internal link or current domain's linking scheme should be used
320 // Use the config option to override this.
321 $useAbsoluteUrl = $conf['forceAbsoluteUrl'] ?? false;
322 // Check if the current page equal to the site of the target page, now only set the absolute URL
323 if ($currentSite->getRootPageId() !== $siteOfTargetPage->getRootPageId()) {
324 $useAbsoluteUrl = true;
325 // @todo: let's only check for host / scheme once we use the Uri interface
326 } elseif ($siteLanguageOfTargetPage->getBase() !== $currentSiteLanguage->getBase()) {
327 $useAbsoluteUrl = true;
328 }
329
330 $targetPageId = (int)($page['l10n_parent'] > 0 ? $page['l10n_parent'] : $page['uid']);
331
332 $uri = GeneralUtility::makeInstance(PageUriBuilder::class)->buildUri(
333 $targetPageId,
334 $queryParameters,
335 $fragment,
336 ['site' => $siteOfTargetPage, 'language' => $siteLanguageOfTargetPage],
337 $useAbsoluteUrl ? PageUriBuilder::ABSOLUTE_URL : PageUriBuilder::ABSOLUTE_PATH
338 );
339 // Override scheme, but only if the site does not define a scheme yet AND the site defines a domain/host
340 if ($useAbsoluteUrl && !$uri->getScheme() && $uri->getHost()) {
341 $scheme = $conf['forceAbsoluteUrl.']['scheme'] ?? 'https';
342 $uri = $uri->withScheme($scheme);
343 }
344 return $uri;
345 }
346
347 /**
348 * Generate a URL for a page without site configuration
349 *
350 * @param array $page
351 * @param string $additionalQueryParams
352 * @param array $conf
353 * @param string $pageType
354 * @param string $sectionMark
355 * @param string $target
356 * @param array $MPvarAcc
357 * @return array
358 */
359 protected function generateUrlForPageWithoutSiteConfiguration(array $page, string $additionalQueryParams, array $conf, string $pageType, string $sectionMark, string $target, array $MPvarAcc): array
360 {
361 // new 'language' property takes precedence over '&L=1' if numeric
362 // here 'additionalParams=&L={language-value}' will be overridden
363 if (MathUtility::canBeInterpretedAsInteger($conf['language'] ?? '')) {
364 $queryParameters = [];
365 parse_str($additionalQueryParams, $queryParameters);
366 $queryParameters['L'] = $conf['language'];
367 $additionalQueryParams = http_build_query(
368 $queryParameters,
369 '',
370 '&',
371 PHP_QUERY_RFC3986
372 );
373 }
374
375 $tsfe = $this->getTypoScriptFrontendController();
376 $enableLinksAcrossDomains = $tsfe->config['config']['typolinkEnableLinksAcrossDomains'];
377 $targetDomain = '';
378 $currentDomain = (string)GeneralUtility::getIndpEnv('HTTP_HOST');
379 if (!empty($MPvarAcc)) {
380 $domainResolver = GeneralUtility::makeInstance(LegacyDomainResolver::class);
381 $targetDomainRecord = $domainResolver->matchPageId((int)$page['uid'], $GLOBALS['TYPO3_REQUEST']);
382 // Do not prepend the domain if it is the current hostname
383 if (!empty($targetDomainRecord) && !$targetDomainRecord['isCurrentDomain']) {
384 $targetDomain = $targetDomainRecord['domainName'];
385 }
386 }
387 $absoluteUrlScheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https' : 'http';
388 // URL shall be absolute:
389 if (isset($conf['forceAbsoluteUrl']) && $conf['forceAbsoluteUrl']) {
390 // Override scheme:
391 if (isset($conf['forceAbsoluteUrl.']['scheme']) && $conf['forceAbsoluteUrl.']['scheme']) {
392 $absoluteUrlScheme = $conf['forceAbsoluteUrl.']['scheme'];
393 }
394 // If no domain records are defined, use current domain
395 $targetDomain = $targetDomain ?: $currentDomain;
396 // If go for an absolute link, add site path if it's not taken care about by absRefPrefix
397 if (!$tsfe->absRefPrefix && $targetDomain === $currentDomain) {
398 $targetDomain = $currentDomain . rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'), '/');
399 }
400 }
401 // If target page has a different domain and the current domain's linking scheme (e.g. RealURL/...) should not be used
402 if ($targetDomain !== '' && $targetDomain !== $currentDomain && !$enableLinksAcrossDomains) {
403 $target = $target ?: $this->resolveTargetAttribute($conf, 'extTarget', false, $tsfe->extTarget);
404 // Convert IDNA-like domain (if any)
405 if (!preg_match('/^[a-z0-9.\\-]*$/i', $targetDomain)) {
406 $targetDomain = GeneralUtility::idnaEncode($targetDomain);
407 }
408 $url = $absoluteUrlScheme . '://' . $targetDomain . '/index.php?id=' . $page['uid'] . $additionalQueryParams;
409 } else {
410 // Internal link or current domain's linking scheme should be used
411 // Internal target:
412 $target = (isset($page['target']) && trim($page['target'])) ? $page['target'] : $target;
413 if (empty($target)) {
414 $target = $this->resolveTargetAttribute($conf, 'target', true, $tsfe->intTarget);
415 }
416 $LD = $this->createTotalUrlAndLinkData($page, $target, $conf['no_cache'], $additionalQueryParams, $pageType, $targetDomain);
417 if ($targetDomain !== '') {
418 // We will add domain only if URL does not have it already.
419 if ($enableLinksAcrossDomains && $targetDomain !== $currentDomain && !empty($tsfe->absRefPrefix)) {
420 // Get rid of the absRefPrefix if necessary. absRefPrefix is applicable only
421 // to the current web site. If we have domain here it means we link across
422 // domains. absRefPrefix can contain domain name, which will screw up
423 // the link to the external domain.
424 $prefixLength = strlen($tsfe->absRefPrefix);
425 if (substr($LD['totalURL'], 0, $prefixLength) === $tsfe->absRefPrefix) {
426 $LD['totalURL'] = substr($LD['totalURL'], $prefixLength);
427 }
428 }
429 $urlParts = parse_url($LD['totalURL']);
430 if (empty($urlParts['host'])) {
431 $LD['totalURL'] = $absoluteUrlScheme . '://' . $targetDomain . ($LD['totalURL'][0] === '/' ? '' : '/') . $LD['totalURL'];
432 }
433 }
434 $url = $LD['totalURL'];
435 }
436 $url .= $sectionMark;
437 // If sectionMark is set, there is no baseURL AND the current page is the page the link is to,
438 // check if there are any additional parameters or addQueryString parameters and if not, drop the url.
439 if ($sectionMark
440 && !$tsfe->config['config']['baseURL']
441 && (int)$page['uid'] === (int)$tsfe->id
442 && !trim($additionalQueryParams)
443 && (empty($conf['addQueryString']) || !isset($conf['addQueryString.']))
444 ) {
445 $currentQueryArray = [];
446 parse_str(GeneralUtility::getIndpEnv('QUERY_STRING'), $currentQueryArray);
447 $currentQueryParams = GeneralUtility::implodeArrayForUrl('', $currentQueryArray, '', false, true);
448
449 if (!trim($currentQueryParams)) {
450 list(, $URLparams) = explode('?', $url);
451 list($URLparams) = explode('#', (string)$URLparams);
452 parse_str($URLparams . $LD['orig_type'], $URLparamsArray);
453 // Type nums must match as well as page ids
454 if ((int)$URLparamsArray['type'] === (int)$tsfe->type) {
455 unset($URLparamsArray['id']);
456 unset($URLparamsArray['type']);
457 // If there are no parameters left.... set the new url.
458 if (empty($URLparamsArray)) {
459 $url = $sectionMark;
460 }
461 }
462 }
463 }
464 return [$url, $target];
465 }
466
467 /**
468 * Returns the &MP variable value for a page id.
469 * 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.
470 *
471 * @param int $pageId page id
472 * @return string MP value, prefixed with &MP= (depending on $raw)
473 */
474 protected function getClosestMountPointValueForPage($pageId)
475 {
476 $tsfe = $this->getTypoScriptFrontendController();
477 if (empty($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) || !$tsfe->MP) {
478 return '';
479 }
480 // Same page as current.
481 if ((int)$tsfe->id === (int)$pageId) {
482 return $tsfe->MP;
483 }
484
485 // Find closest mount point
486 // Gets rootline of linked-to page
487 try {
488 $tCR_rootline = GeneralUtility::makeInstance(RootlineUtility::class, $pageId)->get();
489 } catch (RootLineException $e) {
490 $tCR_rootline = [];
491 }
492 $inverseTmplRootline = array_reverse($tsfe->tmpl->rootLine);
493 $rl_mpArray = [];
494 $startMPaccu = false;
495 // Traverse root line of link uid and inside of that the REAL root line of current position.
496 foreach ($tCR_rootline as $tCR_data) {
497 foreach ($inverseTmplRootline as $rlKey => $invTmplRLRec) {
498 // Force accumulating when in overlay mode: Links to this page have to stay within the current branch
499 if ($invTmplRLRec['_MOUNT_OL'] && (int)$tCR_data['uid'] === (int)$invTmplRLRec['uid']) {
500 $startMPaccu = true;
501 }
502 // Accumulate MP data:
503 if ($startMPaccu && $invTmplRLRec['_MP_PARAM']) {
504 $rl_mpArray[] = $invTmplRLRec['_MP_PARAM'];
505 }
506 // If two PIDs matches and this is NOT the site root, start accumulation of MP data (on the next level):
507 // (The check for site root is done so links to branches outsite the site but sharing the site roots PID
508 // is NOT detected as within the branch!)
509 if ((int)$tCR_data['pid'] === (int)$invTmplRLRec['pid'] && count($inverseTmplRootline) !== $rlKey + 1) {
510 $startMPaccu = true;
511 }
512 }
513 if ($startMPaccu) {
514 // Good enough...
515 break;
516 }
517 }
518 return !empty($rl_mpArray) ? implode(',', array_reverse($rl_mpArray)) : '';
519 }
520
521 /**
522 * Initializes the automatically created mountPointMap coming from the "config.MP_mapRootPoints" setting
523 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
524 *
525 * Previously located within TemplateService::getFromMPmap()
526 *
527 * @param int $pageId Page id to return MPvar value for.
528 * @return string
529 */
530 public function getMountPointParameterFromRootPointMaps(int $pageId)
531 {
532 // Create map if not found already
533 $config = $this->getTypoScriptFrontendController()->config;
534 $mountPointMap = $this->initializeMountPointMap(
535 !empty($config['config']['MP_defaults']) ? $config['config']['MP_defaults'] : null,
536 !empty($config['config']['MP_mapRootPoints']) ? $config['config']['MP_mapRootPoints'] : null
537 );
538
539 // Finding MP var for Page ID:
540 if (!empty($mountPointMap[$pageId])) {
541 return implode(',', $mountPointMap[$pageId]);
542 }
543 return '';
544 }
545
546 /**
547 * Create mount point map, based on TypoScript config.MP_mapRootPoints and config.MP_defaults.
548 *
549 * @param string $defaultMountPoints a string as defined in config.MP_defaults
550 * @param string|null $mapRootPointList a string as defined in config.MP_mapRootPoints
551 * @return array
552 */
553 protected function initializeMountPointMap(string $defaultMountPoints = null, string $mapRootPointList = null): array
554 {
555 $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
556 $mountPointMap = $runtimeCache->get('pageLinkBuilderMountPointMap') ?: [];
557 if (!empty($mountPointMap) || (empty($mapRootPointList) && empty($defaultMountPoints))) {
558 return $mountPointMap;
559 }
560 if ($defaultMountPoints) {
561 $defaultMountPoints = GeneralUtility::trimExplode('|', $defaultMountPoints, true);
562 foreach ($defaultMountPoints as $temp_p) {
563 list($temp_idP, $temp_MPp) = explode(':', $temp_p, 2);
564 $temp_ids = GeneralUtility::intExplode(',', $temp_idP);
565 foreach ($temp_ids as $temp_id) {
566 $mountPointMap[$temp_id] = trim($temp_MPp);
567 }
568 }
569 }
570
571 $rootPoints = GeneralUtility::trimExplode(',', strtolower($mapRootPointList), true);
572 // Traverse rootpoints
573 foreach ($rootPoints as $p) {
574 $initMParray = [];
575 if ($p === 'root') {
576 $rootPage = $this->getTypoScriptFrontendController()->tmpl->rootLine[0];
577 $p = $rootPage['uid'];
578 if ($p['_MOUNT_OL'] && $p['_MP_PARAM']) {
579 $initMParray[] = $p['_MP_PARAM'];
580 }
581 }
582 $this->populateMountPointMapForPageRecursively($mountPointMap, $p, $initMParray);
583 }
584 $runtimeCache->set('pageLinkBuilderMountPointMap', $mountPointMap);
585 return $mountPointMap;
586 }
587
588 /**
589 * Creating mountPointMap for a certain ID root point.
590 * Previously called TemplateService->initMPmap_create()
591 *
592 * @param array $mountPointMap the exiting mount point map
593 * @param int $id Root id from which to start map creation.
594 * @param array $MP_array MP_array passed from root page.
595 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
596 * @see getMountPointParameterFromRootPointMaps()
597 */
598 protected function populateMountPointMapForPageRecursively(array &$mountPointMap, int $id, $MP_array = [], $level = 0)
599 {
600 if ($id <= 0) {
601 return;
602 }
603 // First level, check id
604 if (!$level) {
605 // Find mount point if any:
606 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
607 // Overlay mode:
608 if (is_array($mount_info) && $mount_info['overlay']) {
609 $MP_array[] = $mount_info['MPvar'];
610 $id = $mount_info['mount_pid'];
611 }
612 // Set mapping information for this level:
613 $mountPointMap[$id] = $MP_array;
614 // Normal mode:
615 if (is_array($mount_info) && !$mount_info['overlay']) {
616 $MP_array[] = $mount_info['MPvar'];
617 $id = $mount_info['mount_pid'];
618 }
619 }
620 if ($id && $level < 20) {
621 $nextLevelAcc = [];
622 // Select and traverse current level pages:
623 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
624 $queryBuilder->getRestrictions()
625 ->removeAll()
626 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
627 $queryResult = $queryBuilder
628 ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
629 ->from('pages')
630 ->where(
631 $queryBuilder->expr()->eq(
632 'pid',
633 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
634 ),
635 $queryBuilder->expr()->neq(
636 'doktype',
637 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
638 ),
639 $queryBuilder->expr()->neq(
640 'doktype',
641 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
642 )
643 )->execute();
644 while ($row = $queryResult->fetch()) {
645 // Find mount point if any:
646 $next_id = $row['uid'];
647 $next_MP_array = $MP_array;
648 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
649 // Overlay mode:
650 if (is_array($mount_info) && $mount_info['overlay']) {
651 $next_MP_array[] = $mount_info['MPvar'];
652 $next_id = $mount_info['mount_pid'];
653 }
654 if (!isset($mountPointMap[$next_id])) {
655 // Set mapping information for this level:
656 $mountPointMap[$next_id] = $next_MP_array;
657 // Normal mode:
658 if (is_array($mount_info) && !$mount_info['overlay']) {
659 $next_MP_array[] = $mount_info['MPvar'];
660 $next_id = $mount_info['mount_pid'];
661 }
662 // Register recursive call
663 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
664 $nextLevelAcc[] = [$next_id, $next_MP_array];
665 }
666 }
667 // Call recursively, if any:
668 foreach ($nextLevelAcc as $pSet) {
669 $this->populateMountPointMapForPageRecursively($mountPointMap, $pSet[0], $pSet[1], $level + 1);
670 }
671 }
672 }
673
674 /**
675 * The mother of all functions creating links/URLs etc in a TypoScript environment.
676 * See the references below.
677 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
678 * It is important to pass all links created through this function since this is the guarantee that globally configured settings for link creating are observed and that your applications will conform to the various/many configuration options in TypoScript Templates regarding this.
679 *
680 * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, title and sectionIndex_uid.
681 * @param string $target Target string
682 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
683 * @param string $addParams Additional URL parameters to set in the URL. Syntax is "&foo=bar&foo2=bar2" etc. Also used internally to add parameters if needed.
684 * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $this->getTypoScriptFrontendController()->config['config']['forceTypeValue'] if found.
685 * @param string $targetDomain The target Doamin, if any was detected in typolink
686 * @return array Contains keys like "totalURL", "url", "sectionIndex", "linkVars", "no_cache", "type" of which "totalURL" is normally the value you would use while the other keys contains various parts that was used to construct "totalURL
687 */
688 protected function createTotalUrlAndLinkData($page, $target, $no_cache, $addParams = '', $typeOverride = '', $targetDomain = '')
689 {
690 $LD = [];
691 // Adding Mount Points, "&MP=", parameter for the current page if any is set
692 // but non other set explicitly
693 if (strpos($addParams, '&MP=') === false) {
694 $mountPointParameter = $this->getMountPointParameterFromRootPointMaps((int)$page['uid']);
695 if ($mountPointParameter) {
696 $addParams .= '&MP=' . rawurlencode($mountPointParameter);
697 }
698 }
699 // Setting ID/alias:
700 $script = 'index.php';
701 if ($page['alias']) {
702 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
703 } else {
704 $LD['url'] = $script . '?id=' . $page['uid'];
705 }
706 // typeNum
707 $typeNum = $this->getTypoScriptFrontendController()->tmpl->setup[$target . '.']['typeNum'];
708 if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
709 $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
710 }
711 if ((string)$typeOverride !== '') {
712 $typeNum = $typeOverride;
713 }
714 // Override...
715 if ($typeNum) {
716 $LD['type'] = '&type=' . (int)$typeNum;
717 } else {
718 $LD['type'] = '';
719 }
720 // Preserving the type number.
721 $LD['orig_type'] = $LD['type'];
722 // noCache
723 $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
724 // linkVars
725 if ($addParams) {
726 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', false, true);
727 } else {
728 $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
729 }
730 // Add absRefPrefix if exists.
731 $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
732 // If the special key 'sectionIndex_uid' (added 'manually' in tslib/menu.php to the page-record) is set, then the link jumps directly to a section on the page.
733 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
734 // Compile the normal total url
735 $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
736 // Call post processing function for link rendering:
737 $_params = [
738 'LD' => &$LD,
739 'args' => ['page' => $page, 'oTarget' => $target, 'no_cache' => $no_cache, 'script' => $script, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
740 'typeNum' => $typeNum
741 ];
742 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
743 GeneralUtility::callUserFunction($_funcRef, $_params, $this->getTypoScriptFrontendController()->tmpl);
744 }
745 return $LD;
746 }
747
748 /**
749 * Check if we have a site object in the current request. if null, this usually means that
750 * this class was called from CLI context.
751 *
752 * @return SiteInterface|null
753 */
754 protected function getCurrentSite(): ?SiteInterface
755 {
756 if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
757 return $GLOBALS['TYPO3_REQUEST']->getAttribute('site', null);
758 }
759 if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TSFE']->id) && $GLOBALS['TSFE']->id > 0) {
760 $matcher = GeneralUtility::makeInstance(SiteMatcher::class);
761 return $matcher->matchByPageId((int)$GLOBALS['TSFE']->id);
762 }
763 return null;
764 }
765
766 /**
767 * If the current request has a site language, this means that the SiteResolver has detected a
768 * page with a site configuration and a selected language, so let's choose that one.
769 *
770 * @return SiteLanguage|null
771 */
772 protected function getCurrentSiteLanguage(): ?SiteLanguage
773 {
774 if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
775 return $GLOBALS['TYPO3_REQUEST']->getAttribute('language', null);
776 }
777 return null;
778 }
779 }