Added "relPathprefix" to TEMPLATE cObject and also added support for relative path...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_parsehtml.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@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 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains class with functions for parsing HTML code.
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasper@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 106: class t3lib_parsehtml
41 * 123: function getSubpart($content, $marker)
42 * 151: function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0)
43 *
44 * SECTION: Parsing HTML code
45 * 223: function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0)
46 * 284: function splitIntoBlockRecursiveProc($tag,$content,&$procObj,$callBackContent,$callBackTags,$level=0)
47 * 320: function splitTags($tag,$content)
48 * 354: function getAllParts($parts,$tag_parts=1,$include_tag=1)
49 * 373: function removeFirstAndLastTag($str)
50 * 392: function getFirstTag($str)
51 * 407: function getFirstTagName($str,$preserveCase=FALSE)
52 * 422: function get_tag_attributes($tag,$deHSC=0)
53 * 464: function split_tag_attributes($tag)
54 * 507: function checkTagTypeCounts($content,$blockTags='a,b,blockquote,body,div,em,font,form,h1,h2,h3,h4,h5,h6,i,li,map,ol,option,p,pre,select,span,strong,table,td,textarea,tr,u,ul', $soloTags='br,hr,img,input,area')
55 *
56 * SECTION: Clean HTML code
57 * 598: function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array())
58 * 792: function bidir_htmlspecialchars($value,$dir)
59 * 814: function prefixResourcePath($main_prefix,$content,$alternatives=array())
60 * 882: function prefixRelPath($prefix,$srcVal)
61 * 900: function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0)
62 * 931: function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<')
63 * 948: function unprotectTags($content,$tagList='')
64 * 981: function stripTagsExcept($value,$tagList)
65 * 1004: function caseShift($str,$flag,$cacheKey='')
66 * 1028: function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0)
67 * 1057: function get_tag_attributes_classic($tag,$deHSC=0)
68 * 1070: function indentLines($content, $number=1, $indentChar="\t")
69 * 1087: function HTMLparserConfig($TSconfig,$keepTags=array())
70 * 1211: function XHTML_clean($content)
71 * 1234: function processTag($value,$conf,$endTag,$protected=0)
72 * 1281: function processContent($value,$dir,$conf)
73 *
74 * TOTAL FUNCTIONS: 28
75 * (This index is automatically created/updated by the extension "extdeveval")
76 *
77 */
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98 /**
99 * Functions for parsing HTML.
100 * You are encouraged to use this class in your own applications
101 *
102 * @author Kasper Skaarhoj <kasper@typo3.com>
103 * @package TYPO3
104 * @subpackage t3lib
105 */
106 class t3lib_parsehtml {
107 var $caseShift_cache=array();
108
109
110 // *******************************************'
111 // COPY FROM class.tslib_content.php: / BEGIN
112 // substituteSubpart
113 // Cleaned locally 2/2003 !!!! (so different from tslib_content version)
114 // *******************************************'
115
116 /**
117 * Returns the first subpart encapsulated in the marker, $marker (possibly present in $content as a HTML comment)
118 *
119 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
120 * @param string Marker string, eg. "###CONTENT_PART###"
121 * @return string
122 */
123 function getSubpart($content, $marker) {
124 if ($marker && strstr($content,$marker)) {
125 $start = strpos($content, $marker)+strlen($marker);
126 $stop = @strpos($content, $marker, $start+1);
127 $sub = substr($content, $start, $stop-$start);
128
129 $reg=Array();
130 ereg('^[^<]*-->',$sub,$reg);
131 $start+=strlen($reg[0]);
132
133 $reg=Array();
134 ereg('<!--[^>]*$',$sub,$reg);
135 $stop-=strlen($reg[0]);
136
137 return substr($content, $start, $stop-$start);
138 }
139 }
140
141 /**
142 * Substitutes a subpart in $content with the content of $subpartContent.
143 *
144 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
145 * @param string Marker string, eg. "###CONTENT_PART###"
146 * @param array If $subpartContent happens to be an array, it's [0] and [1] elements are wrapped around the content of the subpart (fetched by getSubpart())
147 * @param boolean If $recursive is set, the function calls itself with the content set to the remaining part of the content after the second marker. This means that proceding subparts are ALSO substituted!
148 * @param boolean If set, the marker around the subpart is not removed, but kept in the output
149 * @return string Processed input content
150 */
151 function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0) {
152 $start = strpos($content, $marker);
153 $stop = @strpos($content, $marker, $start+1)+strlen($marker);
154 if ($start && $stop>$start) {
155 // code before
156 $before = substr($content, 0, $start);
157 $reg=Array();
158 ereg('<!--[^>]*$',$before,$reg);
159 $start-=strlen($reg[0]);
160 if ($keepMarker) {
161 $reg_k=Array();
162 if ($reg[0]) ereg('^[^>]*-->',substr($content,$start),$reg_k);
163 $before_marker = substr($content, $start, strlen($reg_k[0]?$reg_k[0]:$marker));
164 }
165 $before = substr($content, 0, $start);
166 // code after
167 $after = substr($content, $stop);
168 $reg=Array();
169 ereg('^[^<]*-->',$after,$reg);
170 $stop+=strlen($reg[0]);
171 if ($keepMarker) {
172 $reg_k=Array();
173 if ($reg[0]) ereg('<!--[^<]*$',substr($content,0,$stop),$reg_k);
174 $sLen = strlen($reg_k[0]?$reg_k[0]:$marker);
175 $after_marker = substr($content, $stop-$sLen,$sLen);
176 }
177 $after = substr($content, $stop);
178
179
180 // replace?
181 if (is_array($subpartContent)) {
182 $substContent=$subpartContent[0].$this->getSubpart($content,$marker).$subpartContent[1];
183 } else {
184 $substContent=$subpartContent;
185 }
186
187 if ($recursive && strpos($after, $marker)) {
188 return $before.($keepMarker?$before_marker:'').$substContent.($keepMarker?$after_marker:'').$this->substituteSubpart($after,$marker,$subpartContent);
189 } else {
190 return $before.($keepMarker?$before_marker:'').$substContent.($keepMarker?$after_marker:'').$after;
191 }
192 } else {
193 return $content;
194 }
195 }
196 // *******************************************'
197 // COPY FROM class.tslib_content.php: / END
198 // *******************************************'
199
200
201
202
203
204
205
206 /************************************
207 *
208 * Parsing HTML code
209 *
210 ************************************/
211
212 /**
213 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
214 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
215 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
216 *
217 * @param string List of tags, comma separated.
218 * @param string HTML-content
219 * @param boolean If set, excessive end tags are ignored - you should probably set this in most cases.
220 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
221 * @see splitTags(), getAllParts(), removeFirstAndLastTag()
222 */
223 function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0) {
224 $tags=array_unique(t3lib_div::trimExplode(',',$tag,1));
225 $regexStr = '</?('.implode('|',$tags).')(>|[[:space:]][^>]*>)';
226
227 $parts = spliti($regexStr,$content);
228
229 $newParts=array();
230 $pointer=strlen($parts[0]);
231 $buffer=$parts[0];
232 $nested=0;
233 reset($parts);
234 next($parts);
235 while(list($k,$v)=each($parts)) {
236 $isEndTag= substr($content,$pointer,2)=='</' ? 1 : 0;
237 $tagLen = strcspn(substr($content,$pointer),'>')+1;
238
239 if (!$isEndTag) { // We meet a start-tag:
240 if (!$nested) { // Ground level:
241 $newParts[]=$buffer; // previous buffer stored
242 $buffer='';
243 }
244 $nested++; // We are inside now!
245 $mbuffer=substr($content,$pointer,strlen($v)+$tagLen); // New buffer set and pointer increased
246 $pointer+=strlen($mbuffer);
247 $buffer.=$mbuffer;
248 } else { // If we meet an endtag:
249 $nested--; // decrease nested-level
250 $eliminated=0;
251 if ($eliminateExtraEndTags && $nested<0) {
252 $nested=0;
253 $eliminated=1;
254 } else {
255 $buffer.=substr($content,$pointer,$tagLen); // In any case, add the endtag to current buffer and increase pointer
256 }
257 $pointer+=$tagLen;
258 if (!$nested && !$eliminated) { // if we're back on ground level, (and not by eliminating tags...
259 $newParts[]=$buffer;
260 $buffer='';
261 }
262 $mbuffer=substr($content,$pointer,strlen($v)); // New buffer set and pointer increased
263 $pointer+=strlen($mbuffer);
264 $buffer.=$mbuffer;
265 }
266
267 }
268 $newParts[]=$buffer;
269 return $newParts;
270 }
271
272 /**
273 * Splitting content into blocks *recursively* and processing tags/content with call back functions.
274 *
275 * @param string Tag list, see splitIntoBlock()
276 * @param string Content, see splitIntoBlock()
277 * @param object Object where call back methods are.
278 * @param string Name of call back method for content; "function callBackContent($str,$level)"
279 * @param string Name of call back method for tags; "function callBackTags($tags,$level)"
280 * @param integer Indent level
281 * @return string Processed content
282 * @see splitIntoBlock()
283 */
284 function splitIntoBlockRecursiveProc($tag,$content,&$procObj,$callBackContent,$callBackTags,$level=0) {
285 $parts = $this->splitIntoBlock($tag,$content,TRUE);
286 foreach($parts as $k => $v) {
287 if ($k%2) {
288 $firstTagName = $this->getFirstTagName($v, TRUE);
289 $tagsArray = array();
290 $tagsArray['tag_start'] = $this->getFirstTag($v);
291 $tagsArray['tag_end'] = '</'.$firstTagName.'>';
292 $tagsArray['tag_name'] = strtolower($firstTagName);
293 $tagsArray['add_level'] = 1;
294 $tagsArray['content'] = $this->splitIntoBlockRecursiveProc($tag,$this->removeFirstAndLastTag($v),$procObj,$callBackContent,$callBackTags,$level+$tagsArray['add_level']);
295
296 if ($callBackTags) $tagsArray = $procObj->$callBackTags($tagsArray,$level);
297
298 $parts[$k] =
299 $tagsArray['tag_start'].
300 $tagsArray['content'].
301 $tagsArray['tag_end'];
302 } else {
303 if ($callBackContent) $parts[$k] = $procObj->$callBackContent($parts[$k],$level);
304 }
305 }
306
307 return implode('',$parts);
308 }
309
310 /**
311 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
312 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
313 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
314 *
315 * @param string List of tags
316 * @param string HTML-content
317 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
318 * @see splitIntoBlock(), getAllParts(), removeFirstAndLastTag()
319 */
320 function splitTags($tag,$content) {
321 $tags=t3lib_div::trimExplode(',',$tag,1);
322 $regexStr = '<('.implode('|',$tags).')(>|[[:space:]][^>]*>)';
323 $parts = spliti($regexStr,$content);
324
325 $pointer=strlen($parts[0]);
326 $newParts=array();
327 $newParts[]=$parts[0];
328 reset($parts);
329 next($parts);
330 while(list($k,$v)=each($parts)) {
331 $tagLen = strcspn(substr($content,$pointer),'>')+1;
332
333 // Set tag:
334 $tag = substr($content,$pointer,$tagLen); // New buffer set and pointer increased
335 $newParts[]=$tag;
336 $pointer+=strlen($tag);
337
338 // Set content:
339 $newParts[]=$v;
340 $pointer+=strlen($v);
341 }
342 return $newParts;
343 }
344
345 /**
346 * Returns an array with either tag or non-tag content of the result from ->splitIntoBlock()/->splitTags()
347 *
348 * @param array Parts generated by ->splitIntoBlock() or >splitTags()
349 * @param boolean Whether to return the tag-parts (default,true) or what was outside the tags.
350 * @param boolean Whether to include the tags in the tag-parts (most useful for input made by ->splitIntoBlock())
351 * @return array Tag-parts/Non-tag-parts depending on input argument settings
352 * @see splitIntoBlock(), splitTags()
353 */
354 function getAllParts($parts,$tag_parts=1,$include_tag=1) {
355 reset($parts);
356 $newParts=array();
357 while(list($k,$v)=each($parts)) {
358 if (($k+($tag_parts?0:1))%2) {
359 if (!$include_tag) $v=$this->removeFirstAndLastTag($v);
360 $newParts[]=$v;
361 }
362 }
363 return $newParts;
364 }
365
366 /**
367 * Removes the first and last tag in the string
368 * Anything before and after the first and last tags respectively is also removed
369 *
370 * @param string String to process
371 * @return string
372 */
373 function removeFirstAndLastTag($str) {
374 // First:
375 $endLen = strcspn($str,'>')+1;
376 $str = substr($str,$endLen);
377 // Last:
378 $str = strrev($str);
379 $endLen = strcspn($str,'<')+1;
380 $str = substr($str,$endLen);
381 // return
382 return strrev($str);
383 }
384
385 /**
386 * Returns the first tag in $str
387 * Actually everything from the begining of the $str is returned, so you better make sure the tag is the first thing...
388 *
389 * @param string HTML string with tags
390 * @return string
391 */
392 function getFirstTag($str) {
393 // First:
394 $endLen = strcspn($str,'>')+1;
395 $str = substr($str,0,$endLen);
396 return $str;
397 }
398
399 /**
400 * Returns the NAME of the first tag in $str
401 *
402 * @param string HTML tag (The element name MUST be separated from the attributes by a space character! Just *whitespace* will not do)
403 * @param boolean If set, then the tag is NOT converted to uppercase by case is preserved.
404 * @return string Tag name in upper case
405 * @see getFirstTag()
406 */
407 function getFirstTagName($str,$preserveCase=FALSE) {
408 list($tag) = split('[[:space:]]',substr(trim($this->getFirstTag($str)),1,-1), 2);
409 if (!$preserveCase) $tag = strtoupper($tag);
410
411 return trim($tag);
412 }
413
414 /**
415 * Returns an array with all attributes as keys. Attributes are only lowercase a-z
416 * If a attribute is empty (shorthand), then the value for the key is empty. You can check if it existed with isset()
417 *
418 * @param string Tag: $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
419 * @param boolean If set, the attribute values are de-htmlspecialchar'ed. Should actually always be set!
420 * @return array array(Tag attributes,Attribute meta-data)
421 */
422 function get_tag_attributes($tag,$deHSC=0) {
423 list($components,$metaC) = $this->split_tag_attributes($tag);
424 $name = ''; // attribute name is stored here
425 $valuemode = '';
426 $attributes = array();
427 $attributesMeta = array();
428 if (is_array($components)) {
429 while (list($key,$val) = each ($components)) {
430 if ($val != '=') { // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
431 if ($valuemode) {
432 if ($name) {
433 $attributes[$name] = $deHSC?t3lib_div::htmlspecialchars_decode($val):$val;
434 $attributesMeta[$name]['dashType']=$metaC[$key];
435 $name = '';
436 }
437 } else {
438 if ($namekey = ereg_replace('[^a-zA-Z0-9_:-]','',$val)) {
439 $name = strtolower($namekey);
440 $attributesMeta[$name]=array();
441 $attributesMeta[$name]['origTag']=$namekey;
442 $attributes[$name] = '';
443 }
444 }
445 $valuemode = '';
446 } else {
447 $valuemode = 'on';
448 }
449 }
450 if (is_array($attributes)) reset($attributes);
451 return array($attributes,$attributesMeta);
452 }
453 }
454
455 /**
456 * Returns an array with the 'components' from an attribute list. The result is normally analyzed by get_tag_attributes
457 * Removes tag-name if found
458 *
459 * @param string The tag or attributes
460 * @return array
461 * @access private
462 * @see t3lib_div::split_tag_attributes()
463 */
464 function split_tag_attributes($tag) {
465 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
466 // Removes any > in the end of the string
467 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
468
469 $metaValue = array();
470 $value = array();
471 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
472 $firstChar=substr($tag_tmp,0,1);
473 if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
474 $reg=explode($firstChar,$tag_tmp,3);
475 $value[]=$reg[1];
476 $metaValue[]=$firstChar;
477 $tag_tmp=trim($reg[2]);
478 } elseif (!strcmp($firstChar,'=')) {
479 $value[] = '=';
480 $metaValue[]='';
481 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
482 } else {
483 // There are '' around the value. We look for the next ' ' or '>'
484 $reg = split('[[:space:]=]',$tag_tmp,2);
485 $value[] = trim($reg[0]);
486 $metaValue[]='';
487 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
488 }
489 }
490 if (is_array($value)) reset($value);
491 return array($value,$metaValue);
492 }
493
494 /**
495 * Checks whether block/solo tags are found in the correct amounts in HTML content
496 * Block tags are tags which are required to have an equal amount of start and end tags, eg. "<table>...</table>"
497 * Solo tags are tags which are required to have ONLY start tags (possibly with an XHTML ending like ".../>")
498 * NOTICE: Correct XHTML might actually fail since "<br></br>" is allowed as well as "<br/>". However only the LATTER is accepted by this function (with "br" in the "solo-tag" list), the first example will result in a warning.
499 * NOTICE: Correct XHTML might actually fail since "<p/>" is allowed as well as "<p></p>". However only the LATTER is accepted by this function (with "p" in the "block-tag" list), the first example will result in an ERROR!
500 * NOTICE: Correct HTML version "something" allows eg. <p> and <li> to be NON-ended (implicitly ended by other tags). However this is NOT accepted by this function (with "p" and "li" in the block-tag list) and it will result in an ERROR!
501 *
502 * @param string HTML content to analyze
503 * @param string Tag names for block tags (eg. table or div or p) in lowercase, commalist (eg. "table,div,p")
504 * @param string Tag names for solo tags (eg. img, br or input) in lowercase, commalist ("img,br,input")
505 * @return array Analyse data.
506 */
507 function checkTagTypeCounts($content,$blockTags='a,b,blockquote,body,div,em,font,form,h1,h2,h3,h4,h5,h6,i,li,map,ol,option,p,pre,select,span,strong,table,td,textarea,tr,u,ul', $soloTags='br,hr,img,input,area') {
508 $content = strtolower($content);
509 $analyzedOutput=array();
510 $analyzedOutput['counts']=array(); // Counts appearances of start-tags
511 $analyzedOutput['errors']=array(); // Lists ERRORS
512 $analyzedOutput['warnings']=array(); // Lists warnings.
513 $analyzedOutput['blocks']=array(); // Lists stats for block-tags
514 $analyzedOutput['solo']=array(); // Lists stats for solo-tags
515
516 // Block tags, must have endings...
517 $blockTags = explode(',',$blockTags);
518 foreach($blockTags as $tagName) {
519 $countBegin = count(split('<'.$tagName.'[^[:alnum:]]',$content))-1;
520 $countEnd = count(split('<\/'.$tagName.'[^[:alnum:]]',$content))-1;
521 $analyzedOutput['blocks'][$tagName]=array($countBegin,$countEnd,$countBegin-$countEnd);
522 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
523 if ($countBegin-$countEnd) {
524 if ($countBegin-$countEnd > 0) {
525 $analyzedOutput['errors'][$tagName]='There were more start-tags ('.$countBegin.') than end-tags ('.$countEnd.') for the element "'.$tagName.'". There should be an equal amount!';
526 } else {
527 $analyzedOutput['warnings'][$tagName]='There were more end-tags ('.$countEnd.') than start-tags ('.$countBegin.') for the element "'.$tagName.'". There should be an equal amount! However the problem is not fatal.';
528 }
529 }
530 }
531
532 // Solo tags, must NOT have endings...
533 $soloTags = explode(',',$soloTags);
534 foreach($soloTags as $tagName) {
535 $countBegin = count(split('<'.$tagName.'[^[:alnum:]]',$content))-1;
536 $countEnd = count(split('<\/'.$tagName.'[^[:alnum:]]',$content))-1;
537 $analyzedOutput['solo'][$tagName]=array($countBegin,$countEnd);
538 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
539 if ($countEnd) {
540 $analyzedOutput['warnings'][$tagName]='There were end-tags found ('.$countEnd.') for the element "'.$tagName.'". This was not expected (although XHTML technically allows it).';
541 }
542 }
543
544 return $analyzedOutput;
545 }
546
547
548
549
550
551
552
553
554
555
556
557
558 /*********************************
559 *
560 * Clean HTML code
561 *
562 *********************************/
563
564 /**
565 * Function that can clean up HTML content according to configuration given in the $tags array.
566 *
567 * Initializing the $tags array to allow a list of tags (in this case <B>,<I>,<U> and <A>), set it like this: $tags = array_flip(explode(',','b,a,i,u'))
568 * If the value of the $tags[$tagname] entry is an array, advanced processing of the tags is initialized. These are the options:
569 *
570 * $tags[$tagname] = Array(
571 * 'overrideAttribs' => '' If set, this string is preset as the attributes of the tag
572 * 'allowedAttribs' => '0' (zero) = no attributes allowed, '[commalist of attributes]' = only allowed attributes. If blank, all attributes are allowed.
573 * 'fixAttrib' => Array(
574 * '[attribute name]' => Array (
575 * 'set' => Force the attribute value to this value.
576 * 'unset' => Boolean: If set, the attribute is unset.
577 * 'default' => If no attribute exists by this name, this value is set as default value (if this value is not blank)
578 * 'always' => Boolean. If set, the attribute is always processed. Normally an attribute is processed only if it exists
579 * 'trim,intval,lower,upper' => All booleans. If any of these keys are set, the value is passed through the respective PHP-functions.
580 * 'range' => Array ('[low limit]','[high limit, optional]') Setting integer range.
581 * 'list' => Array ('[value1/default]','[value2]','[value3]') Attribute must be in this list. If not, the value is set to the first element.
582 * 'removeIfFalse' => Boolean/'blank'. If set, then the attribute is removed if it is 'false'. If this value is set to 'blank' then the value must be a blank string (that means a 'zero' value will not be removed)
583 * 'removeIfEquals' => [value] If the attribute value matches the value set here, then it is removed.
584 * 'casesensitiveComp' => 1 If set, then the removeIfEquals and list comparisons will be case sensitive. Otherwise not.
585 * )
586 * ),
587 * 'protect' => '', Boolean. If set, the tag <> is converted to &lt; and &gt;
588 * 'remap' => '', String. If set, the tagname is remapped to this tagname
589 * 'rmTagIfNoAttrib' => '', Boolean. If set, then the tag is removed if no attributes happend to be there.
590 * 'nesting' => '', Boolean/'global'. If set true, then this tag must have starting and ending tags in the correct order. Any tags not in this order will be discarded. Thus '</B><B><I></B></I></B>' will be converted to '<B><I></B></I>'. Is the value 'global' then true nesting in relation to other tags marked for 'global' nesting control is preserved. This means that if <B> and <I> are set for global nesting then this string '</B><B><I></B></I></B>' is converted to '<B></B>'
591 * )
592 *
593 * @param string $content; is the HTML-content being processed. This is also the result being returned.
594 * @param array $tags; is an array where each key is a tagname in lowercase. Only tags present as keys in this array are preserved. The value of the key can be an array with a vast number of options to configure.
595 * @param string $keepAll; boolean/'protect', if set, then all tags are kept regardless of tags present as keys in $tags-array. If 'protect' then the preserved tags have their <> converted to &lt; and &gt;
596 * @param integer $hSC; Values -1,0,1,2: Set to zero= disabled, set to 1 then the content BETWEEN tags is htmlspecialchar()'ed, set to -1 its the opposite and set to 2 the content will be HSC'ed BUT with preservation for real entities (eg. "&amp;" or "&#234;")
597 * @param array Configuration array send along as $conf to the internal functions ->processContent() and ->processTag()
598 * @return string Processed HTML content
599 */
600 function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array()) {
601 $newContent = array();
602 $tokArr = explode('<',$content);
603 $newContent[] = $this->processContent(current($tokArr),$hSC,$addConfig);
604 next($tokArr);
605
606 $c = 1;
607 $tagRegister = array();
608 $tagStack = array();
609 while(list(,$tok)=each($tokArr)) {
610 $firstChar = substr($tok,0,1);
611 # if (strcmp(trim($firstChar),'')) { // It is a tag...
612 if (ereg('[[:alnum:]\/]',$firstChar)) { // It is a tag... (first char is a-z0-9 or /) (fixed 19/01 2004). This also avoids triggering on <?xml..> and <!DOCTYPE..>
613 $tagEnd = strcspn($tok,'>');
614 if (strlen($tok)!=$tagEnd) { // If there is and end-bracket...
615 $endTag = $firstChar=='/' ? 1 : 0;
616 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
617 $tagParts = split('[[:space:]]',$tagContent,2);
618 $tagName = strtolower($tagParts[0]);
619 if (isset($tags[$tagName])) {
620 if (is_array($tags[$tagName])) { // If there is processing to do for the tag:
621
622 if (!$endTag) { // If NOT an endtag, do attribute processing (added dec. 2003)
623 // Override attributes
624 if (strcmp($tags[$tagName]['overrideAttribs'],'')) {
625 $tagParts[1]=$tags[$tagName]['overrideAttribs'];
626 }
627
628 // Allowed tags
629 if (strcmp($tags[$tagName]['allowedAttribs'],'')) {
630 if (!strcmp($tags[$tagName]['allowedAttribs'],'0')) { // No attribs allowed
631 $tagParts[1]='';
632 } elseif (trim($tagParts[1])) {
633 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
634 $tagParts[1]='';
635 $newTagAttrib = array();
636 $tList = t3lib_div::trimExplode(',',strtolower($tags[$tagName]['allowedAttribs']),1);
637 while(list(,$allowTag)=each($tList)) {
638 if (isset($tagAttrib[0][$allowTag])) $newTagAttrib[$allowTag]=$tagAttrib[0][$allowTag];
639 }
640 $tagParts[1]=$this->compileTagAttribs($newTagAttrib,$tagAttrib[1]);
641 }
642 }
643
644 // Fixed attrib values
645 if (is_array($tags[$tagName]['fixAttrib'])) {
646 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
647 $tagParts[1]='';
648 reset($tags[$tagName]['fixAttrib']);
649 while(list($attr,$params)=each($tags[$tagName]['fixAttrib'])) {
650 if (strlen($params['set'])) $tagAttrib[0][$attr] = $params['set'];
651 if (strlen($params['unset'])) unset($tagAttrib[0][$attr]);
652 if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr])) $tagAttrib[0][$attr]=$params['default'];
653 if ($params['always'] || isset($tagAttrib[0][$attr])) {
654 if ($params['trim']) {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
655 if ($params['intval']) {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
656 if ($params['lower']) {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
657 if ($params['upper']) {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
658 if ($params['range']) {
659 if (isset($params['range'][1])) {
660 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
661 } else {
662 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
663 }
664 }
665 if (is_array($params['list'])) {
666 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) $tagAttrib[0][$attr]=$params['list'][0];
667 }
668 if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) || ($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],''))) {
669 unset($tagAttrib[0][$attr]);
670 }
671 if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp']))) {
672 unset($tagAttrib[0][$attr]);
673 }
674 if ($params['prefixLocalAnchors']) {
675 if (substr($tagAttrib[0][$attr],0,1)=='#') {
676 $prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');
677 $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
678 if ($params['prefixLocalAnchors']==2 && t3lib_div::isFirstPartOfStr($prefix,t3lib_div::getIndpEnv('TYPO3_SITE_URL'))) {
679 $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
680 }
681 }
682 }
683 if ($params['prefixRelPathWith']) {
684 $urlParts = parse_url($tagAttrib[0][$attr]);
685 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') { // If it is NOT an absolute URL (by http: or starting "/")
686 $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
687 }
688 }
689 if ($params['userFunc']) {
690 $tagAttrib[0][$attr] = t3lib_div::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
691 }
692 }
693 }
694 $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
695 }
696 } else { // If endTag, remove any possible attributes:
697 $tagParts[1]='';
698 }
699
700 // Protecting the tag by converting < and > to &lt; and &gt; ??
701 if ($tags[$tagName]['protect']) {
702 $lt = '&lt;'; $gt = '&gt;';
703 } else {
704 $lt = '<'; $gt = '>';
705 }
706 // Remapping tag name?
707 if ($tags[$tagName]['remap']) $tagParts[0] = $tags[$tagName]['remap'];
708
709 // rmTagIfNoAttrib
710 if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib']) {
711 $setTag=1;
712
713 if ($tags[$tagName]['nesting']) {
714 if (!is_array($tagRegister[$tagName])) $tagRegister[$tagName]=array();
715
716 if ($endTag) {
717 /* if ($tags[$tagName]['nesting']=='global') {
718 $lastEl = end($tagStack);
719 $correctTag = !strcmp($tagName,$lastEl);
720 } else $correctTag=1;
721 */
722 $correctTag=1;
723 if ($tags[$tagName]['nesting']=='global') {
724 $lastEl = end($tagStack);
725 if (strcmp($tagName,$lastEl)) {
726 if (in_array($tagName,$tagStack)) {
727 while(count($tagStack) && strcmp($tagName,$lastEl)) {
728 $elPos = end($tagRegister[$lastEl]);
729 unset($newContent[$elPos]);
730
731 array_pop($tagRegister[$lastEl]);
732 array_pop($tagStack);
733 $lastEl = end($tagStack);
734 }
735 } else {
736 $correctTag=0; // In this case the
737 }
738 }
739 }
740 if (!count($tagRegister[$tagName]) || !$correctTag) {
741 $setTag=0;
742 } else {
743 array_pop($tagRegister[$tagName]);
744 if ($tags[$tagName]['nesting']=='global') {array_pop($tagStack);}
745 }
746 } else {
747 array_push($tagRegister[$tagName],$c);
748 if ($tags[$tagName]['nesting']=='global') {array_push($tagStack,$tagName);}
749 }
750 }
751
752 if ($setTag) {
753 // Setting the tag
754 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='&lt;');
755 }
756 }
757 } else {
758 $newContent[$c++]=$this->processTag('<'.($endTag?'/':'').$tagContent.'>',$addConfig,$endTag);
759 }
760 } elseif ($keepAll) { // This is if the tag was not defined in the array for processing:
761 if (!strcmp($keepAll,'protect')) {
762 $lt = '&lt;'; $gt = '&gt;';
763 } else {
764 $lt = '<'; $gt = '>';
765 }
766 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='&lt;');
767 }
768 $newContent[$c++]=$this->processContent(substr($tok,$tagEnd+1),$hSC,$addConfig);
769 } else {
770 $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig); // There were not end-bracket, so no tag...
771 }
772 } else {
773 $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig); // It was not a tag anyways
774 }
775 }
776
777 // Unsetting tags:
778 reset($tagRegister);
779 while(list($tag,$positions)=each($tagRegister)) {
780 reset($positions);
781 while(list(,$pKey)=each($positions)) {
782 unset($newContent[$pKey]);
783 }
784 }
785
786 return implode('',$newContent);
787 }
788
789 /**
790 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
791 *
792 * @param string Input value
793 * @param integer Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
794 * @return string Output value
795 */
796 function bidir_htmlspecialchars($value,$dir) {
797 if ($dir==1) {
798 $value = htmlspecialchars($value);
799 } elseif ($dir==2) {
800 $value = t3lib_div::deHSCentities(htmlspecialchars($value));
801 } elseif ($dir==-1) {
802 $value = str_replace('&gt;','>',$value);
803 $value = str_replace('&lt;','<',$value);
804 $value = str_replace('&quot;','"',$value);
805 $value = str_replace('&amp;','&',$value);
806 }
807 return $value;
808 }
809
810 /**
811 * Prefixes the relative paths of hrefs/src/action in the tags [td,table,body,img,input,form,link,script,a] in the $content with the $main_prefix or and alternative given by $alternatives
812 *
813 * @param string Prefix string
814 * @param string HTML content
815 * @param array Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
816 * @return string Processed HTML content
817 */
818 function prefixResourcePath($main_prefix,$content,$alternatives=array()) {
819
820 $parts = $this->splitTags('td,table,body,img,input,form,link,script,a',$content);
821 foreach($parts as $k => $v) {
822 if ($k%2) {
823 $params = $this->get_tag_attributes($v,1);
824 $tagEnd = substr($v,-2)=='/>' ? ' />' : '>'; // Detect tag-ending so that it is re-applied correctly.
825 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
826 $somethingDone=0;
827 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
828 switch(strtolower($firstTagName)) {
829 // background - attribute:
830 case 'td':
831 case 'body':
832 case 'table':
833 $src = $params[0]['background'];
834 if ($src) {
835 $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background']);
836 $somethingDone=1;
837 }
838 break;
839 // src attribute
840 case 'img':
841 case 'input':
842 case 'script':
843 $src = $params[0]['src'];
844 if ($src) {
845 $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src']);
846 $somethingDone=1;
847 }
848 break;
849 case 'link':
850 case 'a':
851 $src = $params[0]['href'];
852 if ($src) {
853 $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href']);
854 $somethingDone=1;
855 }
856 break;
857 // action attribute
858 case 'form':
859 $src = $params[0]['action'];
860 if ($src) {
861 $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action']);
862 $somethingDone=1;
863 }
864 break;
865 }
866 if ($somethingDone) {
867 $tagParts = split('[[:space:]]',$v,2);
868 $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
869 $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).
870 $tagEnd;
871 }
872 }
873 }
874 $content = implode('',$parts);
875
876 // Fix <style> section:
877 $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
878 if (strlen($prefix)) {
879 $parts = $this->splitIntoBlock('style',$content);
880 foreach($parts as $k => $v) {
881 if ($k%2) {
882 $parts[$k] = eregi_replace('(url[[:space:]]*\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\))','\1'.$prefix.'\2\3',$parts[$k]);
883 }
884 }
885 debug($parts);
886 $content = implode('',$parts);
887 }
888
889 return $content;
890 }
891
892 /**
893 * Internal sub-function for ->prefixResourcePath()
894 *
895 * @param string Prefix string
896 * @param string Relative path/URL
897 * @return string Output path, prefixed if no scheme in input string
898 * @access private
899 */
900 function prefixRelPath($prefix,$srcVal) {
901 $pU = parse_url($srcVal);
902 if (!$pU['scheme']) { // If not an absolute URL.
903 $srcVal = $prefix.$srcVal;
904 }
905 return $srcVal;
906 }
907
908 /**
909 * Cleans up the input $value for fonttags.
910 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
911 *
912 * @param string HTML content with font-tags inside to clean up.
913 * @param boolean If set, keep "face" attribute
914 * @param boolean If set, keep "size" attribute
915 * @param boolean If set, keep "color" attribute
916 * @return string Processed HTML content
917 */
918 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
919 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
920 reset($fontSplit);
921 while(list($k,$v)=each($fontSplit)) {
922 if ($k%2) { // font:
923 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
924 $newAttribs=array();
925 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
926 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
927 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
928
929 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
930 if (count($newAttribs)) {
931 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
932 } else {
933 $fontSplit[$k]=$innerContent;
934 }
935 }
936 }
937 return implode('',$fontSplit);
938 }
939
940 /**
941 * This is used to map certain tag-names into other names.
942 *
943 * @param string HTML content
944 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
945 * @param string Alternative less-than char to search for (search regex string)
946 * @param string Alternative less-than char to replace with (replace regex string)
947 * @return string Processed HTML content
948 */
949 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
950
951 foreach($tags as $from => $to) {
952 $value = eregi_replace($ltChar.$from.'>',$ltChar2.$to.'>',$value);
953 $value = eregi_replace($ltChar.$from.'[[:space:]]([^>]*)>',$ltChar2.$to.' \\1>',$value);
954 $value = eregi_replace($ltChar.'\/'.$from.'[^>]*>',$ltChar2.'/'.$to.'>',$value);
955 }
956 return $value;
957 }
958
959 /**
960 * This converts htmlspecialchar()'ed tags (from $tagList) back to real tags. Eg. '&lt;strong&gt' would be converted back to '<strong>' if found in $tagList
961 *
962 * @param string HTML content
963 * @param string Tag list, separated by comma. Lowercase!
964 * @return string Processed HTML content
965 */
966 function unprotectTags($content,$tagList='') {
967 $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
968 $contentParts = explode('&lt;',$content);
969 next($contentParts); // bypass the first
970 while(list($k,$tok)=each($contentParts)) {
971 $firstChar = substr($tok,0,1);
972 if (strcmp(trim($firstChar),'')) {
973 $subparts = explode('&gt;',$tok,2);
974 $tagEnd = strlen($subparts[0]);
975 if (strlen($tok)!=$tagEnd) {
976 $endTag = $firstChar=='/' ? 1 : 0;
977 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
978 $tagParts = split('[[:space:]]',$tagContent,2);
979 $tagName = strtolower($tagParts[0]);
980 if (!strcmp($tagList,'') || in_array($tagName,$tagsArray)) {
981 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
982 } else $contentParts[$k] = '&lt;'.$tok;
983 } else $contentParts[$k] = '&lt;'.$tok;
984 } else $contentParts[$k] = '&lt;'.$tok;
985 }
986
987 return implode('',$contentParts);
988 }
989
990 /**
991 * Strips tags except the tags in the list, $tagList
992 * OBSOLETE - use PHP function strip_tags()
993 *
994 * @param string Value to process
995 * @param string List of tags
996 * @return string Output value
997 * @ignore
998 */
999 function stripTagsExcept($value,$tagList) {
1000 $tags=t3lib_div::trimExplode(',',$tagList,1);
1001 $forthArr=array();
1002 $backArr=array();
1003 while(list(,$theTag)=each($tags)) {
1004 $forthArr[$theTag]=md5($theTag);
1005 $backArr[md5($theTag)]=$theTag;
1006 }
1007 $value = $this->mapTags($value,$forthArr,'<','_');
1008 $value=strip_tags($value);
1009 $value = $this->mapTags($value,$backArr,'_','<');
1010 return $value;
1011 }
1012
1013 /**
1014 * Internal function for case shifting of a string or whole array
1015 *
1016 * @param mixed Input string/array
1017 * @param boolean If $str is a string AND this boolean is true, the string is returned in uppercase
1018 * @param string Key string used for internal caching of the results. Could be an MD5 hash of the serialized version of the input $str if that is an array.
1019 * @return string Output string, processed
1020 * @access private
1021 */
1022 function caseShift($str,$flag,$cacheKey='') {
1023 if (is_array($str)) {
1024 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1025 reset($str);
1026 while(list($k)=each($str)) {
1027 $str[$k] = strtoupper($str[$k]);
1028 }
1029 if ($cacheKey) $this->caseShift_cache[$cacheKey]=$str;
1030 } else {
1031 $str = $this->caseShift_cache[$cacheKey];
1032 }
1033 } elseif (!$flag) $str = strtoupper($str);
1034 return $str;
1035 }
1036
1037 /**
1038 * Compiling an array with tag attributes into a string
1039 *
1040 * @param array Tag attributes
1041 * @param array Meta information about these attributes (like if they were quoted)
1042 * @param boolean If set, then the attribute names will be set in lower case, value quotes in double-quotes and the value will be htmlspecialchar()'ed
1043 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1044 * @access private
1045 */
1046 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
1047 $accu=array();
1048 reset($tagAttrib);
1049 while(list($k,$v)=each($tagAttrib)) {
1050 if ($xhtmlClean) {
1051 $attr=strtolower($k);
1052 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1053 $attr.='="'.htmlspecialchars($v).'"';
1054 }
1055 } else {
1056 $attr=$meta[$k]['origTag']?$meta[$k]['origTag']:$k;
1057 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1058 $dash=$meta[$k]['dashType']?$meta[$k]['dashType']:(t3lib_div::testInt($v)?'':'"');
1059 $attr.='='.$dash.$v.$dash;
1060 }
1061 }
1062 $accu[]=$attr;
1063 }
1064 return implode(' ',$accu);
1065 }
1066
1067 /**
1068 * Get tag attributes, the classic version (which had some limitations?)
1069 *
1070 * @param string The tag
1071 * @param boolean De-htmlspecialchar flag.
1072 * @return array
1073 * @access private
1074 */
1075 function get_tag_attributes_classic($tag,$deHSC=0) {
1076 $attr=$this->get_tag_attributes($tag,$deHSC);
1077 return is_array($attr[0])?$attr[0]:array();
1078 }
1079
1080 /**
1081 * Indents input content with $number instances of $indentChar
1082 *
1083 * @param string Content string, multiple lines.
1084 * @param integer Number of indents
1085 * @param string Indent character/string
1086 * @return string Indented code (typ. HTML)
1087 */
1088 function indentLines($content, $number=1, $indentChar="\t") {
1089 $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
1090 $lines = explode(chr(10),str_replace(chr(13),'',$content));
1091 while(list($k,$v) = each($lines)) {
1092 $lines[$k] = $preTab.$v;
1093 }
1094 return implode(chr(10), $lines);
1095 }
1096
1097 /**
1098 * Converts TSconfig into an array for the HTMLcleaner function.
1099 *
1100 * @param array TSconfig for HTMLcleaner
1101 * @param array Array of tags to keep (?)
1102 * @return array
1103 * @access private
1104 */
1105 function HTMLparserConfig($TSconfig,$keepTags=array()) {
1106 // Allow tags (base list, merged with incoming array)
1107 $alTags = array_flip(t3lib_div::trimExplode(',',strtolower($TSconfig['allowTags']),1));
1108 $keepTags = array_merge($alTags,$keepTags);
1109
1110 // Set config properties.
1111 if (is_array($TSconfig['tags.'])) {
1112 reset($TSconfig['tags.']);
1113 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1114 if (!is_array($tagC) && $key==strtolower($key)) {
1115 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
1116 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
1117 }
1118 }
1119
1120 reset($TSconfig['tags.']);
1121 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1122 if (is_array($tagC) && $key==strtolower($key)) {
1123 $key=substr($key,0,-1);
1124 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1125 if (is_array($tagC['fixAttrib.'])) {
1126 reset($tagC['fixAttrib.']);
1127 while(list($atName,$atConfig)=each($tagC['fixAttrib.'])) {
1128 if (is_array($atConfig)) {
1129 $atName=substr($atName,0,-1);
1130 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1131 $keepTags[$key]['fixAttrib'][$atName]=array();
1132 }
1133 $keepTags[$key]['fixAttrib'][$atName] = array_merge($keepTags[$key]['fixAttrib'][$atName],$atConfig); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1134 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1135 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1136 }
1137 }
1138 }
1139 unset($tagC['fixAttrib.']);
1140 unset($tagC['fixAttrib']);
1141 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1142 }
1143 }
1144 }
1145 // localNesting
1146 if ($TSconfig['localNesting']) {
1147 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1148 while(list(,$tn)=each($lN)) {
1149 if (isset($keepTags[$tn])) {
1150 $keepTags[$tn]['nesting']=1;
1151 }
1152 }
1153 }
1154 if ($TSconfig['globalNesting']) {
1155 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1156 while(list(,$tn)=each($lN)) {
1157 if (isset($keepTags[$tn])) {
1158 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1159 $keepTags[$tn]['nesting']='global';
1160 }
1161 }
1162 }
1163 if ($TSconfig['rmTagIfNoAttrib']) {
1164 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1165 while(list(,$tn)=each($lN)) {
1166 if (isset($keepTags[$tn])) {
1167 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1168 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1169 }
1170 }
1171 }
1172 if ($TSconfig['noAttrib']) {
1173 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1174 while(list(,$tn)=each($lN)) {
1175 if (isset($keepTags[$tn])) {
1176 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1177 $keepTags[$tn]['allowedAttribs']=0;
1178 }
1179 }
1180 }
1181 if ($TSconfig['removeTags']) {
1182 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1183 while(list(,$tn)=each($lN)) {
1184 $keepTags[$tn]=array();
1185 $keepTags[$tn]['allowedAttribs']=0;
1186 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1187 }
1188 }
1189
1190 // Create additional configuration:
1191 $addConfig=array();
1192 if ($TSconfig['xhtml_cleaning']) {
1193 $addConfig['xhtml']=1;
1194 }
1195
1196 return array(
1197 $keepTags,
1198 ''.$TSconfig['keepNonMatchedTags'],
1199 intval($TSconfig['htmlSpecialChars']),
1200 $addConfig
1201 );
1202 }
1203
1204 /**
1205 * Tries to convert the content to be XHTML compliant and other stuff like that.
1206 * STILL EXPERIMENTAL. See comments below.
1207 *
1208 * What it does NOT do (yet) according to XHTML specs.:
1209 * - Wellformedness: Nesting is NOT checked
1210 * - name/id attribute issue is not observed at this point.
1211 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1212 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1213 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1214 * - UTF-8 encoding is in fact expected by XML!!
1215 * - stylesheet element and attribute names are NOT converted to lowercase
1216 * - ampersands (and entities in general I think) MUST be converted to an entity reference! (&amps;). This may mean further conversion of non-tag content before output to page. May be related to the charset issue as a whole.
1217 * - Minimized values not allowed: Must do this: selected="selected"
1218 *
1219 * What it does at this point:
1220 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1221 * - Lowercase for elements and attributes
1222 * - All attributes in quotes
1223 * - Add "alt" attribute to img-tags if it's not there already.
1224 *
1225 * @param string Content to clean up
1226 * @return string Cleaned up content returned.
1227 * @access private
1228 */
1229 function XHTML_clean($content) {
1230 $content = $this->HTMLcleaner(
1231 $content,
1232 array(), // No tags treated specially
1233 1, // Keep ALL tags.
1234 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1235 array('xhtml' => 1)
1236 );
1237 return $content;
1238 }
1239
1240 /**
1241 * Processing all tags themselves
1242 * (Some additions by Sacha Vorbeck)
1243 *
1244 * @param string Tag to process
1245 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1246 * @param boolean Is endtag, then set this.
1247 * @param boolean If set, just return value straight away
1248 * @return string Processed value.
1249 * @access private
1250 */
1251 function processTag($value,$conf,$endTag,$protected=0) {
1252 // Return immediately if protected or no parameters
1253 if ($protected || !count($conf)) return $value;
1254 // OK then, begin processing for XHTML output:
1255 // STILL VERY EXPERIMENTAL!!
1256 if ($conf['xhtml']) {
1257 if ($endTag) { // Endtags are just set lowercase right away
1258 $value = strtolower($value);
1259 } elseif (substr($value,0,2)!='<!') { // ... and comments are ignored.
1260 $inValue = substr($value,1,(substr($value,-2)=='/>'?-2:-1)); // Finding inner value with out < >
1261 list($tagName,$tagP)=split('[[:space:]]',$inValue,2); // Separate attributes and tagname
1262 $tagName = strtolower($tagName);
1263
1264 // Process attributes
1265 $tagAttrib = $this->get_tag_attributes($tagP);
1266 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1267 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1268 $outA=array();
1269 reset($tagAttrib[0]);
1270 while(list($attrib_name,$attrib_value)=each($tagAttrib[0])) {
1271 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1272 $outA[]=$attrib_name.'="'.htmlspecialchars($this->bidir_htmlspecialchars($attrib_value,-1)).'"';
1273 }
1274 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1275 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1276 if (t3lib_div::inList('img,br,hr,meta,link,base,area,input',$tagName) || substr($value,-2)=='/>') {
1277 $newTag.=' />';
1278 } else {
1279 $newTag.='>';
1280 }
1281 $value = $newTag;
1282 }
1283 }
1284
1285 return $value;
1286 }
1287
1288 /**
1289 * Processing content between tags for HTML_cleaner
1290 *
1291 * @param string The value
1292 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1293 * @param mixed Not used, ignore.
1294 * @return string The processed value.
1295 * @access private
1296 */
1297 function processContent($value,$dir,$conf) {
1298 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1299 return $value;
1300 }
1301 }
1302
1303
1304
1305 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1306 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);
1307 }
1308 ?>