[BUGFIX] Prevent XSS in ViewHelpers
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / ViewHelpers / Format / HtmlentitiesViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers\Format;
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\SingletonInterface;
18
19 /**
20 * Applies htmlentities() escaping to a value
21 * @see http://www.php.net/manual/function.htmlentities.php
22 *
23 * = Examples =
24 *
25 * <code title="default notation">
26 * <f:format.htmlentities>{text}</f:format.htmlentities>
27 * </code>
28 * <output>
29 * Text with & " ' < > * replaced by HTML entities (htmlentities applied).
30 * </output>
31 *
32 * <code title="inline notation">
33 * {text -> f:format.htmlentities(encoding: 'ISO-8859-1')}
34 * </code>
35 * <output>
36 * Text with & " ' < > * replaced by HTML entities (htmlentities applied).
37 * </output>
38 *
39 * @api
40 */
41 class HtmlentitiesViewHelper extends AbstractEncodingViewHelper implements SingletonInterface
42 {
43 /**
44 * Output gets encoded by this viewhelper
45 *
46 * @var bool
47 */
48 protected $escapeOutput = false;
49
50 /**
51 * This prevents double encoding as the whole output gets encoded at the end
52 *
53 * @var bool
54 */
55 protected $escapeChildren = false;
56
57 /**
58 * Escapes special characters with their escaped counterparts as needed using PHPs htmlentities() function.
59 *
60 * @param string $value string to format
61 * @param bool $keepQuotes if TRUE, single and double quotes won't be replaced (sets ENT_NOQUOTES flag)
62 * @param string $encoding
63 * @param bool $doubleEncode If FALSE existing html entities won't be encoded, the default is to convert everything.
64 * @return string the altered string
65 * @see http://www.php.net/manual/function.htmlentities.php
66 * @api
67 */
68 public function render($value = null, $keepQuotes = false, $encoding = null, $doubleEncode = true)
69 {
70 if ($value === null) {
71 $value = $this->renderChildren();
72 }
73 if (!is_string($value)) {
74 return $value;
75 }
76 if ($encoding === null) {
77 $encoding = self::resolveDefaultEncoding();
78 }
79 $flags = $keepQuotes ? ENT_NOQUOTES : ENT_COMPAT;
80 return htmlentities($value, $flags, $encoding, $doubleEncode);
81 }
82 }