2398a2f37a2b88f4a43baff227fccda71ce04834
2 /***************************************************************
5 * (c) 1999-2003 Kasper Skaarhoj (kasper@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 Skaarhoj
33 * @author Kasper Skaarhoj <kasper@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 100: class t3lib_parsehtml
41 * 117: function getSubpart($content, $marker)
42 * 145: function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0)
43 * 210: function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0)
44 * 269: function splitTags($tag,$content)
45 * 303: function getAllParts($parts,$tag_parts=1,$include_tag=1)
46 * 322: function removeFirstAndLastTag($str)
47 * 341: function getFirstTag($str)
48 * 355: function getFirstTagName($str)
49 * 373: 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')
50 * 447: function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array())
51 * 618: function get_tag_attributes($tag,$deHSC=0)
52 * 659: function split_tag_attributes($tag)
53 * 696: function bidir_htmlspecialchars($value,$dir)
54 * 716: function prefixResourcePath($main_prefix,$content,$alternatives=array())
55 * 784: function prefixRelPath($prefix,$srcVal)
56 * 802: function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0)
57 * 833: function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<')
58 * 850: function unprotectTags($content,$tagList='')
59 * 883: function stripTagsExcept($value,$tagList)
60 * 906: function caseShift($str,$flag,$cacheKey='')
61 * 930: function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0)
62 * 959: function get_tag_attributes_classic($tag,$deHSC=0)
63 * 972: function HTMLparserConfig($TSconfig,$keepTags=array())
64 * 1085: function XHTML_clean($content)
65 * 1107: function processTag($value,$conf,$endTag,$protected=0)
66 * 1153: function processContent($value,$dir,$conf)
69 * (This index is automatically created/updated by the extension "extdeveval")
93 * Functions for parsing HTML.
94 * You are encouraged to use this class in your own applications
96 * @author Kasper Skaarhoj <kasper@typo3.com>
100 class t3lib_parsehtml
{
101 var $caseShift_cache=array();
104 // *******************************************'
105 // COPY FROM class.tslib_content.php: / BEGIN
107 // Cleaned locally 2/2003 !!!! (so different from tslib_content version)
108 // *******************************************'
111 * Returns the first subpart encapsulated in the marker, $marker (possibly present in $content as a HTML comment)
113 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
114 * @param string Marker string, eg. "###CONTENT_PART###"
117 function getSubpart($content, $marker) {
118 if ($marker && strstr($content,$marker)) {
119 $start = strpos($content, $marker)+
strlen($marker);
120 $stop = @strpos
($content, $marker, $start+
1);
121 $sub = substr($content, $start, $stop-$start);
124 ereg('^[^<]*-->',$sub,$reg);
125 $start+
=strlen($reg[0]);
128 ereg('<!--[^>]*$',$sub,$reg);
129 $stop-=strlen($reg[0]);
131 return substr($content, $start, $stop-$start);
136 * Substitutes a subpart in $content with the content of $subpartContent.
138 * @param string Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
139 * @param string Marker string, eg. "###CONTENT_PART###"
140 * @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())
141 * @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!
142 * @param boolean If set, the marker around the subpart is not removed, but kept in the output
143 * @return string Processed input content
145 function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0) {
146 $start = strpos($content, $marker);
147 $stop = @strpos
($content, $marker, $start+
1)+
strlen($marker);
148 if ($start && $stop>$start) {
150 $before = substr($content, 0, $start);
152 ereg('<!--[^>]*$',$before,$reg);
153 $start-=strlen($reg[0]);
156 if ($reg[0]) ereg('^[^>]*-->',substr($content,$start),$reg_k);
157 $before_marker = substr($content, $start, strlen($reg_k[0]?
$reg_k[0]:$marker));
159 $before = substr($content, 0, $start);
161 $after = substr($content, $stop);
163 ereg('^[^<]*-->',$after,$reg);
164 $stop+
=strlen($reg[0]);
167 if ($reg[0]) ereg('<!--[^<]*$',substr($content,0,$stop),$reg_k);
168 $sLen = strlen($reg_k[0]?
$reg_k[0]:$marker);
169 $after_marker = substr($content, $stop-$sLen,$sLen);
171 $after = substr($content, $stop);
175 if (is_array($subpartContent)) {
176 $substContent=$subpartContent[0].$this->getSubpart($content,$marker).$subpartContent[1];
178 $substContent=$subpartContent;
181 if ($recursive && strpos($after, $marker)) {
182 return $before.($keepMarker?
$before_marker:'').$substContent.($keepMarker?
$after_marker:'').$this->substituteSubpart($after,$marker,$subpartContent);
184 return $before.($keepMarker?
$before_marker:'').$substContent.($keepMarker?
$after_marker:'').$after;
190 // *******************************************'
191 // COPY FROM class.tslib_content.php: / END
192 // *******************************************'
200 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
201 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
202 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
204 * @param string List of tags, comma separated.
205 * @param string HTML-content
206 * @param boolean If set, excessive end tags are ignored - you should probably set this in most cases.
207 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
208 * @see splitTags(), getAllParts(), removeFirstAndLastTag()
210 function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0) {
211 $tags=array_unique(t3lib_div
::trimExplode(',',$tag,1));
212 $regexStr = '</?('.implode('|',$tags).')(>|[[:space:]][^>]*>)';
214 $parts = spliti($regexStr,$content);
217 $pointer=strlen($parts[0]);
222 while(list($k,$v)=each($parts)) {
223 $isEndTag= substr($content,$pointer,2)=='</' ?
1 : 0;
224 $tagLen = strcspn(substr($content,$pointer),'>')+
1;
226 if (!$isEndTag) { // We meet a start-tag:
227 if (!$nested) { // Ground level:
228 $newParts[]=$buffer; // previous buffer stored
231 $nested++
; // We are inside now!
232 $mbuffer=substr($content,$pointer,strlen($v)+
$tagLen); // New buffer set and pointer increased
233 $pointer+
=strlen($mbuffer);
235 } else { // If we meet an endtag:
236 $nested--; // decrease nested-level
238 if ($eliminateExtraEndTags && $nested<0) {
242 $buffer.=substr($content,$pointer,$tagLen); // In any case, add the endtag to current buffer and increase pointer
245 if (!$nested && !$eliminated) { // if we're back on ground level, (and not by eliminating tags...
249 $mbuffer=substr($content,$pointer,strlen($v)); // New buffer set and pointer increased
250 $pointer+
=strlen($mbuffer);
260 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
261 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
262 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
264 * @param string List of tags
265 * @param string HTML-content
266 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
267 * @see splitIntoBlock(), getAllParts(), removeFirstAndLastTag()
269 function splitTags($tag,$content) {
270 $tags=t3lib_div
::trimExplode(',',$tag,1);
271 $regexStr = '<('.implode('|',$tags).')(>|[[:space:]][^>]*>)';
272 $parts = spliti($regexStr,$content);
274 $pointer=strlen($parts[0]);
276 $newParts[]=$parts[0];
279 while(list($k,$v)=each($parts)) {
280 $tagLen = strcspn(substr($content,$pointer),'>')+
1;
283 $tag = substr($content,$pointer,$tagLen); // New buffer set and pointer increased
285 $pointer+
=strlen($tag);
289 $pointer+
=strlen($v);
295 * Returns an array with either tag or non-tag content of the result from ->splitIntoBlock()/->splitTags()
297 * @param array Parts generated by ->splitIntoBlock() or >splitTags()
298 * @param boolean Whether to return the tag-parts (default,true) or what was outside the tags.
299 * @param boolean Whether to include the tags in the tag-parts (most useful for input made by ->splitIntoBlock())
300 * @return array Tag-parts/Non-tag-parts depending on input argument settings
301 * @see splitIntoBlock(), splitTags()
303 function getAllParts($parts,$tag_parts=1,$include_tag=1) {
306 while(list($k,$v)=each($parts)) {
307 if (($k+
($tag_parts?
0:1))%2
) {
308 if (!$include_tag) $v=$this->removeFirstAndLastTag($v);
316 * Removes the first and last tag in the string
317 * Anything before and after the first and last tags respectively is also removed
319 * @param string String to process
322 function removeFirstAndLastTag($str) {
324 $endLen = strcspn($str,'>')+
1;
325 $str = substr($str,$endLen);
328 $endLen = strcspn($str,'<')+
1;
329 $str = substr($str,$endLen);
335 * Returns the first tag in $str
336 * Actually everything from the begining of the $str is returned, so you better make sure the tag is the first thing...
338 * @param string HTML string with tags
341 function getFirstTag($str) {
343 $endLen = strcspn($str,'>')+
1;
344 $str = substr($str,0,$endLen);
349 * Returns the NAME of the first tag in $str
351 * @param string HTML tag (The element name MUST be separated from the attributes by a space character! Just *whitespace* will not do)
352 * @return string Tag name in upper case
355 function getFirstTagName($str) {
356 list($tag) = split('[[:space:]]',substr(strtoupper(trim($this->getFirstTag($str))),1,-1), 2);
361 * Checks whether block/solo tags are found in the correct amounts in HTML content
362 * Block tags are tags which are required to have an equal amount of start and end tags, eg. "<table>...</table>"
363 * Solo tags are tags which are required to have ONLY start tags (possibly with an XHTML ending like ".../>")
364 * 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.
365 * 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!
366 * 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!
368 * @param string HTML content to analyze
369 * @param string Tag names for block tags (eg. table or div or p) in lowercase, commalist (eg. "table,div,p")
370 * @param string Tag names for solo tags (eg. img, br or input) in lowercase, commalist ("img,br,input")
371 * @return array Analyse data.
373 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') {
374 $content = strtolower($content);
375 $analyzedOutput=array();
376 $analyzedOutput['counts']=array(); // Counts appearances of start-tags
377 $analyzedOutput['errors']=array(); // Lists ERRORS
378 $analyzedOutput['warnings']=array(); // Lists warnings.
379 $analyzedOutput['blocks']=array(); // Lists stats for block-tags
380 $analyzedOutput['solo']=array(); // Lists stats for solo-tags
382 // Block tags, must have endings...
383 $blockTags = explode(',',$blockTags);
384 foreach($blockTags as $tagName) {
385 $countBegin = count(split('<'.$tagName.'[^[:alnum:]]',$content))-1;
386 $countEnd = count(split('<\/'.$tagName.'[^[:alnum:]]',$content))-1;
387 $analyzedOutput['blocks'][$tagName]=array($countBegin,$countEnd,$countBegin-$countEnd);
388 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
389 if ($countBegin-$countEnd) {
390 if ($countBegin-$countEnd > 0) {
391 $analyzedOutput['errors'][$tagName]='There were more start-tags ('.$countBegin.') than end-tags ('.$countEnd.') for the element "'.$tagName.'". There should be an equal amount!';
393 $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.';
398 // Solo tags, must NOT have endings...
399 $soloTags = explode(',',$soloTags);
400 foreach($soloTags as $tagName) {
401 $countBegin = count(split('<'.$tagName.'[^[:alnum:]]',$content))-1;
402 $countEnd = count(split('<\/'.$tagName.'[^[:alnum:]]',$content))-1;
403 $analyzedOutput['solo'][$tagName]=array($countBegin,$countEnd);
404 if ($countBegin) $analyzedOutput['counts'][$tagName]=$countBegin;
406 $analyzedOutput['warnings'][$tagName]='There were end-tags found ('.$countEnd.') for the element "'.$tagName.'". This was not expected (although XHTML technically allows it).';
410 return $analyzedOutput;
414 * Function that can clean up HTML content according to configuration given in the $tags array.
416 * 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'))
417 * If the value of the $tags[$tagname] entry is an array, advanced processing of the tags is initialized. These are the options:
419 * $tags[$tagname] = Array(
420 * 'overrideAttribs' => '' If set, this string is preset as the attributes of the tag
421 * 'allowedAttribs' => '0' (zero) = no attributes allowed, '[commalist of attributes]' = only allowed attributes. If blank, all attributes are allowed.
422 * 'fixAttrib' => Array(
423 * '[attribute name]' => Array (
424 * 'default' => If no attribute exists by this name, this value is set as default value (if this value is not blank)
425 * 'always' => Boolean. If set, the attribute is always processed. Normally an attribute is processed only if it exists
426 * 'trim,intval,lower,upper' => All booleans. If any of these keys are set, the value is passed through the respective PHP-functions.
427 * 'range' => Array ('[low limit]','[high limit, optional]') Setting integer range.
428 * 'list' => Array ('[value1/default]','[value2]','[value3]') Attribute must be in this list. If not, the value is set to the first element.
429 * '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)
430 * 'removeIfEquals' => [value] If the attribute value matches the value set here, then it is removed.
431 * 'casesensitiveComp' => 1 If set, then the removeIfEquals and list comparisons will be case sensitive. Otherwise not.
434 * 'protect' => '', Boolean. If set, the tag <> is converted to < and >
435 * 'remap' => '', String. If set, the tagname is remapped to this tagname
436 * 'rmTagIfNoAttrib' => '', Boolean. If set, then the tag is removed if no attributes happend to be there.
437 * '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>'
440 * @param string $content; is the HTML-content being processed. This is also the result being returned.
441 * @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.
442 * @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 >
443 * @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 "ê")
444 * @param array Configuration array send along as $conf to the internal functions ->processContent() and ->processTag()
445 * @return string Processed HTML content
447 function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array()) {
448 $newContent = array();
449 $tokArr = explode('<',$content);
450 $newContent[]=$this->processContent(current($tokArr),$hSC,$addConfig);
454 $tagRegister=array();
456 while(list(,$tok)=each($tokArr)) {
457 $firstChar = substr($tok,0,1);
458 if (strcmp(trim($firstChar),'')) { // It is a tag...
459 $tagEnd = strcspn($tok,'>');
460 if (strlen($tok)!=$tagEnd) { // If there is and end-bracket...
461 $endTag = $firstChar=='/' ?
1 : 0;
462 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
463 $tagParts = split('[[:space:]]',$tagContent,2);
464 $tagName = strtolower($tagParts[0]);
465 if (isset($tags[$tagName])) {
466 if (is_array($tags[$tagName])) { // If there is processing to do for the tag:
468 if (!$endTag) { // If NOT an endtag, do attribute processing (added dec. 2003)
469 // Override attributes
470 if (strcmp($tags[$tagName]['overrideAttribs'],'')) {
471 $tagParts[1]=$tags[$tagName]['overrideAttribs'];
475 if (strcmp($tags[$tagName]['allowedAttribs'],'')) {
476 if (!strcmp($tags[$tagName]['allowedAttribs'],'0')) { // No attribs allowed
478 } elseif (trim($tagParts[1])) {
479 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
481 $newTagAttrib = array();
482 $tList = t3lib_div
::trimExplode(',',strtolower($tags[$tagName]['allowedAttribs']),1);
483 while(list(,$allowTag)=each($tList)) {
484 if (isset($tagAttrib[0][$allowTag])) $newTagAttrib[$allowTag]=$tagAttrib[0][$allowTag];
486 $tagParts[1]=$this->compileTagAttribs($newTagAttrib,$tagAttrib[1]);
490 // Fixed attrib values
491 if (is_array($tags[$tagName]['fixAttrib'])) {
492 $tagAttrib = $this->get_tag_attributes($tagParts[1]);
494 reset($tags[$tagName]['fixAttrib']);
495 while(list($attr,$params)=each($tags[$tagName]['fixAttrib'])) {
496 if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr])) $tagAttrib[0][$attr]=$params['default'];
497 if ($params['always'] ||
isset($tagAttrib[0][$attr])) {
498 if ($params['trim']) {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
499 if ($params['intval']) {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
500 if ($params['lower']) {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
501 if ($params['upper']) {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
502 if ($params['range']) {
503 if (isset($params['range'][1])) {
504 $tagAttrib[0][$attr]=t3lib_div
::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
506 $tagAttrib[0][$attr]=t3lib_div
::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
509 if (is_array($params['list'])) {
510 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) $tagAttrib[0][$attr]=$params['list'][0];
512 if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) ||
($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],''))) {
513 unset($tagAttrib[0][$attr]);
515 if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp']))) {
516 unset($tagAttrib[0][$attr]);
520 $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
522 } else { // If endTag, remove any possible attributes:
526 // Protecting the tag by converting < and > to < and > ??
527 if ($tags[$tagName]['protect']) {
528 $lt = '<'; $gt = '>';
530 $lt = '<'; $gt = '>';
532 // Remapping tag name?
533 if ($tags[$tagName]['remap']) $tagParts[0] = $tags[$tagName]['remap'];
536 if ($endTag ||
trim($tagParts[1]) ||
!$tags[$tagName]['rmTagIfNoAttrib']) {
539 if ($tags[$tagName]['nesting']) {
540 if (!is_array($tagRegister[$tagName])) $tagRegister[$tagName]=array();
543 /* if ($tags[$tagName]['nesting']=='global') {
544 $lastEl = end($tagStack);
545 $correctTag = !strcmp($tagName,$lastEl);
546 } else $correctTag=1;
549 if ($tags[$tagName]['nesting']=='global') {
550 $lastEl = end($tagStack);
551 if (strcmp($tagName,$lastEl)) {
552 if (in_array($tagName,$tagStack)) {
553 while(count($tagStack) && strcmp($tagName,$lastEl)) {
554 $elPos = end($tagRegister[$lastEl]);
555 unset($newContent[$elPos]);
557 array_pop($tagRegister[$lastEl]);
558 array_pop($tagStack);
559 $lastEl = end($tagStack);
562 $correctTag=0; // In this case the
566 if (!count($tagRegister[$tagName]) ||
!$correctTag) {
569 array_pop($tagRegister[$tagName]);
570 if ($tags[$tagName]['nesting']=='global') {array_pop($tagStack);}
573 array_push($tagRegister[$tagName],$c);
574 if ($tags[$tagName]['nesting']=='global') {array_push($tagStack,$tagName);}
580 $newContent[$c++
]=$this->processTag($lt.($endTag?
'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='<');
584 $newContent[$c++
]=$this->processTag('<'.($endTag?
'/':'').$tagContent.'>',$addConfig,$endTag);
586 } elseif ($keepAll) { // This is if the tag was not defined in the array for processing:
587 if (!strcmp($keepAll,'protect')) {
588 $lt = '<'; $gt = '>';
590 $lt = '<'; $gt = '>';
592 $newContent[$c++
]=$this->processTag($lt.($endTag?
'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='<');
594 $newContent[$c++
]=$this->processContent(substr($tok,$tagEnd+
1),$hSC,$addConfig);
596 $newContent[$c++
]=$this->processContent('<'.$tok,$hSC,$addConfig); // There were not end-bracket, so no tag...
599 $newContent[$c++
]=$this->processContent('<'.$tok,$hSC,$addConfig); // It was not a tag anyways
605 while(list($tag,$positions)=each($tagRegister)) {
607 while(list(,$pKey)=each($positions)) {
608 unset($newContent[$pKey]);
612 return implode('',$newContent);
616 * Returns an array with all attributes as keys. Attributes are only lowercase a-z
617 * If a attribute is empty (shorthand), then the value for the key is empty. You can check if it existed with isset()
619 * @param string Tag: $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
620 * @param boolean If set, the attribute values are de-htmlspecialchar'ed. Should actually always be set!
621 * @return array array(Tag attributes,Attribute meta-data)
623 function get_tag_attributes($tag,$deHSC=0) {
624 list($components,$metaC) = $this->split_tag_attributes($tag);
625 $name = ''; // attribute name is stored here
628 $attributesMeta=array();
629 if (is_array($components)) {
630 while (list($key,$val) = each ($components)) {
631 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
634 $attributes[$name] = $deHSC?t3lib_div
::htmlspecialchars_decode($val):$val;
635 $attributesMeta[$name]['dashType']=$metaC[$key];
639 if ($namekey = ereg_replace('[^a-zA-Z0-9_-]','',$val)) {
640 $name = strtolower($namekey);
641 $attributesMeta[$name]=array();
642 $attributesMeta[$name]['origTag']=$namekey;
643 $attributes[$name] = '';
651 if (is_array($attributes)) reset($attributes);
652 return array($attributes,$attributesMeta);
657 * Returns an array with the 'components' from an attribute list. The result is normally analyzed by get_tag_attributes
658 * Removes tag-name if found
660 * @param string The tag or attributes
663 * @see t3lib_div::split_tag_attributes()
665 function split_tag_attributes($tag) {
666 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
667 // Removes any > in the end of the string
668 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
670 $metaValue = array();
672 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
673 $firstChar=substr($tag_tmp,0,1);
674 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
675 $reg=explode($firstChar,$tag_tmp,3);
677 $metaValue[]=$firstChar;
678 $tag_tmp=trim($reg[2]);
679 } elseif (!strcmp($firstChar,'=')) {
682 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
684 // There are '' around the value. We look for the next ' ' or '>'
685 $reg = split('[[:space:]=]',$tag_tmp,2);
686 $value[] = trim($reg[0]);
688 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
691 if (is_array($value)) reset($value);
692 return array($value,$metaValue);
696 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
698 * @param string Input value
699 * @param integer Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
700 * @return string Output value
702 function bidir_htmlspecialchars($value,$dir) {
704 $value = htmlspecialchars($value);
706 $value = t3lib_div
::deHSCentities(htmlspecialchars($value));
707 } elseif ($dir==-1) {
708 $value = str_replace('>','>',$value);
709 $value = str_replace('<','<',$value);
710 $value = str_replace('"','"',$value);
711 $value = str_replace('&','&',$value);
717 * 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
719 * @param string Prefix string
720 * @param string HTML content
721 * @param array Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
722 * @return string Processed HTML content
724 function prefixResourcePath($main_prefix,$content,$alternatives=array()) {
725 $parts = $this->splitTags('td,table,body,img,input,form,link,script,a',$content);
727 while(list($k,$v)=each($parts)) {
729 $params = $this->get_tag_attributes($v,1);
730 $tagEnd = substr($v,-2)=='/>' ?
' />' : '>'; // Detect tag-ending so that it is re-applied correctly.
731 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
733 $prefix = isset($alternatives[strtoupper($firstTagName)]) ?
$alternatives[strtoupper($firstTagName)] : $main_prefix;
734 switch(strtolower($firstTagName)) {
735 // background - attribute:
739 $src = $params[0]['background'];
741 $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background']);
749 $src = $params[0]['src'];
751 $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src']);
757 $src = $params[0]['href'];
759 $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href']);
765 $src = $params[0]['action'];
767 $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action']);
772 if ($somethingDone) {
773 $tagParts = split('[[:space:]]',$v,2);
774 $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
775 $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).
781 return implode('',$parts);
785 * Internal sub-function for ->prefixResourcePath()
787 * @param string Prefix string
788 * @param string Relative path/URL
789 * @return string Output path, prefixed if no scheme in input string
792 function prefixRelPath($prefix,$srcVal) {
793 $pU = parse_url($srcVal);
794 if (!$pU['scheme']) { // If not an absolute URL.
795 $srcVal = $prefix.$srcVal;
801 * Cleans up the input $value for fonttags.
802 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
804 * @param string HTML content with font-tags inside to clean up.
805 * @param boolean If set, keep "face" attribute
806 * @param boolean If set, keep "size" attribute
807 * @param boolean If set, keep "color" attribute
808 * @return string Processed HTML content
810 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
811 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
813 while(list($k,$v)=each($fontSplit)) {
815 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
817 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
818 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
819 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
821 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
822 if (count($newAttribs)) {
823 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
825 $fontSplit[$k]=$innerContent;
829 return implode('',$fontSplit);
833 * This is used to map certain tag-names into other names.
835 * @param string HTML content
836 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
837 * @param string Alternative less-than char to search for (search regex string)
838 * @param string Alternative less-than char to replace with (replace regex string)
839 * @return string Processed HTML content
841 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
843 foreach($tags as $from => $to) {
844 $value = eregi_replace($ltChar.$from.'>',$ltChar2.$to.'>',$value);
845 $value = eregi_replace($ltChar.$from.'[[:space:]]([^>]*)>',$ltChar2.$to.' \\1>',$value);
846 $value = eregi_replace($ltChar.'\/'.$from.'[^>]*>',$ltChar2.'/'.$to.'>',$value);
852 * This converts htmlspecialchar()'ed tags (from $tagList) back to real tags. Eg. '<strong>' would be converted back to '<strong>' if found in $tagList
854 * @param string HTML content
855 * @param string Tag list, separated by comma. Lowercase!
856 * @return string Processed HTML content
858 function unprotectTags($content,$tagList='') {
859 $tagsArray = t3lib_div
::trimExplode(',',$tagList,1);
860 $contentParts = explode('<',$content);
861 next($contentParts); // bypass the first
862 while(list($k,$tok)=each($contentParts)) {
863 $firstChar = substr($tok,0,1);
864 if (strcmp(trim($firstChar),'')) {
865 $subparts = explode('>',$tok,2);
866 $tagEnd = strlen($subparts[0]);
867 if (strlen($tok)!=$tagEnd) {
868 $endTag = $firstChar=='/' ?
1 : 0;
869 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
870 $tagParts = split('[[:space:]]',$tagContent,2);
871 $tagName = strtolower($tagParts[0]);
872 if (!strcmp($tagList,'') ||
in_array($tagName,$tagsArray)) {
873 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
874 } else $contentParts[$k] = '<'.$tok;
875 } else $contentParts[$k] = '<'.$tok;
876 } else $contentParts[$k] = '<'.$tok;
879 return implode('',$contentParts);
883 * Strips tags except the tags in the list, $tagList
884 * OBSOLETE - use PHP function strip_tags()
886 * @param string Value to process
887 * @param string List of tags
888 * @return string Output value
891 function stripTagsExcept($value,$tagList) {
892 $tags=t3lib_div
::trimExplode(',',$tagList,1);
895 while(list(,$theTag)=each($tags)) {
896 $forthArr[$theTag]=md5($theTag);
897 $backArr[md5($theTag)]=$theTag;
899 $value = $this->mapTags($value,$forthArr,'<','_');
900 $value=strip_tags($value);
901 $value = $this->mapTags($value,$backArr,'_','<');
906 * Internal function for case shifting of a string or whole array
908 * @param mixed Input string/array
909 * @param boolean If $str is a string AND this boolean is true, the string is returned in uppercase
910 * @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.
911 * @return string Output string, processed
914 function caseShift($str,$flag,$cacheKey='') {
915 if (is_array($str)) {
916 if (!$cacheKey ||
!isset($this->caseShift_cache
[$cacheKey])) {
918 while(list($k)=each($str)) {
919 $str[$k] = strtoupper($str[$k]);
921 if ($cacheKey) $this->caseShift_cache
[$cacheKey]=$str;
923 $str = $this->caseShift_cache
[$cacheKey];
925 } elseif (!$flag) $str = strtoupper($str);
930 * Compiling an array with tag attributes into a string
932 * @param array Tag attributes
933 * @param array Meta information about these attributes (like if they were quoted)
934 * @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
935 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
938 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
941 while(list($k,$v)=each($tagAttrib)) {
943 $attr=strtolower($k);
944 if (strcmp($v,'') ||
isset($meta[$k]['dashType'])) {
945 $attr.='="'.htmlspecialchars($v).'"';
948 $attr=$meta[$k]['origTag']?
$meta[$k]['origTag']:$k;
949 if (strcmp($v,'') ||
isset($meta[$k]['dashType'])) {
950 $dash=$meta[$k]['dashType']?
$meta[$k]['dashType']:(t3lib_div
::testInt($v)?
'':'"');
951 $attr.='='.$dash.$v.$dash;
956 return implode(' ',$accu);
960 * Get tag attributes, the classic version (which had some limitations?)
962 * @param string The tag
963 * @param boolean De-htmlspecialchar flag.
967 function get_tag_attributes_classic($tag,$deHSC=0) {
968 $attr=$this->get_tag_attributes($tag,$deHSC);
969 return is_array($attr[0])?
$attr[0]:array();
973 * Converts TSconfig into an array for the HTMLcleaner function.
975 * @param array TSconfig for HTMLcleaner
976 * @param array Array of tags to keep (?)
980 function HTMLparserConfig($TSconfig,$keepTags=array()) {
981 // Allow tags (base list, merged with incoming array)
982 $alTags = array_flip(t3lib_div
::trimExplode(',',strtolower($TSconfig['allowTags']),1));
983 $keepTags = array_merge($alTags,$keepTags);
985 // Set config properties.
986 if (is_array($TSconfig['tags.'])) {
987 reset($TSconfig['tags.']);
988 while(list($key,$tagC)=each($TSconfig['tags.'])) {
989 if (!is_array($tagC) && $key==strtolower($key)) {
990 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
991 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
995 reset($TSconfig['tags.']);
996 while(list($key,$tagC)=each($TSconfig['tags.'])) {
997 if (is_array($tagC) && $key==strtolower($key)) {
998 $key=substr($key,0,-1);
999 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1000 if (is_array($tagC['fixAttrib.'])) {
1001 reset($tagC['fixAttrib.']);
1002 while(list($atName,$atConfig)=each($tagC['fixAttrib.'])) {
1003 if (is_array($atConfig)) {
1004 $atName=substr($atName,0,-1);
1005 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1006 $keepTags[$key]['fixAttrib'][$atName]=array();
1008 $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...
1009 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div
::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1010 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div
::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1014 unset($tagC['fixAttrib.']);
1015 unset($tagC['fixAttrib']);
1016 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1021 if ($TSconfig['localNesting']) {
1022 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1023 while(list(,$tn)=each($lN)) {
1024 if (isset($keepTags[$tn])) {
1025 $keepTags[$tn]['nesting']=1;
1029 if ($TSconfig['globalNesting']) {
1030 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1031 while(list(,$tn)=each($lN)) {
1032 if (isset($keepTags[$tn])) {
1033 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1034 $keepTags[$tn]['nesting']='global';
1038 if ($TSconfig['rmTagIfNoAttrib']) {
1039 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1040 while(list(,$tn)=each($lN)) {
1041 if (isset($keepTags[$tn])) {
1042 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1043 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1047 if ($TSconfig['noAttrib']) {
1048 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1049 while(list(,$tn)=each($lN)) {
1050 if (isset($keepTags[$tn])) {
1051 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1052 $keepTags[$tn]['allowedAttribs']=0;
1056 if ($TSconfig['removeTags']) {
1057 $lN = t3lib_div
::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1058 while(list(,$tn)=each($lN)) {
1059 $keepTags[$tn]=array();
1060 $keepTags[$tn]['allowedAttribs']=0;
1061 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1065 // Create additional configuration:
1067 if ($TSconfig['xhtml_cleaning']) {
1068 $addConfig['xhtml']=1;
1073 ''.$TSconfig['keepNonMatchedTags'],
1074 intval($TSconfig['htmlSpecialChars']),
1080 * Tries to convert the content to be XHTML compliant and other stuff like that.
1081 * STILL EXPERIMENTAL. See comments below.
1083 * What it does NOT do (yet) according to XHTML specs.:
1084 * - Wellformedness: Nesting is NOT checked
1085 * - name/id attribute issue is not observed at this point.
1086 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1087 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1088 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1089 * - UTF-8 encoding is in fact expected by XML!!
1090 * - stylesheet element and attribute names are NOT converted to lowercase
1091 * - 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.
1092 * - Minimized values not allowed: Must do this: selected="selected"
1094 * What it does at this point:
1095 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1096 * - Lowercase for elements and attributes
1097 * - All attributes in quotes
1098 * - Add "alt" attribute to img-tags if it's not there already.
1100 * @param string Content to clean up
1101 * @return string Cleaned up content returned.
1104 function XHTML_clean($content) {
1105 $content = $this->HTMLcleaner(
1107 array(), // No tags treated specially
1108 1, // Keep ALL tags.
1109 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1117 * Processing all tags themselves
1118 * (Some additions by Sacha Vorbeck)
1120 * @param string Tag to process
1121 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1122 * @param boolean Is endtag, then set this.
1123 * @param boolean If set, just return value straight away
1124 * @return string Processed value.
1127 function processTag($value,$conf,$endTag,$protected=0) {
1128 // Return immediately if protected or no parameters
1129 if ($protected ||
!count($conf)) return $value;
1131 // OK then, begin processing for XHTML output:
1132 // STILL VERY EXPERIMENTAL!!
1133 if ($conf['xhtml']) {
1134 if ($endTag) { // Endtags are just set lowercase right away
1135 $value = strtolower($value);
1136 } elseif (substr($value,0,2)!='<!') { // ... and comments are ignored.
1137 $inValue = substr($value,1,(substr($value,-2)=='/>'?
-2:-1)); // Finding inner value with out < >
1138 list($tagName,$tagP)=split('[[:space:]]',$inValue,2); // Separate attributes and tagname
1139 $tagName = strtolower($tagName);
1141 // Process attributes
1142 $tagAttrib = $this->get_tag_attributes($tagP);
1143 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1144 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1146 reset($tagAttrib[0]);
1147 while(list($attrib_name,$attrib_value)=each($tagAttrib[0])) {
1148 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1149 $outA[]=$attrib_name.'="'.htmlspecialchars($this->bidir_htmlspecialchars($attrib_value,-1)).'"';
1151 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1152 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1153 if (t3lib_div
::inList('img,br,hr,meta,link,base,area,input',$tagName) ||
substr($value,-2)=='/>') {
1166 * Processing content between tags for HTML_cleaner
1168 * @param string The value
1169 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1170 * @param mixed Not used, ignore.
1171 * @return string The processed value.
1174 function processContent($value,$dir,$conf) {
1175 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1182 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1183 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);