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