Updated years from 2004 to 2005 + all function indexes. NO actual code changes done!
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_softrefproc.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2003-2005 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 * 209: function findRef_images($content, $spParams)
45 * 276: function findRef_typolink($content, $spParams)
46 * 313: function findRef_typolink_tag($content, $spParams)
47 * 348: function findRef_TStemplate($content, $spParams)
48 * 430: function findRef_TSconfig($content, $spParams)
49 * 453: function findRef_email($content, $spParams)
50 * 493: function findRef_url($content, $spParams)
51 * 535: function findRef_extension_fileref($content, $spParams)
52 *
53 * SECTION: Helper functions
54 * 587: function fileadminReferences($content, &$elements)
55 * 630: function getTypoLinkParts($typolinkValue)
56 * 714: function setTypoLinkPartsElement($tLP, &$elements, $content, $idx)
57 * 825: function getPageIdFromAlias($link_param)
58 * 837: 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 require_once(PATH_t3lib.'class.t3lib_parsehtml.php');
98
99 /**
100 * Class for processing of the default soft reference types for CMS:
101 *
102 * - 'substitute' : A full field value targeted for manual substitution (for import /export features)
103 * - 'notify' : Just report if a value is found, nothing more.
104 * - 'images' : HTML <img> tags for RTE images / images from fileadmin/
105 * - 'typolink' : references to page id or file, possibly with anchor/target, possibly commaseparated list.
106 * - 'typolink_tag' : As typolink, but searching for <link> tag to encapsulate it.
107 * - 'TSconfig' processing (filerefs? Domains? what do we know...)
108 * - 'TStemplate' : freetext references to "fileadmin/" files.
109 * - 'email' : Email highlight
110 * - 'url' : URL highlights (with a scheme)
111 *
112 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
113 * @package TYPO3
114 * @subpackage t3lib
115 */
116 class t3lib_softrefproc {
117
118 // external configuration
119 var $fileAdminDir = 'fileadmin';
120
121
122 // Internal:
123 var $tokenID_basePrefix = '';
124
125 /**
126 * Main function through which all processing happens
127 *
128 * @param string Database table name
129 * @param string Field name for which processing occurs
130 * @param integer UID of the record
131 * @param string The content/value of the field
132 * @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.
133 * @param array Parameters of the softlink parser. Basically this is the content inside optional []-brackets after the softref keys. Parameters are exploded by ";"
134 * @param string If running from inside a FlexForm structure, this is the path of the tag.
135 * @return array Result array on positive matches, see description above. Otherwise false
136 */
137 function findRef($table, $field, $uid, $content, $spKey, $spParams, $structurePath='') {
138
139 $this->tokenID_basePrefix = $table.':'.$uid.':'.$field.':'.$structurePath.':'.$spKey;
140
141 switch($spKey) {
142 case 'notify': // Simple notification
143 $resultArray = array(
144 'elements' => array(
145 array(
146 'matchString' => $content
147 )
148 )
149 );
150 return $resultArray;
151 break;
152 case 'substitute':
153 $tokenID = $this->makeTokenID();
154 $resultArray = array(
155 'content' => '{softref:'.$tokenID.'}',
156 'elements' => array(
157 array(
158 'matchString' => $content,
159 'subst' => array(
160 'type' => 'string',
161 'tokenID' => $tokenID,
162 'tokenValue' => $content
163 )
164 )
165 )
166 );
167 return $resultArray;
168 break;
169 case 'images':
170 return $this->findRef_images($content, $spParams);
171 break;
172 case 'typolink':
173 return $this->findRef_typolink($content, $spParams);
174 break;
175 case 'typolink_tag':
176 return $this->findRef_typolink_tag($content, $spParams);
177 break;
178 case 'ext_fileref':
179 return $this->findRef_extension_fileref($content, $spParams);
180 break;
181 case 'TStemplate':
182 return $this->findRef_TStemplate($content, $spParams);
183 break;
184 case 'TSconfig':
185 return $this->findRef_TSconfig($content, $spParams);
186 break;
187 case 'email':
188 return $this->findRef_email($content, $spParams);
189 break;
190 case 'url':
191 return $this->findRef_url($content, $spParams);
192 break;
193 default:
194 return FALSE;
195 break;
196 }
197 }
198
199 /**
200 * Finding image tags in the content.
201 * All images that are not from external URLs will be returned with an info text
202 * Will only return files in fileadmin/ and files in uploads/ folders which are prefixed with "RTEmagic[C|P]_" for substitution
203 * Any "clear.gif" images are ignored.
204 *
205 * @param string The input content to analyse
206 * @param array Parameters set for the softref parser key in TCA/columns
207 * @return array Result array on positive matches, see description above. Otherwise false
208 */
209 function findRef_images($content, $spParams) {
210
211 // Start HTML parser and split content by image tag:
212 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
213 $splitContent = $htmlParser->splitTags('img',$content);
214 $elements = array();
215
216 // Traverse splitted parts:
217 foreach($splitContent as $k => $v) {
218 if ($k%2) {
219
220 // Get file reference:
221 $attribs = $htmlParser->get_tag_attributes($v);
222 $srcRef = t3lib_div::htmlspecialchars_decode($attribs[0]['src']);
223 $pI = pathinfo($srcRef);
224
225 // If it looks like a local image, continue. Otherwise ignore it.
226 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$srcRef);
227 if (!$pI['scheme'] && !$pI['query'] && $absPath && $srcRef!=='clear.gif') {
228
229 // Initialize the element entry with info text here:
230 $tokenID = $this->makeTokenID($k);
231 $elements[$k] = array();
232 $elements[$k]['matchString'] = $v;
233
234 // If the image seems to be from fileadmin/ folder or an RTE image, then proceed to set up substitution token:
235 if (t3lib_div::isFirstPartOfStr($srcRef,$this->fileAdminDir.'/') || (t3lib_div::isFirstPartOfStr($srcRef,'uploads/') && ereg('^RTEmagicC_',basename($srcRef)))) {
236 // Token and substitute value:
237 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)
238 $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)
239 $elements[$k]['subst'] = array(
240 'type' => 'file',
241 'relFileName' => $srcRef,
242 'tokenID' => $tokenID,
243 'tokenValue' => $attribs[0]['src'],
244 );
245 if (!@is_file($absPath)) { // Finally, notice if the file does not exist.
246 $elements[$k]['error'] = 'File does not exist!';
247 }
248 } else {
249 $elements[$k]['error'] = 'Could not substitute image source with token!';
250 }
251 }
252 }
253 }
254 }
255
256 // Return result:
257 if (count($elements)) {
258 $resultArray = array(
259 'content' => implode('', $splitContent),
260 'elements' => $elements
261 );
262
263 return $resultArray;
264 }
265 }
266
267 /**
268 * TypoLink value processing.
269 * Will process input value as a TypoLink value.
270 *
271 * @param string The input content to analyse
272 * @param array Parameters set for the softref parser key in TCA/columns. value "linkList" will split the string by comma before processing.
273 * @return array Result array on positive matches, see description above. Otherwise false
274 * @see tslib_content::typolink(), getTypoLinkParts()
275 */
276 function findRef_typolink($content, $spParams) {
277
278 // First, split the input string by a comma if the "linkList" parameter is set.
279 // 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.
280 if (is_array($spParams) && in_array('linkList',$spParams)) {
281 $linkElement = explode(',', $content); // Preserving whitespace on purpose.
282 } else {
283 $linkElement = array($content); // If only one element, just set in this array to make it easy below.
284 }
285
286 // Traverse the links now:
287 $elements = array();
288 foreach($linkElement as $k => $typolinkValue) {
289 $tLP = $this->getTypoLinkParts($typolinkValue);
290 $linkElement[$k] = $this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k);
291 }
292
293 // Return output:
294 if (count($elements)) {
295 $resultArray = array(
296 'content' => implode(',', $linkElement),
297 'elements' => $elements
298 );
299
300 return $resultArray;
301 }
302 }
303
304 /**
305 * TypoLink tag processing.
306 * Will search for <link ...> tags in the content string and process any found.
307 *
308 * @param string The input content to analyse
309 * @param array Parameters set for the softref parser key in TCA/columns
310 * @return array Result array on positive matches, see description above. Otherwise false
311 * @see tslib_content::typolink(), getTypoLinkParts()
312 */
313 function findRef_typolink_tag($content, $spParams) {
314
315 // Parse string for special TYPO3 <link> tag:
316 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
317 $linkTags = $htmlParser->splitTags('link',$content);
318
319 // Traverse result:
320 $elements = array();
321 foreach($linkTags as $k => $foundValue) {
322 if ($k%2) {
323 $typolinkValue = eregi_replace('<LINK[[:space:]]+','',substr($foundValue,0,-1));
324 $tLP = $this->getTypoLinkParts($typolinkValue);
325 $linkTags[$k] = '<LINK '.$this->setTypoLinkPartsElement($tLP, $elements, $typolinkValue, $k).'>';
326 }
327 }
328
329 // Return output:
330 if (count($elements)) {
331 $resultArray = array(
332 'content' => implode('', $linkTags),
333 'elements' => $elements
334 );
335
336 return $resultArray;
337 }
338 }
339
340 /**
341 * Processing the content expected from a TypoScript template
342 * This content includes references to files in fileadmin/ folders and file references in HTML tags like <img src="">, <a href=""> and <form action="">
343 *
344 * @param string The input content to analyse
345 * @param array Parameters set for the softref parser key in TCA/columns
346 * @return array Result array on positive matches, see description above. Otherwise false
347 */
348 function findRef_TStemplate($content, $spParams) {
349 $elements = array();
350
351 // First, try to find images and links:
352 $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
353 $splitContent = $htmlParser->splitTags('img,a,form', $content);
354
355 // Traverse splitted parts:
356 foreach($splitContent as $k => $v) {
357 if ($k%2) {
358
359 $attribs = $htmlParser->get_tag_attributes($v);
360
361 $attributeName = '';
362 switch($htmlParser->getFirstTagName($v)) {
363 case 'img':
364 $attributeName = 'src';
365 break;
366 case 'a':
367 $attributeName = 'href';
368 break;
369 case 'form':
370 $attributeName = 'action';
371 break;
372 }
373
374 // Get file reference:
375 if (isset($attribs[0][$attributeName])) {
376 $srcRef = t3lib_div::htmlspecialchars_decode($attribs[0][$attributeName]);
377
378 // Set entry:
379 $tokenID = $this->makeTokenID($k);
380 $elements[$k] = array();
381 $elements[$k]['matchString'] = $v;
382
383 // OK, if it looks like a local file from fileadmin/, include it:
384 $pI = pathinfo($srcRef);
385 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$srcRef);
386 if (t3lib_div::isFirstPartOfStr($srcRef,$this->fileAdminDir.'/') && !$pI['query'] && $absPath) {
387
388 // Token and substitute value:
389 if (strstr($splitContent[$k], $attribs[0][$attributeName])) { // Very important that the src-value is not DeHSC'ed
390 $splitContent[$k] = str_replace($attribs[0][$attributeName], '{softref:'.$tokenID.'}', $splitContent[$k]);
391 $elements[$k]['subst'] = array(
392 'type' => 'file',
393 'relFileName' => $srcRef,
394 'tokenID' => $tokenID,
395 'tokenValue' => $attribs[0][$attributeName],
396 );
397 if (!@is_file($absPath)) {
398 $elements[$k]['error'] = 'File does not exist!';
399 }
400 } else {
401 $elements[$k]['error'] = 'Could not substitute attribute ('.$attributeName.') value with token!';
402 }
403 }
404 }
405 }
406 }
407 $content = implode('', $splitContent);
408
409 // Process free fileadmin/ references as well:
410 $content = $this->fileadminReferences($content, $elements);
411
412 // Return output:
413 if (count($elements)) {
414 $resultArray = array(
415 'content' => $content,
416 'elements' => $elements
417 );
418 return $resultArray;
419 }
420 }
421
422 /**
423 * Processes possible references inside of Page and User TSconfig fields.
424 * Currently this only includes file references to fileadmin/ but in fact there are currently no properties that supports such references.
425 *
426 * @param string The input content to analyse
427 * @param array Parameters set for the softref parser key in TCA/columns
428 * @return array Result array on positive matches, see description above. Otherwise false
429 */
430 function findRef_TSconfig($content, $spParams) {
431 $elements = array();
432
433 // Process free fileadmin/ references from TSconfig
434 $content = $this->fileadminReferences($content, $elements);
435
436 // Return output:
437 if (count($elements)) {
438 $resultArray = array(
439 'content' => $content,
440 'elements' => $elements
441 );
442 return $resultArray;
443 }
444 }
445
446 /**
447 * Finding email addresses in content and making them substitutable.
448 *
449 * @param string The input content to analyse
450 * @param array Parameters set for the softref parser key in TCA/columns
451 * @return array Result array on positive matches, see description above. Otherwise false
452 */
453 function findRef_email($content, $spParams) {
454 $resultArray = array();
455
456 // email:
457 $parts = preg_split("/([^[:alnum:]]+)([A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
458 foreach($parts as $idx => $value) {
459 if ($idx%3 == 2) {
460
461 $tokenID = $this->makeTokenID($idx);
462 $elements[$idx] = array();
463 $elements[$idx]['matchString'] = $value;
464
465 if (is_array($spParams) && in_array('subst',$spParams)) {
466 $parts[$idx] = '{softref:'.$tokenID.'}';
467 $elements[$idx]['subst'] = array(
468 'type' => 'string',
469 'tokenID' => $tokenID,
470 'tokenValue' => $value,
471 );
472 }
473 }
474 }
475
476 // Return output:
477 if (count($elements)) {
478 $resultArray = array(
479 'content' => substr(implode('',$parts),1,-1),
480 'elements' => $elements
481 );
482 return $resultArray;
483 }
484 }
485
486 /**
487 * Finding URLs in content, but only to notify about their existence. No substitution (could be done later via a parameter)
488 *
489 * @param string The input content to analyse
490 * @param array Parameters set for the softref parser key in TCA/columns
491 * @return array Result array on positive matches, see description above. Otherwise false
492 */
493 function findRef_url($content, $spParams) {
494 $resultArray = array();
495
496 // Fileadmin files:
497 $parts = preg_split("/([^[:alnum:]\"']+)((http|ftp):\/\/[^[:space:]\"'<>]*)([[:space:]])/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
498
499 foreach($parts as $idx => $value) {
500 if ($idx%5 == 3) { unset($parts[$idx]); }
501 if ($idx%5 == 2) {
502
503 $tokenID = $this->makeTokenID($idx);
504 $elements[$idx] = array();
505 $elements[$idx]['matchString'] = $value;
506
507 if (is_array($spParams) && in_array('subst',$spParams)) {
508 $parts[$idx] = '{softref:'.$tokenID.'}';
509 $elements[$idx]['subst'] = array(
510 'type' => 'string',
511 'tokenID' => $tokenID,
512 'tokenValue' => $value,
513 );
514 }
515 }
516 }
517
518 // Return output:
519 if (count($elements)) {
520 $resultArray = array(
521 'content' => substr(implode('',$parts),1,-1),
522 'elements' => $elements
523 );
524 return $resultArray;
525 }
526 }
527
528 /**
529 * Finding reference to files from extensions in content, but only to notify about their existence. No substitution
530 *
531 * @param string The input content to analyse
532 * @param array Parameters set for the softref parser key in TCA/columns
533 * @return array Result array on positive matches, see description above. Otherwise false
534 */
535 function findRef_extension_fileref($content, $spParams) {
536 $resultArray = array();
537
538 // Fileadmin files:
539 $parts = preg_split("/([^[:alnum:]\"']+)(EXT:[[:alnum:]_]+\/[^[:space:]\"',]*)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
540
541 foreach($parts as $idx => $value) {
542 if ($idx%3 == 2) {
543
544 $tokenID = $this->makeTokenID($idx);
545 $elements[$idx] = array();
546 $elements[$idx]['matchString'] = $value;
547 }
548 }
549
550 // Return output:
551 if (count($elements)) {
552 $resultArray = array(
553 'content' => substr(implode('',$parts),1,-1),
554 'elements' => $elements
555 );
556 return $resultArray;
557 }
558 }
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573 /*************************
574 *
575 * Helper functions
576 *
577 *************************/
578
579 /**
580 * Searches the content for a reference to a file in "fileadmin/".
581 * When a match is found it will get substituted with a token.
582 *
583 * @param string Input content to analyse
584 * @param array Element array to be modified with new entries. Passed by reference.
585 * @return string Output content, possibly with tokens inserted.
586 */
587 function fileadminReferences($content, &$elements) {
588
589 // Fileadmin files are found
590 $parts = preg_split("/([^[:alnum:]]+)(".$this->fileAdminDir."\/[^[:space:]\"'<>]*)/", ' '.$content.' ',10000, PREG_SPLIT_DELIM_CAPTURE);
591
592 // Traverse files:
593 foreach($parts as $idx => $value) {
594 if ($idx%3 == 2) {
595
596 // when file is found, set up an entry for the element:
597 $tokenID = $this->makeTokenID('fileadminReferences:'.$idx);
598 $elements['fileadminReferences.'.$idx] = array();
599 $elements['fileadminReferences.'.$idx]['matchString'] = $value;
600 $elements['fileadminReferences.'.$idx]['subst'] = array(
601 'type' => 'file',
602 'relFileName' => $value,
603 'tokenID' => $tokenID,
604 'tokenValue' => $value,
605 );
606 $parts[$idx] = '{softref:'.$tokenID.'}';
607
608 // Check if the file actually exists:
609 $absPath = t3lib_div::getFileAbsFileName(PATH_site.$value);
610 if (!@is_file($absPath)) {
611 $elements['fileadminReferences.'.$idx]['error'] = 'File does not exist!';
612 }
613 }
614 }
615 #debug($parts);
616 // Implode the content again, removing prefixed and trailing white space:
617 return substr(implode('',$parts),1,-1);
618 }
619
620 /**
621 * Analyse content as a TypoLink value and return an array with properties.
622 * TypoLinks format is: <link [typolink] [browser target] [css class]>. See tslib_content::typolink()
623 * The syntax of the [typolink] part is: [typolink] = [page id or alias][,[type value]][#[anchor, if integer = tt_content uid]]
624 * The extraction is based on how tslib_content::typolink() behaves.
625 *
626 * @param string TypoLink value.
627 * @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.
628 * @see tslib_content::typolink(), setTypoLinkPartsElement()
629 */
630 function getTypoLinkParts($typolinkValue) {
631 $finalTagParts = array();
632
633 // Split by space into link / target / class
634 list($link_param, $browserTarget, $cssClass) = t3lib_div::trimExplode(' ',$typolinkValue,1);
635 if (strlen($browserTarget)) $finalTagParts['target'] = $browserTarget;
636 if (strlen($cssClass)) $finalTagParts['class'] = $cssClass;
637
638 // Parse URL:
639 $pU = parse_url($link_param);
640
641 // Detecting the kind of reference:
642 if(strstr($link_param,'@') && !$pU['scheme']) { // If it's a mail address:
643 $link_param = eregi_replace('^mailto:','',$link_param);
644
645 $finalTagParts['LINK_TYPE'] = 'mailto';
646 $finalTagParts['url'] = trim($link_param);
647 } else {
648 $isLocalFile = 0;
649 $fileChar = intval(strpos($link_param, '/'));
650 $urlChar = intval(strpos($link_param, '.'));
651
652 // 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.
653 list($rootFileDat) = explode('?',rawurldecode($link_param));
654 $containsSlash = strstr($rootFileDat,'/');
655 $rFD_fI = pathinfo($rootFileDat);
656 if (trim($rootFileDat) && !$containsSlash && (@is_file(PATH_site.$rootFileDat) || t3lib_div::inList('php,html,htm',strtolower($rFD_fI['extension'])))) {
657 $isLocalFile = 1;
658 } elseif ($containsSlash) {
659 $isLocalFile = 2; // Adding this so realurl directories are linked right (non-existing).
660 }
661
662 if($pU['scheme'] || ($isLocalFile!=1 && $urlChar && (!$containsSlash || $urlChar<$fileChar))) { // url (external): If doubleSlash or if a '.' comes before a '/'.
663 $finalTagParts['LINK_TYPE'] = 'url';
664 $finalTagParts['url'] = $link_param;
665 } elseif ($containsSlash || $isLocalFile) { // file (internal)
666 $splitLinkParam = explode('?', $link_param);
667 if (@file_exists(rawurldecode($splitLinkParam[0])) || $isLocalFile) {
668 $finalTagParts['LINK_TYPE'] = 'file';
669 $finalTagParts['filepath'] = rawurldecode($splitLinkParam[0]);
670 $finalTagParts['query'] = $splitLinkParam[1];
671 }
672 } else { // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to definition in $TCA!)
673 $finalTagParts['LINK_TYPE'] = 'page';
674
675 $link_params_parts = explode('#',$link_param);
676 $link_param = trim($link_params_parts[0]); // Link-data del
677
678 if (strlen($link_params_parts[1])) {
679 $finalTagParts['anchor'] = trim($link_params_parts[1]);
680 }
681
682 // Splitting the parameter by ',' and if the array counts more than 1 element it's a id/type/? pair
683 $pairParts = t3lib_div::trimExplode(',',$link_param);
684 if (count($pairParts)>1) {
685 $link_param = $pairParts[0];
686 $finalTagParts['type'] = $pairParts[1]; // Overruling 'type'
687 }
688
689 // Checking if the id-parameter is an alias.
690 if (strlen($link_param)) {
691 if (!t3lib_div::testInt($link_param)) {
692 $finalTagParts['alias'] = $link_param;
693 $link_param = $this->getPageIdFromAlias($link_param);
694 }
695
696 $finalTagParts['page_id'] = intval($link_param);
697 }
698 }
699 }
700
701 return $finalTagParts;
702 }
703
704 /**
705 * Recompile a TypoLink value from the array of properties made with getTypoLinkParts() into an elements array
706 *
707 * @param array TypoLink properties
708 * @param array Array of elements to be modified with substitution / information entries.
709 * @param string The content to process.
710 * @param integer Index value of the found element - user to make unique but stable tokenID
711 * @return string The input content, possibly containing tokens now according to the added substitution entries in $elements
712 * @see getTypoLinkParts()
713 */
714 function setTypoLinkPartsElement($tLP, &$elements, $content, $idx) {
715
716 // Initialize, set basic values. In any case a link will be shown
717 $tokenID = $this->makeTokenID('setTypoLinkPartsElement:'.$idx);
718 $elements[$tokenID.':'.$idx] = array();
719 $elements[$tokenID.':'.$idx]['matchString'] = $content;
720
721 // Based on link type, maybe do more:
722 switch ((string)$tLP['LINK_TYPE']) {
723 case 'mailto':
724 // Mail addresses can be substituted manually:
725 $elements[$tokenID.':'.$idx]['subst'] = array(
726 'type' => 'string',
727 'tokenID' => $tokenID,
728 'tokenValue' => $tLP['url'],
729 );
730 // Output content will be the token instead:
731 $content = '{softref:'.$tokenID.'}';
732 break;
733 case 'url':
734 // Nothing done, only for informational purposes. So return content right away:
735 return $content;
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 $elements[$tokenID.':'.$idx]['error'] = 'Couldn\t decide typolink mode.';
803 return $content;
804 break;
805 }
806
807 // Finally, for all entries that was rebuild with tokens, add target and class in the end:
808 if (strlen($content) && strlen($tLP['target'])) {
809 $content.= ' '.$tLP['target'];
810 if (strlen($tLP['class'])) {
811 $content.= ' '.$tLP['class'];
812 }
813 }
814
815 // Return rebuilt typolink value:
816 return $content;
817 }
818
819 /**
820 * Look up and return page uid for alias
821 *
822 * @param integer Page alias string value
823 * @return integer Page uid corresponding to alias value.
824 */
825 function getPageIdFromAlias($link_param) {
826 $pRec = t3lib_BEfunc::getRecordsByField('pages','alias',$link_param);
827
828 return $pRec[0]['uid'];
829 }
830
831 /**
832 * Make Token ID for input index.
833 *
834 * @param string suffix value.
835 * @return string Token ID
836 */
837 function makeTokenID($index='') {
838 return md5($this->tokenID_basePrefix.':'.$index);
839 }
840 }
841
842 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_softrefproc.php']) {
843 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_softrefproc.php']);
844 }
845 ?>