[TASK] Deprecate GeneralUtility::array_merge()
[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 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 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 ($params['set'] !== '') {
804 $tagAttrib[0][$attr] = $params['set'];
805 }
806 if (!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 if ($params['prefixLocalAnchors'] == 2) {
863 /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObjectRenderer */
864 $contentObjectRenderer = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
865 $prefix = $contentObjectRenderer->getUrlToCurrentLocation();
866 } else {
867 $prefix = GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL');
868 }
869 $tagAttrib[0][$attr] = $prefix . $tagAttrib[0][$attr];
870 }
871 }
872 if ($params['prefixRelPathWith']) {
873 $urlParts = parse_url($tagAttrib[0][$attr]);
874 if (!$urlParts['scheme'] && $urlParts['path'][0] !== '/') {
875 // If it is NOT an absolute URL (by http: or starting "/")
876 $tagAttrib[0][$attr] = $params['prefixRelPathWith'] . $tagAttrib[0][$attr];
877 }
878 }
879 if ($params['userFunc']) {
880 $tagAttrib[0][$attr] = GeneralUtility::callUserFunction($params['userFunc'], $tagAttrib[0][$attr], $this);
881 }
882 }
883 }
884 $tagParts[1] = $this->compileTagAttribs($tagAttrib[0], $tagAttrib[1]);
885 }
886 } else {
887 // If endTag, remove any possible attributes:
888 $tagParts[1] = '';
889 }
890 // Protecting the tag by converting < and > to &lt; and &gt; ??
891 if ($tags[$tagName]['protect']) {
892 $lt = '&lt;';
893 $gt = '&gt;';
894 } else {
895 $lt = '<';
896 $gt = '>';
897 }
898 // Remapping tag name?
899 if ($tags[$tagName]['remap']) {
900 $tagParts[0] = $tags[$tagName]['remap'];
901 }
902 // rmTagIfNoAttrib
903 if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib']) {
904 $setTag = 1;
905 // Remove this closing tag if $tagName was among $TSconfig['removeTags']
906 if ($endTag && $tags[$tagName]['allowedAttribs'] === 0 && $tags[$tagName]['rmTagIfNoAttrib'] === 1) {
907 $setTag = 0;
908 }
909 if ($tags[$tagName]['nesting']) {
910 if (!is_array($tagRegister[$tagName])) {
911 $tagRegister[$tagName] = array();
912 }
913 if ($endTag) {
914 $correctTag = 1;
915 if ($tags[$tagName]['nesting'] == 'global') {
916 $lastEl = end($tagStack);
917 if ($tagName !== $lastEl) {
918 if (in_array($tagName, $tagStack)) {
919 while (count($tagStack) && $tagName !== $lastEl) {
920 $elPos = end($tagRegister[$lastEl]);
921 unset($newContent[$elPos]);
922 array_pop($tagRegister[$lastEl]);
923 array_pop($tagStack);
924 $lastEl = end($tagStack);
925 }
926 } else {
927 // In this case the
928 $correctTag = 0;
929 }
930 }
931 }
932 if (!count($tagRegister[$tagName]) || !$correctTag) {
933 $setTag = 0;
934 } else {
935 array_pop($tagRegister[$tagName]);
936 if ($tags[$tagName]['nesting'] == 'global') {
937 array_pop($tagStack);
938 }
939 }
940 } else {
941 array_push($tagRegister[$tagName], $c);
942 if ($tags[$tagName]['nesting'] == 'global') {
943 array_push($tagStack, $tagName);
944 }
945 }
946 }
947 if ($setTag) {
948 // Setting the tag
949 $newContent[$c++] = $this->processTag($lt . ($endTag ? '/' : '') . trim(($tagParts[0] . ' ' . $tagParts[1])) . ($emptyTag ? ' /' : '') . $gt, $addConfig, $endTag, $lt == '&lt;');
950 }
951 }
952 } else {
953 $newContent[$c++] = $this->processTag('<' . ($endTag ? '/' : '') . $tagContent . '>', $addConfig, $endTag);
954 }
955 } elseif ($keepAll) {
956 // This is if the tag was not defined in the array for processing:
957 if ($keepAll === 'protect') {
958 $lt = '&lt;';
959 $gt = '&gt;';
960 } else {
961 $lt = '<';
962 $gt = '>';
963 }
964 $newContent[$c++] = $this->processTag($lt . ($endTag ? '/' : '') . $tagContent . $gt, $addConfig, $endTag, $lt == '&lt;');
965 }
966 $newContent[$c++] = $this->processContent(substr($tok, $tagEnd + 1), $hSC, $addConfig);
967 } else {
968 $newContent[$c++] = $this->processContent('<' . $tok, $hSC, $addConfig);
969 }
970 } else {
971 $newContent[$c++] = $this->processContent(($skipTag ? '' : '<') . $tok, $hSC, $addConfig);
972 // It was not a tag anyways
973 $skipTag = FALSE;
974 }
975 }
976 // Unsetting tags:
977 foreach ($tagRegister as $tag => $positions) {
978 foreach ($positions as $pKey) {
979 unset($newContent[$pKey]);
980 }
981 }
982 return implode('', $newContent);
983 }
984
985 /**
986 * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
987 *
988 * @param string $value Input value
989 * @param int $dir Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
990 * @return string Output value
991 */
992 public function bidir_htmlspecialchars($value, $dir) {
993 $dir = (int)$dir;
994 if ($dir === 1) {
995 $value = htmlspecialchars($value);
996 } elseif ($dir === 2) {
997 $value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8', FALSE);
998 } elseif ($dir === -1) {
999 $value = htmlspecialchars_decode($value);
1000 }
1001 return $value;
1002 }
1003
1004 /**
1005 * 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
1006 *
1007 * @param string $main_prefix Prefix string
1008 * @param string $content HTML content
1009 * @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
1010 * @param string $suffix Suffix string (put after the resource).
1011 * @return string Processed HTML content
1012 */
1013 public function prefixResourcePath($main_prefix, $content, $alternatives = array(), $suffix = '') {
1014 $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a,param', $content);
1015 foreach ($parts as $k => $v) {
1016 if ($k % 2) {
1017 $params = $this->get_tag_attributes($v);
1018 // Detect tag-ending so that it is re-applied correctly.
1019 $tagEnd = substr($v, -2) == '/>' ? ' />' : '>';
1020 // The 'name' of the first tag
1021 $firstTagName = $this->getFirstTagName($v);
1022 $somethingDone = 0;
1023 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
1024 switch (strtolower($firstTagName)) {
1025 case 'td':
1026
1027 case 'body':
1028
1029 case 'table':
1030 $src = $params[0]['background'];
1031 if ($src) {
1032 $params[0]['background'] = $this->prefixRelPath($prefix, $params[0]['background'], $suffix);
1033 $somethingDone = 1;
1034 }
1035 break;
1036 case 'img':
1037
1038 case 'input':
1039
1040 case 'script':
1041
1042 case 'embed':
1043 $src = $params[0]['src'];
1044 if ($src) {
1045 $params[0]['src'] = $this->prefixRelPath($prefix, $params[0]['src'], $suffix);
1046 $somethingDone = 1;
1047 }
1048 break;
1049 case 'link':
1050
1051 case 'a':
1052 $src = $params[0]['href'];
1053 if ($src) {
1054 $params[0]['href'] = $this->prefixRelPath($prefix, $params[0]['href'], $suffix);
1055 $somethingDone = 1;
1056 }
1057 break;
1058 case 'form':
1059 $src = $params[0]['action'];
1060 if ($src) {
1061 $params[0]['action'] = $this->prefixRelPath($prefix, $params[0]['action'], $suffix);
1062 $somethingDone = 1;
1063 }
1064 break;
1065 case 'param':
1066 $test = $params[0]['name'];
1067 if ($test && $test === 'movie') {
1068 if ($params[0]['value']) {
1069 $params[0]['value'] = $this->prefixRelPath($prefix, $params[0]['value'], $suffix);
1070 $somethingDone = 1;
1071 }
1072 }
1073 break;
1074 }
1075 if ($somethingDone) {
1076 $tagParts = preg_split('/\\s+/s', $v, 2);
1077 $tagParts[1] = $this->compileTagAttribs($params[0], $params[1]);
1078 $parts[$k] = '<' . trim((strtolower($firstTagName) . ' ' . $tagParts[1])) . $tagEnd;
1079 }
1080 }
1081 }
1082 $content = implode('', $parts);
1083 // Fix <style> section:
1084 $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
1085 if ($prefix !== '') {
1086 $parts = $this->splitIntoBlock('style', $content);
1087 foreach ($parts as $k => &$part) {
1088 if ($k % 2) {
1089 $part = preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $prefix . '\\2' . $suffix . '\\3', $part);
1090 }
1091 }
1092 unset($part);
1093 $content = implode('', $parts);
1094 }
1095 return $content;
1096 }
1097
1098 /**
1099 * Internal sub-function for ->prefixResourcePath()
1100 *
1101 * @param string $prefix Prefix string
1102 * @param string $srcVal Relative path/URL
1103 * @param string $suffix Suffix string
1104 * @return string Output path, prefixed if no scheme in input string
1105 * @access private
1106 */
1107 public function prefixRelPath($prefix, $srcVal, $suffix = '') {
1108 // Only prefix if it's not an absolute URL or
1109 // only a link to a section within the page.
1110 if ($srcVal[0] !== '/' && $srcVal[0] !== '#') {
1111 $urlParts = parse_url($srcVal);
1112 // Only prefix URLs without a scheme
1113 if (!$urlParts['scheme']) {
1114 $srcVal = $prefix . $srcVal . $suffix;
1115 }
1116 }
1117 return $srcVal;
1118 }
1119
1120 /**
1121 * Cleans up the input $value for fonttags.
1122 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
1123 *
1124 * @param string HTML content with font-tags inside to clean up.
1125 * @param bool If set, keep "face" attribute
1126 * @param bool If set, keep "size" attribute
1127 * @param bool If set, keep "color" attribute
1128 * @return string Processed HTML content
1129 */
1130 public function cleanFontTags($value, $keepFace = 0, $keepSize = 0, $keepColor = 0) {
1131 // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
1132 $fontSplit = $this->splitIntoBlock('font', $value);
1133 foreach ($fontSplit as $k => $v) {
1134 // Font
1135 if ($k % 2) {
1136 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v));
1137 $newAttribs = array();
1138 if ($keepFace && $attribArray['face']) {
1139 $newAttribs[] = 'face="' . $attribArray['face'] . '"';
1140 }
1141 if ($keepSize && $attribArray['size']) {
1142 $newAttribs[] = 'size="' . $attribArray['size'] . '"';
1143 }
1144 if ($keepColor && $attribArray['color']) {
1145 $newAttribs[] = 'color="' . $attribArray['color'] . '"';
1146 }
1147 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v), $keepFace, $keepSize, $keepColor);
1148 if (count($newAttribs)) {
1149 $fontSplit[$k] = '<font ' . implode(' ', $newAttribs) . '>' . $innerContent . '</font>';
1150 } else {
1151 $fontSplit[$k] = $innerContent;
1152 }
1153 }
1154 }
1155 return implode('', $fontSplit);
1156 }
1157
1158 /**
1159 * This is used to map certain tag-names into other names.
1160 *
1161 * @param string $value HTML content
1162 * @param array $tags Array with tag key=>value pairs where key is from-tag and value is to-tag
1163 * @param string $ltChar Alternative less-than char to search for (search regex string)
1164 * @param string $ltChar2 Alternative less-than char to replace with (replace regex string)
1165 * @return string Processed HTML content
1166 */
1167 public function mapTags($value, $tags = array(), $ltChar = '<', $ltChar2 = '<') {
1168 foreach ($tags as $from => $to) {
1169 $value = preg_replace('/' . preg_quote($ltChar, '/') . '(\\/)?' . $from . '\\s([^\\>])*(\\/)?\\>/', $ltChar2 . '$1' . $to . ' $2$3>', $value);
1170 }
1171 return $value;
1172 }
1173
1174 /**
1175 * 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
1176 *
1177 * @param string $content HTML content
1178 * @param string $tagList Tag list, separated by comma. Lowercase!
1179 * @return string Processed HTML content
1180 */
1181 public function unprotectTags($content, $tagList = '') {
1182 $tagsArray = GeneralUtility::trimExplode(',', $tagList, TRUE);
1183 $contentParts = explode('&lt;', $content);
1184 next($contentParts);
1185 // bypass the first
1186 while (list($k, $tok) = each($contentParts)) {
1187 $firstChar = $tok[0];
1188 if (trim($firstChar) !== '') {
1189 $subparts = explode('&gt;', $tok, 2);
1190 $tagEnd = strlen($subparts[0]);
1191 if (strlen($tok) != $tagEnd) {
1192 $endTag = $firstChar == '/' ? 1 : 0;
1193 $tagContent = substr($tok, $endTag, $tagEnd - $endTag);
1194 $tagParts = preg_split('/\\s+/s', $tagContent, 2);
1195 $tagName = strtolower($tagParts[0]);
1196 if ((string)$tagList === '' || in_array($tagName, $tagsArray)) {
1197 $contentParts[$k] = '<' . $subparts[0] . '>' . $subparts[1];
1198 } else {
1199 $contentParts[$k] = '&lt;' . $tok;
1200 }
1201 } else {
1202 $contentParts[$k] = '&lt;' . $tok;
1203 }
1204 } else {
1205 $contentParts[$k] = '&lt;' . $tok;
1206 }
1207 }
1208 return implode('', $contentParts);
1209 }
1210
1211 /**
1212 * Internal function for case shifting of a string or whole array
1213 *
1214 * @param mixed $str Input string/array
1215 * @param bool $flag If $str is a string AND this boolean(caseSensitive) is FALSE, the string is returned in uppercase
1216 * @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.
1217 * @return string Output string, processed
1218 * @access private
1219 */
1220 public function caseShift($str, $flag, $cacheKey = '') {
1221 $cacheKey .= $flag ? 1 : 0;
1222 if (is_array($str)) {
1223 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1224 foreach ($str as &$v) {
1225 if (!$flag) {
1226 $v = strtoupper($v);
1227 }
1228 }
1229 unset($v);
1230 if ($cacheKey) {
1231 $this->caseShift_cache[$cacheKey] = $str;
1232 }
1233 } else {
1234 $str = $this->caseShift_cache[$cacheKey];
1235 }
1236 } elseif (!$flag) {
1237 $str = strtoupper($str);
1238 }
1239 return $str;
1240 }
1241
1242 /**
1243 * Compiling an array with tag attributes into a string
1244 *
1245 * @param array $tagAttrib Tag attributes
1246 * @param array $meta Meta information about these attributes (like if they were quoted)
1247 * @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
1248 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1249 * @access private
1250 */
1251 public function compileTagAttribs($tagAttrib, $meta = array(), $xhtmlClean = 0) {
1252 $accu = array();
1253 foreach ($tagAttrib as $k => $v) {
1254 if ($xhtmlClean) {
1255 $attr = strtolower($k);
1256 if ((string)$v !== '' || isset($meta[$k]['dashType'])) {
1257 $attr .= '="' . htmlspecialchars($v) . '"';
1258 }
1259 } else {
1260 $attr = $meta[$k]['origTag'] ?: $k;
1261 if (strcmp($v, '') || isset($meta[$k]['dashType'])) {
1262 $dash = $meta[$k]['dashType'] ?: (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($v) ? '' : '"');
1263 $attr .= '=' . $dash . $v . $dash;
1264 }
1265 }
1266 $accu[] = $attr;
1267 }
1268 return implode(' ', $accu);
1269 }
1270
1271 /**
1272 * Get tag attributes, the classic version (which had some limitations?)
1273 *
1274 * @param string $tag The tag
1275 * @param bool $deHSC De-htmlspecialchar flag.
1276 * @return array
1277 * @access private
1278 */
1279 public function get_tag_attributes_classic($tag, $deHSC = 0) {
1280 $attr = $this->get_tag_attributes($tag, $deHSC);
1281 return is_array($attr[0]) ? $attr[0] : array();
1282 }
1283
1284 /**
1285 * Indents input content with $number instances of $indentChar
1286 *
1287 * @param string $content Content string, multiple lines.
1288 * @param int $number Number of indents
1289 * @param string $indentChar Indent character/string
1290 * @return strin Indented code (typ. HTML)
1291 */
1292 public function indentLines($content, $number = 1, $indentChar = TAB) {
1293 $preTab = str_pad('', $number * strlen($indentChar), $indentChar);
1294 $lines = explode(LF, str_replace(CR, '', $content));
1295 foreach ($lines as &$line) {
1296 $line = $preTab . $line;
1297 }
1298 unset($line);
1299 return implode(LF, $lines);
1300 }
1301
1302 /**
1303 * Converts TSconfig into an array for the HTMLcleaner function.
1304 *
1305 * @param array $TSconfig TSconfig for HTMLcleaner
1306 * @param array $keepTags Array of tags to keep (?)
1307 * @return array
1308 * @access private
1309 */
1310 public function HTMLparserConfig($TSconfig, $keepTags = array()) {
1311 // Allow tags (base list, merged with incoming array)
1312 $alTags = array_flip(GeneralUtility::trimExplode(',', strtolower($TSconfig['allowTags']), TRUE));
1313 $keepTags = array_merge($alTags, $keepTags);
1314 // Set config properties.
1315 if (is_array($TSconfig['tags.'])) {
1316 foreach ($TSconfig['tags.'] as $key => $tagC) {
1317 if (!is_array($tagC) && $key == strtolower($key)) {
1318 if ((string)$tagC === '0') {
1319 unset($keepTags[$key]);
1320 }
1321 if ((string)$tagC === '1' && !isset($keepTags[$key])) {
1322 $keepTags[$key] = 1;
1323 }
1324 }
1325 }
1326 foreach ($TSconfig['tags.'] as $key => $tagC) {
1327 if (is_array($tagC) && $key == strtolower($key)) {
1328 $key = substr($key, 0, -1);
1329 if (!is_array($keepTags[$key])) {
1330 $keepTags[$key] = array();
1331 }
1332 if (is_array($tagC['fixAttrib.'])) {
1333 foreach ($tagC['fixAttrib.'] as $atName => $atConfig) {
1334 if (is_array($atConfig)) {
1335 $atName = substr($atName, 0, -1);
1336 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1337 $keepTags[$key]['fixAttrib'][$atName] = array();
1338 }
1339 $keepTags[$key]['fixAttrib'][$atName] = array_merge($keepTags[$key]['fixAttrib'][$atName], $atConfig);
1340 if ((string)$keepTags[$key]['fixAttrib'][$atName]['range'] !== '') {
1341 $keepTags[$key]['fixAttrib'][$atName]['range'] = GeneralUtility::trimExplode(',', $keepTags[$key]['fixAttrib'][$atName]['range']);
1342 }
1343 if ((string)$keepTags[$key]['fixAttrib'][$atName]['list'] !== '') {
1344 $keepTags[$key]['fixAttrib'][$atName]['list'] = GeneralUtility::trimExplode(',', $keepTags[$key]['fixAttrib'][$atName]['list']);
1345 }
1346 }
1347 }
1348 }
1349 unset($tagC['fixAttrib.']);
1350 unset($tagC['fixAttrib']);
1351 $keepTags[$key] = array_merge($keepTags[$key], $tagC);
1352 }
1353 }
1354 }
1355 // LocalNesting
1356 if ($TSconfig['localNesting']) {
1357 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['localNesting']), TRUE);
1358 foreach ($lN as $tn) {
1359 if (isset($keepTags[$tn])) {
1360 $keepTags[$tn]['nesting'] = 1;
1361 }
1362 }
1363 }
1364 if ($TSconfig['globalNesting']) {
1365 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['globalNesting']), TRUE);
1366 foreach ($lN as $tn) {
1367 if (isset($keepTags[$tn])) {
1368 if (!is_array($keepTags[$tn])) {
1369 $keepTags[$tn] = array();
1370 }
1371 $keepTags[$tn]['nesting'] = 'global';
1372 }
1373 }
1374 }
1375 if ($TSconfig['rmTagIfNoAttrib']) {
1376 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['rmTagIfNoAttrib']), TRUE);
1377 foreach ($lN as $tn) {
1378 if (isset($keepTags[$tn])) {
1379 if (!is_array($keepTags[$tn])) {
1380 $keepTags[$tn] = array();
1381 }
1382 $keepTags[$tn]['rmTagIfNoAttrib'] = 1;
1383 }
1384 }
1385 }
1386 if ($TSconfig['noAttrib']) {
1387 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['noAttrib']), TRUE);
1388 foreach ($lN as $tn) {
1389 if (isset($keepTags[$tn])) {
1390 if (!is_array($keepTags[$tn])) {
1391 $keepTags[$tn] = array();
1392 }
1393 $keepTags[$tn]['allowedAttribs'] = 0;
1394 }
1395 }
1396 }
1397 if ($TSconfig['removeTags']) {
1398 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['removeTags']), TRUE);
1399 foreach ($lN as $tn) {
1400 $keepTags[$tn] = array();
1401 $keepTags[$tn]['allowedAttribs'] = 0;
1402 $keepTags[$tn]['rmTagIfNoAttrib'] = 1;
1403 }
1404 }
1405 // Create additional configuration:
1406 $addConfig = array();
1407 if ($TSconfig['xhtml_cleaning']) {
1408 $addConfig['xhtml'] = 1;
1409 }
1410 return array(
1411 $keepTags,
1412 '' . $TSconfig['keepNonMatchedTags'],
1413 (int)$TSconfig['htmlSpecialChars'],
1414 $addConfig
1415 );
1416 }
1417
1418 /**
1419 * Tries to convert the content to be XHTML compliant and other stuff like that.
1420 * STILL EXPERIMENTAL. See comments below.
1421 *
1422 * What it does NOT do (yet) according to XHTML specs.:
1423 * - Wellformedness: Nesting is NOT checked
1424 * - name/id attribute issue is not observed at this point.
1425 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1426 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1427 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1428 * - UTF-8 encoding is in fact expected by XML!!
1429 * - stylesheet element and attribute names are NOT converted to lowercase
1430 * - 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.
1431 * - Minimized values not allowed: Must do this: selected="selected"
1432 *
1433 * What it does at this point:
1434 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1435 * - Lowercase for elements and attributes
1436 * - All attributes in quotes
1437 * - Add "alt" attribute to img-tags if it's not there already.
1438 *
1439 * @param string $content Content to clean up
1440 * @return string Cleaned up content returned.
1441 * @access private
1442 */
1443 public function XHTML_clean($content) {
1444 $content = $this->HTMLcleaner($content, array(), 1, 0, array('xhtml' => 1));
1445 return $content;
1446 }
1447
1448 /**
1449 * Processing all tags themselves
1450 * (Some additions by Sacha Vorbeck)
1451 *
1452 * @param string Tag to process
1453 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1454 * @param bool Is endtag, then set this.
1455 * @param bool If set, just return value straight away
1456 * @return string Processed value.
1457 * @access private
1458 */
1459 public function processTag($value, $conf, $endTag, $protected = 0) {
1460 // Return immediately if protected or no parameters
1461 if ($protected || !count($conf)) {
1462 return $value;
1463 }
1464 // OK then, begin processing for XHTML output:
1465 // STILL VERY EXPERIMENTAL!!
1466 if ($conf['xhtml']) {
1467 // Endtags are just set lowercase right away
1468 if ($endTag) {
1469 $value = strtolower($value);
1470 } elseif (substr($value, 0, 4) != '<!--') {
1471 // ... and comments are ignored.
1472 // Finding inner value with out < >
1473 $inValue = substr($value, 1, substr($value, -2) == '/>' ? -2 : -1);
1474 // Separate attributes and tagname
1475 list($tagName, $tagP) = preg_split('/\\s+/s', $inValue, 2);
1476 $tagName = strtolower($tagName);
1477 // Process attributes
1478 $tagAttrib = $this->get_tag_attributes($tagP);
1479 if ($tagName === 'img' && !isset($tagAttrib[0]['alt'])) {
1480 $tagAttrib[0]['alt'] = '';
1481 }
1482 // Set alt attribute for all images (not XHTML though...)
1483 if ($tagName === 'script' && !isset($tagAttrib[0]['type'])) {
1484 $tagAttrib[0]['type'] = 'text/javascript';
1485 }
1486 // Set type attribute for all script-tags
1487 $outA = array();
1488 foreach ($tagAttrib[0] as $attrib_name => $attrib_value) {
1489 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1490 $outA[] = $attrib_name . '="' . $this->bidir_htmlspecialchars($attrib_value, 2) . '"';
1491 }
1492 $newTag = '<' . trim(($tagName . ' ' . implode(' ', $outA)));
1493 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1494 if (GeneralUtility::inList('img,br,hr,meta,link,base,area,input,param,col', $tagName) || substr($value, -2) == '/>') {
1495 $newTag .= ' />';
1496 } else {
1497 $newTag .= '>';
1498 }
1499 $value = $newTag;
1500 }
1501 }
1502 return $value;
1503 }
1504
1505 /**
1506 * Processing content between tags for HTML_cleaner
1507 *
1508 * @param string $value The value
1509 * @param int $dir Direction, either -1 or +1. 0 (zero) means no change to input value.
1510 * @param mixed $conf Not used, ignore.
1511 * @return string The processed value.
1512 * @access private
1513 */
1514 public function processContent($value, $dir, $conf) {
1515 if ($dir != 0) {
1516 $value = $this->bidir_htmlspecialchars($value, $dir);
1517 }
1518 return $value;
1519 }
1520
1521 }