]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-formatting.php
Properly (hopefully?) encoding URL before they get sanitized. See issue 1299. Please...
[Github/YOURLS.git] / includes / functions-formatting.php
1 <?php\r
2 /*\r
3  * YOURLS\r
4  * Function library for anything related to formatting / validating / sanitizing\r
5  */\r
6 \r
7 // function to convert an integer (1337) to a string (3jk).\r
8 function yourls_int2string( $num, $chars = null ) {\r
9         if( $chars == null )\r
10                 $chars = yourls_get_shorturl_charset();\r
11         $string = '';\r
12         $len = strlen( $chars );\r
13         while( $num >= $len ) {\r
14                 $mod = bcmod( $num, $len );\r
15                 $num = bcdiv( $num, $len );\r
16                 $string = $chars[ $mod ] . $string;\r
17         }\r
18         $string = $chars[ $num ] . $string;\r
19         \r
20         return yourls_apply_filter( 'int2string', $string, $num, $chars );\r
21 }\r
22 \r
23 // function to convert a string (3jk) to an integer (1337)\r
24 function yourls_string2int( $string, $chars = null ) {\r
25         if( $chars == null )\r
26                 $chars = yourls_get_shorturl_charset();\r
27         $integer = 0;\r
28         $string = strrev( $string  );\r
29         $baselen = strlen( $chars );\r
30         $inputlen = strlen( $string );\r
31         for ($i = 0; $i < $inputlen; $i++) {\r
32                 $index = strpos( $chars, $string[$i] );\r
33                 $integer = bcadd( $integer, bcmul( $index, bcpow( $baselen, $i ) ) );\r
34         }\r
35 \r
36         return yourls_apply_filter( 'string2int', $integer, $string, $chars );\r
37 }\r
38 \r
39 // return a unique(ish) hash for a string to be used as a valid HTML id\r
40 function yourls_string2htmlid( $string ) {\r
41         return yourls_apply_filter( 'string2htmlid', 'y'.abs( crc32( $string ) ) );\r
42 }\r
43 \r
44 // Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.\r
45 function yourls_sanitize_string( $string ) {\r
46         // make a regexp pattern with the shorturl charset, and remove everything but this\r
47         $pattern = yourls_make_regexp_pattern( yourls_get_shorturl_charset() );\r
48         $valid = substr( preg_replace( '![^'.$pattern.']!', '', $string ), 0, 199 );\r
49         \r
50         return yourls_apply_filter( 'sanitize_string', $valid, $string );\r
51 }\r
52 \r
53 // Alias function. I was always getting it wrong.\r
54 function yourls_sanitize_keyword( $keyword ) {\r
55         return yourls_sanitize_string( $keyword );\r
56 }\r
57 \r
58 // Sanitize a page title. No HTML per W3C http://www.w3.org/TR/html401/struct/global.html#h-7.4.2\r
59 function yourls_sanitize_title( $unsafe_title ) {\r
60         $title = $unsafe_title;\r
61         $title = strip_tags( $title );\r
62         $title = preg_replace( "/\s+/", ' ', trim( $title ) );\r
63         return yourls_apply_filter( 'sanitize_title', $title, $unsafe_title );\r
64 }\r
65 \r
66 // A few sanity checks on the URL. Used for redirection or DB. For display purpose, see yourls_esc_url()\r
67 function yourls_sanitize_url( $unsafe_url ) {\r
68         $url = yourls_esc_url( $unsafe_url, 'redirection' );    \r
69         return yourls_apply_filter( 'sanitize_url', $url, $unsafe_url );\r
70 }\r
71 \r
72 // Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''\r
73 // Stolen from WP's _deep_replace\r
74 function yourls_deep_replace( $search, $subject ){\r
75         $found = true;\r
76         while($found) {\r
77                 $found = false;\r
78                 foreach( (array) $search as $val ) {\r
79                         while( strpos( $subject, $val ) !== false ) {\r
80                                 $found = true;\r
81                                 $subject = str_replace( $val, '', $subject );\r
82                         }\r
83                 }\r
84         }\r
85         \r
86         return $subject;\r
87 }\r
88 \r
89 // Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)\r
90 // TODO FIXME FFS: unused ?\r
91 function yourls_sanitize_int( $in ) {\r
92         return ( substr( preg_replace( '/[^0-9]/', '', strval( $in ) ), 0, 20 ) );\r
93 }\r
94 \r
95 // Make sure a integer is safe\r
96 // Note: this is not checking for integers, since integers on 32bits system are way too limited\r
97 // TODO: find a way to validate as integer\r
98 function yourls_intval( $in ) {\r
99         return yourls_escape( $in );\r
100 }\r
101 \r
102 // Escape a string\r
103 function yourls_escape( $in ) {\r
104         return mysql_real_escape_string( $in );\r
105 }\r
106 \r
107 // Sanitize an IP address\r
108 function yourls_sanitize_ip( $ip ) {\r
109         return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );\r
110 }\r
111 \r
112 // Make sure a date is m(m)/d(d)/yyyy, return false otherwise\r
113 function yourls_sanitize_date( $date ) {\r
114         if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {\r
115                 return false;\r
116         }\r
117         return $date;\r
118 }\r
119 \r
120 // Sanitize a date for SQL search. Return false if malformed input.\r
121 function yourls_sanitize_date_for_sql( $date ) {\r
122         if( !yourls_sanitize_date( $date ) )\r
123                 return false;\r
124         return date( 'Y-m-d', strtotime( $date ) );\r
125 }\r
126 \r
127 // Return word or words if more than one\r
128 function yourls_plural( $word, $count=1 ) {\r
129         return $word . ($count > 1 ? 's' : '');\r
130 }\r
131 \r
132 // Return trimmed string\r
133 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {\r
134         $newstring = $string;\r
135         if( function_exists( 'mb_substr' ) ) {\r
136                 if ( mb_strlen( $newstring ) > $length ) {\r
137                         $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;     \r
138                 }\r
139         } else {\r
140                 if ( strlen( $newstring ) > $length ) {\r
141                         $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;    \r
142                 }\r
143         }\r
144         return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );\r
145 }\r
146 \r
147 // Sanitize a version number (1.4.1-whatever -> 1.4.1)\r
148 function yourls_sanitize_version( $ver ) {\r
149         return preg_replace( '/[^0-9.]/', '', $ver );\r
150 }\r
151 \r
152 // Sanitize a filename (no Win32 stuff)\r
153 function yourls_sanitize_filename( $file ) {\r
154         $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs\r
155         $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash\r
156         return $file;\r
157 }\r
158 \r
159 // Check if a string seems to be UTF-8. Stolen from WP.\r
160 function yourls_seems_utf8( $str ) {\r
161         $length = strlen( $str );\r
162         for ( $i=0; $i < $length; $i++ ) {\r
163                 $c = ord( $str[ $i ] );\r
164                 if ( $c < 0x80 ) $n = 0; # 0bbbbbbb\r
165                 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb\r
166                 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb\r
167                 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb\r
168                 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb\r
169                 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b\r
170                 else return false; # Does not match any model\r
171                 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?\r
172                         if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))\r
173                                 return false;\r
174                 }\r
175         }\r
176         return true;\r
177 }\r
178 \r
179 /**\r
180  * Checks for invalid UTF8 in a string. Stolen from WP\r
181  *\r
182  * @since 1.6\r
183  *\r
184  * @param string $string The text which is to be checked.\r
185  * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.\r
186  * @return string The checked text.\r
187  */\r
188 function yourls_check_invalid_utf8( $string, $strip = false ) {\r
189         $string = (string) $string;\r
190 \r
191         if ( 0 === strlen( $string ) ) {\r
192                 return '';\r
193         }\r
194 \r
195         // Check for support for utf8 in the installed PCRE library once and store the result in a static\r
196         static $utf8_pcre;\r
197         if ( !isset( $utf8_pcre ) ) {\r
198                 $utf8_pcre = @preg_match( '/^./u', 'a' );\r
199         }\r
200         // We can't demand utf8 in the PCRE installation, so just return the string in those cases\r
201         if ( !$utf8_pcre ) {\r
202                 return $string;\r
203         }\r
204 \r
205         // preg_match fails when it encounters invalid UTF8 in $string\r
206         if ( 1 === @preg_match( '/^./us', $string ) ) {\r
207                 return $string;\r
208         }\r
209 \r
210         // Attempt to strip the bad chars if requested (not recommended)\r
211         if ( $strip && function_exists( 'iconv' ) ) {\r
212                 return iconv( 'utf-8', 'utf-8', $string );\r
213         }\r
214 \r
215         return '';\r
216 }\r
217 \r
218 /**\r
219  * Converts a number of special characters into their HTML entities. Stolen from WP.\r
220  *\r
221  * Specifically deals with: &, <, >, ", and '.\r
222  *\r
223  * $quote_style can be set to ENT_COMPAT to encode " to\r
224  * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.\r
225  *\r
226  * @since 1.6\r
227  *\r
228  * @param string $string The text which is to be encoded.\r
229  * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.\r
230  * @param string $charset Optional. The character encoding of the string. Default is false.\r
231  * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.\r
232  * @return string The encoded text with HTML entities.\r
233  */\r
234 function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {\r
235         $string = (string) $string;\r
236 \r
237         if ( 0 === strlen( $string ) )\r
238                 return '';\r
239 \r
240         // Don't bother if there are no specialchars - saves some processing\r
241         if ( ! preg_match( '/[&<>"\']/', $string ) )\r
242                 return $string;\r
243 \r
244         // Account for the previous behaviour of the function when the $quote_style is not an accepted value\r
245         if ( empty( $quote_style ) )\r
246                 $quote_style = ENT_NOQUOTES;\r
247         elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )\r
248                 $quote_style = ENT_QUOTES;\r
249 \r
250         $charset = 'UTF-8';\r
251 \r
252         $_quote_style = $quote_style;\r
253 \r
254         if ( $quote_style === 'double' ) {\r
255                 $quote_style = ENT_COMPAT;\r
256                 $_quote_style = ENT_COMPAT;\r
257         } elseif ( $quote_style === 'single' ) {\r
258                 $quote_style = ENT_NOQUOTES;\r
259         }\r
260 \r
261         // Handle double encoding ourselves\r
262         if ( $double_encode ) {\r
263                 $string = @htmlspecialchars( $string, $quote_style, $charset );\r
264         } else {\r
265                 // Decode &amp; into &\r
266                 $string = yourls_specialchars_decode( $string, $_quote_style );\r
267 \r
268                 // Guarantee every &entity; is valid or re-encode the &\r
269                 $string = yourls_kses_normalize_entities( $string );\r
270 \r
271                 // Now re-encode everything except &entity;\r
272                 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );\r
273 \r
274                 for ( $i = 0; $i < count( $string ); $i += 2 )\r
275                         $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );\r
276 \r
277                 $string = implode( '', $string );\r
278         }\r
279 \r
280         // Backwards compatibility\r
281         if ( 'single' === $_quote_style )\r
282                 $string = str_replace( "'", '&#039;', $string );\r
283 \r
284         return $string;\r
285 }\r
286 \r
287 /**\r
288  * Converts a number of HTML entities into their special characters. Stolen from WP.\r
289  *\r
290  * Specifically deals with: &, <, >, ", and '.\r
291  *\r
292  * $quote_style can be set to ENT_COMPAT to decode " entities,\r
293  * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.\r
294  *\r
295  * @since 1.6\r
296  *\r
297  * @param string $string The text which is to be decoded.\r
298  * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.\r
299  * @return string The decoded text without HTML entities.\r
300  */\r
301 function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {\r
302         $string = (string) $string;\r
303 \r
304         if ( 0 === strlen( $string ) ) {\r
305                 return '';\r
306         }\r
307 \r
308         // Don't bother if there are no entities - saves a lot of processing\r
309         if ( strpos( $string, '&' ) === false ) {\r
310                 return $string;\r
311         }\r
312 \r
313         // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value\r
314         if ( empty( $quote_style ) ) {\r
315                 $quote_style = ENT_NOQUOTES;\r
316         } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {\r
317                 $quote_style = ENT_QUOTES;\r
318         }\r
319 \r
320         // More complete than get_html_translation_table( HTML_SPECIALCHARS )\r
321         $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );\r
322         $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );\r
323         $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );\r
324         $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );\r
325         $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );\r
326         $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );\r
327 \r
328         if ( $quote_style === ENT_QUOTES ) {\r
329                 $translation = array_merge( $single, $double, $others );\r
330                 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );\r
331         } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {\r
332                 $translation = array_merge( $double, $others );\r
333                 $translation_preg = array_merge( $double_preg, $others_preg );\r
334         } elseif ( $quote_style === 'single' ) {\r
335                 $translation = array_merge( $single, $others );\r
336                 $translation_preg = array_merge( $single_preg, $others_preg );\r
337         } elseif ( $quote_style === ENT_NOQUOTES ) {\r
338                 $translation = $others;\r
339                 $translation_preg = $others_preg;\r
340         }\r
341 \r
342         // Remove zero padding on numeric entities\r
343         $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );\r
344 \r
345         // Replace characters according to translation table\r
346         return strtr( $string, $translation );\r
347 }\r
348 \r
349 \r
350 /**\r
351  * Escaping for HTML blocks. Stolen from WP\r
352  *\r
353  * @since 1.6\r
354  *\r
355  * @param string $text\r
356  * @return string\r
357  */\r
358 function yourls_esc_html( $text ) {\r
359         $safe_text = yourls_check_invalid_utf8( $text );\r
360         $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );\r
361         return yourls_apply_filters( 'esc_html', $safe_text, $text );\r
362 }\r
363 \r
364 /**\r
365  * Escaping for HTML attributes.  Stolen from WP\r
366  *\r
367  * @since 1.6\r
368  *\r
369  * @param string $text\r
370  * @return string\r
371  */\r
372 function yourls_esc_attr( $text ) {\r
373         $safe_text = yourls_check_invalid_utf8( $text );\r
374         $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );\r
375         return yourls_apply_filters( 'esc_attr', $safe_text, $text );\r
376 }\r
377 \r
378 /**\r
379  * Checks and cleans a URL before printing it. Stolen from WP.\r
380  *\r
381  * A number of characters are removed from the URL. If the URL is for displaying\r
382  * (the default behaviour) ampersands are also replaced.\r
383  *\r
384  * @since 1.6\r
385  *\r
386  * @param string $url The URL to be cleaned.\r
387  * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.\r
388  * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols\r
389  * @return string The cleaned $url\r
390  */\r
391 function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {\r
392         // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')\r
393         $url = str_replace( \r
394                 array( 'http://http://', 'http://https://' ),\r
395                 array( 'http://',        'https://'        ),\r
396                 $url\r
397         );\r
398 \r
399         if ( '' == $url )\r
400                 return $url;\r
401 \r
402         // make sure there's a protocol, add http:// if not\r
403         if ( ! yourls_get_protocol( $url ) )\r
404                 $url = 'http://'.$url;\r
405 \r
406         // force scheme and domain to lowercase - see issue 591\r
407         preg_match( '!^([a-zA-Z]+://([^/]+))(.*)$!', $url, $matches );\r
408         if( isset( $matches[1] ) && isset( $matches[3] ) )\r
409                 $url = strtolower( $matches[1] ) . $matches[3];\r
410 \r
411         $original_url = $url;\r
412 \r
413         $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url );\r
414         // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'\r
415         // TODO: check if that was it too destructive\r
416         $strip = array( '%0d', '%0a', '%0D', '%0A' );\r
417         $url = yourls_deep_replace( $strip, $url );\r
418         $url = str_replace( ';//', '://', $url );\r
419 \r
420         // Replace ampersands and single quotes only when displaying.\r
421         if ( 'display' == $context ) {\r
422                 $url = yourls_kses_normalize_entities( $url );\r
423                 $url = str_replace( '&amp;', '&#038;', $url );\r
424                 $url = str_replace( "'", '&#039;', $url );\r
425         }\r
426         \r
427         if ( ! is_array( $protocols ) or ! $protocols ) {\r
428                 global $yourls_allowedprotocols;\r
429                 $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );\r
430                 // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()\r
431         }\r
432 \r
433         if ( !yourls_is_allowed_protocol( $url, $protocols ) )\r
434                 return '';\r
435         \r
436         // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)\r
437 \r
438         $url = substr( $url, 0, 1999 );\r
439         \r
440         return yourls_apply_filter( 'esc_url', $url, $original_url, $context );\r
441 }\r
442 \r
443 /**\r
444  * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.\r
445  *\r
446  * Escapes text strings for echoing in JS. It is intended to be used for inline JS\r
447  * (in a tag attribute, for example onclick="..."). Note that the strings have to\r
448  * be in single quotes. The filter 'js_escape' is also applied here.\r
449  *\r
450  * @since 1.6\r
451  *\r
452  * @param string $text The text to be escaped.\r
453  * @return string Escaped text.\r
454  */\r
455 function yourls_esc_js( $text ) {\r
456         $safe_text = yourls_check_invalid_utf8( $text );\r
457         $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );\r
458         $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );\r
459         $safe_text = str_replace( "\r", '', $safe_text );\r
460         $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );\r
461         return yourls_apply_filters( 'esc_js', $safe_text, $text );\r
462 }\r
463 \r
464 /**\r
465  * Escaping for textarea values. Stolen from WP.\r
466  *\r
467  * @since 1.6\r
468  *\r
469  * @param string $text\r
470  * @return string\r
471  */\r
472 function yourls_esc_textarea( $text ) {\r
473         $safe_text = htmlspecialchars( $text, ENT_QUOTES );\r
474         return yourls_apply_filters( 'esc_textarea', $safe_text, $text );\r
475 }\r
476 \r
477 \r
478 /**\r
479 * PHP emulation of JS's encodeURI\r
480 *\r
481 * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI\r
482 * @param $url\r
483 * @return string\r
484 */\r
485 function yourls_encodeURI( $url ) {\r
486     return strtr( rawurlencode( $url ), array (\r
487         '%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':', '%40' => '@',\r
488                 '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$', '%21' => '!', '%2A' => '*',\r
489                 '%27' => '\'', '%28' => '(', '%29' => ')', '%23' => '#',\r
490     ) );\r
491 }