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