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