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