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