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