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