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