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