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