* Changed a bunch of things, added a few new features to make TYPO3 accessible. One...
[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 $parts = $this->splitTags('td,table,body,img,input,form,link,script,a',$content);
820 reset($parts);
821 while(list($k,$v)=each($parts)) {
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
875 return implode('',$parts);
876 }
877
878 /**
879 * Internal sub-function for ->prefixResourcePath()
880 *
881 * @param string Prefix string
882 * @param string Relative path/URL
883 * @return string Output path, prefixed if no scheme in input string
884 * @access private
885 */
886 function prefixRelPath($prefix,$srcVal) {
887 $pU = parse_url($srcVal);
888 if (!$pU['scheme']) { // If not an absolute URL.
889 $srcVal = $prefix.$srcVal;
890 }
891 return $srcVal;
892 }
893
894 /**
895 * Cleans up the input $value for fonttags.
896 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
897 *
898 * @param string HTML content with font-tags inside to clean up.
899 * @param boolean If set, keep "face" attribute
900 * @param boolean If set, keep "size" attribute
901 * @param boolean If set, keep "color" attribute
902 * @return string Processed HTML content
903 */
904 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
905 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
906 reset($fontSplit);
907 while(list($k,$v)=each($fontSplit)) {
908 if ($k%2) { // font:
909 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
910 $newAttribs=array();
911 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
912 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
913 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
914
915 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
916 if (count($newAttribs)) {
917 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
918 } else {
919 $fontSplit[$k]=$innerContent;
920 }
921 }
922 }
923 return implode('',$fontSplit);
924 }
925
926 /**
927 * This is used to map certain tag-names into other names.
928 *
929 * @param string HTML content
930 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
931 * @param string Alternative less-than char to search for (search regex string)
932 * @param string Alternative less-than char to replace with (replace regex string)
933 * @return string Processed HTML content
934 */
935 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
936
937 foreach($tags as $from => $to) {
938 $value = eregi_replace($ltChar.$from.'>',$ltChar2.$to.'>',$value);
939 $value = eregi_replace($ltChar.$from.'[[:space:]]([^>]*)>',$ltChar2.$to.' \\1>',$value);
940 $value = eregi_replace($ltChar.'\/'.$from.'[^>]*>',$ltChar2.'/'.$to.'>',$value);
941 }
942 return $value;
943 }
944
945 /**
946 * 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
947 *
948 * @param string HTML content
949 * @param string Tag list, separated by comma. Lowercase!
950 * @return string Processed HTML content
951 */
952 function unprotectTags($content,$tagList='') {
953 $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
954 $contentParts = explode('&lt;',$content);
955 next($contentParts); // bypass the first
956 while(list($k,$tok)=each($contentParts)) {
957 $firstChar = substr($tok,0,1);
958 if (strcmp(trim($firstChar),'')) {
959 $subparts = explode('&gt;',$tok,2);
960 $tagEnd = strlen($subparts[0]);
961 if (strlen($tok)!=$tagEnd) {
962 $endTag = $firstChar=='/' ? 1 : 0;
963 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
964 $tagParts = split('[[:space:]]',$tagContent,2);
965 $tagName = strtolower($tagParts[0]);
966 if (!strcmp($tagList,'') || in_array($tagName,$tagsArray)) {
967 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
968 } else $contentParts[$k] = '&lt;'.$tok;
969 } else $contentParts[$k] = '&lt;'.$tok;
970 } else $contentParts[$k] = '&lt;'.$tok;
971 }
972
973 return implode('',$contentParts);
974 }
975
976 /**
977 * Strips tags except the tags in the list, $tagList
978 * OBSOLETE - use PHP function strip_tags()
979 *
980 * @param string Value to process
981 * @param string List of tags
982 * @return string Output value
983 * @ignore
984 */
985 function stripTagsExcept($value,$tagList) {
986 $tags=t3lib_div::trimExplode(',',$tagList,1);
987 $forthArr=array();
988 $backArr=array();
989 while(list(,$theTag)=each($tags)) {
990 $forthArr[$theTag]=md5($theTag);
991 $backArr[md5($theTag)]=$theTag;
992 }
993 $value = $this->mapTags($value,$forthArr,'<','_');
994 $value=strip_tags($value);
995 $value = $this->mapTags($value,$backArr,'_','<');
996 return $value;
997 }
998
999 /**
1000 * Internal function for case shifting of a string or whole array
1001 *
1002 * @param mixed Input string/array
1003 * @param boolean If $str is a string AND this boolean is true, the string is returned in uppercase
1004 * @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.
1005 * @return string Output string, processed
1006 * @access private
1007 */
1008 function caseShift($str,$flag,$cacheKey='') {
1009 if (is_array($str)) {
1010 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1011 reset($str);
1012 while(list($k)=each($str)) {
1013 $str[$k] = strtoupper($str[$k]);
1014 }
1015 if ($cacheKey) $this->caseShift_cache[$cacheKey]=$str;
1016 } else {
1017 $str = $this->caseShift_cache[$cacheKey];
1018 }
1019 } elseif (!$flag) $str = strtoupper($str);
1020 return $str;
1021 }
1022
1023 /**
1024 * Compiling an array with tag attributes into a string
1025 *
1026 * @param array Tag attributes
1027 * @param array Meta information about these attributes (like if they were quoted)
1028 * @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
1029 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1030 * @access private
1031 */
1032 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
1033 $accu=array();
1034 reset($tagAttrib);
1035 while(list($k,$v)=each($tagAttrib)) {
1036 if ($xhtmlClean) {
1037 $attr=strtolower($k);
1038 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1039 $attr.='="'.htmlspecialchars($v).'"';
1040 }
1041 } else {
1042 $attr=$meta[$k]['origTag']?$meta[$k]['origTag']:$k;
1043 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1044 $dash=$meta[$k]['dashType']?$meta[$k]['dashType']:(t3lib_div::testInt($v)?'':'"');
1045 $attr.='='.$dash.$v.$dash;
1046 }
1047 }
1048 $accu[]=$attr;
1049 }
1050 return implode(' ',$accu);
1051 }
1052
1053 /**
1054 * Get tag attributes, the classic version (which had some limitations?)
1055 *
1056 * @param string The tag
1057 * @param boolean De-htmlspecialchar flag.
1058 * @return array
1059 * @access private
1060 */
1061 function get_tag_attributes_classic($tag,$deHSC=0) {
1062 $attr=$this->get_tag_attributes($tag,$deHSC);
1063 return is_array($attr[0])?$attr[0]:array();
1064 }
1065
1066 /**
1067 * Indents input content with $number instances of $indentChar
1068 *
1069 * @param string Content string, multiple lines.
1070 * @param integer Number of indents
1071 * @param string Indent character/string
1072 * @return string Indented code (typ. HTML)
1073 */
1074 function indentLines($content, $number=1, $indentChar="\t") {
1075 $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
1076 $lines = explode(chr(10),str_replace(chr(13),'',$content));
1077 while(list($k,$v) = each($lines)) {
1078 $lines[$k] = $preTab.$v;
1079 }
1080 return implode(chr(10), $lines);
1081 }
1082
1083 /**
1084 * Converts TSconfig into an array for the HTMLcleaner function.
1085 *
1086 * @param array TSconfig for HTMLcleaner
1087 * @param array Array of tags to keep (?)
1088 * @return array
1089 * @access private
1090 */
1091 function HTMLparserConfig($TSconfig,$keepTags=array()) {
1092 // Allow tags (base list, merged with incoming array)
1093 $alTags = array_flip(t3lib_div::trimExplode(',',strtolower($TSconfig['allowTags']),1));
1094 $keepTags = array_merge($alTags,$keepTags);
1095
1096 // Set config properties.
1097 if (is_array($TSconfig['tags.'])) {
1098 reset($TSconfig['tags.']);
1099 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1100 if (!is_array($tagC) && $key==strtolower($key)) {
1101 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
1102 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
1103 }
1104 }
1105
1106 reset($TSconfig['tags.']);
1107 while(list($key,$tagC)=each($TSconfig['tags.'])) {
1108 if (is_array($tagC) && $key==strtolower($key)) {
1109 $key=substr($key,0,-1);
1110 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1111 if (is_array($tagC['fixAttrib.'])) {
1112 reset($tagC['fixAttrib.']);
1113 while(list($atName,$atConfig)=each($tagC['fixAttrib.'])) {
1114 if (is_array($atConfig)) {
1115 $atName=substr($atName,0,-1);
1116 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1117 $keepTags[$key]['fixAttrib'][$atName]=array();
1118 }
1119 $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...
1120 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1121 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1122 }
1123 }
1124 }
1125 unset($tagC['fixAttrib.']);
1126 unset($tagC['fixAttrib']);
1127 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1128 }
1129 }
1130 }
1131 // localNesting
1132 if ($TSconfig['localNesting']) {
1133 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1134 while(list(,$tn)=each($lN)) {
1135 if (isset($keepTags[$tn])) {
1136 $keepTags[$tn]['nesting']=1;
1137 }
1138 }
1139 }
1140 if ($TSconfig['globalNesting']) {
1141 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1142 while(list(,$tn)=each($lN)) {
1143 if (isset($keepTags[$tn])) {
1144 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1145 $keepTags[$tn]['nesting']='global';
1146 }
1147 }
1148 }
1149 if ($TSconfig['rmTagIfNoAttrib']) {
1150 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1151 while(list(,$tn)=each($lN)) {
1152 if (isset($keepTags[$tn])) {
1153 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1154 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1155 }
1156 }
1157 }
1158 if ($TSconfig['noAttrib']) {
1159 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1160 while(list(,$tn)=each($lN)) {
1161 if (isset($keepTags[$tn])) {
1162 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1163 $keepTags[$tn]['allowedAttribs']=0;
1164 }
1165 }
1166 }
1167 if ($TSconfig['removeTags']) {
1168 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1169 while(list(,$tn)=each($lN)) {
1170 $keepTags[$tn]=array();
1171 $keepTags[$tn]['allowedAttribs']=0;
1172 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1173 }
1174 }
1175
1176 // Create additional configuration:
1177 $addConfig=array();
1178 if ($TSconfig['xhtml_cleaning']) {
1179 $addConfig['xhtml']=1;
1180 }
1181
1182 return array(
1183 $keepTags,
1184 ''.$TSconfig['keepNonMatchedTags'],
1185 intval($TSconfig['htmlSpecialChars']),
1186 $addConfig
1187 );
1188 }
1189
1190 /**
1191 * Tries to convert the content to be XHTML compliant and other stuff like that.
1192 * STILL EXPERIMENTAL. See comments below.
1193 *
1194 * What it does NOT do (yet) according to XHTML specs.:
1195 * - Wellformedness: Nesting is NOT checked
1196 * - name/id attribute issue is not observed at this point.
1197 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1198 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1199 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1200 * - UTF-8 encoding is in fact expected by XML!!
1201 * - stylesheet element and attribute names are NOT converted to lowercase
1202 * - 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.
1203 * - Minimized values not allowed: Must do this: selected="selected"
1204 *
1205 * What it does at this point:
1206 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1207 * - Lowercase for elements and attributes
1208 * - All attributes in quotes
1209 * - Add "alt" attribute to img-tags if it's not there already.
1210 *
1211 * @param string Content to clean up
1212 * @return string Cleaned up content returned.
1213 * @access private
1214 */
1215 function XHTML_clean($content) {
1216 $content = $this->HTMLcleaner(
1217 $content,
1218 array(), // No tags treated specially
1219 1, // Keep ALL tags.
1220 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1221 array('xhtml' => 1)
1222 );
1223 return $content;
1224 }
1225
1226 /**
1227 * Processing all tags themselves
1228 * (Some additions by Sacha Vorbeck)
1229 *
1230 * @param string Tag to process
1231 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1232 * @param boolean Is endtag, then set this.
1233 * @param boolean If set, just return value straight away
1234 * @return string Processed value.
1235 * @access private
1236 */
1237 function processTag($value,$conf,$endTag,$protected=0) {
1238 // Return immediately if protected or no parameters
1239 if ($protected || !count($conf)) return $value;
1240 // OK then, begin processing for XHTML output:
1241 // STILL VERY EXPERIMENTAL!!
1242 if ($conf['xhtml']) {
1243 if ($endTag) { // Endtags are just set lowercase right away
1244 $value = strtolower($value);
1245 } elseif (substr($value,0,2)!='<!') { // ... and comments are ignored.
1246 $inValue = substr($value,1,(substr($value,-2)=='/>'?-2:-1)); // Finding inner value with out < >
1247 list($tagName,$tagP)=split('[[:space:]]',$inValue,2); // Separate attributes and tagname
1248 $tagName = strtolower($tagName);
1249
1250 // Process attributes
1251 $tagAttrib = $this->get_tag_attributes($tagP);
1252 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1253 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1254 $outA=array();
1255 reset($tagAttrib[0]);
1256 while(list($attrib_name,$attrib_value)=each($tagAttrib[0])) {
1257 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1258 $outA[]=$attrib_name.'="'.htmlspecialchars($this->bidir_htmlspecialchars($attrib_value,-1)).'"';
1259 }
1260 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1261 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1262 if (t3lib_div::inList('img,br,hr,meta,link,base,area,input',$tagName) || substr($value,-2)=='/>') {
1263 $newTag.=' />';
1264 } else {
1265 $newTag.='>';
1266 }
1267 $value = $newTag;
1268 }
1269 }
1270
1271 return $value;
1272 }
1273
1274 /**
1275 * Processing content between tags for HTML_cleaner
1276 *
1277 * @param string The value
1278 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1279 * @param mixed Not used, ignore.
1280 * @return string The processed value.
1281 * @access private
1282 */
1283 function processContent($value,$dir,$conf) {
1284 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1285 return $value;
1286 }
1287 }
1288
1289
1290
1291 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1292 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);
1293 }
1294 ?>