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