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