[TASK] Move PageUriBuilder to EXT:core
[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 TYPO3\CMS\Core\Cache\CacheManager;
20 use TYPO3\CMS\Core\Database\ConnectionPool;
21 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
22 use TYPO3\CMS\Core\Exception\Page\RootLineException;
23 use TYPO3\CMS\Core\Routing\PageUriBuilder;
24 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Core\Utility\MathUtility;
27 use TYPO3\CMS\Core\Utility\RootlineUtility;
28 use TYPO3\CMS\Frontend\ContentObject\TypolinkModifyLinkConfigForPageLinksHookInterface;
29 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
30 use TYPO3\CMS\Frontend\Page\PageRepository;
31
32 /**
33 * Builds a TypoLink to a certain page
34 */
35 class PageLinkBuilder extends AbstractTypolinkBuilder
36 {
37 /**
38 * @inheritdoc
39 */
40 public function build(array &$linkDetails, string $linkText, string $target, array $conf): array
41 {
42 $tsfe = $this->getTypoScriptFrontendController();
43 // Checking if the id-parameter is an alias.
44 if (!empty($linkDetails['pagealias'])) {
45 $linkDetails['pageuid'] = $tsfe->sys_page->getPageIdFromAlias($linkDetails['pagealias']);
46 } elseif (empty($linkDetails['pageuid']) || $linkDetails['pageuid'] === 'current') {
47 // If no id or alias is given
48 $linkDetails['pageuid'] = $tsfe->id;
49 }
50
51 // Link to page even if access is missing?
52 if (isset($conf['linkAccessRestrictedPages'])) {
53 $disableGroupAccessCheck = (bool)$conf['linkAccessRestrictedPages'];
54 } else {
55 $disableGroupAccessCheck = (bool)$tsfe->config['config']['typolinkLinkAccessRestrictedPages'];
56 }
57
58 // Looking up the page record to verify its existence:
59 $page = $tsfe->sys_page->getPage($linkDetails['pageuid'], $disableGroupAccessCheck);
60
61 if (empty($page)) {
62 throw new UnableToLinkException('Page id "' . $linkDetails['typoLinkParameter'] . '" was not found, so "' . $linkText . '" was not linked.', 1490987336, null, $linkText);
63 }
64 $language = $page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
65 if ($language === 0 && GeneralUtility::hideIfDefaultLanguage($page['l18n_cfg'])) {
66 throw new UnableToLinkException('Default language of page "' . $linkDetails['typoLinkParameter'] . '" is hidden, so "' . $linkText . '" was not linked.', 1529527301, null, $linkText);
67 }
68 if ($language > 0 && !isset($page['_PAGES_OVERLAY']) && GeneralUtility::hideIfNotTranslated($page['l18n_cfg'])) {
69 throw new UnableToLinkException('Fallback to default language of page "' . $linkDetails['typoLinkParameter'] . '" is disabled, so "' . $linkText . '" was not linked.', 1529527488, 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 $hookObject TypolinkModifyLinkConfigForPageLinksHookInterface */
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 // Setting title if blank value to link
116 $linkText = $this->parseFallbackLinkTextIfLinkTextIsEmpty($linkText, $page['title']);
117 // Query Params:
118 $addQueryParams = $conf['addQueryString'] ? $this->contentObjectRenderer->getQueryArguments($conf['addQueryString.']) : '';
119 $addQueryParams .= isset($conf['additionalParams.']) ? trim((string)$this->contentObjectRenderer->stdWrap($conf['additionalParams'], $conf['additionalParams.'])) : trim((string)$conf['additionalParams']);
120 if ($addQueryParams === '&' || $addQueryParams[0] !== '&') {
121 $addQueryParams = '';
122 }
123 $targetDomain = '';
124 $currentDomain = (string)GeneralUtility::getIndpEnv('HTTP_HOST');
125 // Mount pages are always local and never link to another domain
126 if (!empty($MPvarAcc)) {
127 // Add "&MP" var:
128 $addQueryParams .= '&MP=' . rawurlencode(implode(',', $MPvarAcc));
129 } elseif (strpos($addQueryParams, '&MP=') === false) {
130 // We do not come here if additionalParams had '&MP='. This happens when typoLink is called from
131 // menu. Mount points always work in the content of the current domain and we must not change
132 // domain if MP variables exist.
133 // If we link across domains and page is free type shortcut, we must resolve the shortcut first!
134 // If we do not do it, TYPO3 will fail to (1) link proper page in RealURL/CoolURI because
135 // they return relative links and (2) show proper page if no RealURL/CoolURI exists when link is clicked
136 if ($enableLinksAcrossDomains
137 && (int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
138 && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
139 ) {
140 // Save in case of broken destination or endless loop
141 $page2 = $page;
142 // Same as in RealURL, seems enough
143 $maxLoopCount = 20;
144 while ($maxLoopCount
145 && is_array($page)
146 && (int)$page['doktype'] === PageRepository::DOKTYPE_SHORTCUT
147 && (int)$page['shortcut_mode'] === PageRepository::SHORTCUT_MODE_NONE
148 ) {
149 $page = $tsfe->sys_page->getPage($page['shortcut'], $disableGroupAccessCheck);
150 $maxLoopCount--;
151 }
152 if (empty($page) || $maxLoopCount === 0) {
153 // We revert if shortcut is broken or maximum number of loops is exceeded (indicates endless loop)
154 $page = $page2;
155 }
156 }
157
158 $targetDomainRecord = $tsfe->getDomainDataForPid($page['uid']);
159 $targetDomain = $targetDomainRecord ? $targetDomainRecord['domainName'] : null;
160 // Do not prepend the domain if it is the current hostname
161 if (!$targetDomain || $tsfe->domainNameMatchesCurrentRequest($targetDomain)) {
162 $targetDomain = '';
163 }
164 }
165 if ($conf['useCacheHash']) {
166 $params = $tsfe->linkVars . $addQueryParams . '&id=' . $page['uid'];
167 if (trim($params, '& ') !== '') {
168 $cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
169 $cHash = $cacheHash->generateForParameters($params);
170 $addQueryParams .= $cHash ? '&cHash=' . $cHash : '';
171 }
172 unset($params);
173 }
174 $absoluteUrlScheme = GeneralUtility::getIndpEnv('TYPO3_SSL') ? 'https' : 'http';
175 // URL shall be absolute:
176 if (isset($conf['forceAbsoluteUrl']) && $conf['forceAbsoluteUrl']) {
177 // Override scheme:
178 if (isset($conf['forceAbsoluteUrl.']['scheme']) && $conf['forceAbsoluteUrl.']['scheme']) {
179 $absoluteUrlScheme = $conf['forceAbsoluteUrl.']['scheme'];
180 }
181 // If no domain records are defined, use current domain:
182 $currentUrlScheme = parse_url(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'), PHP_URL_SCHEME);
183 if ($targetDomain === '' && ($conf['forceAbsoluteUrl'] || $absoluteUrlScheme !== $currentUrlScheme)) {
184 $targetDomain = $currentDomain;
185 }
186 // If go for an absolute link, add site path if it's not taken care about by absRefPrefix
187 if (!$tsfe->config['config']['absRefPrefix'] && $targetDomain === $currentDomain) {
188 $targetDomain = $currentDomain . rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'), '/');
189 }
190 }
191 // If target page has a different domain and the current domain's linking scheme (e.g. RealURL/...) should not be used
192 if ($targetDomain !== '' && $targetDomain !== $currentDomain && !$enableLinksAcrossDomains) {
193 $target = $target ?: $this->resolveTargetAttribute($conf, 'extTarget', false, $tsfe->extTarget);
194 // Convert IDNA-like domain (if any)
195 if (!preg_match('/^[a-z0-9.\\-]*$/i', $targetDomain)) {
196 $targetDomain = GeneralUtility::idnaEncode($targetDomain);
197 }
198 $url = $absoluteUrlScheme . '://' . $targetDomain . '/index.php?id=' . $page['uid'] . $addQueryParams . $sectionMark;
199 } else {
200 // Internal link or current domain's linking scheme should be used
201 // Internal target:
202 $target = (isset($page['target']) && trim($page['target'])) ? $page['target'] : $target;
203 if (empty($target)) {
204 $target = $this->resolveTargetAttribute($conf, 'target', true, $tsfe->intTarget);
205 }
206 $LD = $this->createTotalUrlAndLinkData($page, $target, $conf['no_cache'], $addQueryParams, $pageType, $targetDomain);
207 if ($targetDomain !== '') {
208 // We will add domain only if URL does not have it already.
209 if ($enableLinksAcrossDomains && $targetDomain !== $currentDomain && isset($tsfe->config['config']['absRefPrefix'])) {
210 // Get rid of the absRefPrefix if necessary. absRefPrefix is applicable only
211 // to the current web site. If we have domain here it means we link across
212 // domains. absRefPrefix can contain domain name, which will screw up
213 // the link to the external domain.
214 $prefixLength = strlen($tsfe->config['config']['absRefPrefix']);
215 if (substr($LD['totalURL'], 0, $prefixLength) === $tsfe->config['config']['absRefPrefix']) {
216 $LD['totalURL'] = substr($LD['totalURL'], $prefixLength);
217 }
218 }
219 $urlParts = parse_url($LD['totalURL']);
220 if (empty($urlParts['host'])) {
221 $LD['totalURL'] = $absoluteUrlScheme . '://' . $targetDomain . ($LD['totalURL'][0] === '/' ? '' : '/') . $LD['totalURL'];
222 }
223 }
224 $url = $LD['totalURL'] . $sectionMark;
225 }
226 // If sectionMark is set, there is no baseURL AND the current page is the page the link is to, check if there are any additional parameters or addQueryString parameters and if not, drop the url.
227 if ($sectionMark
228 && !$tsfe->config['config']['baseURL']
229 && (int)$page['uid'] === (int)$tsfe->id
230 && !trim($addQueryParams)
231 && (empty($conf['addQueryString']) || !isset($conf['addQueryString.']))
232 ) {
233 $currentQueryArray = GeneralUtility::explodeUrl2Array(GeneralUtility::getIndpEnv('QUERY_STRING'), true);
234 $currentQueryParams = GeneralUtility::implodeArrayForUrl('', $currentQueryArray, '', false, true);
235
236 if (!trim($currentQueryParams)) {
237 list(, $URLparams) = explode('?', $url);
238 list($URLparams) = explode('#', (string)$URLparams);
239 parse_str($URLparams . $LD['orig_type'], $URLparamsArray);
240 // Type nums must match as well as page ids
241 if ((int)$URLparamsArray['type'] === (int)$tsfe->type) {
242 unset($URLparamsArray['id']);
243 unset($URLparamsArray['type']);
244 // If there are no parameters left.... set the new url.
245 if (empty($URLparamsArray)) {
246 $url = $sectionMark;
247 }
248 }
249 }
250 }
251
252 // If link is to an access restricted page which should be redirected, then find new URL:
253 if (empty($conf['linkAccessRestrictedPages'])
254 && $tsfe->config['config']['typolinkLinkAccessRestrictedPages']
255 && $tsfe->config['config']['typolinkLinkAccessRestrictedPages'] !== 'NONE'
256 && !$tsfe->checkPageGroupAccess($page)
257 ) {
258 $thePage = $tsfe->sys_page->getPage($tsfe->config['config']['typolinkLinkAccessRestrictedPages']);
259 $addParams = str_replace(
260 [
261 '###RETURN_URL###',
262 '###PAGE_ID###'
263 ],
264 [
265 rawurlencode($url),
266 $page['uid']
267 ],
268 $tsfe->config['config']['typolinkLinkAccessRestrictedPages_addParams']
269 );
270 $url = $this->contentObjectRenderer->getTypoLink_URL($thePage['uid'] . ($pageType ? ',' . $pageType : ''), $addParams, $target);
271 $url = $this->forceAbsoluteUrl($url, $conf);
272 $this->contentObjectRenderer->lastTypoLinkLD['totalUrl'] = $url;
273 }
274
275 return [$url, $linkText, $target];
276 }
277
278 /**
279 * Returns the &MP variable value for a page id.
280 * 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.
281 *
282 * @param int $pageId page id
283 * @return string MP value, prefixed with &MP= (depending on $raw)
284 */
285 protected function getClosestMountPointValueForPage($pageId)
286 {
287 $tsfe = $this->getTypoScriptFrontendController();
288 if (empty($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) || !$tsfe->MP) {
289 return '';
290 }
291 // Same page as current.
292 if ((int)$tsfe->id === (int)$pageId) {
293 return $tsfe->MP;
294 }
295
296 // Find closest mount point
297 // Gets rootline of linked-to page
298 try {
299 $tCR_rootline = GeneralUtility::makeInstance(RootlineUtility::class, $pageId)->get();
300 } catch (RootLineException $e) {
301 $tCR_rootline = [];
302 }
303 $inverseTmplRootline = array_reverse($tsfe->tmpl->rootLine);
304 $rl_mpArray = [];
305 $startMPaccu = false;
306 // Traverse root line of link uid and inside of that the REAL root line of current position.
307 foreach ($tCR_rootline as $tCR_data) {
308 foreach ($inverseTmplRootline as $rlKey => $invTmplRLRec) {
309 // Force accumulating when in overlay mode: Links to this page have to stay within the current branch
310 if ($invTmplRLRec['_MOUNT_OL'] && (int)$tCR_data['uid'] === (int)$invTmplRLRec['uid']) {
311 $startMPaccu = true;
312 }
313 // Accumulate MP data:
314 if ($startMPaccu && $invTmplRLRec['_MP_PARAM']) {
315 $rl_mpArray[] = $invTmplRLRec['_MP_PARAM'];
316 }
317 // If two PIDs matches and this is NOT the site root, start accumulation of MP data (on the next level):
318 // (The check for site root is done so links to branches outsite the site but sharing the site roots PID
319 // is NOT detected as within the branch!)
320 if ((int)$tCR_data['pid'] === (int)$invTmplRLRec['pid'] && count($inverseTmplRootline) !== $rlKey + 1) {
321 $startMPaccu = true;
322 }
323 }
324 if ($startMPaccu) {
325 // Good enough...
326 break;
327 }
328 }
329 return !empty($rl_mpArray) ? implode(',', array_reverse($rl_mpArray)) : '';
330 }
331
332 /**
333 * Initializes the automatically created mountPointMap coming from the "config.MP_mapRootPoints" setting
334 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
335 *
336 * Previously located within TemplateService::getFromMPmap()
337 *
338 * @param int $pageId Page id to return MPvar value for.
339 * @return string
340 */
341 public function getMountPointParameterFromRootPointMaps(int $pageId)
342 {
343 // Create map if not found already
344 $config = $this->getTypoScriptFrontendController()->config;
345 $mountPointMap = $this->initializeMountPointMap(
346 !empty($config['config']['MP_defaults']) ? $config['config']['MP_defaults'] : null,
347 !empty($config['config']['MP_mapRootPoints']) ? $config['config']['MP_mapRootPoints'] : null
348 );
349
350 // Finding MP var for Page ID:
351 if (!empty($mountPointMap[$pageId])) {
352 return implode(',', $mountPointMap[$pageId]);
353 }
354 return '';
355 }
356
357 /**
358 * Create mount point map, based on TypoScript config.MP_mapRootPoints and config.MP_defaults.
359 *
360 * @param string $defaultMountPoints a string as defined in config.MP_defaults
361 * @param string|null $mapRootPointList a string as defined in config.MP_mapRootPoints
362 * @return array
363 */
364 protected function initializeMountPointMap(string $defaultMountPoints = null, string $mapRootPointList = null): array
365 {
366 $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
367 $mountPointMap = $runtimeCache->get('pageLinkBuilderMountPointMap') ?: [];
368 if (!empty($mountPointMap) || (empty($mapRootPointList) && empty($defaultMountPoints))) {
369 return $mountPointMap;
370 }
371 if ($defaultMountPoints) {
372 $defaultMountPoints = GeneralUtility::trimExplode('|', $defaultMountPoints, true);
373 foreach ($defaultMountPoints as $temp_p) {
374 list($temp_idP, $temp_MPp) = explode(':', $temp_p, 2);
375 $temp_ids = GeneralUtility::intExplode(',', $temp_idP);
376 foreach ($temp_ids as $temp_id) {
377 $mountPointMap[$temp_id] = trim($temp_MPp);
378 }
379 }
380 }
381
382 $rootPoints = GeneralUtility::trimExplode(',', strtolower($mapRootPointList), true);
383 // Traverse rootpoints
384 foreach ($rootPoints as $p) {
385 $initMParray = [];
386 if ($p === 'root') {
387 $rootPage = $this->getTypoScriptFrontendController()->tmpl->rootLine[0];
388 $p = $rootPage['uid'];
389 if ($p['_MOUNT_OL'] && $p['_MP_PARAM']) {
390 $initMParray[] = $p['_MP_PARAM'];
391 }
392 }
393 $this->populateMountPointMapForPageRecursively($mountPointMap, $p, $initMParray);
394 }
395 $runtimeCache->set('pageLinkBuilderMountPointMap', $mountPointMap);
396 return $mountPointMap;
397 }
398
399 /**
400 * Creating mountPointMap for a certain ID root point.
401 * Previously called TemplateService->initMPmap_create()
402 *
403 * @param array $mountPointMap the exiting mount point map
404 * @param int $id Root id from which to start map creation.
405 * @param array $MP_array MP_array passed from root page.
406 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
407 * @see getMountPointParameterFromRootPointMaps()
408 */
409 protected function populateMountPointMapForPageRecursively(array &$mountPointMap, int $id, $MP_array = [], $level = 0)
410 {
411 if ($id <= 0) {
412 return;
413 }
414 // First level, check id
415 if (!$level) {
416 // Find mount point if any:
417 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
418 // Overlay mode:
419 if (is_array($mount_info) && $mount_info['overlay']) {
420 $MP_array[] = $mount_info['MPvar'];
421 $id = $mount_info['mount_pid'];
422 }
423 // Set mapping information for this level:
424 $mountPointMap[$id] = $MP_array;
425 // Normal mode:
426 if (is_array($mount_info) && !$mount_info['overlay']) {
427 $MP_array[] = $mount_info['MPvar'];
428 $id = $mount_info['mount_pid'];
429 }
430 }
431 if ($id && $level < 20) {
432 $nextLevelAcc = [];
433 // Select and traverse current level pages:
434 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
435 $queryBuilder->getRestrictions()
436 ->removeAll()
437 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
438 $queryResult = $queryBuilder
439 ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
440 ->from('pages')
441 ->where(
442 $queryBuilder->expr()->eq(
443 'pid',
444 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
445 ),
446 $queryBuilder->expr()->neq(
447 'doktype',
448 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
449 ),
450 $queryBuilder->expr()->neq(
451 'doktype',
452 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
453 )
454 )->execute();
455 while ($row = $queryResult->fetch()) {
456 // Find mount point if any:
457 $next_id = $row['uid'];
458 $next_MP_array = $MP_array;
459 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
460 // Overlay mode:
461 if (is_array($mount_info) && $mount_info['overlay']) {
462 $next_MP_array[] = $mount_info['MPvar'];
463 $next_id = $mount_info['mount_pid'];
464 }
465 if (!isset($mountPointMap[$next_id])) {
466 // Set mapping information for this level:
467 $mountPointMap[$next_id] = $next_MP_array;
468 // Normal mode:
469 if (is_array($mount_info) && !$mount_info['overlay']) {
470 $next_MP_array[] = $mount_info['MPvar'];
471 $next_id = $mount_info['mount_pid'];
472 }
473 // Register recursive call
474 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
475 $nextLevelAcc[] = [$next_id, $next_MP_array];
476 }
477 }
478 // Call recursively, if any:
479 foreach ($nextLevelAcc as $pSet) {
480 $this->populateMountPointMapForPageRecursively($mountPointMap, $pSet[0], $pSet[1], $level + 1);
481 }
482 }
483 }
484
485 /**
486 * The mother of all functions creating links/URLs etc in a TypoScript environment.
487 * See the references below.
488 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
489 * 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.
490 *
491 * @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.
492 * @param string $target Target string
493 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
494 * @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.
495 * @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.
496 * @param string $targetDomain The target Doamin, if any was detected in typolink
497 * @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
498 */
499 protected function createTotalUrlAndLinkData($page, $target, $no_cache, $addParams = '', $typeOverride = '', $targetDomain = '')
500 {
501 $allQueryParameters = [];
502 $LD = [];
503 // Adding Mount Points, "&MP=", parameter for the current page if any is set
504 // but non other set explicitly
505 if (strpos($addParams, '&MP=') === false) {
506 $mountPointParameter = $this->getMountPointParameterFromRootPointMaps((int)$page['uid']);
507 if ($mountPointParameter) {
508 $addParams .= '&MP=' . rawurlencode($mountPointParameter);
509 }
510 }
511 // Setting ID/alias:
512 $script = 'index.php';
513 if ($page['alias']) {
514 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
515 } else {
516 $LD['url'] = $script . '?id=' . $page['uid'];
517 }
518 // typeNum
519 $typeNum = $this->getTypoScriptFrontendController()->tmpl->setup[$target . '.']['typeNum'];
520 $config = $this->getTypoScriptFrontendController()->config;
521 if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && !empty($config['config']['forceTypeValue']) && (int)$config['config']['forceTypeValue']) {
522 $typeOverride = (int)$config['config']['forceTypeValue'];
523 }
524 if ((string)$typeOverride !== '') {
525 $typeNum = $typeOverride;
526 }
527 // Override...
528 if ($typeNum) {
529 $LD['type'] = '&type=' . (int)$typeNum;
530 $allQueryParameters['type'] = (int)$typeNum;
531 } else {
532 $LD['type'] = '';
533 }
534 // Preserving the type number.
535 $LD['orig_type'] = $LD['type'];
536 // noCache
537 if ($no_cache) {
538 $LD['no_cache'] = '&no_cache=1';
539 $allQueryParameters['no_cache'] = 1;
540 } else {
541 $LD['no_cache'] = '';
542 }
543 // linkVars
544 $queryParameters = GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams);
545 if (!empty($queryParameters)) {
546 $allQueryParameters = array_replace_recursive($queryParameters, $allQueryParameters);
547 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', $queryParameters, '', false, true);
548 }
549 // Add absRefPrefix if exists.
550 $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
551 // 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.
552 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
553
554 // Compile the total url
555 $urlParts = parse_url($LD['url']);
556
557 // Now see if the URL can be replaced by a URL generated by the Site-based Page Builder,
558 // but first find out if a language has been set explicitly
559 if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
560 $currentSiteLanguage = $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
561 if ($currentSiteLanguage instanceof SiteLanguage) {
562 $languageId = $currentSiteLanguage->getLanguageId();
563 }
564 }
565 $absRefPrefix = $this->getTypoScriptFrontendController()->absRefPrefix;
566 $languageId = $queryParameters['L'] ?? $languageId ?? null;
567 $totalUrl = (string)GeneralUtility::makeInstance(PageUriBuilder::class)->buildUri(
568 (int)$page['uid'],
569 $allQueryParameters,
570 $LD['sectionIndex'],
571 ['language' => $languageId, 'alternativePageId' => $page['alias'] ?: $page['uid'], 'legacyUrlPrefix' => $absRefPrefix],
572 (!$urlParts['scheme'] && !$urlParts['host']) ? PageUriBuilder::ABSOLUTE_PATH : PageUriBuilder::ABSOLUTE_URL
573 );
574
575 // $totalUri contains /index.php for legacy URLs, as previously "it was index.php"
576 // In case an URI has is prefixed with "/" which is not the absRefPrefix, remove it.
577 // this might change in the future
578 if (strpos($totalUrl, '/index.php') === 0 && $absRefPrefix !== '/') {
579 $totalUrl = substr($totalUrl, 1);
580 }
581
582 // Add the method url id token later-on
583 if ($this->getTypoScriptFrontendController()->getMethodUrlIdToken) {
584 if (strpos($totalUrl, '#') !== false) {
585 $totalUrl = str_replace('#', $this->getTypoScriptFrontendController()->getMethodUrlIdToken . '#', $totalUrl);
586 } else {
587 $totalUrl .= $this->getTypoScriptFrontendController()->getMethodUrlIdToken;
588 }
589 }
590 $LD['totalURL'] = $totalUrl;
591 // Call post processing function for link rendering:
592 $_params = [
593 'LD' => &$LD,
594 'args' => ['page' => $page, 'oTarget' => $target, 'no_cache' => $no_cache, 'script' => $script, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
595 'typeNum' => $typeNum
596 ];
597 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
598 GeneralUtility::callUserFunction($_funcRef, $_params, $this->getTypoScriptFrontendController()->tmpl);
599 }
600 return $LD;
601 }
602 }