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