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