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