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