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