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