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