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