[!!!][TASK] Remove legacy soft references functionality
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / SoftReferenceIndex.php
1 <?php
2 namespace TYPO3\CMS\Core\Database;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\GeneralUtility;
18 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
19
20 /**
21 * Soft Reference processing class
22 * "Soft References" are references to database elements, files, email addresses, URls etc.
23 * which are found in-text in content. The <link [page_id]> tag from typical bodytext fields
24 * are an example of this.
25 * This class contains generic parsers for the most well-known types
26 * which are default for most TYPO3 installations. Soft References can also be userdefined.
27 * The Soft Reference parsers are used by the system to find these references and process them accordingly in import/export actions and copy operations.
28 *
29 * Example of usage
30 * Soft References:
31 * if ($conf['softref'] && (strong)$value !== '')) { // Check if a TCA configured field has softreferences defined (see TYPO3 Core API document)
32 * $softRefs = \TYPO3\CMS\Backend\Utility\BackendUtility::explodeSoftRefParserList($conf['softref']); // Explode the list of softreferences/parameters
33 * if ($softRefs !== FALSE) { // If there are soft references
34 * foreach($softRefs as $spKey => $spParams) { // Traverse soft references
35 * $softRefObj = \TYPO3\CMS\Backend\Utility\BackendUtility::softRefParserObj($spKey); // create / get object
36 * if (is_object($softRefObj)) { // If there was an object returned...:
37 * $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams); // Do processing
38 *
39 * Result Array:
40 * The Result array should contain two keys: "content" and "elements".
41 * "content" is a string containing the input content but possibly with tokens inside.
42 * Tokens are strings like {softref:[tokenID]} which is a placeholder for a value extracted by a softref parser
43 * For each token there MUST be an entry in the "elements" key which has a "subst" key defining the tokenID and the tokenValue. See below.
44 * "elements" is an array where the keys are insignificant, but the values are arrays with these keys:
45 * "matchString" => The value of the match. This is only for informational purposes to show what was found.
46 * "error" => An error message can be set here, like "file not found" etc.
47 * "subst" => array( // If this array is found there MUST be a token in the output content as well!
48 * "tokenID" => The tokenID string corresponding to the token in output content, {softref:[tokenID]}. This is typically an md5 hash of a string defining uniquely the position of the element.
49 * "tokenValue" => The value that the token substitutes in the text. Basically, if this value is inserted instead of the token the content should match what was inputted originally.
50 * "type" => file / db / string = the type of substitution. "file" means it is a relative file [automatically mapped], "db" means a database record reference [automatically mapped], "string" means it is manually modified string content (eg. an email address)
51 * "relFileName" => (for "file" type): Relative filename. May not necessarily exist. This could be noticed in the error key.
52 * "recordRef" => (for "db" type) : Reference to DB record on the form [table]:[uid]. May not necessarily exist.
53 * "title" => Title of element (for backend information)
54 * "description" => Description of element (for backend information)
55 * )
56 */
57 /**
58 * Class for processing of the default soft reference types for CMS:
59 *
60 * - 'substitute' : A full field value targeted for manual substitution (for import /export features)
61 * - 'notify' : Just report if a value is found, nothing more.
62 * - 'images' : HTML <img> tags for RTE images
63 * - 'typolink' : references to page id or file, possibly with anchor/target, possibly commaseparated list.
64 * - 'typolink_tag' : As typolink, but searching for <link> tag to encapsulate it.
65 * - 'email' : Email highlight
66 * - 'url' : URL highlights (with a scheme)
67 */
68 class SoftReferenceIndex
69 {
70 /**
71 * @var string
72 */
73 public $tokenID_basePrefix = '';
74
75 /**
76 * Main function through which all processing happens
77 *
78 * @param string $table Database table name
79 * @param string $field Field name for which processing occurs
80 * @param int $uid UID of the record
81 * @param string $content The content/value of the field
82 * @param string $spKey The softlink parser key. This is only interesting if more than one parser is grouped in the same class. That is the case with this parser.
83 * @param array $spParams Parameters of the softlink parser. Basically this is the content inside optional []-brackets after the softref keys. Parameters are exploded by ";
84 * @param string $structurePath If running from inside a FlexForm structure, this is the path of the tag.
85 * @return array Result array on positive matches, see description above. Otherwise FALSE
86 */
87 public function findRef($table, $field, $uid, $content, $spKey, $spParams, $structurePath = '')
88 {
89 $retVal = false;
90 $this->tokenID_basePrefix = $table . ':' . $uid . ':' . $field . ':' . $structurePath . ':' . $spKey;
91 switch ($spKey) {
92 case 'notify':
93 // Simple notification
94 $resultArray = array(
95 'elements' => array(
96 array(
97 'matchString' => $content
98 )
99 )
100 );
101 $retVal = $resultArray;
102 break;
103 case 'substitute':
104 $tokenID = $this->makeTokenID();
105 $resultArray = array(
106 'content' => '{softref:' . $tokenID . '}',
107 'elements' => array(
108 array(
109 'matchString' => $content,
110 'subst' => array(
111 'type' => 'string',
112 'tokenID' => $tokenID,
113 'tokenValue' => $content
114 )
115 )
116 )
117 );
118 $retVal = $resultArray;
119 break;
120 case 'images':
121 $retVal = $this->findRef_images($content, $spParams);
122 break;
123 case 'typolink':
124 $retVal = $this->findRef_typolink($content, $spParams);
125 break;
126 case 'typolink_tag':
127 $retVal = $this->findRef_typolink_tag($content, $spParams);
128 break;
129 case 'ext_fileref':
130 $retVal = $this->findRef_extension_fileref($content, $spParams);
131 break;
132 case 'email':
133 $retVal = $this->findRef_email($content, $spParams);
134 break;
135 case 'url':
136 $retVal = $this->findRef_url($content, $spParams);
137 break;
138 default:
139 $retVal = false;
140 }
141 return $retVal;
142 }
143
144 /**
145 * Finding image tags in the content.
146 * All images that are not from external URLs will be returned with an info text
147 * Will only return files in uploads/ folders which are prefixed with "RTEmagic[C|P]_" for substitution
148 * Any "clear.gif" images are ignored.
149 *
150 * @param string $content The input content to analyse
151 * @param array $spParams Parameters set for the softref parser key in TCA/columns
152 * @return array Result array on positive matches, see description above. Otherwise FALSE
153 */
154 public function findRef_images($content, $spParams)
155 {
156 // Start HTML parser and split content by image tag:
157 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
158 $splitContent = $htmlParser->splitTags('img', $content);
159 $elements = array();
160 // Traverse splitted parts:
161 foreach ($splitContent as $k => $v) {
162 if ($k % 2) {
163 // Get file reference:
164 $attribs = $htmlParser->get_tag_attributes($v);
165 $srcRef = htmlspecialchars_decode($attribs[0]['src']);
166 $pI = pathinfo($srcRef);
167 // If it looks like a local image, continue. Otherwise ignore it.
168 $absPath = GeneralUtility::getFileAbsFileName(PATH_site . $srcRef);
169 if (!$pI['scheme'] && !$pI['query'] && $absPath && $srcRef !== 'clear.gif') {
170 // Initialize the element entry with info text here:
171 $tokenID = $this->makeTokenID($k);
172 $elements[$k] = array();
173 $elements[$k]['matchString'] = $v;
174 // If the image seems to be an RTE image, then proceed to set up substitution token:
175 if (GeneralUtility::isFirstPartOfStr($srcRef, 'uploads/') && preg_match('/^RTEmagicC_/', basename($srcRef))) {
176 // Token and substitute value:
177 // Make sure the value we work on is found and will get substituted in the content (Very important that the src-value is not DeHSC'ed)
178 if (strstr($splitContent[$k], $attribs[0]['src'])) {
179 // Substitute value with token (this is not be an exact method if the value is in there twice, but we assume it will not)
180 $splitContent[$k] = str_replace($attribs[0]['src'], '{softref:' . $tokenID . '}', $splitContent[$k]);
181 $elements[$k]['subst'] = array(
182 'type' => 'file',
183 'relFileName' => $srcRef,
184 'tokenID' => $tokenID,
185 'tokenValue' => $attribs[0]['src']
186 );
187 // Finally, notice if the file does not exist.
188 if (!@is_file($absPath)) {
189 $elements[$k]['error'] = 'File does not exist!';
190 }
191 } else {
192 $elements[$k]['error'] = 'Could not substitute image source with token!';
193 }
194 }
195 }
196 }
197 }
198 // Return result:
199 if (!empty($elements)) {
200 $resultArray = array(
201 'content' => implode('', $splitContent),
202 'elements' => $elements
203 );
204 return $resultArray;
205 }
206 }
207
208 /**
209 * TypoLink value processing.
210 * Will process input value as a TypoLink value.
211 *
212 * @param string $content The input content to analyse
213 * @param array $spParams Parameters set for the softref parser key in TCA/columns. value "linkList" will split the string by comma before processing.
214 * @return array Result array on positive matches, see description above. Otherwise FALSE
215 * @see \TYPO3\CMS\Frontend\ContentObject::typolink(), getTypoLinkParts()
216 */
217 public function findRef_typolink($content, $spParams)
218 {
219 // First, split the input string by a comma if the "linkList" parameter is set.
220 // An example: the link field for images in content elements of type "textpic" or "image". This field CAN be configured to define a link per image, separated by comma.
221 if (is_array($spParams) && in_array('linkList', $spParams)) {
222 // Preserving whitespace on purpose.
223 $linkElement = explode(',', $content);
224 } else {
225 // If only one element, just set in this array to make it easy below.
226 $linkElement = array($content);
227 }
228 // Traverse the links now:
229 $elements = array();
230 foreach ($linkElement as $k => $typolinkValue) {
231 $tLP = $this->getTypoLinkParts($typolinkValue);
232 $linkElement[$k] = $this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k);
233 }
234 // Return output:
235 if (!empty($elements)) {
236 $resultArray = array(
237 'content' => implode(',', $linkElement),
238 'elements' => $elements
239 );
240 return $resultArray;
241 }
242 }
243
244 /**
245 * TypoLink tag processing.
246 * Will search for <link ...> tags in the content string and process any found.
247 *
248 * @param string $content The input content to analyse
249 * @param array $spParams Parameters set for the softref parser key in TCA/columns
250 * @return array Result array on positive matches, see description above. Otherwise FALSE
251 * @see \TYPO3\CMS\Frontend\ContentObject::typolink(), getTypoLinkParts()
252 */
253 public function findRef_typolink_tag($content, $spParams)
254 {
255 // Parse string for special TYPO3 <link> tag:
256 $htmlParser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
257 $linkTags = $htmlParser->splitTags('link', $content);
258 // Traverse result:
259 $elements = array();
260 foreach ($linkTags as $k => $foundValue) {
261 if ($k % 2) {
262 $typolinkValue = preg_replace('/<LINK[[:space:]]+/i', '', substr($foundValue, 0, -1));
263 $tLP = $this->getTypoLinkParts($typolinkValue);
264 $linkTags[$k] = '<LINK ' . $this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k) . '>';
265 }
266 }
267 // Return output:
268 if (!empty($elements)) {
269 $resultArray = array(
270 'content' => implode('', $linkTags),
271 'elements' => $elements
272 );
273 return $resultArray;
274 }
275 }
276
277 /**
278 * Finding email addresses in content and making them substitutable.
279 *
280 * @param string $content The input content to analyse
281 * @param array $spParams Parameters set for the softref parser key in TCA/columns
282 * @return array Result array on positive matches, see description above. Otherwise FALSE
283 */
284 public function findRef_email($content, $spParams)
285 {
286 $resultArray = array();
287 // Email:
288 $parts = preg_split('/([^[:alnum:]]+)([A-Za-z0-9\\._-]+[@][A-Za-z0-9\\._-]+[\\.].[A-Za-z0-9]+)/', ' ' . $content . ' ', 10000, PREG_SPLIT_DELIM_CAPTURE);
289 foreach ($parts as $idx => $value) {
290 if ($idx % 3 == 2) {
291 $tokenID = $this->makeTokenID($idx);
292 $elements[$idx] = array();
293 $elements[$idx]['matchString'] = $value;
294 if (is_array($spParams) && in_array('subst', $spParams)) {
295 $parts[$idx] = '{softref:' . $tokenID . '}';
296 $elements[$idx]['subst'] = array(
297 'type' => 'string',
298 'tokenID' => $tokenID,
299 'tokenValue' => $value
300 );
301 }
302 }
303 }
304 // Return output:
305 if (!empty($elements)) {
306 $resultArray = array(
307 'content' => substr(implode('', $parts), 1, -1),
308 'elements' => $elements
309 );
310 return $resultArray;
311 }
312 }
313
314 /**
315 * Finding URLs in content
316 *
317 * @param string $content The input content to analyse
318 * @param array $spParams Parameters set for the softref parser key in TCA/columns
319 * @return array Result array on positive matches, see description above. Otherwise FALSE
320 */
321 public function findRef_url($content, $spParams)
322 {
323 $resultArray = array();
324 // URLs
325 $parts = preg_split('/([^[:alnum:]"\']+)((http|ftp):\\/\\/[^[:space:]"\'<>]*)([[:space:]])/', ' ' . $content . ' ', 10000, PREG_SPLIT_DELIM_CAPTURE);
326 foreach ($parts as $idx => $value) {
327 if ($idx % 5 == 3) {
328 unset($parts[$idx]);
329 }
330 if ($idx % 5 == 2) {
331 $tokenID = $this->makeTokenID($idx);
332 $elements[$idx] = array();
333 $elements[$idx]['matchString'] = $value;
334 if (is_array($spParams) && in_array('subst', $spParams)) {
335 $parts[$idx] = '{softref:' . $tokenID . '}';
336 $elements[$idx]['subst'] = array(
337 'type' => 'string',
338 'tokenID' => $tokenID,
339 'tokenValue' => $value
340 );
341 }
342 }
343 }
344 // Return output:
345 if (!empty($elements)) {
346 $resultArray = array(
347 'content' => substr(implode('', $parts), 1, -1),
348 'elements' => $elements
349 );
350 return $resultArray;
351 }
352 }
353
354 /**
355 * Finding reference to files from extensions in content, but only to notify about their existence. No substitution
356 *
357 * @param string $content The input content to analyse
358 * @param array $spParams Parameters set for the softref parser key in TCA/columns
359 * @return array Result array on positive matches, see description above. Otherwise FALSE
360 */
361 public function findRef_extension_fileref($content, $spParams)
362 {
363 $resultArray = array();
364 // Files starting with EXT:
365 $parts = preg_split('/([^[:alnum:]"\']+)(EXT:[[:alnum:]_]+\\/[^[:space:]"\',]*)/', ' ' . $content . ' ', 10000, PREG_SPLIT_DELIM_CAPTURE);
366 foreach ($parts as $idx => $value) {
367 if ($idx % 3 == 2) {
368 $tokenID = $this->makeTokenID($idx);
369 $elements[$idx] = array();
370 $elements[$idx]['matchString'] = $value;
371 }
372 }
373 // Return output:
374 if (!empty($elements)) {
375 $resultArray = array(
376 'content' => substr(implode('', $parts), 1, -1),
377 'elements' => $elements
378 );
379 return $resultArray;
380 }
381 }
382
383 /*************************
384 *
385 * Helper functions
386 *
387 *************************/
388
389 /**
390 * Analyse content as a TypoLink value and return an array with properties.
391 * TypoLinks format is: <link [typolink] [browser target] [css class] [title attribute] [additionalParams]>.
392 * See TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typolink()
393 * The syntax of the [typolink] part is: [typolink] = [page id or alias][,[type value]][#[anchor, if integer = tt_content uid]]
394 * The extraction is based on how \TYPO3\CMS\Frontend\ContentObject::typolink() behaves.
395 *
396 * @param string $typolinkValue TypoLink value.
397 * @return array Array with the properties of the input link specified. The key "LINK_TYPE" will reveal the type. If that is blank it could not be determined.
398 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typolink(), setTypoLinkPartsElement()
399 */
400 public function getTypoLinkParts($typolinkValue)
401 {
402 $finalTagParts = GeneralUtility::makeInstance(TypoLinkCodecService::class)->decode($typolinkValue);
403
404 $link_param = $finalTagParts['url'];
405 // we define various keys below, "url" might be misleading
406 unset($finalTagParts['url']);
407
408 // Parse URL:
409 $pU = @parse_url($link_param);
410
411 // If it's a mail address:
412 if (strstr($link_param, '@') && !$pU['scheme']) {
413 $link_param = preg_replace('/^mailto:/i', '', $link_param);
414 $finalTagParts['LINK_TYPE'] = 'mailto';
415 $finalTagParts['url'] = trim($link_param);
416 return $finalTagParts;
417 }
418
419 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', trim($link_param), 2);
420
421 // Dispatch available signal slots.
422 $linkHandlerFound = false;
423 list($linkHandlerFound, $finalTagParts) = $this->emitGetTypoLinkParts($linkHandlerFound, $finalTagParts, $linkHandlerKeyword, $linkHandlerValue);
424 if ($linkHandlerFound) {
425 return $finalTagParts;
426 }
427
428 // Check for FAL link-handler keyword
429 if ($linkHandlerKeyword === 'file') {
430 $finalTagParts['LINK_TYPE'] = 'file';
431 $finalTagParts['identifier'] = trim($link_param);
432 return $finalTagParts;
433 }
434
435 $isLocalFile = 0;
436 $fileChar = (int)strpos($link_param, '/');
437 $urlChar = (int)strpos($link_param, '.');
438
439 // Detects if a file is found in site-root and if so it will be treated like a normal file.
440 list($rootFileDat) = explode('?', rawurldecode($link_param));
441 $containsSlash = strstr($rootFileDat, '/');
442 $rFD_fI = pathinfo($rootFileDat);
443 $fileExtension = strtolower($rFD_fI['extension']);
444 if (!$containsSlash && trim($rootFileDat) && (@is_file(PATH_site . $rootFileDat) || $fileExtension === 'php' || $fileExtension === 'html' || $fileExtension === 'htm')) {
445 $isLocalFile = 1;
446 } elseif ($containsSlash) {
447 // Adding this so realurl directories are linked right (non-existing).
448 $isLocalFile = 2;
449 }
450 if ($pU['scheme'] || ($isLocalFile != 1 && $urlChar && (!$containsSlash || $urlChar < $fileChar))) { // url (external): If doubleSlash or if a '.' comes before a '/'.
451 $finalTagParts['LINK_TYPE'] = 'url';
452 $finalTagParts['url'] = $link_param;
453 } elseif ($containsSlash || $isLocalFile) { // file (internal)
454 $splitLinkParam = explode('?', $link_param);
455 if (file_exists(rawurldecode($splitLinkParam[0])) || $isLocalFile) {
456 $finalTagParts['LINK_TYPE'] = 'file';
457 $finalTagParts['filepath'] = rawurldecode($splitLinkParam[0]);
458 $finalTagParts['query'] = $splitLinkParam[1];
459 }
460 } else {
461 // integer or alias (alias is without slashes or periods or commas, that is
462 // 'nospace,alphanum_x,lower,unique' according to definition in $GLOBALS['TCA']!)
463 $finalTagParts['LINK_TYPE'] = 'page';
464
465 $link_params_parts = explode('#', $link_param);
466 // Link-data del
467 $link_param = trim($link_params_parts[0]);
468
469 if ((string)$link_params_parts[1] !== '') {
470 $finalTagParts['anchor'] = trim($link_params_parts[1]);
471 }
472
473 // Splitting the parameter by ',' and if the array counts more than 1 element it's a id/type/? pair
474 $pairParts = GeneralUtility::trimExplode(',', $link_param);
475 if (count($pairParts) > 1) {
476 $link_param = $pairParts[0];
477 $finalTagParts['type'] = $pairParts[1]; // Overruling 'type'
478 }
479
480 // Checking if the id-parameter is an alias.
481 if ((string)$link_param !== '') {
482 if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($link_param)) {
483 $finalTagParts['alias'] = $link_param;
484 $link_param = $this->getPageIdFromAlias($link_param);
485 }
486
487 $finalTagParts['page_id'] = (int)$link_param;
488 }
489 }
490
491 return $finalTagParts;
492 }
493
494 /**
495 * Recompile a TypoLink value from the array of properties made with getTypoLinkParts() into an elements array
496 *
497 * @param array $tLP TypoLink properties
498 * @param array $elements Array of elements to be modified with substitution / information entries.
499 * @param string $content The content to process.
500 * @param int $idx Index value of the found element - user to make unique but stable tokenID
501 * @return string The input content, possibly containing tokens now according to the added substitution entries in $elements
502 * @see getTypoLinkParts()
503 */
504 public function setTypoLinkPartsElement($tLP, &$elements, $content, $idx)
505 {
506 // Initialize, set basic values. In any case a link will be shown
507 $tokenID = $this->makeTokenID('setTypoLinkPartsElement:' . $idx);
508 $elements[$tokenID . ':' . $idx] = array();
509 $elements[$tokenID . ':' . $idx]['matchString'] = $content;
510 // Based on link type, maybe do more:
511 switch ((string)$tLP['LINK_TYPE']) {
512 case 'mailto':
513
514 case 'url':
515 // Mail addresses and URLs can be substituted manually:
516 $elements[$tokenID . ':' . $idx]['subst'] = array(
517 'type' => 'string',
518 'tokenID' => $tokenID,
519 'tokenValue' => $tLP['url']
520 );
521 // Output content will be the token instead:
522 $content = '{softref:' . $tokenID . '}';
523 break;
524 case 'file':
525 // Process files referenced by their FAL uid
526 if ($tLP['identifier']) {
527 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', trim($tLP['identifier']), 2);
528 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($linkHandlerValue)) {
529 // Token and substitute value
530 $elements[$tokenID . ':' . $idx]['subst'] = array(
531 'type' => 'db',
532 'recordRef' => 'sys_file:' . $linkHandlerValue,
533 'tokenID' => $tokenID,
534 'tokenValue' => $tLP['identifier'],
535 );
536 // Output content will be the token instead:
537 $content = '{softref:' . $tokenID . '}';
538 } else {
539 // This is a link to a folder...
540 return $content;
541 }
542 } else {
543 return $content;
544 }
545 break;
546 case 'page':
547 // Rebuild page reference typolink part:
548 $content = '';
549 // Set page id:
550 if ($tLP['page_id']) {
551 $content .= '{softref:' . $tokenID . '}';
552 $elements[$tokenID . ':' . $idx]['subst'] = array(
553 'type' => 'db',
554 'recordRef' => 'pages:' . $tLP['page_id'],
555 'tokenID' => $tokenID,
556 'tokenValue' => $tLP['alias'] ? $tLP['alias'] : $tLP['page_id']
557 );
558 }
559 // Add type if applicable
560 if ((string)$tLP['type'] !== '') {
561 $content .= ',' . $tLP['type'];
562 }
563 // Add anchor if applicable
564 if ((string)$tLP['anchor'] !== '') {
565 // Anchor is assumed to point to a content elements:
566 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($tLP['anchor'])) {
567 // Initialize a new entry because we have a new relation:
568 $newTokenID = $this->makeTokenID('setTypoLinkPartsElement:anchor:' . $idx);
569 $elements[$newTokenID . ':' . $idx] = array();
570 $elements[$newTokenID . ':' . $idx]['matchString'] = 'Anchor Content Element: ' . $tLP['anchor'];
571 $content .= '#{softref:' . $newTokenID . '}';
572 $elements[$newTokenID . ':' . $idx]['subst'] = array(
573 'type' => 'db',
574 'recordRef' => 'tt_content:' . $tLP['anchor'],
575 'tokenID' => $newTokenID,
576 'tokenValue' => $tLP['anchor']
577 );
578 } else {
579 // Anchor is a hardcoded string
580 $content .= '#' . $tLP['type'];
581 }
582 }
583 break;
584 default:
585 $linkHandlerFound = false;
586 list($linkHandlerFound, $tLP, $content, $newElements) = $this->emitSetTypoLinkPartsElement($linkHandlerFound, $tLP, $content, $elements, $idx, $tokenID);
587 // We need to merge the array, otherwise we would loose the reference.
588 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($elements, $newElements);
589
590 if (!$linkHandlerFound) {
591 $elements[$tokenID . ':' . $idx]['error'] = 'Couldn\'t decide typolink mode.';
592 return $content;
593 }
594 }
595 // Finally, for all entries that was rebuild with tokens, add target, class, title and additionalParams in the end:
596 $tLP['url'] = $content;
597 $content = GeneralUtility::makeInstance(TypoLinkCodecService::class)->encode($tLP);
598
599 // Return rebuilt typolink value:
600 return $content;
601 }
602
603 /**
604 * Look up and return page uid for alias
605 *
606 * @param int $link_param Page alias string value
607 * @return int Page uid corresponding to alias value.
608 */
609 public function getPageIdFromAlias($link_param)
610 {
611 $pRec = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordsByField('pages', 'alias', $link_param);
612 return $pRec[0]['uid'];
613 }
614
615 /**
616 * Make Token ID for input index.
617 *
618 * @param string $index Suffix value.
619 * @return string Token ID
620 */
621 public function makeTokenID($index = '')
622 {
623 return md5($this->tokenID_basePrefix . ':' . $index);
624 }
625
626 /**
627 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
628 */
629 protected function getSignalSlotDispatcher()
630 {
631 return GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
632 }
633
634 /**
635 * @param bool $linkHandlerFound
636 * @param array $finalTagParts
637 * @param string $linkHandlerKeyword
638 * @param string $linkHandlerValue
639 * @return array
640 */
641 protected function emitGetTypoLinkParts($linkHandlerFound, $finalTagParts, $linkHandlerKeyword, $linkHandlerValue)
642 {
643 return $this->getSignalSlotDispatcher()->dispatch(get_class($this), 'getTypoLinkParts', array($linkHandlerFound, $finalTagParts, $linkHandlerKeyword, $linkHandlerValue));
644 }
645
646 /**
647 * @param bool $linkHandlerFound
648 * @param array $tLP
649 * @param string $content
650 * @param array $elements
651 * @param int $idx
652 * @param string $tokenID
653 * @return array
654 */
655 protected function emitSetTypoLinkPartsElement($linkHandlerFound, $tLP, $content, $elements, $idx, $tokenID)
656 {
657 return $this->getSignalSlotDispatcher()->dispatch(get_class($this), 'setTypoLinkPartsElement', array($linkHandlerFound, $tLP, $content, $elements, $idx, $tokenID, $this));
658 }
659 }