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