e68e32b05d5cc4126f9a3a9ccce1b06e995e3da9
[yaffs-website] / vendor / zendframework / zend-escaper / src / Escaper.php
1 <?php
2 /**
3  * Zend Framework (http://framework.zend.com/)
4  *
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
8  */
9
10 namespace Zend\Escaper;
11
12 /**
13  * Context specific methods for use in secure output escaping
14  */
15 class Escaper
16 {
17     /**
18      * Entity Map mapping Unicode codepoints to any available named HTML entities.
19      *
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
24      *
25      * @var array
26      */
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
32     ];
33
34     /**
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.
37      *
38      * @var string
39      */
40     protected $encoding = 'utf-8';
41
42     /**
43      * Holds the value of the special flags passed as second parameter to
44      * htmlspecialchars().
45      *
46      * @var int
47      */
48     protected $htmlSpecialCharsFlags;
49
50     /**
51      * Static Matcher which escapes characters for HTML Attribute contexts
52      *
53      * @var callable
54      */
55     protected $htmlAttrMatcher;
56
57     /**
58      * Static Matcher which escapes characters for Javascript contexts
59      *
60      * @var callable
61      */
62     protected $jsMatcher;
63
64     /**
65      * Static Matcher which escapes characters for CSS Attribute contexts
66      *
67      * @var callable
68      */
69     protected $cssMatcher;
70
71     /**
72      * List of all encoding supported by this class
73      *
74      * @var array
75      */
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'
86     ];
87
88     /**
89      * Constructor: Single parameter allows setting of global encoding for use by
90      * the current object.
91      *
92      * @param string $encoding
93      * @throws Exception\InvalidArgumentException
94      */
95     public function __construct($encoding = null)
96     {
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'
102                 );
103             }
104
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()'
110                 );
111             }
112
113             $this->encoding = $encoding;
114         }
115
116         // We take advantage of ENT_SUBSTITUTE flag to correctly deal with invalid UTF-8 sequences.
117         $this->htmlSpecialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE;
118
119         // set matcher callbacks
120         $this->htmlAttrMatcher = [$this, 'htmlAttrMatcher'];
121         $this->jsMatcher       = [$this, 'jsMatcher'];
122         $this->cssMatcher      = [$this, 'cssMatcher'];
123     }
124
125     /**
126      * Return the encoding that all output/input is expected to be encoded in.
127      *
128      * @return string
129      */
130     public function getEncoding()
131     {
132         return $this->encoding;
133     }
134
135     /**
136      * Escape a string for the HTML Body context where there are very few characters
137      * of special meaning. Internally this will use htmlspecialchars().
138      *
139      * @param string $string
140      * @return string
141      */
142     public function escapeHtml($string)
143     {
144         return htmlspecialchars($string, $this->htmlSpecialCharsFlags, $this->encoding);
145     }
146
147     /**
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).
151      *
152      * @param string $string
153      * @return string
154      */
155     public function escapeHtmlAttr($string)
156     {
157         $string = $this->toUtf8($string);
158         if ($string === '' || ctype_digit($string)) {
159             return $string;
160         }
161
162         $result = preg_replace_callback('/[^a-z0-9,\.\-_]/iSu', $this->htmlAttrMatcher, $string);
163         return $this->fromUtf8($result);
164     }
165
166     /**
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.
174      *
175      * @param string $string
176      * @return string
177      */
178     public function escapeJs($string)
179     {
180         $string = $this->toUtf8($string);
181         if ($string === '' || ctype_digit($string)) {
182             return $string;
183         }
184
185         $result = preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string);
186         return $this->fromUtf8($result);
187     }
188
189     /**
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.
193      *
194      * @param string $string
195      * @return string
196      */
197     public function escapeUrl($string)
198     {
199         return rawurlencode($string);
200     }
201
202     /**
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.
205      *
206      * @param string $string
207      * @return string
208      */
209     public function escapeCss($string)
210     {
211         $string = $this->toUtf8($string);
212         if ($string === '' || ctype_digit($string)) {
213             return $string;
214         }
215
216         $result = preg_replace_callback('/[^a-z0-9]/iSu', $this->cssMatcher, $string);
217         return $this->fromUtf8($result);
218     }
219
220     /**
221      * Callback function for preg_replace_callback that applies HTML Attribute
222      * escaping to all matches.
223      *
224      * @param array $matches
225      * @return string
226      */
227     protected function htmlAttrMatcher($matches)
228     {
229         $chr = $matches[0];
230         $ord = ord($chr);
231
232         /**
233          * The following replaces characters undefined in HTML with the
234          * hex entity for the Unicode replacement character.
235          */
236         if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r")
237             || ($ord >= 0x7f && $ord <= 0x9f)
238         ) {
239             return '&#xFFFD;';
240         }
241
242         /**
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.
245          */
246         if (strlen($chr) > 1) {
247             $chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
248         }
249
250         $hex = bin2hex($chr);
251         $ord = hexdec($hex);
252         if (isset(static::$htmlNamedEntityMap[$ord])) {
253             return '&' . static::$htmlNamedEntityMap[$ord] . ';';
254         }
255
256         /**
257          * Per OWASP recommendations, we'll use upper hex entities
258          * for any other characters where a named entity does not exist.
259          */
260         if ($ord > 255) {
261             return sprintf('&#x%04X;', $ord);
262         }
263         return sprintf('&#x%02X;', $ord);
264     }
265
266     /**
267      * Callback function for preg_replace_callback that applies Javascript
268      * escaping to all matches.
269      *
270      * @param array $matches
271      * @return string
272      */
273     protected function jsMatcher($matches)
274     {
275         $chr = $matches[0];
276         if (strlen($chr) == 1) {
277             return sprintf('\\x%02X', ord($chr));
278         }
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);
283         }
284         $highSurrogate = substr($hex, 0, 4);
285         $lowSurrogate = substr($hex, 4, 4);
286         return sprintf('\\u%04s\\u%04s', $highSurrogate, $lowSurrogate);
287     }
288
289     /**
290      * Callback function for preg_replace_callback that applies CSS
291      * escaping to all matches.
292      *
293      * @param array $matches
294      * @return string
295      */
296     protected function cssMatcher($matches)
297     {
298         $chr = $matches[0];
299         if (strlen($chr) == 1) {
300             $ord = ord($chr);
301         } else {
302             $chr = $this->convertEncoding($chr, 'UTF-32BE', 'UTF-8');
303             $ord = hexdec(bin2hex($chr));
304         }
305         return sprintf('\\%X ', $ord);
306     }
307
308     /**
309      * Converts a string to UTF-8 from the base encoding. The base encoding is set via this
310      * class' constructor.
311      *
312      * @param string $string
313      * @throws Exception\RuntimeException
314      * @return string
315      */
316     protected function toUtf8($string)
317     {
318         if ($this->getEncoding() === 'utf-8') {
319             $result = $string;
320         } else {
321             $result = $this->convertEncoding($string, 'UTF-8', $this->getEncoding());
322         }
323
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)
327             );
328         }
329
330         return $result;
331     }
332
333     /**
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
337      * @return string
338      */
339     protected function fromUtf8($string)
340     {
341         if ($this->getEncoding() === 'utf-8') {
342             return $string;
343         }
344
345         return $this->convertEncoding($string, $this->getEncoding(), 'UTF-8');
346     }
347
348     /**
349      * Checks if a given string appears to be valid UTF-8 or not.
350      *
351      * @param string $string
352      * @return bool
353      */
354     protected function isUtf8($string)
355     {
356         return ($string === '' || preg_match('/^./su', $string));
357     }
358
359     /**
360      * Encoding conversion helper which wraps iconv and mbstring where they exist or throws
361      * and exception where neither is available.
362      *
363      * @param string $string
364      * @param string $to
365      * @param array|string $from
366      * @throws Exception\RuntimeException
367      * @return string
368      */
369     protected function convertEncoding($string, $to, $from)
370     {
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);
375         } else {
376             throw new Exception\RuntimeException(
377                 get_class($this)
378                 . ' requires either the iconv or mbstring extension to be installed'
379                 . ' when escaping for non UTF-8 strings.'
380             );
381         }
382
383         if ($result === false) {
384             return ''; // return non-fatal blank string on encoding errors from users
385         }
386         return $result;
387     }
388 }