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