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