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