*** empty log message ***
[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 * 319: function splitTags($tag,$content)
48 * 353: function getAllParts($parts,$tag_parts=1,$include_tag=1)
49 * 372: function removeFirstAndLastTag($str)
50 * 391: function getFirstTag($str)
51 * 406: function getFirstTagName($str,$preserveCase=FALSE)
52 * 421: function get_tag_attributes($tag,$deHSC=0)
53 * 463: function split_tag_attributes($tag)
54 * 506: 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 * 597: function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array())
58 * 791: function bidir_htmlspecialchars($value,$dir)
59 * 813: function prefixResourcePath($main_prefix,$content,$alternatives=array())
60 * 881: function prefixRelPath($prefix,$srcVal)
61 * 899: function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0)
62 * 930: function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<')
63 * 947: function unprotectTags($content,$tagList='')
64 * 980: function stripTagsExcept($value,$tagList)
65 * 1003: function caseShift($str,$flag,$cacheKey='')
66 * 1027: function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0)
67 * 1056: function get_tag_attributes_classic($tag,$deHSC=0)
68 * 1069: function indentLines($content, $number=1, $indentChar="\t")
69 * 1086: function HTMLparserConfig($TSconfig,$keepTags=array())
70 * 1210: function XHTML_clean($content)
71 * 1233: function processTag($value,$conf,$endTag,$protected=0)
72 * 1280: 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 * 'default' => If no attribute exists by this name, this value is set as default value (if this value is not blank)
576 * 'always' => Boolean. If set, the attribute is always processed. Normally an attribute is processed only if it exists
577 * 'trim,intval,lower,upper' => All booleans. If any of these keys are set, the value is passed through the respective PHP-functions.
578 * 'range' => Array ('[low limit]','[high limit, optional]') Setting integer range.
579 * 'list' => Array ('[value1/default]','[value2]','[value3]') Attribute must be in this list. If not, the value is set to the first element.
580 * '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)
581 * 'removeIfEquals' => [value] If the attribute value matches the value set here, then it is removed.
582 * 'casesensitiveComp' => 1 If set, then the removeIfEquals and list comparisons will be case sensitive. Otherwise not.
583 * )
584 * ),
585 * 'protect' => '', Boolean. If set, the tag <> is converted to &lt; and &gt;
586 * 'remap' => '', String. If set, the tagname is remapped to this tagname
587 * 'rmTagIfNoAttrib' => '', Boolean. If set, then the tag is removed if no attributes happend to be there.
588 * '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>'
589 * )
590 *
591 * @param string $content; is the HTML-content being processed. This is also the result being returned.
592 * @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.
593 * @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;
594 * @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;")
595 * @param array Configuration array send along as $conf to the internal functions ->processContent() and ->processTag()
596 * @return string Processed HTML content
597 */
598 function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array()) {
599 $newContent = array();
600 $tokArr = explode('<',$content);
601 $newContent[]=$this->processContent(current($tokArr),$hSC,$addConfig);
602 next($tokArr);
603
604 $c=1;
605 $tagRegister=array();
606 $tagStack=array();
607 while(list(,$tok)=each($tokArr)) {
608 $firstChar = substr($tok,0,1);
609 # if (strcmp(trim($firstChar),'')) { // It is a tag...
610 if (ereg('[[:alnum:]\/]',$firstChar)) { // It is a tag... (first char is a-z0-9 or /) (fixed 19/01 2004)
611 $tagEnd = strcspn($tok,'>');
612 if (strlen($tok)!=$tagEnd) { // If there is and end-bracket...
613 $endTag = $firstChar=='/' ? 1 : 0;
614 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
615 $tagParts = split('[[:space:]]',$tagContent,2);
616 $tagName = strtolower($tagParts[0]);
617 if (isset($tags[$tagName])) {
618 if (is_array($tags[$tagName])) { // If there is processing to do for the tag:
619
620 if (!$endTag) { // If NOT an endtag, do attribute processing (added dec. 2003)
621 // Override attributes
622 if (strcmp($tags[$tagName]['overrideAttribs'],'')) {
623 $tagParts[1]=$tags[$tagName]['overrideAttribs'];
624 }
625
626 // Allowed tags
627 if (strcmp($tags[$tagName]['allowedAttribs'],'')) {
628 if (!strcmp($tags[$tagName]['allowedAttribs'],'0')) { // No attribs allowed
629 $tagParts[1]='';
630 } elseif (trim($tagParts[1])) {
631 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
632 $tagParts[1]='';
633 $newTagAttrib = array();
634 $tList = t3lib_div::trimExplode(',',strtolower($tags[$tagName]['allowedAttribs']),1);
635 while(list(,$allowTag)=each($tList)) {
636 if (isset($tagAttrib[0][$allowTag])) $newTagAttrib[$allowTag]=$tagAttrib[0][$allowTag];
637 }
638 $tagParts[1]=$this->compileTagAttribs($newTagAttrib,$tagAttrib[1]);
639 }
640 }
641
642 // Fixed attrib values
643 if (is_array($tags[$tagName]['fixAttrib'])) {
644 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
645 $tagParts[1]='';
646 reset($tags[$tagName]['fixAttrib']);
647 while(list($attr,$params)=each($tags[$tagName]['fixAttrib'])) {
648 if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr])) $tagAttrib[0][$attr]=$params['default'];
649 if ($params['always'] || isset($tagAttrib[0][$attr])) {
650 if ($params['trim']) {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
651 if ($params['intval']) {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
652 if ($params['lower']) {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
653 if ($params['upper']) {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
654 if ($params['range']) {
655 if (isset($params['range'][1])) {
656 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
657 } else {
658 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
659 }
660 }
661 if (is_array($params['list'])) {
662 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) $tagAttrib[0][$attr]=$params['list'][0];
663 }
664 if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) || ($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],''))) {
665 unset($tagAttrib[0][$attr]);
666 }
667 if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp']))) {
668 unset($tagAttrib[0][$attr]);
669 }
670 if ($params['prefixLocalAnchors']) {
671 if (substr($tagAttrib[0][$attr],0,1)=='#') {
672 $prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');
673 $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
674 if ($params['prefixLocalAnchors']==2 && t3lib_div::isFirstPartOfStr($prefix,t3lib_div::getIndpEnv('TYPO3_SITE_URL'))) {
675 $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
676 }
677 }
678 }
679 if ($params['prefixRelPathWith']) {
680 $urlParts = parse_url($tagAttrib[0][$attr]);
681 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') { // If it is NOT an absolute URL (by http: or starting "/")
682 $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
683 }
684 }
685 if ($params['userFunc']) {
686 $tagAttrib[0][$attr] = t3lib_div::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
687 }
688 }
689 }
690 $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
691 }
692 } else { // If endTag, remove any possible attributes:
693 $tagParts[1]='';
694 }
695
696 // Protecting the tag by converting < and > to &lt; and &gt; ??
697 if ($tags[$tagName]['protect']) {
698 $lt = '&lt;'; $gt = '&gt;';
699 } else {
700 $lt = '<'; $gt = '>';
701 }
702 // Remapping tag name?
703 if ($tags[$tagName]['remap']) $tagParts[0] = $tags[$tagName]['remap'];
704
705 // rmTagIfNoAttrib
706 if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib']) {
707 $setTag=1;
708
709 if ($tags[$tagName]['nesting']) {
710 if (!is_array($tagRegister[$tagName])) $tagRegister[$tagName]=array();
711
712 if ($endTag) {
713 /* if ($tags[$tagName]['nesting']=='global') {
714 $lastEl = end($tagStack);
715 $correctTag = !strcmp($tagName,$lastEl);
716 } else $correctTag=1;
717 */
718 $correctTag=1;
719 if ($tags[$tagName]['nesting']=='global') {
720 $lastEl = end($tagStack);
721 if (strcmp($tagName,$lastEl)) {
722 if (in_array($tagName,$tagStack)) {
723 while(count($tagStack) && strcmp($tagName,$lastEl)) {
724 $elPos = end($tagRegister[$lastEl]);
725 unset($newContent[$elPos]);
726
727 array_pop($tagRegister[$lastEl]);
728 array_pop($tagStack);
729 $lastEl = end($tagStack);
730 }
731 } else {
732 $correctTag=0; // In this case the
733 }
734 }
735 }
736 if (!count($tagRegister[$tagName]) || !$correctTag) {
737 $setTag=0;
738 } else {
739 array_pop($tagRegister[$tagName]);
740 if ($tags[$tagName]['nesting']=='global') {array_pop($tagStack);}
741 }
742 } else {
743 array_push($tagRegister[$tagName],$c);
744 if ($tags[$tagName]['nesting']=='global') {array_push($tagStack,$tagName);}
745 }
746 }
747
748 if ($setTag) {
749 // Setting the tag
750 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='&lt;');
751 }
752 }
753 } else {
754 $newContent[$c++]=$this->processTag('<'.($endTag?'/':'').$tagContent.'>',$addConfig,$endTag);
755 }
756 } elseif ($keepAll) { // This is if the tag was not defined in the array for processing:
757 if (!strcmp($keepAll,'protect')) {
758 $lt = '&lt;'; $gt = '&gt;';
759 } else {
760 $lt = '<'; $gt = '>';
761 }
762 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='&lt;');
763 }
764 $newContent[$c++]=$this->processContent(substr($tok,$tagEnd+1),$hSC,$addConfig);
765 } else {
766 $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig); // There were not end-bracket, so no tag...
767 }
768 } else {
769 $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig); // It was not a tag anyways
770 }
771 }
772
773 // Unsetting tags:
774 reset($tagRegister);
775 while(list($tag,$positions)=each($tagRegister)) {
776 reset($positions);
777 while(list(,$pKey)=each($positions)) {
778 unset($newContent[$pKey]);
779 }
780 }
781
782 return implode('',$newContent);
783 }
784
785 /**
786 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
787 *
788 * @param string Input value
789 * @param integer Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
790 * @return string Output value
791 */
792 function bidir_htmlspecialchars($value,$dir) {
793 if ($dir==1) {
794 $value = htmlspecialchars($value);
795 } elseif ($dir==2) {
796 $value = t3lib_div::deHSCentities(htmlspecialchars($value));
797 } elseif ($dir==-1) {
798 $value = str_replace('&gt;','>',$value);
799 $value = str_replace('&lt;','<',$value);
800 $value = str_replace('&quot;','"',$value);
801 $value = str_replace('&amp;','&',$value);
802 }
803 return $value;
804 }
805
806 /**
807 * 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
808 *
809 * @param string Prefix string
810 * @param string HTML content
811 * @param array Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
812 * @return string Processed HTML content
813 */
814 function prefixResourcePath($main_prefix,$content,$alternatives=array()) {
815 $parts = $this->splitTags('td,table,body,img,input,form,link,script,a',$content);
816 reset($parts);
817 while(list($k,$v)=each($parts)) {
818 if ($k%2) {
819 $params = $this->get_tag_attributes($v,1);
820 $tagEnd = substr($v,-2)=='/>' ? ' />' : '>'; // Detect tag-ending so that it is re-applied correctly.
821 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
822 $somethingDone=0;
823 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
824 switch(strtolower($firstTagName)) {
825 // background - attribute:
826 case 'td':
827 case 'body':
828 case 'table':
829 $src = $params[0]['background'];
830 if ($src) {
831 $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background']);
832 $somethingDone=1;
833 }
834 break;
835 // src attribute
836 case 'img':
837 case 'input':
838 case 'script':
839 $src = $params[0]['src'];
840 if ($src) {
841 $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src']);
842 $somethingDone=1;
843 }
844 break;
845 case 'link':
846 case 'a':
847 $src = $params[0]['href'];
848 if ($src) {
849 $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href']);
850 $somethingDone=1;
851 }
852 break;
853 // action attribute
854 case 'form':
855 $src = $params[0]['action'];
856 if ($src) {
857 $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action']);
858 $somethingDone=1;
859 }
860 break;
861 }
862 if ($somethingDone) {
863 $tagParts = split('[[:space:]]',$v,2);
864 $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
865 $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).
866 $tagEnd;
867 }
868 }
869 }
870
871 return implode('',$parts);
872 }
873
874 /**
875 * Internal sub-function for ->prefixResourcePath()
876 *
877 * @param string Prefix string
878 * @param string Relative path/URL
879 * @return string Output path, prefixed if no scheme in input string
880 * @access private
881 */
882 function prefixRelPath($prefix,$srcVal) {
883 $pU = parse_url($srcVal);
884 if (!$pU['scheme']) { // If not an absolute URL.
885 $srcVal = $prefix.$srcVal;
886 }
887 return $srcVal;
888 }
889
890 /**
891 * Cleans up the input $value for fonttags.
892 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
893 *
894 * @param string HTML content with font-tags inside to clean up.
895 * @param boolean If set, keep "face" attribute
896 * @param boolean If set, keep "size" attribute
897 * @param boolean If set, keep "color" attribute
898 * @return string Processed HTML content
899 */
900 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
901 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
902 reset($fontSplit);
903 while(list($k,$v)=each($fontSplit)) {
904 if ($k%2) { // font:
905 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
906 $newAttribs=array();
907 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
908 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
909 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
910
911 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
912 if (count($newAttribs)) {
913 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
914 } else {
915 $fontSplit[$k]=$innerContent;
916 }
917 }
918 }
919 return implode('',$fontSplit);
920 }
921
922 /**
923 * This is used to map certain tag-names into other names.
924 *
925 * @param string HTML content
926 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
927 * @param string Alternative less-than char to search for (search regex string)
928 * @param string Alternative less-than char to replace with (replace regex string)
929 * @return string Processed HTML content
930 */
931 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
932
933 foreach($tags as $from => $to) {
934 $value = eregi_replace($ltChar.$from.'>',$ltChar2.$to.'>',$value);
935 $value = eregi_replace($ltChar.$from.'[[:space:]]([^>]*)>',$ltChar2.$to.' \\1>',$value);
936 $value = eregi_replace($ltChar.'\/'.$from.'[^>]*>',$ltChar2.'/'.$to.'>',$value);
937 }
938 return $value;
939 }
940
941 /**
942 * 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
943 *
944 * @param string HTML content
945 * @param string Tag list, separated by comma. Lowercase!
946 * @return string Processed HTML content
947 */
948 function unprotectTags($content,$tagList='') {
949 $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
950 $contentParts = explode('&lt;',$content);
951 next($contentParts); // bypass the first
952 while(list($k,$tok)=each($contentParts)) {
953 $firstChar = substr($tok,0,1);
954 if (strcmp(trim($firstChar),'')) {
955 $subparts = explode('&gt;',$tok,2);
956 $tagEnd = strlen($subparts[0]);
957 if (strlen($tok)!=$tagEnd) {
958 $endTag = $firstChar=='/' ? 1 : 0;
959 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
960 $tagParts = split('[[:space:]]',$tagContent,2);
961 $tagName = strtolower($tagParts[0]);
962 if (!strcmp($tagList,'') || in_array($tagName,$tagsArray)) {
963 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
964 } else $contentParts[$k] = '&lt;'.$tok;
965 } else $contentParts[$k] = '&lt;'.$tok;
966 } else $contentParts[$k] = '&lt;'.$tok;
967 }
968
969 return implode('',$contentParts);
970 }
971
972 /**
973 * Strips tags except the tags in the list, $tagList
974 * OBSOLETE - use PHP function strip_tags()
975 *
976 * @param string Value to process
977 * @param string List of tags
978 * @return string Output value
979 * @ignore
980 */
981 function stripTagsExcept($value,$tagList) {
982 $tags=t3lib_div::trimExplode(',',$tagList,1);
983 $forthArr=array();
984 $backArr=array();
985 while(list(,$theTag)=each($tags)) {
986 $forthArr[$theTag]=md5($theTag);
987 $backArr[md5($theTag)]=$theTag;
988 }
989 $value = $this->mapTags($value,$forthArr,'<','_');
990 $value=strip_tags($value);
991 $value = $this->mapTags($value,$backArr,'_','<');
992 return $value;
993 }
994
995 /**
996 * Internal function for case shifting of a string or whole array
997 *
998 * @param mixed Input string/array
999 * @param boolean If $str is a string AND this boolean is true, the string is returned in uppercase
1000 * @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.
1001 * @return string Output string, processed
1002 * @access private
1003 */
1004 function caseShift($str,$flag,$cacheKey='') {
1005 if (is_array($str)) {
1006 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1007 reset($str);
1008 while(list($k)=each($str)) {
1009 $str[$k] = strtoupper($str[$k]);
1010 }
1011 if ($cacheKey) $this->caseShift_cache[$cacheKey]=$str;
1012 } else {
1013 $str = $this->caseShift_cache[$cacheKey];
1014 }
1015 } elseif (!$flag) $str = strtoupper($str);
1016 return $str;
1017 }
1018
1019 /**
1020 * Compiling an array with tag attributes into a string
1021 *
1022 * @param array Tag attributes
1023 * @param array Meta information about these attributes (like if they were quoted)
1024 * @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
1025 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1026 * @access private
1027 */
1028 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
1029 $accu=array();
1030 reset($tagAttrib);
1031 while(list($k,$v)=each($tagAttrib)) {
1032 if ($xhtmlClean) {
1033 $attr=strtolower($k);
1034 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1035 $attr.='="'.htmlspecialchars($v).'"';
1036 }
1037 } else {
1038 $attr=$meta[$k]['origTag']?$meta[$k]['origTag']:$k;
1039 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1040 $dash=$meta[$k]['dashType']?$meta[$k]['dashType']:(t3lib_div::testInt($v)?'':'"');
1041 $attr.='='.$dash.$v.$dash;
1042 }
1043 }
1044 $accu[]=$attr;
1045 }
1046 return implode(' ',$accu);
1047 }
1048
1049 /**
1050 * Get tag attributes, the classic version (which had some limitations?)
1051 *
1052 * @param string The tag
1053 * @param boolean De-htmlspecialchar flag.
1054 * @return array
1055 * @access private
1056 */
1057 function get_tag_attributes_classic($tag,$deHSC=0) {
1058 $attr=$this->get_tag_attributes($tag,$deHSC);
1059 return is_array($attr[0])?$attr[0]:array();
1060 }
1061
1062 /**
1063 * Indents input content with $number instances of $indentChar
1064 *
1065 * @param string Content string, multiple lines.
1066 * @param integer Number of indents
1067 * @param string Indent character/string
1068 * @return string Indented code (typ. HTML)
1069 */
1070 function indentLines($content, $number=1, $indentChar="\t") {
1071 $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
1072 $lines = explode(chr(10),str_replace(chr(13),'',$content));
1073 while(list($k,$v) = each($lines)) {
1074 $lines[$k] = $preTab.$v;
1075 }
1076 return implode(chr(10), $lines);
1077 }
1078
1079 /**
1080 * Converts TSconfig into an array for the HTMLcleaner function.
1081 *
1082 * @param array TSconfig for HTMLcleaner
1083 * @param array Array of tags to keep (?)
1084 * @return array
1085 * @access private
1086 */
1087 function HTMLparserConfig($TSconfig,$keepTags=array()) {
1088 // Allow tags (base list, merged with incoming array)
1089 $alTags = array_flip(t3lib_div::trimExplode(',',strtolower($TSconfig['allowTags']),1));
1090 $keepTags = array_merge($alTags,$keepTags);
1091
1092 // Set config properties.
1093 if (is_array($TSconfig['tags.'])) {
1094 reset($TSconfig['tags.']);
1095 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1096 if (!is_array($tagC) && $key==strtolower($key)) {
1097 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
1098 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
1099 }
1100 }
1101
1102 reset($TSconfig['tags.']);
1103 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1104 if (is_array($tagC) && $key==strtolower($key)) {
1105 $key=substr($key,0,-1);
1106 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1107 if (is_array($tagC['fixAttrib.'])) {
1108 reset($tagC['fixAttrib.']);
1109 while(list($atName,$atConfig)=each($tagC['fixAttrib.'])) {
1110 if (is_array($atConfig)) {
1111 $atName=substr($atName,0,-1);
1112 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1113 $keepTags[$key]['fixAttrib'][$atName]=array();
1114 }
1115 $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...
1116 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1117 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1118 }
1119 }
1120 }
1121 unset($tagC['fixAttrib.']);
1122 unset($tagC['fixAttrib']);
1123 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1124 }
1125 }
1126 }
1127 // localNesting
1128 if ($TSconfig['localNesting']) {
1129 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1130 while(list(,$tn)=each($lN)) {
1131 if (isset($keepTags[$tn])) {
1132 $keepTags[$tn]['nesting']=1;
1133 }
1134 }
1135 }
1136 if ($TSconfig['globalNesting']) {
1137 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1138 while(list(,$tn)=each($lN)) {
1139 if (isset($keepTags[$tn])) {
1140 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1141 $keepTags[$tn]['nesting']='global';
1142 }
1143 }
1144 }
1145 if ($TSconfig['rmTagIfNoAttrib']) {
1146 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1147 while(list(,$tn)=each($lN)) {
1148 if (isset($keepTags[$tn])) {
1149 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1150 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1151 }
1152 }
1153 }
1154 if ($TSconfig['noAttrib']) {
1155 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1156 while(list(,$tn)=each($lN)) {
1157 if (isset($keepTags[$tn])) {
1158 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1159 $keepTags[$tn]['allowedAttribs']=0;
1160 }
1161 }
1162 }
1163 if ($TSconfig['removeTags']) {
1164 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1165 while(list(,$tn)=each($lN)) {
1166 $keepTags[$tn]=array();
1167 $keepTags[$tn]['allowedAttribs']=0;
1168 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1169 }
1170 }
1171
1172 // Create additional configuration:
1173 $addConfig=array();
1174 if ($TSconfig['xhtml_cleaning']) {
1175 $addConfig['xhtml']=1;
1176 }
1177
1178 return array(
1179 $keepTags,
1180 ''.$TSconfig['keepNonMatchedTags'],
1181 intval($TSconfig['htmlSpecialChars']),
1182 $addConfig
1183 );
1184 }
1185
1186 /**
1187 * Tries to convert the content to be XHTML compliant and other stuff like that.
1188 * STILL EXPERIMENTAL. See comments below.
1189 *
1190 * What it does NOT do (yet) according to XHTML specs.:
1191 * - Wellformedness: Nesting is NOT checked
1192 * - name/id attribute issue is not observed at this point.
1193 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1194 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1195 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1196 * - UTF-8 encoding is in fact expected by XML!!
1197 * - stylesheet element and attribute names are NOT converted to lowercase
1198 * - 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.
1199 * - Minimized values not allowed: Must do this: selected="selected"
1200 *
1201 * What it does at this point:
1202 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1203 * - Lowercase for elements and attributes
1204 * - All attributes in quotes
1205 * - Add "alt" attribute to img-tags if it's not there already.
1206 *
1207 * @param string Content to clean up
1208 * @return string Cleaned up content returned.
1209 * @access private
1210 */
1211 function XHTML_clean($content) {
1212 $content = $this->HTMLcleaner(
1213 $content,
1214 array(), // No tags treated specially
1215 1, // Keep ALL tags.
1216 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1217 array('xhtml' => 1)
1218 );
1219
1220 return $content;
1221 }
1222
1223 /**
1224 * Processing all tags themselves
1225 * (Some additions by Sacha Vorbeck)
1226 *
1227 * @param string Tag to process
1228 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1229 * @param boolean Is endtag, then set this.
1230 * @param boolean If set, just return value straight away
1231 * @return string Processed value.
1232 * @access private
1233 */
1234 function processTag($value,$conf,$endTag,$protected=0) {
1235 // Return immediately if protected or no parameters
1236 if ($protected || !count($conf)) return $value;
1237
1238 // OK then, begin processing for XHTML output:
1239 // STILL VERY EXPERIMENTAL!!
1240 if ($conf['xhtml']) {
1241 if ($endTag) { // Endtags are just set lowercase right away
1242 $value = strtolower($value);
1243 } elseif (substr($value,0,2)!='<!') { // ... and comments are ignored.
1244 $inValue = substr($value,1,(substr($value,-2)=='/>'?-2:-1)); // Finding inner value with out < >
1245 list($tagName,$tagP)=split('[[:space:]]',$inValue,2); // Separate attributes and tagname
1246 $tagName = strtolower($tagName);
1247
1248 // Process attributes
1249 $tagAttrib = $this->get_tag_attributes($tagP);
1250 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1251 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1252 $outA=array();
1253 reset($tagAttrib[0]);
1254 while(list($attrib_name,$attrib_value)=each($tagAttrib[0])) {
1255 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1256 $outA[]=$attrib_name.'="'.htmlspecialchars($this->bidir_htmlspecialchars($attrib_value,-1)).'"';
1257 }
1258 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1259 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1260 if (t3lib_div::inList('img,br,hr,meta,link,base,area,input',$tagName) || substr($value,-2)=='/>') {
1261 $newTag.=' />';
1262 } else {
1263 $newTag.='>';
1264 }
1265 $value = $newTag;
1266 }
1267 }
1268
1269 return $value;
1270 }
1271
1272 /**
1273 * Processing content between tags for HTML_cleaner
1274 *
1275 * @param string The value
1276 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1277 * @param mixed Not used, ignore.
1278 * @return string The processed value.
1279 * @access private
1280 */
1281 function processContent($value,$dir,$conf) {
1282 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1283 return $value;
1284 }
1285 }
1286
1287
1288
1289 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1290 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);
1291 }
1292 ?>