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