Updating version number to 4.3-dev after release of 4.3.0RC1
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_softrefproc.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2003-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the Typo3 project. The Typo3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 *
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
24 /**
25 * Soft Reference processing class
26 * "Soft References" are references to database elements, files, email addresses, URls etc.
27 * which are found in-text in content. The <link [page_id]> tag from typical bodytext fields
28 * are an example of this.
29 * This class contains generic parsers for the most well-known types
30 * which are default for most TYPO3 installations. Soft References can also be userdefined.
31 * The Soft Reference parsers are used by the system to find these references and process them accordingly in import/export actions and copy operations.
32 *
33 * $Id$
34 *
35 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
36 */
37 /**
38 * [CLASS/FUNCTION INDEX of SCRIPT]
39 *
40 *
41 *
42 * 116: class t3lib_softrefproc
43 * 137: function findRef($table, $field, $uid, $content, $spKey, $spParams, $structurePath='')
44 * 213: function findRef_images($content, $spParams)
45 * 280: function findRef_typolink($content, $spParams)
46 * 317: function findRef_typolink_tag($content, $spParams)
47 * 352: function findRef_TStemplate($content, $spParams)
48 * 434: function findRef_TSconfig($content, $spParams)
49 * 457: function findRef_email($content, $spParams)
50 * 497: function findRef_url($content, $spParams)
51 * 539: function findRef_extension_fileref($content, $spParams)
52 *
53 * SECTION: Helper functions
54 * 591: function fileadminReferences($content, &$elements)
55 * 634: function getTypoLinkParts($typolinkValue)
56 * 718: function setTypoLinkPartsElement($tLP, &$elements, $content, $idx)
57 * 833: function getPageIdFromAlias($link_param)
58 * 845: function makeTokenID($index='')
59 *
60 * TOTAL FUNCTIONS: 14
61 * (This index is automatically created/updated by the extension "extdeveval")
62 *
63 */
64
65
66 /**
67 * Example of usage
68 * // Soft References:
69 * if ($conf['softref'] && strlen($value)) { // Check if a TCA configured field has softreferences defined (see TYPO3 Core API document)
70 * $softRefs = t3lib_BEfunc::explodeSoftRefParserList($conf['softref']); // Explode the list of softreferences/parameters
71 * foreach($softRefs as $spKey => $spParams) { // Traverse soft references
72 * $softRefObj = &t3lib_BEfunc::softRefParserObj($spKey); // create / get object
73 * if (is_object($softRefObj)) { // If there was an object returned...:
74 * $resultArray = $softRefObj->findRef($table, $field, $uid, $softRefValue, $spKey, $spParams); // Do processing
75 *
76 * Result Array:
77 * The Result array should contain two keys: "content" and "elements".
78 * "content" is a string containing the input content but possibly with tokens inside.
79 * Tokens are strings like {softref:[tokenID]} which is a placeholder for a value extracted by a softref parser
80 * 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.
81 * "elements" is an array where the keys are insignificant, but the values are arrays with these keys:
82 * "matchString" => The value of the match. This is only for informational purposes to show what was found.
83 * "error" => An error message can be set here, like "file not found" etc.
84 * "subst" => array( // If this array is found there MUST be a token in the output content as well!
85 * "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.
86 * "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.
87 * "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)
88 * "relFileName" => (for "file" type): Relative filename. May not necessarily exist. This could be noticed in the error key.
89 * "recordRef" => (for "db" type) : Reference to DB record on the form [table]:[uid]. May not necessarily exist.
90 * "title" => Title of element (for backend information)
91 * "description" => Description of element (for backend information)
92 * )
93 *
94 */
95
96
97
98 /**
99 * Class for processing of the default soft reference types for CMS:
100 *
101 * - 'substitute' : A full field value targeted for manual substitution (for import /export features)
102 * - 'notify' : Just report if a value is found, nothing more.
103 * - 'images' : HTML <img> tags for RTE images / images from fileadmin/
104 * - 'typolink' : references to page id or file, possibly with anchor/target, possibly commaseparated list.
105 * - 'typolink_tag' : As typolink, but searching for <link> tag to encapsulate it.
106 * - 'TSconfig' processing (filerefs? Domains? what do we know...)
107 * - 'TStemplate' : freetext references to "fileadmin/" files.
108 * - 'email' : Email highlight
109 * - 'url' : URL highlights (with a scheme)
110 *
111 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
112 * @package TYPO3
113 * @subpackage t3lib
114 */
115 class t3lib_softrefproc {
116
117 // external configuration
118 var $fileAdminDir = 'fileadmin';
119
120
121 // Internal:
122 var $tokenID_basePrefix = '';
123
124 /**
125 * Main function through which all processing happens
126 *
127 * @param string Database table name
128 * @param string Field name for which processing occurs
129 * @param integer UID of the record
130 * @param string The content/value of the field
131 * @param string 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.
132 * @param array Parameters of the softlink parser. Basically this is the content inside optional []-brackets after the softref keys. Parameters are exploded by ";"
133 * @param string If running from inside a FlexForm structure, this is the path of the tag.
134 * @return array Result array on positive matches, see description above. Otherwise false
135 */
136 function findRef($table, $field, $uid, $content, $spKey, $spParams, $structurePath='') {
137
138 $retVal = FALSE;
139
140 $this->tokenID_basePrefix = $table.':'.$uid.':'.$field.':'.$structurePath.':'.$spKey;
141
142 switch($spKey) {
143 case 'notify': // Simple notification
144 $resultArray = array(
145 'elements' => array(
146 array(
147 'matchString' => $content
148 )
149 )
150 );
151 $retVal = $resultArray;
152 break;
153 case 'substitute':
154 $tokenID = $this->makeTokenID();
155 $resultArray = array(
156 'content' => '{softref:'.$tokenID.'}',
157 'elements' => array(
158 array(
159 'matchString' => $content,
160 'subst' => array(
161 'type' => 'string',
162 'tokenID' => $tokenID,
163 'tokenValue' => $content
164 )
165 )
166 )
167 );
168 $retVal = $resultArray;
169 break;
170 case 'images':
171 $retVal = $this->findRef_images($content, $spParams);
172 break;
173 case 'typolink':
174 $retVal = $this->findRef_typolink($content, $spParams);
175 break;
176 case 'typolink_tag':
177 $retVal = $this->findRef_typolink_tag($content, $spParams);
178 break;
179 case 'ext_fileref':
180 $retVal = $this->findRef_extension_fileref($content, $spParams);
181 break;
182 case 'TStemplate':
183 $retVal = $this->findRef_TStemplate($content, $spParams);
184 break;
185 case 'TSconfig':
186 $retVal = $this->findRef_TSconfig($content, $spParams);
187 break;
188 case 'email':
189 $retVal = $this->findRef_email($content, $spParams);
190 break;
191 case 'url':
192 $retVal = $this->findRef_url($content, $spParams);
193 break;
194 default:
195 $retVal = FALSE;
196 break;
197 }
198
199 return $retVal;
200 }
201
202 /**
203 * Finding image tags in the content.
204 * All images that are not from external URLs will be returned with an info text
205 * Will only return files in fileadmin/ and files in uploads/ folders which are prefixed with "RTEmagic[C|P]_" for substitution
206 * Any "clear.gif" images are ignored.
207 *
208 * @param string The input content to analyse
209 * @param array Parameters set for the softref parser key in TCA/columns
210 * @return array Result array on positive matches, see description above. Otherwise false
211 */
212 function findRef_images($content, $spParams) {
213
214 // Start HTML parser and split content by image tag:
215 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
216 $splitContent = $htmlParser->splitTags('img',$content);
217 $elements = array();
218
219 // Traverse splitted parts:
220 foreach($splitContent as $k => $v) {
221 if ($k%2) {
222
223 // Get file reference:
224 $attribs = $htmlParser->get_tag_attributes($v);
225 $srcRef = t3lib_div::htmlspecialchars_decode($attribs[0]['src']);
226 $pI = pathinfo($srcRef);
227
228 // If it looks like a local image, continue. Otherwise ignore it.
229 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$srcRef);
230 if (!$pI['scheme'] && !$pI['query'] && $absPath && $srcRef!=='clear.gif') {
231
232 // Initialize the element entry with info text here:
233 $tokenID = $this->makeTokenID($k);
234 $elements[$k] = array();
235 $elements[$k]['matchString'] = $v;
236
237 // If the image seems to be from fileadmin/ folder or an RTE image, then proceed to set up substitution token:
238 if (t3lib_div::isFirstPartOfStr($srcRef,$this->fileAdminDir.'/') || (t3lib_div::isFirstPartOfStr($srcRef,'uploads/') && preg_match('/^RTEmagicC_/',basename($srcRef)))) {
239 // Token and substitute value:
240 if (strstr($splitContent[$k], $attribs[0]['src'])) { // 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)
241 $splitContent[$k] = str_replace($attribs[0]['src'], '{softref:'.$tokenID.'}', $splitContent[$k]); // Substitute value with token (this is not be an exact method if the value is in there twice, but we assume it will not)
242 $elements[$k]['subst'] = array(
243 'type' => 'file',
244 'relFileName' => $srcRef,
245 'tokenID' => $tokenID,
246 'tokenValue' => $attribs[0]['src'],
247 );
248 if (!@is_file($absPath)) { // Finally, notice if the file does not exist.
249 $elements[$k]['error'] = 'File does not exist!';
250 }
251 } else {
252 $elements[$k]['error'] = 'Could not substitute image source with token!';
253 }
254 }
255 }
256 }
257 }
258
259 // Return result:
260 if (count($elements)) {
261 $resultArray = array(
262 'content' => implode('', $splitContent),
263 'elements' => $elements
264 );
265
266 return $resultArray;
267 }
268 }
269
270 /**
271 * TypoLink value processing.
272 * Will process input value as a TypoLink value.
273 *
274 * @param string The input content to analyse
275 * @param array Parameters set for the softref parser key in TCA/columns. value "linkList" will split the string by comma before processing.
276 * @return array Result array on positive matches, see description above. Otherwise false
277 * @see tslib_content::typolink(), getTypoLinkParts()
278 */
279 function findRef_typolink($content, $spParams) {
280
281 // First, split the input string by a comma if the "linkList" parameter is set.
282 // 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.
283 if (is_array($spParams) && in_array('linkList',$spParams)) {
284 $linkElement = explode(',', $content); // Preserving whitespace on purpose.
285 } else {
286 $linkElement = array($content); // If only one element, just set in this array to make it easy below.
287 }
288
289 // Traverse the links now:
290 $elements = array();
291 foreach($linkElement as $k => $typolinkValue) {
292 $tLP = $this->getTypoLinkParts($typolinkValue);
293 $linkElement[$k] = $this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k);
294 }
295
296 // Return output:
297 if (count($elements)) {
298 $resultArray = array(
299 'content' => implode(',', $linkElement),
300 'elements' => $elements
301 );
302
303 return $resultArray;
304 }
305 }
306
307 /**
308 * TypoLink tag processing.
309 * Will search for <link ...> tags in the content string and process any found.
310 *
311 * @param string The input content to analyse
312 * @param array Parameters set for the softref parser key in TCA/columns
313 * @return array Result array on positive matches, see description above. Otherwise false
314 * @see tslib_content::typolink(), getTypoLinkParts()
315 */
316 function findRef_typolink_tag($content, $spParams) {
317
318 // Parse string for special TYPO3 <link> tag:
319 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
320 $linkTags = $htmlParser->splitTags('link',$content);
321
322 // Traverse result:
323 $elements = array();
324 foreach($linkTags as $k => $foundValue) {
325 if ($k%2) {
326 $typolinkValue = preg_replace('/<LINK[[:space:]]+/i','',substr($foundValue,0,-1));
327 $tLP = $this->getTypoLinkParts($typolinkValue);
328 $linkTags[$k] = '<LINK '.$this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k).'>';
329 }
330 }
331
332 // Return output:
333 if (count($elements)) {
334 $resultArray = array(
335 'content' => implode('', $linkTags),
336 'elements' => $elements
337 );
338
339 return $resultArray;
340 }
341 }
342
343 /**
344 * Processing the content expected from a TypoScript template
345 * This content includes references to files in fileadmin/ folders and file references in HTML tags like <img src="">, <a href=""> and <form action="">
346 *
347 * @param string The input content to analyse
348 * @param array Parameters set for the softref parser key in TCA/columns
349 * @return array Result array on positive matches, see description above. Otherwise false
350 */
351 function findRef_TStemplate($content, $spParams) {
352 $elements = array();
353
354 // First, try to find images and links:
355 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
356 $splitContent = $htmlParser->splitTags('img,a,form', $content);
357
358 // Traverse splitted parts:
359 foreach($splitContent as $k => $v) {
360 if ($k%2) {
361
362 $attribs = $htmlParser->get_tag_attributes($v);
363
364 $attributeName = '';
365 switch($htmlParser->getFirstTagName($v)) {
366 case 'img':
367 $attributeName = 'src';
368 break;
369 case 'a':
370 $attributeName = 'href';
371 break;
372 case 'form':
373 $attributeName = 'action';
374 break;
375 }
376
377 // Get file reference:
378 if (isset($attribs[0][$attributeName])) {
379 $srcRef = t3lib_div::htmlspecialchars_decode($attribs[0][$attributeName]);
380
381 // Set entry:
382 $tokenID = $this->makeTokenID($k);
383 $elements[$k] = array();
384 $elements[$k]['matchString'] = $v;
385
386 // OK, if it looks like a local file from fileadmin/, include it:
387 $pI = pathinfo($srcRef);
388 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$srcRef);
389 if (t3lib_div::isFirstPartOfStr($srcRef,$this->fileAdminDir.'/') && !$pI['query'] && $absPath) {
390
391 // Token and substitute value:
392 if (strstr($splitContent[$k], $attribs[0][$attributeName])) { // Very important that the src-value is not DeHSC'ed
393 $splitContent[$k] = str_replace($attribs[0][$attributeName], '{softref:'.$tokenID.'}', $splitContent[$k]);
394 $elements[$k]['subst'] = array(
395 'type' => 'file',
396 'relFileName' => $srcRef,
397 'tokenID' => $tokenID,
398 'tokenValue' => $attribs[0][$attributeName],
399 );
400 if (!@is_file($absPath)) {
401 $elements[$k]['error'] = 'File does not exist!';
402 }
403 } else {
404 $elements[$k]['error'] = 'Could not substitute attribute ('.$attributeName.') value with token!';
405 }
406 }
407 }
408 }
409 }
410 $content = implode('', $splitContent);
411
412 // Process free fileadmin/ references as well:
413 $content = $this->fileadminReferences($content, $elements);
414
415 // Return output:
416 if (count($elements)) {
417 $resultArray = array(
418 'content' => $content,
419 'elements' => $elements
420 );
421 return $resultArray;
422 }
423 }
424
425 /**
426 * Processes possible references inside of Page and User TSconfig fields.
427 * Currently this only includes file references to fileadmin/ but in fact there are currently no properties that supports such references.
428 *
429 * @param string The input content to analyse
430 * @param array Parameters set for the softref parser key in TCA/columns
431 * @return array Result array on positive matches, see description above. Otherwise false
432 */
433 function findRef_TSconfig($content, $spParams) {
434 $elements = array();
435
436 // Process free fileadmin/ references from TSconfig
437 $content = $this->fileadminReferences($content, $elements);
438
439 // Return output:
440 if (count($elements)) {
441 $resultArray = array(
442 'content' => $content,
443 'elements' => $elements
444 );
445 return $resultArray;
446 }
447 }
448
449 /**
450 * Finding email addresses in content and making them substitutable.
451 *
452 * @param string The input content to analyse
453 * @param array Parameters set for the softref parser key in TCA/columns
454 * @return array Result array on positive matches, see description above. Otherwise false
455 */
456 function findRef_email($content, $spParams) {
457 $resultArray = array();
458
459 // email:
460 $parts = preg_split("/([^[:alnum:]]+)([A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
461 foreach($parts as $idx => $value) {
462 if ($idx%3 == 2) {
463
464 $tokenID = $this->makeTokenID($idx);
465 $elements[$idx] = array();
466 $elements[$idx]['matchString'] = $value;
467
468 if (is_array($spParams) && in_array('subst',$spParams)) {
469 $parts[$idx] = '{softref:'.$tokenID.'}';
470 $elements[$idx]['subst'] = array(
471 'type' => 'string',
472 'tokenID' => $tokenID,
473 'tokenValue' => $value,
474 );
475 }
476 }
477 }
478
479 // Return output:
480 if (count($elements)) {
481 $resultArray = array(
482 'content' => substr(implode('',$parts),1,-1),
483 'elements' => $elements
484 );
485 return $resultArray;
486 }
487 }
488
489 /**
490 * Finding URLs in content
491 *
492 * @param string The input content to analyse
493 * @param array Parameters set for the softref parser key in TCA/columns
494 * @return array Result array on positive matches, see description above. Otherwise false
495 */
496 function findRef_url($content, $spParams) {
497 $resultArray = array();
498
499 // Fileadmin files:
500 $parts = preg_split("/([^[:alnum:]\"']+)((http|ftp):\/\/[^[:space:]\"'<>]*)([[:space:]])/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
501
502 foreach($parts as $idx => $value) {
503 if ($idx%5 == 3) { unset($parts[$idx]); }
504 if ($idx%5 == 2) {
505
506 $tokenID = $this->makeTokenID($idx);
507 $elements[$idx] = array();
508 $elements[$idx]['matchString'] = $value;
509
510 if (is_array($spParams) && in_array('subst',$spParams)) {
511 $parts[$idx] = '{softref:'.$tokenID.'}';
512 $elements[$idx]['subst'] = array(
513 'type' => 'string',
514 'tokenID' => $tokenID,
515 'tokenValue' => $value,
516 );
517 }
518 }
519 }
520
521 // Return output:
522 if (count($elements)) {
523 $resultArray = array(
524 'content' => substr(implode('',$parts),1,-1),
525 'elements' => $elements
526 );
527 return $resultArray;
528 }
529 }
530
531 /**
532 * Finding reference to files from extensions in content, but only to notify about their existence. No substitution
533 *
534 * @param string The input content to analyse
535 * @param array Parameters set for the softref parser key in TCA/columns
536 * @return array Result array on positive matches, see description above. Otherwise false
537 */
538 function findRef_extension_fileref($content, $spParams) {
539 $resultArray = array();
540
541 // Fileadmin files:
542 $parts = preg_split("/([^[:alnum:]\"']+)(EXT:[[:alnum:]_]+\/[^[:space:]\"',]*)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
543
544 foreach($parts as $idx => $value) {
545 if ($idx%3 == 2) {
546
547 $tokenID = $this->makeTokenID($idx);
548 $elements[$idx] = array();
549 $elements[$idx]['matchString'] = $value;
550 }
551 }
552
553 // Return output:
554 if (count($elements)) {
555 $resultArray = array(
556 'content' => substr(implode('',$parts),1,-1),
557 'elements' => $elements
558 );
559 return $resultArray;
560 }
561 }
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576 /*************************
577 *
578 * Helper functions
579 *
580 *************************/
581
582 /**
583 * Searches the content for a reference to a file in "fileadmin/".
584 * When a match is found it will get substituted with a token.
585 *
586 * @param string Input content to analyse
587 * @param array Element array to be modified with new entries. Passed by reference.
588 * @return string Output content, possibly with tokens inserted.
589 */
590 function fileadminReferences($content, &$elements) {
591
592 // Fileadmin files are found
593 $parts = preg_split("/([^[:alnum:]]+)(".$this->fileAdminDir."\/[^[:space:]\"'<>]*)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
594
595 // Traverse files:
596 foreach($parts as $idx => $value) {
597 if ($idx%3 == 2) {
598
599 // when file is found, set up an entry for the element:
600 $tokenID = $this->makeTokenID('fileadminReferences:'.$idx);
601 $elements['fileadminReferences.'.$idx] = array();
602 $elements['fileadminReferences.'.$idx]['matchString'] = $value;
603 $elements['fileadminReferences.'.$idx]['subst'] = array(
604 'type' => 'file',
605 'relFileName' => $value,
606 'tokenID' => $tokenID,
607 'tokenValue' => $value,
608 );
609 $parts[$idx] = '{softref:'.$tokenID.'}';
610
611 // Check if the file actually exists:
612 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$value);
613 if (!@is_file($absPath)) {
614 $elements['fileadminReferences.'.$idx]['error'] = 'File does not exist!';
615 }
616 }
617 }
618 #debug($parts);
619 // Implode the content again, removing prefixed and trailing white space:
620 return substr(implode('',$parts),1,-1);
621 }
622
623 /**
624 * Analyse content as a TypoLink value and return an array with properties.
625 * TypoLinks format is: <link [typolink] [browser target] [css class]>. See tslib_content::typolink()
626 * The syntax of the [typolink] part is: [typolink] = [page id or alias][,[type value]][#[anchor, if integer = tt_content uid]]
627 * The extraction is based on how tslib_content::typolink() behaves.
628 *
629 * @param string TypoLink value.
630 * @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.
631 * @see tslib_content::typolink(), setTypoLinkPartsElement()
632 */
633 function getTypoLinkParts($typolinkValue) {
634 $finalTagParts = array();
635
636 // Split by space into link / target / class
637 list($link_param, $browserTarget, $cssClass) = t3lib_div::trimExplode(' ',$typolinkValue,1);
638 if (strlen($browserTarget)) $finalTagParts['target'] = $browserTarget;
639 if (strlen($cssClass)) $finalTagParts['class'] = $cssClass;
640
641 // Parse URL:
642 $pU = @parse_url($link_param);
643
644 // Detecting the kind of reference:
645 if(strstr($link_param,'@') && !$pU['scheme']) { // If it's a mail address:
646 $link_param = preg_replace('/^mailto:/i','',$link_param);
647
648 $finalTagParts['LINK_TYPE'] = 'mailto';
649 $finalTagParts['url'] = trim($link_param);
650 } else {
651 $isLocalFile = 0;
652 $fileChar = intval(strpos($link_param, '/'));
653 $urlChar = intval(strpos($link_param, '.'));
654
655 // Detects if a file is found in site-root (or is a 'virtual' simulateStaticDocument file!) and if so it will be treated like a normal file.
656 list($rootFileDat) = explode('?',rawurldecode($link_param));
657 $containsSlash = strstr($rootFileDat,'/');
658 $rFD_fI = pathinfo($rootFileDat);
659 if (trim($rootFileDat) && !$containsSlash && (@is_file(PATH_site.$rootFileDat) || t3lib_div::inList('php,html,htm',strtolower($rFD_fI['extension'])))) {
660 $isLocalFile = 1;
661 } elseif ($containsSlash) {
662 $isLocalFile = 2; // Adding this so realurl directories are linked right (non-existing).
663 }
664
665 if($pU['scheme'] || ($isLocalFile!=1 && $urlChar && (!$containsSlash || $urlChar<$fileChar))) { // url (external): If doubleSlash or if a '.' comes before a '/'.
666 $finalTagParts['LINK_TYPE'] = 'url';
667 $finalTagParts['url'] = $link_param;
668 } elseif ($containsSlash || $isLocalFile) { // file (internal)
669 $splitLinkParam = explode('?', $link_param);
670 if (file_exists(rawurldecode($splitLinkParam[0])) || $isLocalFile) {
671 $finalTagParts['LINK_TYPE'] = 'file';
672 $finalTagParts['filepath'] = rawurldecode($splitLinkParam[0]);
673 $finalTagParts['query'] = $splitLinkParam[1];
674 }
675 } else { // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to definition in $TCA!)
676 $finalTagParts['LINK_TYPE'] = 'page';
677
678 $link_params_parts = explode('#',$link_param);
679 $link_param = trim($link_params_parts[0]); // Link-data del
680
681 if (strlen($link_params_parts[1])) {
682 $finalTagParts['anchor'] = trim($link_params_parts[1]);
683 }
684
685 // Splitting the parameter by ',' and if the array counts more than 1 element it's a id/type/? pair
686 $pairParts = t3lib_div::trimExplode(',',$link_param);
687 if (count($pairParts)>1) {
688 $link_param = $pairParts[0];
689 $finalTagParts['type'] = $pairParts[1]; // Overruling 'type'
690 }
691
692 // Checking if the id-parameter is an alias.
693 if (strlen($link_param)) {
694 if (!t3lib_div::testInt($link_param)) {
695 $finalTagParts['alias'] = $link_param;
696 $link_param = $this->getPageIdFromAlias($link_param);
697 }
698
699 $finalTagParts['page_id'] = intval($link_param);
700 }
701 }
702 }
703
704 return $finalTagParts;
705 }
706
707 /**
708 * Recompile a TypoLink value from the array of properties made with getTypoLinkParts() into an elements array
709 *
710 * @param array TypoLink properties
711 * @param array Array of elements to be modified with substitution / information entries.
712 * @param string The content to process.
713 * @param integer Index value of the found element - user to make unique but stable tokenID
714 * @return string The input content, possibly containing tokens now according to the added substitution entries in $elements
715 * @see getTypoLinkParts()
716 */
717 function setTypoLinkPartsElement($tLP, &$elements, $content, $idx) {
718
719 // Initialize, set basic values. In any case a link will be shown
720 $tokenID = $this->makeTokenID('setTypoLinkPartsElement:'.$idx);
721 $elements[$tokenID.':'.$idx] = array();
722 $elements[$tokenID.':'.$idx]['matchString'] = $content;
723
724 // Based on link type, maybe do more:
725 switch ((string)$tLP['LINK_TYPE']) {
726 case 'mailto':
727 case 'url':
728 // Mail addresses and URLs can be substituted manually:
729 $elements[$tokenID.':'.$idx]['subst'] = array(
730 'type' => 'string',
731 'tokenID' => $tokenID,
732 'tokenValue' => $tLP['url'],
733 );
734 // Output content will be the token instead:
735 $content = '{softref:'.$tokenID.'}';
736 break;
737 case 'file':
738 // Process files found in fileadmin directory:
739 if (!$tLP['query']) { // We will not process files which has a query added to it. That will look like a script we don't want to move.
740 if (t3lib_div::isFirstPartOfStr($tLP['filepath'],$this->fileAdminDir.'/')) { // File must be inside fileadmin/
741
742 // Set up the basic token and token value for the relative file:
743 $elements[$tokenID.':'.$idx]['subst'] = array(
744 'type' => 'file',
745 'relFileName' => $tLP['filepath'],
746 'tokenID' => $tokenID,
747 'tokenValue' => $tLP['filepath'],
748 );
749
750 // Depending on whether the file exists or not we will set the
751 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$tLP['filepath']);
752 if (!@is_file($absPath)) {
753 $elements[$tokenID.':'.$idx]['error'] = 'File does not exist!';
754 }
755
756 // Output content will be the token instead
757 $content = '{softref:'.$tokenID.'}';
758 } else return $content;
759 } else return $content;
760 break;
761 case 'page':
762 // Rebuild page reference typolink part:
763 $content = '';
764
765 // Set page id:
766 if ($tLP['page_id']) {
767 $content.= '{softref:'.$tokenID.'}';
768 $elements[$tokenID.':'.$idx]['subst'] = array(
769 'type' => 'db',
770 'recordRef' => 'pages:'.$tLP['page_id'],
771 'tokenID' => $tokenID,
772 'tokenValue' => $tLP['alias'] ? $tLP['alias'] : $tLP['page_id'], // Set page alias if that was used.
773 );
774 }
775
776 // Add type if applicable
777 if (strlen($tLP['type'])) {
778 $content.= ','.$tLP['type'];
779 }
780
781 // Add anchor if applicable
782 if (strlen($tLP['anchor'])) {
783 if (t3lib_div::testInt($tLP['anchor'])) { // Anchor is assumed to point to a content elements:
784 // Initialize a new entry because we have a new relation:
785 $newTokenID = $this->makeTokenID('setTypoLinkPartsElement:anchor:'.$idx);
786 $elements[$newTokenID.':'.$idx] = array();
787 $elements[$newTokenID.':'.$idx]['matchString'] = 'Anchor Content Element: '.$tLP['anchor'];
788
789 $content.= '#{softref:'.$newTokenID.'}';
790 $elements[$newTokenID.':'.$idx]['subst'] = array(
791 'type' => 'db',
792 'recordRef' => 'tt_content:'.$tLP['anchor'],
793 'tokenID' => $newTokenID,
794 'tokenValue' => $tLP['anchor'],
795 );
796 } else { // Anchor is a hardcoded string
797 $content.= '#'.$tLP['type'];
798 }
799 }
800 break;
801 default:
802 {
803 $elements[$tokenID.':'.$idx]['error'] = 'Couldn\t decide typolink mode.';
804 return $content;
805 }
806 break;
807 }
808
809 // Finally, for all entries that was rebuild with tokens, add target and class in the end:
810 if (strlen($content) && strlen($tLP['target'])) {
811 $content.= ' '.$tLP['target'];
812 if (strlen($tLP['class'])) {
813 $content.= ' '.$tLP['class'];
814 }
815 }
816
817 // Return rebuilt typolink value:
818 return $content;
819 }
820
821 /**
822 * Look up and return page uid for alias
823 *
824 * @param integer Page alias string value
825 * @return integer Page uid corresponding to alias value.
826 */
827 function getPageIdFromAlias($link_param) {
828 $pRec = t3lib_BEfunc::getRecordsByField('pages','alias',$link_param);
829
830 return $pRec[0]['uid'];
831 }
832
833 /**
834 * Make Token ID for input index.
835 *
836 * @param string suffix value.
837 * @return string Token ID
838 */
839 function makeTokenID($index='') {
840 return md5($this->tokenID_basePrefix.':'.$index);
841 }
842 }
843
844 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_softrefproc.php']) {
845 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_softrefproc.php']);
846 }
847
848 ?>