3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Escaper;
13 * Context specific methods for use in secure output escaping
18 * Entity Map mapping Unicode codepoints to any available named HTML entities.
20 * While HTML supports far more named entities, the lowest common denominator
21 * has become HTML5's XML Serialisation which is restricted to the those named
22 * entities that XML supports. Using HTML entities would result in this error:
23 * XML Parsing Error: undefined entity
27 protected static $htmlNamedEntityMap = [
28 34 => 'quot', // quotation mark
29 38 => 'amp', // ampersand
30 60 => 'lt', // less-than sign
31 62 => 'gt', // greater-than sign
35 * Current encoding for escaping. If not UTF-8, we convert strings from this encoding
36 * pre-escaping and back to this encoding post-escaping.
40 protected $encoding = 'utf-8';
43 * Holds the value of the special flags passed as second parameter to
48 protected $htmlSpecialCharsFlags;
51 * Static Matcher which escapes characters for HTML Attribute contexts
55 protected $htmlAttrMatcher;
58 * Static Matcher which escapes characters for Javascript contexts
65 * Static Matcher which escapes characters for CSS Attribute contexts
69 protected $cssMatcher;
72 * List of all encoding supported by this class
76 protected $supportedEncodings = [
77 'iso-8859-1', 'iso8859-1', 'iso-8859-5', 'iso8859-5',
78 'iso-8859-15', 'iso8859-15', 'utf-8', 'cp866',
79 'ibm866', '866', 'cp1251', 'windows-1251',
80 'win-1251', '1251', 'cp1252', 'windows-1252',
81 '1252', 'koi8-r', 'koi8-ru', 'koi8r',
82 'big5', '950', 'gb2312', '936',
83 'big5-hkscs', 'shift_jis', 'sjis', 'sjis-win',
84 'cp932', '932', 'euc-jp', 'eucjp',
85 'eucjp-win', 'macroman'
89 * Constructor: Single parameter allows setting of global encoding for use by
92 * @param string $encoding
93 * @throws Exception\InvalidArgumentException
95 public function __construct($encoding = null)
97 if ($encoding !== null) {
98 $encoding = (string) $encoding;
99 if ($encoding === '') {
100 throw new Exception\InvalidArgumentException(
101 get_class($this) . ' constructor parameter does not allow a blank value'
105 $encoding = strtolower($encoding);
106 if (!in_array($encoding, $this->supportedEncodings)) {
107 throw new Exception\InvalidArgumentException(
108 'Value of \'' . $encoding . '\' passed to ' . get_class($this)
109 . ' constructor parameter is invalid. Provide an encoding supported by htmlspecialchars()'
113 $this->encoding = $encoding;
116 // We take advantage of ENT_SUBSTITUTE flag to correctly deal with invalid UTF-8 sequences.
117 $this->htmlSpecialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE;
119 // set matcher callbacks
120 $this->htmlAttrMatcher = [$this, 'htmlAttrMatcher'];
121 $this->jsMatcher = [$this, 'jsMatcher'];
122 $this->cssMatcher = [$this, 'cssMatcher'];
126 * Return the encoding that all output/input is expected to be encoded in.
130 public function getEncoding()
132 return $this->encoding;
136 * Escape a string for the HTML Body context where there are very few characters
137 * of special meaning. Internally this will use htmlspecialchars().
139 * @param string $string
142 public function escapeHtml($string)
144 return htmlspecialchars($string, $this->htmlSpecialCharsFlags, $this->encoding);
148 * Escape a string for the HTML Attribute context. We use an extended set of characters
149 * to escape that are not covered by htmlspecialchars() to cover cases where an attribute
150 * might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE).
152 * @param string $string
155 public function escapeHtmlAttr($string)
157 $string = $this->toUtf8($string);
158 if ($string === '' || ctype_digit($string)) {
162 $result = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $this->htmlAttrMatcher, $string);
163 return $this->fromUtf8($result);
167 * Escape a string for the Javascript context. This does not use json_encode(). An extended
168 * set of characters are escaped beyond ECMAScript's rules for Javascript literal string
169 * escaping in order to prevent misinterpretation of Javascript as HTML leading to the
170 * injection of special characters and entities. The escaping used should be tolerant
171 * of cases where HTML escaping was not applied on top of Javascript escaping correctly.
172 * Backslash escaping is not used as it still leaves the escaped character as-is and so
173 * is not useful in a HTML context.
175 * @param string $string
178 public function escapeJs($string)
180 $string = $this->toUtf8($string);
181 if ($string === '' || ctype_digit($string)) {
185 $result = preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string);
186 return $this->fromUtf8($result);
190 * Escape a string for the URI or Parameter contexts. This should not be used to escape
191 * an entire URI - only a subcomponent being inserted. The function is a simple proxy
192 * to rawurlencode() which now implements RFC 3986 since PHP 5.3 completely.
194 * @param string $string
197 public function escapeUrl($string)
199 return rawurlencode($string);
203 * Escape a string for the CSS context. CSS escaping can be applied to any string being
204 * inserted into CSS and escapes everything except alphanumerics.
206 * @param string $string
209 public function escapeCss($string)
211 $string = $this->toUtf8($string);
212 if ($string === '' || ctype_digit($string)) {
216 $result = preg_replace_callback('/[^a-z0-9]/iSu', $this->cssMatcher, $string);
217 return $this->fromUtf8($result);
221 * Callback function for preg_replace_callback that applies HTML Attribute
222 * escaping to all matches.
224 * @param array $matches
227 protected function htmlAttrMatcher($matches)
233 * The following replaces characters undefined in HTML with the
234 * hex entity for the Unicode replacement character.
236 if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r")
237 || ($ord >= 0x7f && $ord <= 0x9f)
243 * Check if the current character to escape has a name entity we should
244 * replace it with while grabbing the integer value of the character.
246 if (strlen($chr) > 1) {
247 $chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
250 $hex = bin2hex($chr);
252 if (isset(static::$htmlNamedEntityMap[$ord])) {
253 return '&' . static::$htmlNamedEntityMap[$ord] . ';';
257 * Per OWASP recommendations, we'll use upper hex entities
258 * for any other characters where a named entity does not exist.
261 return sprintf('&#x%04X;', $ord);
263 return sprintf('&#x%02X;', $ord);
267 * Callback function for preg_replace_callback that applies Javascript
268 * escaping to all matches.
270 * @param array $matches
273 protected function jsMatcher($matches)
276 if (strlen($chr) == 1) {
277 return sprintf('\\x%02X', ord($chr));
279 $chr = $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8');
280 $hex = strtoupper(bin2hex($chr));
281 if (strlen($hex) <= 4) {
282 return sprintf('\\u%04s', $hex);
284 $highSurrogate = substr($hex, 0, 4);
285 $lowSurrogate = substr($hex, 4, 4);
286 return sprintf('\\u%04s\\u%04s', $highSurrogate, $lowSurrogate);
290 * Callback function for preg_replace_callback that applies CSS
291 * escaping to all matches.
293 * @param array $matches
296 protected function cssMatcher($matches)
299 if (strlen($chr) == 1) {
302 $chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
303 $ord = hexdec(bin2hex($chr));
305 return sprintf('\\%X ', $ord);
309 * Converts a string to UTF-8 from the base encoding. The base encoding is set via this
310 * class' constructor.
312 * @param string $string
313 * @throws Exception\RuntimeException
316 protected function toUtf8($string)
318 if ($this->getEncoding() === 'utf-8') {
321 $result = $this->convertEncoding($string, 'UTF-8', $this->getEncoding());
324 if (!$this->isUtf8($result)) {
325 throw new Exception\RuntimeException(
326 sprintf('String to be escaped was not valid UTF-8 or could not be converted: %s', $result)
334 * Converts a string from UTF-8 to the base encoding. The base encoding is set via this
335 * class' constructor.
336 * @param string $string
339 protected function fromUtf8($string)
341 if ($this->getEncoding() === 'utf-8') {
345 return $this->convertEncoding($string, $this->getEncoding(), 'UTF-8');
349 * Checks if a given string appears to be valid UTF-8 or not.
351 * @param string $string
354 protected function isUtf8($string)
356 return ($string === '' || preg_match('/^./su', $string));
360 * Encoding conversion helper which wraps iconv and mbstring where they exist or throws
361 * and exception where neither is available.
363 * @param string $string
365 * @param array|string $from
366 * @throws Exception\RuntimeException
369 protected function convertEncoding($string, $to, $from)
371 if (function_exists('iconv')) {
372 $result = iconv($from, $to, $string);
373 } elseif (function_exists('mb_convert_encoding')) {
374 $result = mb_convert_encoding($string, $to, $from);
376 throw new Exception\RuntimeException(
378 . ' requires either the iconv or mbstring extension to be installed'
379 . ' when escaping for non UTF-8 strings.'
383 if ($result === false) {
384 return ''; // return non-fatal blank string on encoding errors from users