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