Fixed bug #14748: Span tags with multiple classes being removed by RTE transformation
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_parsehtml.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2010 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=TAB)
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 = self::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 = self::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 foreach ($tags[$tagName]['fixAttrib'] as $attr => $params) {
798 if (strlen($params['set'])) $tagAttrib[0][$attr] = $params['set'];
799 if (strlen($params['unset'])) unset($tagAttrib[0][$attr]);
800 if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr])) $tagAttrib[0][$attr]=$params['default'];
801 if ($params['always'] || isset($tagAttrib[0][$attr])) {
802 if ($params['trim']) {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
803 if ($params['intval']) {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
804 if ($params['lower']) {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
805 if ($params['upper']) {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
806 if ($params['range']) {
807 if (isset($params['range'][1])) {
808 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
809 } else {
810 $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
811 }
812 }
813 if (is_array($params['list'])) {
814 // For the class attribute, remove from the attribute value any class not in the list
815 // Classes are case sensitive
816 if ($attr == 'class') {
817 $newClasses = array();
818 $classes = t3lib_div::trimExplode(' ', $tagAttrib[0][$attr], TRUE);
819 foreach ($classes as $class) {
820 if (in_array($class, $params['list'])) {
821 $newClasses[] = $class;
822 }
823 }
824 if (count($newClasses)) {
825 $tagAttrib[0][$attr] = implode(' ', $newClasses);
826 } else {
827 $tagAttrib[0][$attr] = '';
828 }
829 } else {
830 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) {
831 $tagAttrib[0][$attr]=$params['list'][0];
832 }
833 }
834 }
835 if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) || ($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],''))) {
836 unset($tagAttrib[0][$attr]);
837 }
838 if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp']))) {
839 unset($tagAttrib[0][$attr]);
840 }
841 if ($params['prefixLocalAnchors']) {
842 if (substr($tagAttrib[0][$attr],0,1)=='#') {
843 $prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');
844 $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
845 if ($params['prefixLocalAnchors']==2 && t3lib_div::isFirstPartOfStr($prefix,t3lib_div::getIndpEnv('TYPO3_SITE_URL'))) {
846 $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
847 }
848 }
849 }
850 if ($params['prefixRelPathWith']) {
851 $urlParts = parse_url($tagAttrib[0][$attr]);
852 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') { // If it is NOT an absolute URL (by http: or starting "/")
853 $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
854 }
855 }
856 if ($params['userFunc']) {
857 $tagAttrib[0][$attr] = t3lib_div::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
858 }
859 }
860 }
861 $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
862 }
863 } else { // If endTag, remove any possible attributes:
864 $tagParts[1]='';
865 }
866
867 // Protecting the tag by converting < and > to &lt; and &gt; ??
868 if ($tags[$tagName]['protect']) {
869 $lt = '&lt;'; $gt = '&gt;';
870 } else {
871 $lt = '<'; $gt = '>';
872 }
873 // Remapping tag name?
874 if ($tags[$tagName]['remap']) $tagParts[0] = $tags[$tagName]['remap'];
875
876 // rmTagIfNoAttrib
877 if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib']) {
878 $setTag=1;
879
880 if ($tags[$tagName]['nesting']) {
881 if (!is_array($tagRegister[$tagName])) $tagRegister[$tagName]=array();
882
883 if ($endTag) {
884 /* if ($tags[$tagName]['nesting']=='global') {
885 $lastEl = end($tagStack);
886 $correctTag = !strcmp($tagName,$lastEl);
887 } else $correctTag=1;
888 */
889 $correctTag=1;
890 if ($tags[$tagName]['nesting']=='global') {
891 $lastEl = end($tagStack);
892 if (strcmp($tagName,$lastEl)) {
893 if (in_array($tagName,$tagStack)) {
894 while(count($tagStack) && strcmp($tagName,$lastEl)) {
895 $elPos = end($tagRegister[$lastEl]);
896 unset($newContent[$elPos]);
897
898 array_pop($tagRegister[$lastEl]);
899 array_pop($tagStack);
900 $lastEl = end($tagStack);
901 }
902 } else {
903 $correctTag=0; // In this case the
904 }
905 }
906 }
907 if (!count($tagRegister[$tagName]) || !$correctTag) {
908 $setTag=0;
909 } else {
910 array_pop($tagRegister[$tagName]);
911 if ($tags[$tagName]['nesting']=='global') {array_pop($tagStack);}
912 }
913 } else {
914 array_push($tagRegister[$tagName],$c);
915 if ($tags[$tagName]['nesting']=='global') {array_push($tagStack,$tagName);}
916 }
917 }
918
919 if ($setTag) {
920 // Setting the tag
921 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='&lt;');
922 }
923 }
924 } else {
925 $newContent[$c++]=$this->processTag('<'.($endTag?'/':'').$tagContent.'>',$addConfig,$endTag);
926 }
927 } elseif ($keepAll) { // This is if the tag was not defined in the array for processing:
928 if (!strcmp($keepAll,'protect')) {
929 $lt = '&lt;'; $gt = '&gt;';
930 } else {
931 $lt = '<'; $gt = '>';
932 }
933 $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='&lt;');
934 }
935 $newContent[$c++]=$this->processContent(substr($tok,$tagEnd+1),$hSC,$addConfig);
936 } else {
937 $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig); // There were not end-bracket, so no tag...
938 }
939 } else {
940 $newContent[$c++]=$this->processContent(($skipTag ? '' : '<') . $tok, $hSC, $addConfig); // It was not a tag anyways
941 $skipTag = false;
942 }
943 }
944
945 // Unsetting tags:
946 foreach ($tagRegister as $tag => $positions) {
947 foreach ($positions as $pKey) {
948 unset($newContent[$pKey]);
949 }
950 }
951
952 return implode('',$newContent);
953 }
954
955 /**
956 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
957 *
958 * @param string Input value
959 * @param integer Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
960 * @return string Output value
961 */
962 function bidir_htmlspecialchars($value,$dir) {
963 if ($dir==1) {
964 $value = htmlspecialchars($value);
965 } elseif ($dir==2) {
966 $value = t3lib_div::deHSCentities(htmlspecialchars($value));
967 } elseif ($dir==-1) {
968 $value = str_replace('&gt;','>',$value);
969 $value = str_replace('&lt;','<',$value);
970 $value = str_replace('&quot;','"',$value);
971 $value = str_replace('&amp;','&',$value);
972 }
973 return $value;
974 }
975
976 /**
977 * 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
978 *
979 * @param string Prefix string
980 * @param string HTML content
981 * @param array Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
982 * @param string Suffix string (put after the resource).
983 * @return string Processed HTML content
984 */
985 function prefixResourcePath($main_prefix,$content,$alternatives=array(),$suffix='') {
986
987 $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a,param',$content);
988 foreach ($parts as $k => $v) {
989 if ($k%2) {
990 $params = $this->get_tag_attributes($v);
991 $tagEnd = substr($v,-2)=='/>' ? ' />' : '>'; // Detect tag-ending so that it is re-applied correctly.
992 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
993 $somethingDone=0;
994 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
995 switch(strtolower($firstTagName)) {
996 // background - attribute:
997 case 'td':
998 case 'body':
999 case 'table':
1000 $src = $params[0]['background'];
1001 if ($src) {
1002 $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background'],$suffix);
1003 $somethingDone=1;
1004 }
1005 break;
1006 // src attribute
1007 case 'img':
1008 case 'input':
1009 case 'script':
1010 case 'embed':
1011 $src = $params[0]['src'];
1012 if ($src) {
1013 $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src'],$suffix);
1014 $somethingDone=1;
1015 }
1016 break;
1017 case 'link':
1018 case 'a':
1019 $src = $params[0]['href'];
1020 if ($src) {
1021 $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href'],$suffix);
1022 $somethingDone=1;
1023 }
1024 break;
1025 // action attribute
1026 case 'form':
1027 $src = $params[0]['action'];
1028 if ($src) {
1029 $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action'],$suffix);
1030 $somethingDone=1;
1031 }
1032 break;
1033 // value attribute
1034 case 'param':
1035 $test = $params[0]['name'];
1036 if ($test && $test === 'movie') {
1037 if ($params[0]['value']) {
1038 $params[0]['value'] = $this->prefixRelPath($prefix, $params[0]['value'], $suffix);
1039 $somethingDone = 1;
1040 }
1041 }
1042 break;
1043 }
1044 if ($somethingDone) {
1045 $tagParts = preg_split('/\s+/s',$v,2);
1046 $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
1047 $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).$tagEnd;
1048 }
1049 }
1050 }
1051 $content = implode('',$parts);
1052
1053 // Fix <style> section:
1054 $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
1055 if (strlen($prefix)) {
1056 $parts = $this->splitIntoBlock('style',$content);
1057 foreach($parts as $k => $v) {
1058 if ($k%2) {
1059 $parts[$k] = preg_replace('/(url[[:space:]]*\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\))/i','\1'.$prefix.'\2'.$suffix.'\3',$parts[$k]);
1060 }
1061 }
1062 $content = implode('',$parts);
1063 }
1064
1065 return $content;
1066 }
1067
1068 /**
1069 * Internal sub-function for ->prefixResourcePath()
1070 *
1071 * @param string Prefix string
1072 * @param string Relative path/URL
1073 * @param string Suffix string
1074 * @return string Output path, prefixed if no scheme in input string
1075 * @access private
1076 */
1077 function prefixRelPath($prefix, $srcVal, $suffix = '') {
1078 // Only prefix if it's not an absolute URL or
1079 // only a link to a section within the page.
1080 if (substr($srcVal, 0, 1) != '/' && substr($srcVal, 0, 1) != '#') {
1081 $urlParts = parse_url($srcVal);
1082 // only prefix URLs without a scheme
1083 if (!$urlParts['scheme']) {
1084 $srcVal = $prefix . $srcVal . $suffix;
1085 }
1086 }
1087 return $srcVal;
1088 }
1089
1090 /**
1091 * Cleans up the input $value for fonttags.
1092 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
1093 *
1094 * @param string HTML content with font-tags inside to clean up.
1095 * @param boolean If set, keep "face" attribute
1096 * @param boolean If set, keep "size" attribute
1097 * @param boolean If set, keep "color" attribute
1098 * @return string Processed HTML content
1099 */
1100 function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
1101 $fontSplit = $this->splitIntoBlock('font',$value); // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
1102 foreach ($fontSplit as $k => $v) {
1103 if ($k%2) { // font:
1104 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
1105 $newAttribs=array();
1106 if ($keepFace && $attribArray['face']) $newAttribs[]='face="'.$attribArray['face'].'"';
1107 if ($keepSize && $attribArray['size']) $newAttribs[]='size="'.$attribArray['size'].'"';
1108 if ($keepColor && $attribArray['color']) $newAttribs[]='color="'.$attribArray['color'].'"';
1109
1110 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
1111 if (count($newAttribs)) {
1112 $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
1113 } else {
1114 $fontSplit[$k]=$innerContent;
1115 }
1116 }
1117 }
1118 return implode('',$fontSplit);
1119 }
1120
1121 /**
1122 * This is used to map certain tag-names into other names.
1123 *
1124 * @param string HTML content
1125 * @param array Array with tag key=>value pairs where key is from-tag and value is to-tag
1126 * @param string Alternative less-than char to search for (search regex string)
1127 * @param string Alternative less-than char to replace with (replace regex string)
1128 * @return string Processed HTML content
1129 */
1130 function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
1131
1132 foreach($tags as $from => $to) {
1133 $value = preg_replace('/'.preg_quote($ltChar).'(\/)?'.$from.'\s([^\>])*(\/)?\>/', $ltChar2.'$1'.$to.' $2$3>', $value);
1134 }
1135 return $value;
1136 }
1137
1138 /**
1139 * 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
1140 *
1141 * @param string HTML content
1142 * @param string Tag list, separated by comma. Lowercase!
1143 * @return string Processed HTML content
1144 */
1145 function unprotectTags($content,$tagList='') {
1146 $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
1147 $contentParts = explode('&lt;',$content);
1148 next($contentParts); // bypass the first
1149 while(list($k,$tok)=each($contentParts)) {
1150 $firstChar = substr($tok,0,1);
1151 if (strcmp(trim($firstChar),'')) {
1152 $subparts = explode('&gt;',$tok,2);
1153 $tagEnd = strlen($subparts[0]);
1154 if (strlen($tok)!=$tagEnd) {
1155 $endTag = $firstChar=='/' ? 1 : 0;
1156 $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
1157 $tagParts = preg_split('/\s+/s',$tagContent,2);
1158 $tagName = strtolower($tagParts[0]);
1159 if (!strcmp($tagList,'') || in_array($tagName,$tagsArray)) {
1160 $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
1161 } else $contentParts[$k] = '&lt;'.$tok;
1162 } else $contentParts[$k] = '&lt;'.$tok;
1163 } else $contentParts[$k] = '&lt;'.$tok;
1164 }
1165
1166 return implode('',$contentParts);
1167 }
1168
1169 /**
1170 * Strips tags except the tags in the list, $tagList
1171 * OBSOLETE - use PHP function strip_tags()
1172 *
1173 * @param string Value to process
1174 * @param string List of tags
1175 * @return string Output value
1176 * @ignore
1177 */
1178 function stripTagsExcept($value,$tagList) {
1179 $tags=t3lib_div::trimExplode(',',$tagList,1);
1180 $forthArr=array();
1181 $backArr=array();
1182 foreach ($tags as $theTag) {
1183 $forthArr[$theTag]=md5($theTag);
1184 $backArr[md5($theTag)]=$theTag;
1185 }
1186 $value = $this->mapTags($value,$forthArr,'<','_');
1187 $value=strip_tags($value);
1188 $value = $this->mapTags($value,$backArr,'_','<');
1189 return $value;
1190 }
1191
1192 /**
1193 * Internal function for case shifting of a string or whole array
1194 *
1195 * @param mixed Input string/array
1196 * @param boolean If $str is a string AND this boolean(caseSensitive) is false, the string is returned in uppercase
1197 * @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.
1198 * @return string Output string, processed
1199 * @access private
1200 */
1201 function caseShift($str,$flag,$cacheKey='') {
1202 $cacheKey .= $flag?1:0;
1203 if (is_array($str)) {
1204 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1205 reset($str);
1206 foreach ($str as $k => $v) {
1207 if (!$flag) {
1208 $str[$k] = strtoupper($v);
1209 }
1210 }
1211 if ($cacheKey) $this->caseShift_cache[$cacheKey]=$str;
1212 } else {
1213 $str = $this->caseShift_cache[$cacheKey];
1214 }
1215 } elseif (!$flag) { $str = strtoupper($str); }
1216 return $str;
1217 }
1218
1219 /**
1220 * Compiling an array with tag attributes into a string
1221 *
1222 * @param array Tag attributes
1223 * @param array Meta information about these attributes (like if they were quoted)
1224 * @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
1225 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1226 * @access private
1227 */
1228 function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
1229 $accu=array();
1230 foreach ($tagAttrib as $k =>$v) {
1231 if ($xhtmlClean) {
1232 $attr=strtolower($k);
1233 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1234 $attr.='="'.htmlspecialchars($v).'"';
1235 }
1236 } else {
1237 $attr=$meta[$k]['origTag']?$meta[$k]['origTag']:$k;
1238 if (strcmp($v,'') || isset($meta[$k]['dashType'])) {
1239 $dash=$meta[$k]['dashType']?$meta[$k]['dashType']:(t3lib_div::testInt($v)?'':'"');
1240 $attr.='='.$dash.$v.$dash;
1241 }
1242 }
1243 $accu[]=$attr;
1244 }
1245 return implode(' ',$accu);
1246 }
1247
1248 /**
1249 * Get tag attributes, the classic version (which had some limitations?)
1250 *
1251 * @param string The tag
1252 * @param boolean De-htmlspecialchar flag.
1253 * @return array
1254 * @access private
1255 */
1256 function get_tag_attributes_classic($tag,$deHSC=0) {
1257 $attr=$this->get_tag_attributes($tag,$deHSC);
1258 return is_array($attr[0])?$attr[0]:array();
1259 }
1260
1261 /**
1262 * Indents input content with $number instances of $indentChar
1263 *
1264 * @param string Content string, multiple lines.
1265 * @param integer Number of indents
1266 * @param string Indent character/string
1267 * @return string Indented code (typ. HTML)
1268 */
1269 function indentLines($content, $number=1, $indentChar=TAB) {
1270 $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
1271 $lines = explode(LF,str_replace(CR,'',$content));
1272 foreach ($lines as $k => $v) {
1273 $lines[$k] = $preTab.$v;
1274 }
1275 return implode(LF, $lines);
1276 }
1277
1278 /**
1279 * Converts TSconfig into an array for the HTMLcleaner function.
1280 *
1281 * @param array TSconfig for HTMLcleaner
1282 * @param array Array of tags to keep (?)
1283 * @return array
1284 * @access private
1285 */
1286 function HTMLparserConfig($TSconfig,$keepTags=array()) {
1287 // Allow tags (base list, merged with incoming array)
1288 $alTags = array_flip(t3lib_div::trimExplode(',',strtolower($TSconfig['allowTags']),1));
1289 $keepTags = array_merge($alTags,$keepTags);
1290
1291 // Set config properties.
1292 if (is_array($TSconfig['tags.'])) {
1293 foreach ($TSconfig['tags.'] as $key => $tagC) {
1294 if (!is_array($tagC) && $key==strtolower($key)) {
1295 if (!strcmp($tagC,'0')) unset($keepTags[$key]);
1296 if (!strcmp($tagC,'1') && !isset($keepTags[$key])) $keepTags[$key]=1;
1297 }
1298 }
1299
1300 foreach ($TSconfig['tags.'] as $key => $tagC) {
1301 if (is_array($tagC) && $key==strtolower($key)) {
1302 $key=substr($key,0,-1);
1303 if (!is_array($keepTags[$key])) $keepTags[$key]=array();
1304 if (is_array($tagC['fixAttrib.'])) {
1305 foreach ($tagC['fixAttrib.'] as $atName => $atConfig) {
1306 if (is_array($atConfig)) {
1307 $atName=substr($atName,0,-1);
1308 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1309 $keepTags[$key]['fixAttrib'][$atName]=array();
1310 }
1311 $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...
1312 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],'')) $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
1313 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],'')) $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
1314 }
1315 }
1316 }
1317 unset($tagC['fixAttrib.']);
1318 unset($tagC['fixAttrib']);
1319 $keepTags[$key] = array_merge($keepTags[$key],$tagC); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1320 }
1321 }
1322 }
1323 // localNesting
1324 if ($TSconfig['localNesting']) {
1325 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['localNesting']),1);
1326 foreach ($lN as $tn) {
1327 if (isset($keepTags[$tn])) {
1328 $keepTags[$tn]['nesting']=1;
1329 }
1330 }
1331 }
1332 if ($TSconfig['globalNesting']) {
1333 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
1334 foreach ($lN as $tn) {
1335 if (isset($keepTags[$tn])) {
1336 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1337 $keepTags[$tn]['nesting']='global';
1338 }
1339 }
1340 }
1341 if ($TSconfig['rmTagIfNoAttrib']) {
1342 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
1343 foreach ($lN as $tn) {
1344 if (isset($keepTags[$tn])) {
1345 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1346 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1347 }
1348 }
1349 }
1350 if ($TSconfig['noAttrib']) {
1351 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
1352 foreach ($lN as $tn) {
1353 if (isset($keepTags[$tn])) {
1354 if (!is_array($keepTags[$tn])) $keepTags[$tn]=array();
1355 $keepTags[$tn]['allowedAttribs']=0;
1356 }
1357 }
1358 }
1359 if ($TSconfig['removeTags']) {
1360 $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['removeTags']),1);
1361 foreach ($lN as $tn) {
1362 $keepTags[$tn]=array();
1363 $keepTags[$tn]['allowedAttribs']=0;
1364 $keepTags[$tn]['rmTagIfNoAttrib']=1;
1365 }
1366 }
1367
1368 // Create additional configuration:
1369 $addConfig=array();
1370 if ($TSconfig['xhtml_cleaning']) {
1371 $addConfig['xhtml']=1;
1372 }
1373
1374 return array(
1375 $keepTags,
1376 ''.$TSconfig['keepNonMatchedTags'],
1377 intval($TSconfig['htmlSpecialChars']),
1378 $addConfig
1379 );
1380 }
1381
1382 /**
1383 * Tries to convert the content to be XHTML compliant and other stuff like that.
1384 * STILL EXPERIMENTAL. See comments below.
1385 *
1386 * What it does NOT do (yet) according to XHTML specs.:
1387 * - Wellformedness: Nesting is NOT checked
1388 * - name/id attribute issue is not observed at this point.
1389 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1390 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1391 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1392 * - UTF-8 encoding is in fact expected by XML!!
1393 * - stylesheet element and attribute names are NOT converted to lowercase
1394 * - 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.
1395 * - Minimized values not allowed: Must do this: selected="selected"
1396 *
1397 * What it does at this point:
1398 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1399 * - Lowercase for elements and attributes
1400 * - All attributes in quotes
1401 * - Add "alt" attribute to img-tags if it's not there already.
1402 *
1403 * @param string Content to clean up
1404 * @return string Cleaned up content returned.
1405 * @access private
1406 */
1407 function XHTML_clean($content) {
1408 $content = $this->HTMLcleaner(
1409 $content,
1410 array(), // No tags treated specially
1411 1, // Keep ALL tags.
1412 0, // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
1413 array('xhtml' => 1)
1414 );
1415 return $content;
1416 }
1417
1418 /**
1419 * Processing all tags themselves
1420 * (Some additions by Sacha Vorbeck)
1421 *
1422 * @param string Tag to process
1423 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1424 * @param boolean Is endtag, then set this.
1425 * @param boolean If set, just return value straight away
1426 * @return string Processed value.
1427 * @access private
1428 */
1429 function processTag($value,$conf,$endTag,$protected=0) {
1430 // Return immediately if protected or no parameters
1431 if ($protected || !count($conf)) return $value;
1432 // OK then, begin processing for XHTML output:
1433 // STILL VERY EXPERIMENTAL!!
1434 if ($conf['xhtml']) {
1435 if ($endTag) { // Endtags are just set lowercase right away
1436 $value = strtolower($value);
1437 } elseif (substr($value,0,4)!='<!--') { // ... and comments are ignored.
1438 $inValue = substr($value,1,(substr($value,-2)=='/>'?-2:-1)); // Finding inner value with out < >
1439 list($tagName,$tagP)=preg_split('/\s+/s',$inValue,2); // Separate attributes and tagname
1440 $tagName = strtolower($tagName);
1441
1442 // Process attributes
1443 $tagAttrib = $this->get_tag_attributes($tagP);
1444 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt'])) $tagAttrib[0]['alt']=''; // Set alt attribute for all images (not XHTML though...)
1445 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type'])) $tagAttrib[0]['type']='text/javascript'; // Set type attribute for all script-tags
1446 $outA=array();
1447 foreach ($tagAttrib[0] as $attrib_name => $attrib_value) {
1448 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1449 $outA[]=$attrib_name.'="'.$this->bidir_htmlspecialchars($attrib_value,2).'"';
1450 }
1451 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
1452 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1453 if (t3lib_div::inList('img,br,hr,meta,link,base,area,input,param,col',$tagName) || substr($value,-2)=='/>') {
1454 $newTag.=' />';
1455 } else {
1456 $newTag.='>';
1457 }
1458 $value = $newTag;
1459 }
1460 }
1461
1462 return $value;
1463 }
1464
1465 /**
1466 * Processing content between tags for HTML_cleaner
1467 *
1468 * @param string The value
1469 * @param integer Direction, either -1 or +1. 0 (zero) means no change to input value.
1470 * @param mixed Not used, ignore.
1471 * @return string The processed value.
1472 * @access private
1473 */
1474 function processContent($value,$dir,$conf) {
1475 if ($dir!=0) $value = $this->bidir_htmlspecialchars($value,$dir);
1476 return $value;
1477 }
1478 }
1479
1480
1481
1482 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
1483 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);
1484 }
1485
1486 ?>