[TASK] Re-work/simplify copyright header in PHP files - Part 2
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Html / HtmlParser.php
1 <?php
2 namespace TYPO3\CMS\Core\Html;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19 /**
20 * Functions for parsing HTML.
21 * You are encouraged to use this class in your own applications
22 *
23 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
24 */
25 class HtmlParser {
26
27 protected $caseShift_cache = array();
28
29 // Void elements that do not have closing tags, as defined by HTML5, except link element
30 const VOID_ELEMENTS = 'area|base|br|col|command|embed|hr|img|input|keygen|meta|param|source|track|wbr';
31 /**
32 * Returns the first subpart encapsulated in the marker, $marker
33 * (possibly present in $content as a HTML comment)
34 *
35 * @param string $content Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
36 * @param string $marker Marker string, eg. "###CONTENT_PART###
37 * @return string
38 */
39 static public function getSubpart($content, $marker) {
40 $start = strpos($content, $marker);
41 if ($start === FALSE) {
42 return '';
43 }
44 $start += strlen($marker);
45 $stop = strpos($content, $marker, $start);
46 // Q: What shall get returned if no stop marker is given
47 // Everything till the end or nothing?
48 if ($stop === FALSE) {
49 return '';
50 }
51 $content = substr($content, $start, $stop - $start);
52 $matches = array();
53 if (preg_match('/^([^\\<]*\\-\\-\\>)(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $content, $matches) === 1) {
54 return $matches[2];
55 }
56 // Resetting $matches
57 $matches = array();
58 if (preg_match('/(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $content, $matches) === 1) {
59 return $matches[1];
60 }
61 // Resetting $matches
62 $matches = array();
63 if (preg_match('/^([^\\<]*\\-\\-\\>)(.*)$/s', $content, $matches) === 1) {
64 return $matches[2];
65 }
66 return $content;
67 }
68
69 /**
70 * Substitutes a subpart in $content with the content of $subpartContent.
71 *
72 * @param string $content Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
73 * @param string $marker Marker string, eg. "###CONTENT_PART###
74 * @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())
75 * @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!
76 * @param boolean $keepMarker If set, the marker around the subpart is not removed, but kept in the output
77 * @return string Processed input content
78 */
79 static public function substituteSubpart($content, $marker, $subpartContent, $recursive = TRUE, $keepMarker = FALSE) {
80 $start = strpos($content, $marker);
81 if ($start === FALSE) {
82 return $content;
83 }
84 $startAM = $start + strlen($marker);
85 $stop = strpos($content, $marker, $startAM);
86 if ($stop === FALSE) {
87 return $content;
88 }
89 $stopAM = $stop + strlen($marker);
90 $before = substr($content, 0, $start);
91 $after = substr($content, $stopAM);
92 $between = substr($content, $startAM, $stop - $startAM);
93 if ($recursive) {
94 $after = self::substituteSubpart($after, $marker, $subpartContent, $recursive, $keepMarker);
95 }
96 if ($keepMarker) {
97 $matches = array();
98 if (preg_match('/^([^\\<]*\\-\\-\\>)(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $between, $matches) === 1) {
99 $before .= $marker . $matches[1];
100 $between = $matches[2];
101 $after = $matches[3] . $marker . $after;
102 } elseif (preg_match('/^(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $between, $matches) === 1) {
103 $before .= $marker;
104 $between = $matches[1];
105 $after = $matches[2] . $marker . $after;
106 } elseif (preg_match('/^([^\\<]*\\-\\-\\>)(.*)$/s', $between, $matches) === 1) {
107 $before .= $marker . $matches[1];
108 $between = $matches[2];
109 $after = $marker . $after;
110 } else {
111 $before .= $marker;
112 $after = $marker . $after;
113 }
114 } else {
115 $matches = array();
116 if (preg_match('/^(.*)\\<\\!\\-\\-[^\\>]*$/s', $before, $matches) === 1) {
117 $before = $matches[1];
118 }
119 if (is_array($subpartContent)) {
120 $matches = array();
121 if (preg_match('/^([^\\<]*\\-\\-\\>)(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $between, $matches) === 1) {
122 $between = $matches[2];
123 } elseif (preg_match('/^(.*)(\\<\\!\\-\\-[^\\>]*)$/s', $between, $matches) === 1) {
124 $between = $matches[1];
125 } elseif (preg_match('/^([^\\<]*\\-\\-\\>)(.*)$/s', $between, $matches) === 1) {
126 $between = $matches[2];
127 }
128 }
129 $matches = array();
130 // resetting $matches
131 if (preg_match('/^[^\\<]*\\-\\-\\>(.*)$/s', $after, $matches) === 1) {
132 $after = $matches[1];
133 }
134 }
135 if (is_array($subpartContent)) {
136 $between = $subpartContent[0] . $between . $subpartContent[1];
137 } else {
138 $between = $subpartContent;
139 }
140 return $before . $between . $after;
141 }
142
143 /**
144 * Substitues multiple subparts at once
145 *
146 * @param string $content The content stream, typically HTML template content.
147 * @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.
148 * @return string The processed HTML content string.
149 */
150 static public function substituteSubpartArray($content, array $subpartsContent) {
151 foreach ($subpartsContent as $subpartMarker => $subpartContent) {
152 $content = self::substituteSubpart($content, $subpartMarker, $subpartContent);
153 }
154 return $content;
155 }
156
157 /**
158 * Substitutes a marker string in the input content
159 * (by a simple str_replace())
160 *
161 * @param string $content The content stream, typically HTML template content.
162 * @param string $marker The marker string, typically on the form "###[the marker string]###
163 * @param mixed $markContent The content to insert instead of the marker string found.
164 * @return string The processed HTML content string.
165 * @see substituteSubpart()
166 */
167 static public function substituteMarker($content, $marker, $markContent) {
168 return str_replace($marker, $markContent, $content);
169 }
170
171 /**
172 * Traverses the input $markContentArray array and for each key the marker
173 * by the same name (possibly wrapped and in upper case) will be
174 * substituted with the keys value in the array. This is very useful if you
175 * have a data-record to substitute in some content. In particular when you
176 * use the $wrap and $uppercase values to pre-process the markers. Eg. a
177 * key name like "myfield" could effectively be represented by the marker
178 * "###MYFIELD###" if the wrap value was "###|###" and the $uppercase
179 * boolean TRUE.
180 *
181 * @param string $content The content stream, typically HTML template content.
182 * @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.
183 * @param string $wrap A wrap value - [part 1] | [part 2] - for the markers before substitution
184 * @param boolean $uppercase If set, all marker string substitution is done with upper-case markers.
185 * @param boolean $deleteUnused If set, all unused marker are deleted.
186 * @return string The processed output stream
187 * @see substituteMarker(), substituteMarkerInObject(), TEMPLATE()
188 */
189 static public function substituteMarkerArray($content, $markContentArray, $wrap = '', $uppercase = FALSE, $deleteUnused = FALSE) {
190 if (is_array($markContentArray)) {
191 $wrapArr = GeneralUtility::trimExplode('|', $wrap);
192 $search = array();
193 $replace = array();
194 foreach ($markContentArray as $marker => $markContent) {
195 if ($uppercase) {
196 // use strtr instead of strtoupper to avoid locale problems with Turkish
197 $marker = strtr($marker, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
198 }
199 if (count($wrapArr) > 0) {
200 $marker = $wrapArr[0] . $marker . $wrapArr[1];
201 }
202 $search[] = $marker;
203 $replace[] = $markContent;
204 }
205 $content = str_replace($search, $replace, $content);
206 unset($search, $replace);
207 if ($deleteUnused) {
208 if (empty($wrap)) {
209 $wrapArr = array('###', '###');
210 }
211 $content = preg_replace('/' . preg_quote($wrapArr[0], '/') . '([A-Z0-9_|\\-]*)' . preg_quote($wrapArr[1], '/') . '/is', '', $content);
212 }
213 }
214 return $content;
215 }
216
217 /**
218 * Replaces all markers and subparts in a template with the content provided in the structured array.
219 *
220 * The array is built like the template with its markers and subparts. Keys represent the marker name and the values the
221 * content.
222 * If the value is not an array the key will be treated as a single marker.
223 * If the value is an array the key will be treated as a subpart marker.
224 * Repeated subpart contents are of course elements in the array, so every subpart value must contain an array with its
225 * markers.
226 *
227 * $markersAndSubparts = array (
228 * '###SINGLEMARKER1###' => 'value 1',
229 * '###SUBPARTMARKER1###' => array(
230 * 0 => array(
231 * '###SINGLEMARKER2###' => 'value 2',
232 * ),
233 * 1 => array(
234 * '###SINGLEMARKER2###' => 'value 3',
235 * )
236 * ),
237 * '###SUBPARTMARKER2###' => array(
238 * ),
239 * )
240 * Subparts can be nested, so below the 'SINGLEMARKER2' it is possible to have another subpart marker with an array as the
241 * value, which in its turn contains the elements of the sub-subparts.
242 * Empty arrays for Subparts will cause the subtemplate to be cleared.
243 *
244 * @static
245 * @param string $content The content stream, typically HTML template content.
246 * @param array $markersAndSubparts The array of single markers and subpart contents.
247 * @param string $wrap A wrap value - [part1] | [part2] - for the markers before substitution.
248 * @param bool $uppercase If set, all marker string substitution is done with upper-case markers.
249 * @param bool $deleteUnused If set, all unused single markers are deleted.
250 * @return string The processed output stream
251 */
252 static public function substituteMarkerAndSubpartArrayRecursive($content, array $markersAndSubparts, $wrap = '', $uppercase = FALSE, $deleteUnused = FALSE) {
253 $wraps = GeneralUtility::trimExplode('|', $wrap);
254 $singleItems = array();
255 $compoundItems = array();
256 // Split markers and subparts into separate arrays
257 foreach ($markersAndSubparts as $markerName => $markerContent) {
258 if (is_array($markerContent)) {
259 $compoundItems[] = $markerName;
260 } else {
261 $singleItems[$markerName] = $markerContent;
262 }
263 }
264 $subTemplates = array();
265 $subpartSubstitutes = array();
266 // Build a cache for the sub template
267 foreach ($compoundItems as $subpartMarker) {
268 if ($uppercase) {
269 // Use strtr instead of strtoupper to avoid locale problems with Turkish
270 $subpartMarker = strtr($subpartMarker, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
271 }
272 if (count($wraps) > 0) {
273 $subpartMarker = $wraps[0] . $subpartMarker . $wraps[1];
274 }
275 $subTemplates[$subpartMarker] = self::getSubpart($content, $subpartMarker);
276 }
277 // Replace the subpart contents recursively
278 foreach ($compoundItems as $subpartMarker) {
279 $completeMarker = $subpartMarker;
280 if ($uppercase) {
281 // use strtr instead of strtoupper to avoid locale problems with Turkish
282 $completeMarker = strtr($completeMarker, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
283 }
284 if (count($wraps) > 0) {
285 $completeMarker = $wraps[0] . $completeMarker . $wraps[1];
286 }
287 if (count($markersAndSubparts[$subpartMarker]) > 0) {
288 foreach ($markersAndSubparts[$subpartMarker] as $partialMarkersAndSubparts) {
289 $subpartSubstitutes[$completeMarker] .= self::substituteMarkerAndSubpartArrayRecursive($subTemplates[$completeMarker],
290 $partialMarkersAndSubparts, $wrap, $uppercase, $deleteUnused);
291 }
292 } else {
293 $subpartSubstitutes[$completeMarker] = '';
294 }
295 }
296 // Substitute the single markers and subparts
297 $result = self::substituteSubpartArray($content, $subpartSubstitutes);
298 $result = self::substituteMarkerArray($result, $singleItems, $wrap, $uppercase, $deleteUnused);
299 return $result;
300 }
301
302 /************************************
303 *
304 * Parsing HTML code
305 *
306 ************************************/
307 /**
308 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
309 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
310 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
311 *
312 * @param string $tag List of tags, comma separated.
313 * @param string $content HTML-content
314 * @param boolean $eliminateExtraEndTags If set, excessive end tags are ignored - you should probably set this in most cases.
315 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
316 * @see splitTags(), getAllParts(), removeFirstAndLastTag()
317 * @todo Define visibility
318 */
319 public function splitIntoBlock($tag, $content, $eliminateExtraEndTags = FALSE) {
320 $tags = array_unique(GeneralUtility::trimExplode(',', $tag, TRUE));
321 foreach ($tags as &$tag) {
322 $tag = preg_quote($tag, '/');
323 }
324 $regexStr = '/\\<\\/?(' . implode('|', $tags) . ')(\\s*\\>|\\s[^\\>]*\\>)/si';
325 $parts = preg_split($regexStr, $content);
326 $newParts = array();
327 $pointer = strlen($parts[0]);
328 $buffer = $parts[0];
329 $nested = 0;
330 reset($parts);
331 next($parts);
332 while (list($k, $v) = each($parts)) {
333 $isEndTag = substr($content, $pointer, 2) == '</' ? 1 : 0;
334 $tagLen = strcspn(substr($content, $pointer), '>') + 1;
335 // We meet a start-tag:
336 if (!$isEndTag) {
337 // Ground level:
338 if (!$nested) {
339 // Previous buffer stored
340 $newParts[] = $buffer;
341 $buffer = '';
342 }
343 // We are inside now!
344 $nested++;
345 // New buffer set and pointer increased
346 $mbuffer = substr($content, $pointer, strlen($v) + $tagLen);
347 $pointer += strlen($mbuffer);
348 $buffer .= $mbuffer;
349 } else {
350 // If we meet an endtag:
351 // Decrease nested-level
352 $nested--;
353 $eliminated = 0;
354 if ($eliminateExtraEndTags && $nested < 0) {
355 $nested = 0;
356 $eliminated = 1;
357 } else {
358 // In any case, add the endtag to current buffer and increase pointer
359 $buffer .= substr($content, $pointer, $tagLen);
360 }
361 $pointer += $tagLen;
362 // if we're back on ground level, (and not by eliminating tags...
363 if (!$nested && !$eliminated) {
364 $newParts[] = $buffer;
365 $buffer = '';
366 }
367 // New buffer set and pointer increased
368 $mbuffer = substr($content, $pointer, strlen($v));
369 $pointer += strlen($mbuffer);
370 $buffer .= $mbuffer;
371 }
372 }
373 $newParts[] = $buffer;
374 return $newParts;
375 }
376
377 /**
378 * Splitting content into blocks *recursively* and processing tags/content with call back functions.
379 *
380 * @param string $tag Tag list, see splitIntoBlock()
381 * @param string $content Content, see splitIntoBlock()
382 * @param object $procObj Object where call back methods are.
383 * @param string $callBackContent Name of call back method for content; "function callBackContent($str,$level)
384 * @param string $callBackTags Name of call back method for tags; "function callBackTags($tags,$level)
385 * @param integer $level Indent level
386 * @return string Processed content
387 * @see splitIntoBlock()
388 * @todo Define visibility
389 */
390 public function splitIntoBlockRecursiveProc($tag, $content, &$procObj, $callBackContent, $callBackTags, $level = 0) {
391 $parts = $this->splitIntoBlock($tag, $content, TRUE);
392 foreach ($parts as $k => $v) {
393 if ($k % 2) {
394 $firstTagName = $this->getFirstTagName($v, TRUE);
395 $tagsArray = array();
396 $tagsArray['tag_start'] = $this->getFirstTag($v);
397 $tagsArray['tag_end'] = '</' . $firstTagName . '>';
398 $tagsArray['tag_name'] = strtolower($firstTagName);
399 $tagsArray['add_level'] = 1;
400 $tagsArray['content'] = $this->splitIntoBlockRecursiveProc($tag, $this->removeFirstAndLastTag($v), $procObj, $callBackContent, $callBackTags, $level + $tagsArray['add_level']);
401 if ($callBackTags) {
402 $tagsArray = $procObj->{$callBackTags}($tagsArray, $level);
403 }
404 $parts[$k] = $tagsArray['tag_start'] . $tagsArray['content'] . $tagsArray['tag_end'];
405 } else {
406 if ($callBackContent) {
407 $parts[$k] = $procObj->{$callBackContent}($parts[$k], $level);
408 }
409 }
410 }
411 return implode('', $parts);
412 }
413
414 /**
415 * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
416 * Even numbers in the array are outside the blocks, Odd numbers are block-content.
417 * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
418 *
419 * @param string $tag List of tags
420 * @param string $content HTML-content
421 * @return array Even numbers in the array are outside the blocks, Odd numbers are block-content.
422 * @see splitIntoBlock(), getAllParts(), removeFirstAndLastTag()
423 * @todo Define visibility
424 */
425 public function splitTags($tag, $content) {
426 $tags = GeneralUtility::trimExplode(',', $tag, TRUE);
427 foreach ($tags as &$tag) {
428 $tag = preg_quote($tag, '/');
429 }
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 while (list($k, $v) = each($parts)) {
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 ? 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 \TYPO3\CMS\Core\Utility\GeneralUtility::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 = $part[0];
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(('/\\<' . preg_quote($tagName, '/') . '(\\s|\\>)/s'), $content)) - 1;
633 $countEnd = count(preg_split(('/\\<\\/' . preg_quote($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(('/\\<' . preg_quote($tagName, '/') . '(\\s|\\>)/s'), $content)) - 1;
650 $countEnd = count(preg_split(('/\\<\\/' . preg_quote($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 while (list(, $tok) = each($tokArr)) {
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 = $tok[0];
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 ((string)$tags[$tagName]['overrideAttribs'] !== '') {
759 $tagParts[1] = $tags[$tagName]['overrideAttribs'];
760 }
761 // Allowed tags
762 if ((string)$tags[$tagName]['allowedAttribs'] !== '') {
763 // No attribs allowed
764 if ((string)$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'] = GeneralUtility::trimExplode(',', strtolower($tags[$tagName]['allowedAttribs']), TRUE));
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 (!isset($tagAttrib[0][$attr]) && (string)$params['default'] !== '') {
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] = (int)$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], (int)$params['range'][0], (int)$params['range'][1]);
812 } else {
813 $tagAttrib[0][$attr] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($tagAttrib[0][$attr], (int)$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 = 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' && (string)$tagAttrib[0][$attr] === '') {
839 unset($tagAttrib[0][$attr]);
840 }
841 if ((string)$params['removeIfEquals'] !== '' && $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 ($tagAttrib[0][$attr][0] === '#') {
846 $prefix = GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL');
847 $tagAttrib[0][$attr] = $prefix . $tagAttrib[0][$attr];
848 if ($params['prefixLocalAnchors'] == 2 && GeneralUtility::isFirstPartOfStr($prefix, GeneralUtility::getIndpEnv('TYPO3_SITE_URL'))) {
849 $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr], strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_URL')));
850 }
851 }
852 }
853 if ($params['prefixRelPathWith']) {
854 $urlParts = parse_url($tagAttrib[0][$attr]);
855 if (!$urlParts['scheme'] && $urlParts['path'][0] !== '/') {
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] = 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 ($tagName !== $lastEl) {
899 if (in_array($tagName, $tagStack)) {
900 while (count($tagStack) && $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 ($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 int $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 $dir = (int)$dir;
976 if ($dir === 1) {
977 $value = htmlspecialchars($value);
978 } elseif ($dir === 2) {
979 $value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8', FALSE);
980 } elseif ($dir === -1) {
981 $value = htmlspecialchars_decode($value);
982 }
983 return $value;
984 }
985
986 /**
987 * Prefixes the relative paths of hrefs/src/action in the tags [td,table,body,img,input,form,link,script,a] in the $content with the $main_prefix or and alternative given by $alternatives
988 *
989 * @param string $main_prefix Prefix string
990 * @param string $content HTML content
991 * @param array $alternatives Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
992 * @param string $suffix Suffix string (put after the resource).
993 * @return string Processed HTML content
994 * @todo Define visibility
995 */
996 public function prefixResourcePath($main_prefix, $content, $alternatives = array(), $suffix = '') {
997 $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a,param', $content);
998 foreach ($parts as $k => $v) {
999 if ($k % 2) {
1000 $params = $this->get_tag_attributes($v);
1001 // Detect tag-ending so that it is re-applied correctly.
1002 $tagEnd = substr($v, -2) == '/>' ? ' />' : '>';
1003 // The 'name' of the first tag
1004 $firstTagName = $this->getFirstTagName($v);
1005 $somethingDone = 0;
1006 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
1007 switch (strtolower($firstTagName)) {
1008 case 'td':
1009
1010 case 'body':
1011
1012 case 'table':
1013 $src = $params[0]['background'];
1014 if ($src) {
1015 $params[0]['background'] = $this->prefixRelPath($prefix, $params[0]['background'], $suffix);
1016 $somethingDone = 1;
1017 }
1018 break;
1019 case 'img':
1020
1021 case 'input':
1022
1023 case 'script':
1024
1025 case 'embed':
1026 $src = $params[0]['src'];
1027 if ($src) {
1028 $params[0]['src'] = $this->prefixRelPath($prefix, $params[0]['src'], $suffix);
1029 $somethingDone = 1;
1030 }
1031 break;
1032 case 'link':
1033
1034 case 'a':
1035 $src = $params[0]['href'];
1036 if ($src) {
1037 $params[0]['href'] = $this->prefixRelPath($prefix, $params[0]['href'], $suffix);
1038 $somethingDone = 1;
1039 }
1040 break;
1041 case 'form':
1042 $src = $params[0]['action'];
1043 if ($src) {
1044 $params[0]['action'] = $this->prefixRelPath($prefix, $params[0]['action'], $suffix);
1045 $somethingDone = 1;
1046 }
1047 break;
1048 case 'param':
1049 $test = $params[0]['name'];
1050 if ($test && $test === 'movie') {
1051 if ($params[0]['value']) {
1052 $params[0]['value'] = $this->prefixRelPath($prefix, $params[0]['value'], $suffix);
1053 $somethingDone = 1;
1054 }
1055 }
1056 break;
1057 }
1058 if ($somethingDone) {
1059 $tagParts = preg_split('/\\s+/s', $v, 2);
1060 $tagParts[1] = $this->compileTagAttribs($params[0], $params[1]);
1061 $parts[$k] = '<' . trim((strtolower($firstTagName) . ' ' . $tagParts[1])) . $tagEnd;
1062 }
1063 }
1064 }
1065 $content = implode('', $parts);
1066 // Fix <style> section:
1067 $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
1068 if (strlen($prefix)) {
1069 $parts = $this->splitIntoBlock('style', $content);
1070 foreach ($parts as $k => &$part) {
1071 if ($k % 2) {
1072 $part = preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $prefix . '\\2' . $suffix . '\\3', $part);
1073 }
1074 }
1075 unset($part);
1076 $content = implode('', $parts);
1077 }
1078 return $content;
1079 }
1080
1081 /**
1082 * Internal sub-function for ->prefixResourcePath()
1083 *
1084 * @param string $prefix Prefix string
1085 * @param string $srcVal Relative path/URL
1086 * @param string $suffix Suffix string
1087 * @return string Output path, prefixed if no scheme in input string
1088 * @access private
1089 * @todo Define visibility
1090 */
1091 public function prefixRelPath($prefix, $srcVal, $suffix = '') {
1092 // Only prefix if it's not an absolute URL or
1093 // only a link to a section within the page.
1094 if ($srcVal[0] !== '/' && $srcVal[0] !== '#') {
1095 $urlParts = parse_url($srcVal);
1096 // Only prefix URLs without a scheme
1097 if (!$urlParts['scheme']) {
1098 $srcVal = $prefix . $srcVal . $suffix;
1099 }
1100 }
1101 return $srcVal;
1102 }
1103
1104 /**
1105 * Cleans up the input $value for fonttags.
1106 * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
1107 *
1108 * @param string HTML content with font-tags inside to clean up.
1109 * @param boolean If set, keep "face" attribute
1110 * @param boolean If set, keep "size" attribute
1111 * @param boolean If set, keep "color" attribute
1112 * @return string Processed HTML content
1113 * @todo Define visibility
1114 */
1115 public function cleanFontTags($value, $keepFace = 0, $keepSize = 0, $keepColor = 0) {
1116 // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
1117 $fontSplit = $this->splitIntoBlock('font', $value);
1118 foreach ($fontSplit as $k => $v) {
1119 // Font
1120 if ($k % 2) {
1121 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v));
1122 $newAttribs = array();
1123 if ($keepFace && $attribArray['face']) {
1124 $newAttribs[] = 'face="' . $attribArray['face'] . '"';
1125 }
1126 if ($keepSize && $attribArray['size']) {
1127 $newAttribs[] = 'size="' . $attribArray['size'] . '"';
1128 }
1129 if ($keepColor && $attribArray['color']) {
1130 $newAttribs[] = 'color="' . $attribArray['color'] . '"';
1131 }
1132 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v), $keepFace, $keepSize, $keepColor);
1133 if (count($newAttribs)) {
1134 $fontSplit[$k] = '<font ' . implode(' ', $newAttribs) . '>' . $innerContent . '</font>';
1135 } else {
1136 $fontSplit[$k] = $innerContent;
1137 }
1138 }
1139 }
1140 return implode('', $fontSplit);
1141 }
1142
1143 /**
1144 * This is used to map certain tag-names into other names.
1145 *
1146 * @param string $value HTML content
1147 * @param array $tags Array with tag key=>value pairs where key is from-tag and value is to-tag
1148 * @param string $ltChar Alternative less-than char to search for (search regex string)
1149 * @param string $ltChar2 Alternative less-than char to replace with (replace regex string)
1150 * @return string Processed HTML content
1151 * @todo Define visibility
1152 */
1153 public function mapTags($value, $tags = array(), $ltChar = '<', $ltChar2 = '<') {
1154 foreach ($tags as $from => $to) {
1155 $value = preg_replace('/' . preg_quote($ltChar, '/') . '(\\/)?' . $from . '\\s([^\\>])*(\\/)?\\>/', $ltChar2 . '$1' . $to . ' $2$3>', $value);
1156 }
1157 return $value;
1158 }
1159
1160 /**
1161 * This converts htmlspecialchar()'ed tags (from $tagList) back to real tags. Eg. '&lt;strong&gt' would be converted back to '<strong>' if found in $tagList
1162 *
1163 * @param string $content HTML content
1164 * @param string $tagList Tag list, separated by comma. Lowercase!
1165 * @return string Processed HTML content
1166 * @todo Define visibility
1167 */
1168 public function unprotectTags($content, $tagList = '') {
1169 $tagsArray = GeneralUtility::trimExplode(',', $tagList, TRUE);
1170 $contentParts = explode('&lt;', $content);
1171 next($contentParts);
1172 // bypass the first
1173 while (list($k, $tok) = each($contentParts)) {
1174 $firstChar = $tok[0];
1175 if (trim($firstChar) !== '') {
1176 $subparts = explode('&gt;', $tok, 2);
1177 $tagEnd = strlen($subparts[0]);
1178 if (strlen($tok) != $tagEnd) {
1179 $endTag = $firstChar == '/' ? 1 : 0;
1180 $tagContent = substr($tok, $endTag, $tagEnd - $endTag);
1181 $tagParts = preg_split('/\\s+/s', $tagContent, 2);
1182 $tagName = strtolower($tagParts[0]);
1183 if ((string)$tagList === '' || in_array($tagName, $tagsArray)) {
1184 $contentParts[$k] = '<' . $subparts[0] . '>' . $subparts[1];
1185 } else {
1186 $contentParts[$k] = '&lt;' . $tok;
1187 }
1188 } else {
1189 $contentParts[$k] = '&lt;' . $tok;
1190 }
1191 } else {
1192 $contentParts[$k] = '&lt;' . $tok;
1193 }
1194 }
1195 return implode('', $contentParts);
1196 }
1197
1198 /**
1199 * Internal function for case shifting of a string or whole array
1200 *
1201 * @param mixed $str Input string/array
1202 * @param boolean $flag If $str is a string AND this boolean(caseSensitive) is FALSE, the string is returned in uppercase
1203 * @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.
1204 * @return string Output string, processed
1205 * @access private
1206 * @todo Define visibility
1207 */
1208 public function caseShift($str, $flag, $cacheKey = '') {
1209 $cacheKey .= $flag ? 1 : 0;
1210 if (is_array($str)) {
1211 if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey])) {
1212 foreach ($str as &$v) {
1213 if (!$flag) {
1214 $v = strtoupper($v);
1215 }
1216 }
1217 unset($v);
1218 if ($cacheKey) {
1219 $this->caseShift_cache[$cacheKey] = $str;
1220 }
1221 } else {
1222 $str = $this->caseShift_cache[$cacheKey];
1223 }
1224 } elseif (!$flag) {
1225 $str = strtoupper($str);
1226 }
1227 return $str;
1228 }
1229
1230 /**
1231 * Compiling an array with tag attributes into a string
1232 *
1233 * @param array $tagAttrib Tag attributes
1234 * @param array $meta Meta information about these attributes (like if they were quoted)
1235 * @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
1236 * @return string Imploded attributes, eg: 'attribute="value" attrib2="value2"'
1237 * @access private
1238 * @todo Define visibility
1239 */
1240 public function compileTagAttribs($tagAttrib, $meta = array(), $xhtmlClean = 0) {
1241 $accu = array();
1242 foreach ($tagAttrib as $k => $v) {
1243 if ($xhtmlClean) {
1244 $attr = strtolower($k);
1245 if ((string)$v !== '' || isset($meta[$k]['dashType'])) {
1246 $attr .= '="' . htmlspecialchars($v) . '"';
1247 }
1248 } else {
1249 $attr = $meta[$k]['origTag'] ?: $k;
1250 if (strcmp($v, '') || isset($meta[$k]['dashType'])) {
1251 $dash = $meta[$k]['dashType'] ?: (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($v) ? '' : '"');
1252 $attr .= '=' . $dash . $v . $dash;
1253 }
1254 }
1255 $accu[] = $attr;
1256 }
1257 return implode(' ', $accu);
1258 }
1259
1260 /**
1261 * Get tag attributes, the classic version (which had some limitations?)
1262 *
1263 * @param string $tag The tag
1264 * @param boolean $deHSC De-htmlspecialchar flag.
1265 * @return array
1266 * @access private
1267 * @todo Define visibility
1268 */
1269 public function get_tag_attributes_classic($tag, $deHSC = 0) {
1270 $attr = $this->get_tag_attributes($tag, $deHSC);
1271 return is_array($attr[0]) ? $attr[0] : array();
1272 }
1273
1274 /**
1275 * Indents input content with $number instances of $indentChar
1276 *
1277 * @param string $content Content string, multiple lines.
1278 * @param integer $number Number of indents
1279 * @param string $indentChar Indent character/string
1280 * @return strin Indented code (typ. HTML)
1281 * @todo Define visibility
1282 */
1283 public function indentLines($content, $number = 1, $indentChar = TAB) {
1284 $preTab = str_pad('', $number * strlen($indentChar), $indentChar);
1285 $lines = explode(LF, str_replace(CR, '', $content));
1286 foreach ($lines as &$line) {
1287 $line = $preTab . $line;
1288 }
1289 unset($line);
1290 return implode(LF, $lines);
1291 }
1292
1293 /**
1294 * Converts TSconfig into an array for the HTMLcleaner function.
1295 *
1296 * @param array $TSconfig TSconfig for HTMLcleaner
1297 * @param array $keepTags Array of tags to keep (?)
1298 * @return array
1299 * @access private
1300 * @todo Define visibility
1301 */
1302 public function HTMLparserConfig($TSconfig, $keepTags = array()) {
1303 // Allow tags (base list, merged with incoming array)
1304 $alTags = array_flip(GeneralUtility::trimExplode(',', strtolower($TSconfig['allowTags']), TRUE));
1305 $keepTags = array_merge($alTags, $keepTags);
1306 // Set config properties.
1307 if (is_array($TSconfig['tags.'])) {
1308 foreach ($TSconfig['tags.'] as $key => $tagC) {
1309 if (!is_array($tagC) && $key == strtolower($key)) {
1310 if ((string)$tagC === '0') {
1311 unset($keepTags[$key]);
1312 }
1313 if ((string)$tagC === '1' && !isset($keepTags[$key])) {
1314 $keepTags[$key] = 1;
1315 }
1316 }
1317 }
1318 foreach ($TSconfig['tags.'] as $key => $tagC) {
1319 if (is_array($tagC) && $key == strtolower($key)) {
1320 $key = substr($key, 0, -1);
1321 if (!is_array($keepTags[$key])) {
1322 $keepTags[$key] = array();
1323 }
1324 if (is_array($tagC['fixAttrib.'])) {
1325 foreach ($tagC['fixAttrib.'] as $atName => $atConfig) {
1326 if (is_array($atConfig)) {
1327 $atName = substr($atName, 0, -1);
1328 if (!is_array($keepTags[$key]['fixAttrib'][$atName])) {
1329 $keepTags[$key]['fixAttrib'][$atName] = array();
1330 }
1331 $keepTags[$key]['fixAttrib'][$atName] = array_merge($keepTags[$key]['fixAttrib'][$atName], $atConfig);
1332 // Candidate for \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge() if integer-keys will some day make trouble...
1333 if ((string)$keepTags[$key]['fixAttrib'][$atName]['range'] !== '') {
1334 $keepTags[$key]['fixAttrib'][$atName]['range'] = GeneralUtility::trimExplode(',', $keepTags[$key]['fixAttrib'][$atName]['range']);
1335 }
1336 if ((string)$keepTags[$key]['fixAttrib'][$atName]['list'] !== '') {
1337 $keepTags[$key]['fixAttrib'][$atName]['list'] = GeneralUtility::trimExplode(',', $keepTags[$key]['fixAttrib'][$atName]['list']);
1338 }
1339 }
1340 }
1341 }
1342 unset($tagC['fixAttrib.']);
1343 unset($tagC['fixAttrib']);
1344 // Candidate for \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge() if integer-keys will some day make trouble...
1345 $keepTags[$key] = array_merge($keepTags[$key], $tagC);
1346 }
1347 }
1348 }
1349 // LocalNesting
1350 if ($TSconfig['localNesting']) {
1351 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['localNesting']), TRUE);
1352 foreach ($lN as $tn) {
1353 if (isset($keepTags[$tn])) {
1354 $keepTags[$tn]['nesting'] = 1;
1355 }
1356 }
1357 }
1358 if ($TSconfig['globalNesting']) {
1359 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['globalNesting']), TRUE);
1360 foreach ($lN as $tn) {
1361 if (isset($keepTags[$tn])) {
1362 if (!is_array($keepTags[$tn])) {
1363 $keepTags[$tn] = array();
1364 }
1365 $keepTags[$tn]['nesting'] = 'global';
1366 }
1367 }
1368 }
1369 if ($TSconfig['rmTagIfNoAttrib']) {
1370 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['rmTagIfNoAttrib']), TRUE);
1371 foreach ($lN as $tn) {
1372 if (isset($keepTags[$tn])) {
1373 if (!is_array($keepTags[$tn])) {
1374 $keepTags[$tn] = array();
1375 }
1376 $keepTags[$tn]['rmTagIfNoAttrib'] = 1;
1377 }
1378 }
1379 }
1380 if ($TSconfig['noAttrib']) {
1381 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['noAttrib']), TRUE);
1382 foreach ($lN as $tn) {
1383 if (isset($keepTags[$tn])) {
1384 if (!is_array($keepTags[$tn])) {
1385 $keepTags[$tn] = array();
1386 }
1387 $keepTags[$tn]['allowedAttribs'] = 0;
1388 }
1389 }
1390 }
1391 if ($TSconfig['removeTags']) {
1392 $lN = GeneralUtility::trimExplode(',', strtolower($TSconfig['removeTags']), TRUE);
1393 foreach ($lN as $tn) {
1394 $keepTags[$tn] = array();
1395 $keepTags[$tn]['allowedAttribs'] = 0;
1396 $keepTags[$tn]['rmTagIfNoAttrib'] = 1;
1397 }
1398 }
1399 // Create additional configuration:
1400 $addConfig = array();
1401 if ($TSconfig['xhtml_cleaning']) {
1402 $addConfig['xhtml'] = 1;
1403 }
1404 return array(
1405 $keepTags,
1406 '' . $TSconfig['keepNonMatchedTags'],
1407 (int)$TSconfig['htmlSpecialChars'],
1408 $addConfig
1409 );
1410 }
1411
1412 /**
1413 * Tries to convert the content to be XHTML compliant and other stuff like that.
1414 * STILL EXPERIMENTAL. See comments below.
1415 *
1416 * What it does NOT do (yet) according to XHTML specs.:
1417 * - Wellformedness: Nesting is NOT checked
1418 * - name/id attribute issue is not observed at this point.
1419 * - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
1420 * - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
1421 * - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
1422 * - UTF-8 encoding is in fact expected by XML!!
1423 * - stylesheet element and attribute names are NOT converted to lowercase
1424 * - 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.
1425 * - Minimized values not allowed: Must do this: selected="selected"
1426 *
1427 * What it does at this point:
1428 * - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
1429 * - Lowercase for elements and attributes
1430 * - All attributes in quotes
1431 * - Add "alt" attribute to img-tags if it's not there already.
1432 *
1433 * @param string $content Content to clean up
1434 * @return string Cleaned up content returned.
1435 * @access private
1436 * @todo Define visibility
1437 */
1438 public function XHTML_clean($content) {
1439 $content = $this->HTMLcleaner($content, array(), 1, 0, array('xhtml' => 1));
1440 return $content;
1441 }
1442
1443 /**
1444 * Processing all tags themselves
1445 * (Some additions by Sacha Vorbeck)
1446 *
1447 * @param string Tag to process
1448 * @param array Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
1449 * @param boolean Is endtag, then set this.
1450 * @param boolean If set, just return value straight away
1451 * @return string Processed value.
1452 * @access private
1453 * @todo Define visibility
1454 */
1455 public function processTag($value, $conf, $endTag, $protected = 0) {
1456 // Return immediately if protected or no parameters
1457 if ($protected || !count($conf)) {
1458 return $value;
1459 }
1460 // OK then, begin processing for XHTML output:
1461 // STILL VERY EXPERIMENTAL!!
1462 if ($conf['xhtml']) {
1463 // Endtags are just set lowercase right away
1464 if ($endTag) {
1465 $value = strtolower($value);
1466 } elseif (substr($value, 0, 4) != '<!--') {
1467 // ... and comments are ignored.
1468 // Finding inner value with out < >
1469 $inValue = substr($value, 1, substr($value, -2) == '/>' ? -2 : -1);
1470 // Separate attributes and tagname
1471 list($tagName, $tagP) = preg_split('/\\s+/s', $inValue, 2);
1472 $tagName = strtolower($tagName);
1473 // Process attributes
1474 $tagAttrib = $this->get_tag_attributes($tagP);
1475 if ($tagName === 'img' && !isset($tagAttrib[0]['alt'])) {
1476 $tagAttrib[0]['alt'] = '';
1477 }
1478 // Set alt attribute for all images (not XHTML though...)
1479 if ($tagName === 'script' && !isset($tagAttrib[0]['type'])) {
1480 $tagAttrib[0]['type'] = 'text/javascript';
1481 }
1482 // Set type attribute for all script-tags
1483 $outA = array();
1484 foreach ($tagAttrib[0] as $attrib_name => $attrib_value) {
1485 // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
1486 $outA[] = $attrib_name . '="' . $this->bidir_htmlspecialchars($attrib_value, 2) . '"';
1487 }
1488 $newTag = '<' . trim(($tagName . ' ' . implode(' ', $outA)));
1489 // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
1490 if (GeneralUtility::inList('img,br,hr,meta,link,base,area,input,param,col', $tagName) || substr($value, -2) == '/>') {
1491 $newTag .= ' />';
1492 } else {
1493 $newTag .= '>';
1494 }
1495 $value = $newTag;
1496 }
1497 }
1498 return $value;
1499 }
1500
1501 /**
1502 * Processing content between tags for HTML_cleaner
1503 *
1504 * @param string $value The value
1505 * @param integer $dir Direction, either -1 or +1. 0 (zero) means no change to input value.
1506 * @param mixed $conf Not used, ignore.
1507 * @return string The processed value.
1508 * @access private
1509 * @todo Define visibility
1510 */
1511 public function processContent($value, $dir, $conf) {
1512 if ($dir != 0) {
1513 $value = $this->bidir_htmlspecialchars($value, $dir);
1514 }
1515 return $value;
1516 }
1517
1518 }