91a72b79d3b2f541ad2da926204c456effc73301
2 /***************************************************************
5 * (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains class with functions for parsing HTML code.
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 106: class t3lib_parsehtml
41 * 123: function getSubpart($content, $marker)
42 * 156: function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0)
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')
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=TAB)
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)
75 * (This index is automatically created/updated by the extension "extdeveval")
99 * Functions for parsing HTML.
100 * You are encouraged to use this class in your own applications
102 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
106 class t3lib_parsehtml
{
108 protected $caseShift_cache = array();
111 * Returns the first subpart encapsulated in the marker, $marker
112 * (possibly present in $content as a HTML comment)
114 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
115 * @param string Marker string, eg. "###CONTENT_PART###"
118 public static function getSubpart($content, $marker) {
119 $start = strpos($content, $marker);
121 if ($start === false) {
125 $start +
= strlen($marker);
126 $stop = strpos($content, $marker, $start);
128 // Q: What shall get returned if no stop marker is given
129 // /*everything till the end*/ or nothing?
131 return ''; /*substr($content, $start)*/
134 $content = substr($content, $start, $stop-$start);
137 if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $content, $matches) === 1) {
141 $matches = array(); // resetting $matches
142 if (preg_match('/(.*)(\<\!\-\-[^\>]*)$/s', $content, $matches) === 1) {
146 $matches = array(); // resetting $matches
147 if (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $content, $matches) === 1) {
155 * Substitutes a subpart in $content with the content of $subpartContent.
157 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
158 * @param string Marker string, eg. "###CONTENT_PART###"
159 * @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())
160 * @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!
161 * @param boolean If set, the marker around the subpart is not removed, but kept in the output
162 * @return string Processed input content
164 public static function substituteSubpart($content, $marker, $subpartContent, $recursive = 1, $keepMarker = 0) {
165 $start = strpos($content, $marker);
167 if ($start === false) {
171 $startAM = $start +
strlen($marker);
172 $stop = strpos($content, $marker, $startAM);
178 $stopAM = $stop +
strlen($marker);
179 $before = substr($content, 0, $start);
180 $after = substr($content, $stopAM);
181 $between = substr($content, $startAM, $stop-$startAM);
184 $after = self
::substituteSubpart(
195 if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
196 $before .= $marker.$matches[1];
197 $between = $matches[2];
198 $after = $matches[3] . $marker . $after;
199 } elseif (preg_match('/^(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
201 $between = $matches[1];
202 $after = $matches[2] . $marker . $after;
203 } elseif (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $between, $matches) === 1) {
204 $before .= $marker . $matches[1];
205 $between = $matches[2];
206 $after = $marker . $after;
209 $after = $marker . $after;
214 if (preg_match('/^(.*)\<\!\-\-[^\>]*$/s', $before, $matches) === 1) {
215 $before = $matches[1];
218 if (is_array($subpartContent)) {
220 if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
221 $between = $matches[2];
222 } elseif (preg_match('/^(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches)===1) {
223 $between = $matches[1];
224 } elseif (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $between, $matches)===1) {
225 $between = $matches[2];
229 $matches = array(); // resetting $matches
230 if (preg_match('/^[^\<]*\-\-\>(.*)$/s', $after, $matches) === 1) {
231 $after = $matches[1];
235 if (is_array($subpartContent)) {
236 $between = $subpartContent[0] . $between . $subpartContent[1];
238 $between = $subpartContent;
241 return $before . $between . $after;
245 * Substitues multiple subparts at once
247 * @param string The content stream, typically HTML template content.
248 * @param array The array of key/value pairs being subpart/content values used in the substitution. For each element in this array the function will substitute a subpart in the content stream with the content.
249 * @return string The processed HTML content string.
251 public static function substituteSubpartArray($content, array $subpartsContent) {
252 foreach ($subpartsContent as $subpartMarker => $subpartContent) {
253 $content = self
::substituteSubpart(
265 * Substitutes a marker string in the input content
266 * (by a simple str_replace())
268 * @param string The content stream, typically HTML template content.
269 * @param string The marker string, typically on the form "###[the marker string]###"
270 * @param mixed The content to insert instead of the marker string found.
271 * @return string The processed HTML content string.
272 * @see substituteSubpart()
274 public static function substituteMarker($content, $marker, $markContent) {
275 return str_replace($marker, $markContent, $content);
280 * Traverses the input $markContentArray array and for each key the marker
281 * by the same name (possibly wrapped and in upper case) will be
282 * substituted with the keys value in the array. This is very useful if you
283 * have a data-record to substitute in some content. In particular when you
284 * use the $wrap and $uppercase values to pre-process the markers. Eg. a
285 * key name like "myfield" could effectively be represented by the marker
286 * "###MYFIELD###" if the wrap value was "###|###" and the $uppercase
289 * @param string The content stream, typically HTML template content.
290 * @param array The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content stream with the content.
291 * @param string A wrap value - [part 1] | [part 2] - for the markers before substitution
292 * @param boolean If set, all marker string substitution is done with upper-case markers.
293 * @param boolean If set, all unused marker are deleted.
294 * @return string The processed output stream
295 * @see substituteMarker(), substituteMarkerInObject(), TEMPLATE()
297 public static function substituteMarkerArray($content, $markContentArray, $wrap = '', $uppercase = 0, $deleteUnused = 0) {
298 if (is_array($markContentArray)) {
299 $wrapArr = t3lib_div
::trimExplode('|', $wrap);
301 foreach ($markContentArray as $marker => $markContent) {
303 // use strtr instead of strtoupper to avoid locale problems with Turkish
306 'abcdefghijklmnopqrstuvwxyz',
307 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
311 if (count($wrapArr) > 0) {
312 $marker = $wrapArr[0] . $marker . $wrapArr[1];
315 $content = str_replace($marker, $markContent, $content);
320 $wrapArr = array('###', '###');
323 $content = preg_replace('/' . preg_quote($wrapArr[0]) . '([A-Z0-9_|\-]*)' . preg_quote($wrapArr[1]) . '/is', '', $content);
336 /************************************
340 ************************************/
343 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
344 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
345 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
347 * @param string List of tags, comma separated.
348 * @param string HTML-content
349 * @param boolean If set, excessive end tags are ignored - you should probably set this in most cases.
350 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
351 * @see splitTags(), getAllParts(), removeFirstAndLastTag()
353 function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0) {
354 $tags=array_unique(t3lib_div
::trimExplode(',',$tag,1));
355 $regexStr = '/\<\/?('.implode('|', $tags).')(\s*\>|\s[^\>]*\>)/si';
357 $parts = preg_split($regexStr, $content);
360 $pointer=strlen($parts[0]);
365 while(list($k,$v)=each($parts)) {
366 $isEndTag= substr($content,$pointer,2)=='</' ?
1 : 0;
367 $tagLen = strcspn(substr($content,$pointer),'>')+
1;
369 if (!$isEndTag) { // We meet a start-tag:
370 if (!$nested) { // Ground level:
371 $newParts[]=$buffer; // previous buffer stored
374 $nested++
; // We are inside now!
375 $mbuffer=substr($content,$pointer,strlen($v)+
$tagLen); // New buffer set and pointer increased
376 $pointer+
=strlen($mbuffer);
378 } else { // If we meet an endtag:
379 $nested--; // decrease nested-level
381 if ($eliminateExtraEndTags && $nested<0) {
385 $buffer.=substr($content,$pointer,$tagLen); // In any case, add the endtag to current buffer and increase pointer
388 if (!$nested && !$eliminated) { // if we're back on ground level, (and not by eliminating tags...
392 $mbuffer=substr($content,$pointer,strlen($v)); // New buffer set and pointer increased
393 $pointer+
=strlen($mbuffer);
403 * Splitting content into blocks *recursively* and processing tags/content with call back functions.
405 * @param string Tag list, see splitIntoBlock()
406 * @param string Content, see splitIntoBlock()
407 * @param object Object where call back methods are.
408 * @param string Name of call back method for content; "function callBackContent($str,$level)"
409 * @param string Name of call back method for tags; "function callBackTags($tags,$level)"
410 * @param integer Indent level
411 * @return string Processed content
412 * @see splitIntoBlock()
414 function splitIntoBlockRecursiveProc($tag,$content,&$procObj,$callBackContent,$callBackTags,$level=0) {
415 $parts = $this->splitIntoBlock($tag,$content,TRUE);
416 foreach($parts as $k => $v) {
418 $firstTagName = $this->getFirstTagName($v, TRUE);
419 $tagsArray = array();
420 $tagsArray['tag_start'] = $this->getFirstTag($v);
421 $tagsArray['tag_end'] = '</'.$firstTagName.'>';
422 $tagsArray['tag_name'] = strtolower($firstTagName);
423 $tagsArray['add_level'] = 1;
424 $tagsArray['content'] = $this->splitIntoBlockRecursiveProc($tag,$this->removeFirstAndLastTag($v),$procObj,$callBackContent,$callBackTags,$level+
$tagsArray['add_level']);
426 if ($callBackTags) $tagsArray = $procObj->$callBackTags($tagsArray,$level);
429 $tagsArray['tag_start'].
430 $tagsArray['content'].
431 $tagsArray['tag_end'];
433 if ($callBackContent) $parts[$k] = $procObj->$callBackContent($parts[$k],$level);
437 return implode('',$parts);
441 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
442 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
443 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
445 * @param string List of tags
446 * @param string HTML-content
447 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
448 * @see splitIntoBlock(), getAllParts(), removeFirstAndLastTag()
450 function splitTags($tag,$content) {
451 $tags = t3lib_div
::trimExplode(',',$tag,1);
452 $regexStr = '/\<('.implode('|', $tags).')(\s[^>]*)?\/?>/si';
453 $parts = preg_split($regexStr, $content);
455 $pointer = strlen($parts[0]);
457 $newParts[] = $parts[0];
460 while(list($k,$v)=each($parts)) {
461 $tagLen = strcspn(substr($content,$pointer),'>')+
1;
464 $tag = substr($content,$pointer,$tagLen); // New buffer set and pointer increased
466 $pointer+
= strlen($tag);
470 $pointer+
= strlen($v);
476 * Returns an array with either tag or non-tag content of the result from ->splitIntoBlock()/->splitTags()
478 * @param array Parts generated by ->splitIntoBlock() or >splitTags()
479 * @param boolean Whether to return the tag-parts (default,true) or what was outside the tags.
480 * @param boolean Whether to include the tags in the tag-parts (most useful for input made by ->splitIntoBlock())
481 * @return array Tag-parts/Non-tag-parts depending on input argument settings
482 * @see splitIntoBlock(), splitTags()
484 function getAllParts($parts,$tag_parts=1,$include_tag=1) {
486 foreach ($parts as $k => $v) {
487 if (($k+
($tag_parts?
0:1))%2
) {
488 if (!$include_tag) $v=$this->removeFirstAndLastTag($v);
496 * Removes the first and last tag in the string
497 * Anything before the first and after the last tags respectively is also removed
499 * @param string String to process
502 function removeFirstAndLastTag($str) {
504 $start = strpos($str,'>');
505 // Begin of last tag:
506 $end = strrpos($str,'<');
508 return substr($str, $start+
1, $end-$start-1);
512 * Returns the first tag in $str
513 * Actually everything from the begining of the $str is returned, so you better make sure the tag is the first thing...
515 * @param string HTML string with tags
518 function getFirstTag($str) {
520 $endLen = strpos($str,'>')+
1;
521 return substr($str,0,$endLen);
525 * Returns the NAME of the first tag in $str
527 * @param string HTML tag (The element name MUST be separated from the attributes by a space character! Just *whitespace* will not do)
528 * @param boolean If set, then the tag is NOT converted to uppercase by case is preserved.
529 * @return string Tag name in upper case
532 function getFirstTagName($str,$preserveCase=FALSE) {
534 if (preg_match('/^\s*\<([^\s\>]+)(\s|\>)/', $str, $matches)===1) {
535 if (!$preserveCase) {
536 return strtoupper($matches[1]);
544 * Returns an array with all attributes as keys. Attributes are only lowercase a-z
545 * If a attribute is empty (shorthand), then the value for the key is empty. You can check if it existed with isset()
547 * @param string Tag: $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
548 * @param boolean If set, the attribute values are de-htmlspecialchar'ed. Should actually always be set!
549 * @return array array(Tag attributes,Attribute meta-data)
551 function get_tag_attributes($tag,$deHSC=0) {
552 list($components,$metaC) = $this->split_tag_attributes($tag);
553 $name = ''; // attribute name is stored here
555 $attributes = array();
556 $attributesMeta = array();
557 if (is_array($components)) {
558 foreach ($components as $key => $val) {
559 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
562 $attributes[$name] = $deHSC?t3lib_div
::htmlspecialchars_decode($val):$val;
563 $attributesMeta[$name]['dashType']=$metaC[$key];
567 if ($namekey = preg_replace('/[^[:alnum:]_\:\-]/','',$val)) {
568 $name = strtolower($namekey);
569 $attributesMeta[$name]=array();
570 $attributesMeta[$name]['origTag']=$namekey;
571 $attributes[$name] = '';
579 return array($attributes,$attributesMeta);
584 * Returns an array with the 'components' from an attribute list. The result is normally analyzed by get_tag_attributes
585 * Removes tag-name if found
587 * @param string The tag or attributes
590 * @see t3lib_div::split_tag_attributes()
592 function split_tag_attributes($tag) {
594 if (preg_match('/(\<[^\s]+\s+)?(.*?)\s*(\>)?$/s', $tag, $matches)!==1) {
595 return array(array(), array());
597 $tag_tmp = $matches[2];
599 $metaValue = array();
602 if (preg_match_all('/("[^"]*"|\'[^\']*\'|[^\s"\'\=]+|\=)/s', $tag_tmp, $matches)>0) {
603 foreach ($matches[1] as $part) {
604 $firstChar = substr($part, 0, 1);
605 if ($firstChar=='"' ||
$firstChar=="'") {
606 $metaValue[] = $firstChar;
607 $value[] = substr($part, 1, -1);
614 return array($value,$metaValue);
618 * Checks whether block/solo tags are found in the correct amounts in HTML content
619 * Block tags are tags which are required to have an equal amount of start and end tags, eg. "<table>...</table>"
620 * Solo tags are tags which are required to have ONLY start tags (possibly with an XHTML ending like ".../>")
621 * 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.
622 * 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!
623 * 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!
625 * @param string HTML content to analyze
626 * @param string Tag names for block tags (eg. table or div or p) in lowercase, commalist (eg. "table,div,p")
627 * @param string Tag names for solo tags (eg. img, br or input) in lowercase, commalist ("img,br,input")
628 * @return array Analyse data.
630 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') {
631 $content = strtolower($content);
632 $analyzedOutput=array();
633 $analyzedOutput['counts']=array(); // Counts appearances of start-tags
634 $analyzedOutput['errors']=array(); // Lists ERRORS
635 $analyzedOutput['warnings']=array(); // Lists warnings.
636 $analyzedOutput['blocks']=array(); // Lists stats for block-tags
637 $analyzedOutput['solo']=array(); // Lists stats for solo-tags
639 // Block tags, must have endings...
640 $blockTags = explode(',',$blockTags);
641 foreach($blockTags as $tagName) {
642 $countBegin = count(preg_split('/\<'.$tagName.'(\s|\>)/s',$content))-1;
643 $countEnd = count(preg_split('/\<\/'.$tagName.'(\s|\>)/s',$content))-1;
644 $analyzedOutput['blocks'][$tagName]=array($countBegin,$countEnd,$countBegin-$countEnd);
645 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
646 if ($countBegin-$countEnd) {
647 if ($countBegin-$countEnd > 0) {
648 $analyzedOutput['errors'][$tagName]='There were more start-tags ('.$countBegin.') than end-tags ('.$countEnd.') for the element "'.$tagName.'". There should be an equal amount!';
650 $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.';
655 // Solo tags, must NOT have endings...
656 $soloTags = explode(',',$soloTags);
657 foreach($soloTags as $tagName) {
658 $countBegin = count(preg_split('/\<'.$tagName.'(\s|\>)/s',$content))-1;
659 $countEnd = count(preg_split('/\<\/'.$tagName.'(\s|\>)/s',$content))-1;
660 $analyzedOutput['solo'][$tagName]=array($countBegin,$countEnd);
661 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
663 $analyzedOutput['warnings'][$tagName]='There were end-tags found ('.$countEnd.') for the element "'.$tagName.'". This was not expected (although XHTML technically allows it).';
667 return $analyzedOutput;
681 /*********************************
685 *********************************/
688 * Function that can clean up HTML content according to configuration given in the $tags array.
690 * 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'))
691 * If the value of the $tags[$tagname] entry is an array, advanced processing of the tags is initialized. These are the options:
693 * $tags[$tagname] = Array(
694 * 'overrideAttribs' => '' If set, this string is preset as the attributes of the tag
695 * 'allowedAttribs' => '0' (zero) = no attributes allowed, '[commalist of attributes]' = only allowed attributes. If blank, all attributes are allowed.
696 * 'fixAttrib' => Array(
697 * '[attribute name]' => Array (
698 * 'set' => Force the attribute value to this value.
699 * 'unset' => Boolean: If set, the attribute is unset.
700 * 'default' => If no attribute exists by this name, this value is set as default value (if this value is not blank)
701 * 'always' => Boolean. If set, the attribute is always processed. Normally an attribute is processed only if it exists
702 * 'trim,intval,lower,upper' => All booleans. If any of these keys are set, the value is passed through the respective PHP-functions.
703 * 'range' => Array ('[low limit]','[high limit, optional]') Setting integer range.
704 * 'list' => Array ('[value1/default]','[value2]','[value3]') Attribute must be in this list. If not, the value is set to the first element.
705 * '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)
706 * 'removeIfEquals' => [value] If the attribute value matches the value set here, then it is removed.
707 * 'casesensitiveComp' => 1 If set, then the removeIfEquals and list comparisons will be case sensitive. Otherwise not.
710 * 'protect' => '', Boolean. If set, the tag <> is converted to < and >
711 * 'remap' => '', String. If set, the tagname is remapped to this tagname
712 * 'rmTagIfNoAttrib' => '', Boolean. If set, then the tag is removed if no attributes happend to be there.
713 * '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>'
716 * @param string $content; is the HTML-content being processed. This is also the result being returned.
717 * @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.
718 * @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 < and >
719 * @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. "&" or "ê")
720 * @param array Configuration array send along as $conf to the internal functions ->processContent() and ->processTag()
721 * @return string Processed HTML content
723 function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array()) {
724 $newContent = array();
725 $tokArr = explode('<',$content);
726 $newContent[] = $this->processContent(current($tokArr),$hSC,$addConfig);
730 $tagRegister = array();
732 $inComment = false; $skipTag = false;
733 while(list(,$tok)=each($tokArr)) {
735 if (($eocPos = strpos($tok, '-->')) === false) {
736 // End of comment is not found in the token. Go futher until end of comment is found in other tokens.
737 $newContent[$c++
] = '<' . $tok;
740 // Comment ends in the middle of the token: add comment and proceed with rest of the token
741 $newContent[$c++
] = '<' . substr($tok, 0, $eocPos +
3);
742 $tok = substr($tok, $eocPos +
3);
743 $inComment = false; $skipTag = true;
745 elseif (substr($tok, 0, 3) == '!--') {
746 if (($eocPos = strpos($tok, '-->')) === false) {
747 // Comment started in this token but it does end in the same token. Set a flag to skip till the end of comment
748 $newContent[$c++
] = '<' . $tok;
752 // Start and end of comment are both in the current token. Add comment and proceed with rest of the token
753 $newContent[$c++
] = '<' . substr($tok, 0, $eocPos +
3);
754 $tok = substr($tok, $eocPos +
3);
757 $firstChar = substr($tok,0,1);
758 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..>
759 $tagEnd = strpos($tok,'>');
760 if ($tagEnd) { // If there is and end-bracket... tagEnd can't be 0 as the first character can't be a >
761 $endTag = $firstChar=='/' ?
1 : 0;
762 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
763 $tagParts = preg_split('/\s+/s',$tagContent,2);
764 $tagName = strtolower($tagParts[0]);
765 if (isset($tags[$tagName])) {
766 if (is_array($tags[$tagName])) { // If there is processing to do for the tag:
768 if (!$endTag) { // If NOT an endtag, do attribute processing (added dec. 2003)
769 // Override attributes
770 if (strcmp($tags[$tagName]['overrideAttribs'],'')) {
771 $tagParts[1]=$tags[$tagName]['overrideAttribs'];
775 if (strcmp($tags[$tagName]['allowedAttribs'],'')) {
776 if (!strcmp($tags[$tagName]['allowedAttribs'],'0')) { // No attribs allowed
778 } elseif (trim($tagParts[1])) {
779 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
781 $newTagAttrib = array();
782 if (!($tList = $tags[$tagName]['_allowedAttribs'])) {
783 // Just explode attribts for tag once
784 $tList = $tags[$tagName]['_allowedAttribs'] = t3lib_div
::trimExplode(',',strtolower($tags[$tagName]['allowedAttribs']),1);
786 foreach ($tList as $allowTag) {
787 if (isset($tagAttrib[0][$allowTag])) $newTagAttrib[$allowTag]=$tagAttrib[0][$allowTag];
789 $tagParts[1]=$this->compileTagAttribs($newTagAttrib,$tagAttrib[1]);
793 // Fixed attrib values
794 if (is_array($tags[$tagName]['fixAttrib'])) {
795 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
797 foreach ($tags[$tagName]['fixAttrib'] as $attr => $params) {
798 if (strlen($params['set'])) $tagAttrib[0][$attr] = $params['set'];
799 if (strlen($params['unset'])) unset($tagAttrib[0][$attr]);
800 if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr])) $tagAttrib[0][$attr]=$params['default'];
801 if ($params['always'] ||
isset($tagAttrib[0][$attr])) {
802 if ($params['trim']) {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
803 if ($params['intval']) {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
804 if ($params['lower']) {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
805 if ($params['upper']) {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
806 if ($params['range']) {
807 if (isset($params['range'][1])) {
808 $tagAttrib[0][$attr]=t3lib_div
::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
810 $tagAttrib[0][$attr]=t3lib_div
::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
813 if (is_array($params['list'])) {
814 // For the class attribute, remove from the attribute value any class not in the list
815 // Classes are case sensitive
816 if ($attr == 'class') {
817 $newClasses = array();
818 $classes = t3lib_div
::trimExplode(' ', $tagAttrib[0][$attr], TRUE);
819 foreach ($classes as $class) {
820 if (in_array($class, $params['list'])) {
821 $newClasses[] = $class;
824 if (count($newClasses)) {
825 $tagAttrib[0][$attr] = implode(' ', $newClasses);
827 $tagAttrib[0][$attr] = '';
830 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) {
831 $tagAttrib[0][$attr]=$params['list'][0];
835 if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) ||
($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],''))) {
836 unset($tagAttrib[0][$attr]);
838 if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp']))) {
839 unset($tagAttrib[0][$attr]);
841 if ($params['prefixLocalAnchors']) {
842 if (substr($tagAttrib[0][$attr],0,1)=='#') {
843 $prefix = t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL');
844 $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
845 if ($params['prefixLocalAnchors']==2 && t3lib_div
::isFirstPartOfStr($prefix,t3lib_div
::getIndpEnv('TYPO3_SITE_URL'))) {
846 $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
850 if ($params['prefixRelPathWith']) {
851 $urlParts = parse_url($tagAttrib[0][$attr]);
852 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') { // If it is NOT an absolute URL (by http: or starting "/")
853 $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
856 if ($params['userFunc']) {
857 $tagAttrib[0][$attr] = t3lib_div
::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
861 $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
863 } else { // If endTag, remove any possible attributes:
867 // Protecting the tag by converting < and > to < and > ??
868 if ($tags[$tagName]['protect']) {
869 $lt = '<'; $gt = '>';
871 $lt = '<'; $gt = '>';
873 // Remapping tag name?
874 if ($tags[$tagName]['remap']) $tagParts[0] = $tags[$tagName]['remap'];
877 if ($endTag ||
trim($tagParts[1]) ||
!$tags[$tagName]['rmTagIfNoAttrib']) {
878 $setTag = !$tags[$tagName]['rmTagIfNoAttrib'];
880 if ($tags[$tagName]['nesting']) {
881 if (!is_array($tagRegister[$tagName])) $tagRegister[$tagName]=array();
884 /* if ($tags[$tagName]['nesting']=='global') {
885 $lastEl = end($tagStack);
886 $correctTag = !strcmp($tagName,$lastEl);
887 } else $correctTag=1;
890 if ($tags[$tagName]['nesting']=='global') {
891 $lastEl = end($tagStack);
892 if (strcmp($tagName,$lastEl)) {
893 if (in_array($tagName,$tagStack)) {
894 while(count($tagStack) && strcmp($tagName,$lastEl)) {
895 $elPos = end($tagRegister[$lastEl]);
896 unset($newContent[$elPos]);
898 array_pop($tagRegister[$lastEl]);
899 array_pop($tagStack);
900 $lastEl = end($tagStack);
903 $correctTag=0; // In this case the
907 if (!count($tagRegister[$tagName]) ||
!$correctTag) {
910 array_pop($tagRegister[$tagName]);
911 if ($tags[$tagName]['nesting']=='global') {array_pop($tagStack);}
914 array_push($tagRegister[$tagName],$c);
915 if ($tags[$tagName]['nesting']=='global') {array_push($tagStack,$tagName);}
921 $newContent[$c++
]=$this->processTag($lt.($endTag?
'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='<');
925 $newContent[$c++
]=$this->processTag('<'.($endTag?
'/':'').$tagContent.'>',$addConfig,$endTag);
927 } elseif ($keepAll) { // This is if the tag was not defined in the array for processing:
928 if (!strcmp($keepAll,'protect')) {
929 $lt = '<'; $gt = '>';
931 $lt = '<'; $gt = '>';
933 $newContent[$c++
]=$this->processTag($lt.($endTag?
'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='<');
935 $newContent[$c++
]=$this->processContent(substr($tok,$tagEnd+
1),$hSC,$addConfig);
937 $newContent[$c++
]=$this->processContent('<'.$tok,$hSC,$addConfig); // There were not end-bracket, so no tag...
940 $newContent[$c++
]=$this->processContent(($skipTag ?
'' : '<') . $tok, $hSC, $addConfig); // It was not a tag anyways
946 foreach ($tagRegister as $tag => $positions) {
947 foreach ($positions as $pKey) {
948 unset($newContent[$pKey]);
952 return implode('',$newContent);
956 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
958 * @param string Input value
959 * @param integer Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
960 * @return string Output value
962 function bidir_htmlspecialchars($value,$dir) {
964 $value = htmlspecialchars($value);
966 $value = t3lib_div
::deHSCentities(htmlspecialchars($value));
967 } elseif ($dir==-1) {
968 $value = str_replace('>','>',$value);
969 $value = str_replace('<','<',$value);
970 $value = str_replace('"','"',$value);
971 $value = str_replace('&','&',$value);
977 * 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
979 * @param string Prefix string
980 * @param string HTML content
981 * @param array Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
982 * @param string Suffix string (put after the resource).
983 * @return string Processed HTML content
985 function prefixResourcePath($main_prefix,$content,$alternatives=array(),$suffix='') {
987 $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a,param',$content);
988 foreach ($parts as $k => $v) {
990 $params = $this->get_tag_attributes($v);
991 $tagEnd = substr($v,-2)=='/>' ?
' />' : '>'; // Detect tag-ending so that it is re-applied correctly.
992 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
994 $prefix = isset($alternatives[strtoupper($firstTagName)]) ?
$alternatives[strtoupper($firstTagName)] : $main_prefix;
995 switch(strtolower($firstTagName)) {
996 // background - attribute:
1000 $src = $params[0]['background'];
1002 $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background'],$suffix);
1011 $src = $params[0]['src'];
1013 $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src'],$suffix);
1019 $src = $params[0]['href'];
1021 $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href'],$suffix);
1027 $src = $params[0]['action'];
1029 $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action'],$suffix);
1035 $test = $params[0]['name'];
1036 if ($test && $test === 'movie') {
1037 if ($params[0]['value']) {
1038 $params[0]['value'] = $this->prefixRelPath($prefix, $params[0]['value'], $suffix);
1044 if ($somethingDone) {
1045 $tagParts = preg_split('/\s+/s',$v,2);
1046 $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
1047 $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).$tagEnd;
1051 $content = implode('',$parts);
1053 // Fix <style> section:
1054 $prefix = isset($alternatives['style']) ?
$alternatives['style'] : $main_prefix;
1055 if (strlen($prefix)) {
1056 $parts = $this->splitIntoBlock('style',$content);
1057 foreach($parts as $k => $v) {
1059 $parts[$k] = preg_replace('/(url[[:space:]]*\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\))/i','\1'.$prefix.'\2'.$suffix.'\3',$parts[$k]);
1062 $content = implode('',$parts);
1069 * Internal sub-function for ->prefixResourcePath()
1071 * @param string Prefix string
1072 * @param string Relative path/URL
1073 * @param string Suffix string
1074 * @return string Output path, prefixed if no scheme in input string
1077 function prefixRelPath($prefix, $srcVal, $suffix = '') {
1078 // Only prefix if it's not an absolute URL or
1079 // only a link to a section within the page.
1080 if (substr($srcVal, 0, 1) != '/' && substr($srcVal, 0, 1) != '#') {
1081 $urlParts = parse_url($srcVal);
1082 // only prefix URLs without a scheme
1083 if (!$urlParts['scheme']) {
1084 $srcVal = $prefix . $srcVal . $suffix;
1091 * Cleans up the input $value for fonttags.
1092 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
1094 * @param string HTML content with font-tags inside to clean up.
1095 * @param boolean If set, keep "face" attribute
1096 * @param boolean If set, keep "size" attribute
1097 * @param boolean If set, keep "color" attribute
1098 * @return string Processed HTML content
1100 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
1101 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
1102 foreach ($fontSplit as $k => $v) {
1103 if ($k%2
) { // font:
1104 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
1105 $newAttribs=array();
1106 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
1107 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
1108 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
1110 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
1111 if (count($newAttribs)) {
1112 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
1114 $fontSplit[$k]=$innerContent;
1118 return implode('',$fontSplit);
1122 * This is used to map certain tag-names into other names.
1124 * @param string HTML content
1125 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
1126 * @param string Alternative less-than char to search for (search regex string)
1127 * @param string Alternative less-than char to replace with (replace regex string)
1128 * @return string Processed HTML content
1130 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
1132 foreach($tags as $from => $to) {
1133 $value = preg_replace('/'.preg_quote($ltChar).'(\/)?'.$from.'\s([^\>])*(\/)?\>/', $ltChar2.'$1'.$to.' $2$3>', $value);
1139 * This converts htmlspecialchar()'ed tags (from $tagList) back to real tags. Eg. '<strong>' would be converted back to '<strong>' if found in $tagList
1141 * @param string HTML content
1142 * @param string Tag list, separated by comma. Lowercase!
1143 * @return string Processed HTML content
1145 function unprotectTags($content,$tagList='') {
1146 $tagsArray = t3lib_div
::trimExplode(',',$tagList,1);
1147 $contentParts = explode('<',$content);
1148 next($contentParts); // bypass the first
1149 while(list($k,$tok)=each($contentParts)) {
1150 $firstChar = substr($tok,0,1);
1151 if (strcmp(trim($firstChar),'')) {
1152 $subparts = explode('>',$tok,2);
1153 $tagEnd = strlen($subparts[0]);
1154 if (strlen($tok)!=$tagEnd) {
1155 $endTag = $firstChar=='/' ?
1 : 0;
1156 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
1157 $tagParts = preg_split('/\s+/s',$tagContent,2);
1158 $tagName = strtolower($tagParts[0]);
1159 if (!strcmp($tagList,'') ||
in_array($tagName,$tagsArray)) {
1160 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
1161 } else $contentParts[$k] = '<'.$tok;
1162 } else $contentParts[$k] = '<'.$tok;
1163 } else $contentParts[$k] = '<'.$tok;
1166 return implode('',$contentParts);
1170 * Strips tags except the tags in the list, $tagList
1171 * OBSOLETE - use PHP function strip_tags()
1173 * @param string Value to process
1174 * @param string List of tags
1175 * @return string Output value
1178 function stripTagsExcept($value,$tagList) {
1179 $tags=t3lib_div
::trimExplode(',',$tagList,1);
1182 foreach ($tags as $theTag) {
1183 $forthArr[$theTag]=md5($theTag);
1184 $backArr[md5($theTag)]=$theTag;
1186 $value = $this->mapTags($value,$forthArr,'<','_');
1187 $value=strip_tags($value);
1188 $value = $this->mapTags($value,$backArr,'_','<');
1193 * Internal function for case shifting of a string or whole array
1195 * @param mixed Input string/array
1196 * @param boolean If $str is a string AND this boolean(caseSensitive) is false, the string is returned in uppercase
1197 * @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.
1198 * @return string Output string, processed
1201 function caseShift($str,$flag,$cacheKey='') {
1202 $cacheKey .= $flag?
1:0;
1203 if (is_array($str)) {
1204 if (!$cacheKey ||
!isset($this->caseShift_cache
[$cacheKey])) {
1206 foreach ($str as $k => $v) {
1208 $str[$k] = strtoupper($v);
1211 if ($cacheKey) $this->caseShift_cache
[$cacheKey]=$str;
1213 $str = $this->caseShift_cache
[$cacheKey];
1215 } elseif (!$flag) { $str = strtoupper($str); }
1220 * Compiling an array with tag attributes into a string
1222 * @param array Tag attributes
1223 * @param array Meta information about these attributes (like if they were quoted)
1224 * @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
1225 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1228 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
1230 foreach ($tagAttrib as $k =>$v) {
1232 $attr=strtolower($k);
1233 if (strcmp($v,'') ||
isset($meta[$k]['dashType'])) {
1234 $attr.='="'.htmlspecialchars($v).'"';
1237 $attr=$meta[$k]['origTag']?
$meta[$k]['origTag']:$k;
1238 if (strcmp($v,'') ||
isset($meta[$k]['dashType'])) {
1239 $dash=$meta[$k]['dashType']?
$meta[$k]['dashType']:(t3lib_div
::testInt($v)?
'':'"');
1240 $attr.='='.$dash.$v.$dash;
1245 return implode(' ',$accu);
1249 * Get tag attributes, the classic version (which had some limitations?)
1251 * @param string The tag
1252 * @param boolean De-htmlspecialchar flag.
1256 function get_tag_attributes_classic($tag,$deHSC=0) {
1257 $attr=$this->get_tag_attributes($tag,$deHSC);
1258 return is_array($attr[0])?
$attr[0]:array();
1262 * Indents input content with $number instances of $indentChar
1264 * @param string Content string, multiple lines.
1265 * @param integer Number of indents
1266 * @param string Indent character/string
1267 * @return string Indented code (typ. HTML)
1269 function indentLines($content, $number=1, $indentChar=TAB
) {
1270 $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
1271 $lines = explode(LF
,str_replace(CR
,'',$content));
1272 foreach ($lines as $k => $v) {
1273 $lines[$k] = $preTab.$v;
1275 return implode(LF
, $lines);
1279 * Converts TSconfig into an array for the HTMLcleaner function.
1281 * @param array TSconfig for HTMLcleaner
1282 * @param array Array of tags to keep (?)
1286 function HTMLparserConfig($TSconfig,$keepTags=array()) {
1287 // Allow tags (base list, merged with incoming array)
1288 $alTags = array_flip(t3lib_div
::trimExplode(',',strtolower($TSconfig['allowTags']),1));
1289 $keepTags = array_merge($alTags,$keepTags);
1291 // Set config properties.
1292 if (is_array($TSconfig['tags.'])) {
1293 foreach ($TSconfig['tags.'] as $key => $tagC) {
1294 if (!is_array($tagC) && $key==strtolower($key)) {
1295 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
1296 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
1300 foreach ($TSconfig['tags.'] as $key => $tagC) {
1301 if (is_array($tagC) && $key==strtolower($key)) {
1302 $key=substr($key,0,-1);
1303 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1304 if (is_array($tagC['fixAttrib.'])) {
1305 foreach ($tagC['fixAttrib.'] as $atName => $atConfig) {
1306 if (is_array($atConfig)) {
1307 $atName=substr($atName,0,-1);
1308 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1309 $keepTags[$key]['fixAttrib'][$atName]=array();
1311 $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...
1312 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div
::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1313 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div
::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1317 unset($tagC['fixAttrib.']);
1318 unset($tagC['fixAttrib']);
1319 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1324 if ($TSconfig['localNesting']) {
1325 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1326 foreach ($lN as $tn) {
1327 if (isset($keepTags[$tn])) {
1328 $keepTags[$tn]['nesting']=1;
1332 if ($TSconfig['globalNesting']) {
1333 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1334 foreach ($lN as $tn) {
1335 if (isset($keepTags[$tn])) {
1336 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1337 $keepTags[$tn]['nesting']='global';
1341 if ($TSconfig['rmTagIfNoAttrib']) {
1342 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1343 foreach ($lN as $tn) {
1344 if (isset($keepTags[$tn])) {
1345 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1346 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1350 if ($TSconfig['noAttrib']) {
1351 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1352 foreach ($lN as $tn) {
1353 if (isset($keepTags[$tn])) {
1354 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1355 $keepTags[$tn]['allowedAttribs']=0;
1359 if ($TSconfig['removeTags']) {
1360 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1361 foreach ($lN as $tn) {
1362 $keepTags[$tn]=array();
1363 $keepTags[$tn]['allowedAttribs']=0;
1364 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1368 // Create additional configuration:
1370 if ($TSconfig['xhtml_cleaning']) {
1371 $addConfig['xhtml']=1;
1376 ''.$TSconfig['keepNonMatchedTags'],
1377 intval($TSconfig['htmlSpecialChars']),
1383 * Tries to convert the content to be XHTML compliant and other stuff like that.
1384 * STILL EXPERIMENTAL. See comments below.
1386 * What it does NOT do (yet) according to XHTML specs.:
1387 * - Wellformedness: Nesting is NOT checked
1388 * - name/id attribute issue is not observed at this point.
1389 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1390 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1391 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1392 * - UTF-8 encoding is in fact expected by XML!!
1393 * - stylesheet element and attribute names are NOT converted to lowercase
1394 * - ampersands (and entities in general I think) MUST be converted to an entity reference! (&s;). This may mean further conversion of non-tag content before output to page. May be related to the charset issue as a whole.
1395 * - Minimized values not allowed: Must do this: selected="selected"
1397 * What it does at this point:
1398 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1399 * - Lowercase for elements and attributes
1400 * - All attributes in quotes
1401 * - Add "alt" attribute to img-tags if it's not there already.
1403 * @param string Content to clean up
1404 * @return string Cleaned up content returned.
1407 function XHTML_clean($content) {
1408 $content = $this->HTMLcleaner(
1410 array(), // No tags treated specially
1411 1, // Keep ALL tags.
1412 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1419 * Processing all tags themselves
1420 * (Some additions by Sacha Vorbeck)
1422 * @param string Tag to process
1423 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1424 * @param boolean Is endtag, then set this.
1425 * @param boolean If set, just return value straight away
1426 * @return string Processed value.
1429 function processTag($value,$conf,$endTag,$protected=0) {
1430 // Return immediately if protected or no parameters
1431 if ($protected ||
!count($conf)) return $value;
1432 // OK then, begin processing for XHTML output:
1433 // STILL VERY EXPERIMENTAL!!
1434 if ($conf['xhtml']) {
1435 if ($endTag) { // Endtags are just set lowercase right away
1436 $value = strtolower($value);
1437 } elseif (substr($value,0,4)!='<!--') { // ... and comments are ignored.
1438 $inValue = substr($value,1,(substr($value,-2)=='/>'?
-2:-1)); // Finding inner value with out < >
1439 list($tagName,$tagP)=preg_split('/\s+/s',$inValue,2); // Separate attributes and tagname
1440 $tagName = strtolower($tagName);
1442 // Process attributes
1443 $tagAttrib = $this->get_tag_attributes($tagP);
1444 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1445 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1447 foreach ($tagAttrib[0] as $attrib_name => $attrib_value) {
1448 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1449 $outA[]=$attrib_name.'="'.$this->bidir_htmlspecialchars($attrib_value,2).'"';
1451 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1452 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1453 if (t3lib_div
::inList('img,br,hr,meta,link,base,area,input,param,col',$tagName) ||
substr($value,-2)=='/>') {
1466 * Processing content between tags for HTML_cleaner
1468 * @param string The value
1469 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1470 * @param mixed Not used, ignore.
1471 * @return string The processed value.
1474 function processContent($value,$dir,$conf) {
1475 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1482 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1483 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);