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