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