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