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