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