4 * Function library for anything related to formatting / validating / sanitizing
\r
8 * Convert an integer (1337) to a string (3jk).
11 function yourls_int2string( $num, $chars = null ) {
\r
12 if( $chars == null )
\r
13 $chars = yourls_get_shorturl_charset();
\r
15 $len = strlen( $chars );
\r
16 while( $num >= $len ) {
\r
17 $mod = bcmod( $num, $len );
\r
18 $num = bcdiv( $num, $len );
\r
19 $string = $chars[ $mod ] . $string;
\r
21 $string = $chars[ $num ] . $string;
\r
23 return yourls_apply_filter( 'int2string', $string, $num, $chars );
\r
27 * Convert a string (3jk) to an integer (1337)
30 function yourls_string2int( $string, $chars = null ) {
\r
31 if( $chars == null )
\r
32 $chars = yourls_get_shorturl_charset();
\r
34 $string = strrev( $string );
\r
35 $baselen = strlen( $chars );
\r
36 $inputlen = strlen( $string );
\r
37 for ($i = 0; $i < $inputlen; $i++) {
\r
38 $index = strpos( $chars, $string[$i] );
\r
39 $integer = bcadd( $integer, bcmul( $index, bcpow( $baselen, $i ) ) );
\r
42 return yourls_apply_filter( 'string2int', $integer, $string, $chars );
\r
46 * Return a unique(ish) hash for a string to be used as a valid HTML id
49 function yourls_string2htmlid( $string ) {
\r
50 return yourls_apply_filter( 'string2htmlid', 'y'.abs( crc32( $string ) ) );
\r
54 * Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.
57 function yourls_sanitize_string( $string ) {
\r
58 // make a regexp pattern with the shorturl charset, and remove everything but this
\r
59 $pattern = yourls_make_regexp_pattern( yourls_get_shorturl_charset() );
\r
60 $valid = substr( preg_replace( '![^'.$pattern.']!', '', $string ), 0, 199 );
\r
62 return yourls_apply_filter( 'sanitize_string', $valid, $string );
\r
66 * Alias function. I was always getting it wrong.
69 function yourls_sanitize_keyword( $keyword ) {
\r
70 return yourls_sanitize_string( $keyword );
\r
74 * Sanitize a page title. No HTML per W3C http://www.w3.org/TR/html401/struct/global.html#h-7.4.2
77 function yourls_sanitize_title( $unsafe_title ) {
\r
78 $title = $unsafe_title;
\r
79 $title = strip_tags( $title );
\r
80 $title = preg_replace( "/\s+/", ' ', trim( $title ) );
\r
81 return yourls_apply_filter( 'sanitize_title', $title, $unsafe_title );
\r
85 * A few sanity checks on the URL. Used for redirection or DB. For display purpose, see yourls_esc_url()
88 function yourls_sanitize_url( $unsafe_url ) {
\r
89 $url = yourls_esc_url( $unsafe_url, 'redirection' );
\r
90 return yourls_apply_filter( 'sanitize_url', $url, $unsafe_url );
\r
94 * Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''
\r
96 * Stolen from WP's _deep_replace
99 function yourls_deep_replace( $search, $subject ){
\r
103 foreach( (array) $search as $val ) {
\r
104 while( strpos( $subject, $val ) !== false ) {
\r
106 $subject = str_replace( $val, '', $subject );
\r
115 * Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)
118 function yourls_sanitize_int( $in ) {
\r
119 return ( substr( preg_replace( '/[^0-9]/', '', strval( $in ) ), 0, 20 ) );
\r
123 * Make sure a integer is safe
\r
125 * Note: this is not checking for integers, since integers on 32bits system are way too limited
\r
126 * TODO: find a way to validate as integer
129 function yourls_intval( $in ) {
\r
130 return yourls_escape( $in );
\r
137 function yourls_escape( $in ) {
\r
138 return mysql_real_escape_string( $in );
\r
142 * Sanitize an IP address
145 function yourls_sanitize_ip( $ip ) {
\r
146 return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
\r
150 * Make sure a date is m(m)/d(d)/yyyy, return false otherwise
153 function yourls_sanitize_date( $date ) {
\r
154 if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {
\r
161 * Sanitize a date for SQL search. Return false if malformed input.
164 function yourls_sanitize_date_for_sql( $date ) {
\r
165 if( !yourls_sanitize_date( $date ) )
\r
167 return date( 'Y-m-d', strtotime( $date ) );
\r
171 * Return word or words if more than one
174 function yourls_plural( $word, $count=1 ) {
\r
175 yourls_deprecated_function( __FUNCTION__, '1.6', 'yourls_n' );
\r
176 return $word . ($count > 1 ? 's' : '');
\r
180 * Return trimmed string
183 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {
\r
184 $newstring = $string;
\r
185 if( function_exists( 'mb_substr' ) ) {
\r
186 if ( mb_strlen( $newstring ) > $length ) {
\r
187 $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;
\r
190 if ( strlen( $newstring ) > $length ) {
\r
191 $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;
\r
194 return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );
\r
198 * Sanitize a version number (1.4.1-whatever -> 1.4.1)
201 function yourls_sanitize_version( $ver ) {
\r
202 return preg_replace( '/[^0-9.]/', '', $ver );
\r
206 * Sanitize a filename (no Win32 stuff)
209 function yourls_sanitize_filename( $file ) {
\r
210 $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs
\r
211 $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash
\r
216 * Check if a string seems to be UTF-8. Stolen from WP.
219 function yourls_seems_utf8( $str ) {
\r
220 $length = strlen( $str );
\r
221 for ( $i=0; $i < $length; $i++ ) {
\r
222 $c = ord( $str[ $i ] );
\r
223 if ( $c < 0x80 ) $n = 0; # 0bbbbbbb
\r
224 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
\r
225 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
\r
226 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
\r
227 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
\r
228 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
\r
229 else return false; # Does not match any model
\r
230 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
\r
231 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
\r
239 * Checks for invalid UTF8 in a string. Stolen from WP
\r
243 * @param string $string The text which is to be checked.
\r
244 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
\r
245 * @return string The checked text.
\r
247 function yourls_check_invalid_utf8( $string, $strip = false ) {
\r
248 $string = (string) $string;
\r
250 if ( 0 === strlen( $string ) ) {
\r
254 // Check for support for utf8 in the installed PCRE library once and store the result in a static
\r
256 if ( !isset( $utf8_pcre ) ) {
\r
257 $utf8_pcre = @preg_match( '/^./u', 'a' );
\r
259 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
\r
260 if ( !$utf8_pcre ) {
\r
264 // preg_match fails when it encounters invalid UTF8 in $string
\r
265 if ( 1 === @preg_match( '/^./us', $string ) ) {
\r
269 // Attempt to strip the bad chars if requested (not recommended)
\r
270 if ( $strip && function_exists( 'iconv' ) ) {
\r
271 return iconv( 'utf-8', 'utf-8', $string );
\r
278 * Converts a number of special characters into their HTML entities. Stolen from WP.
\r
280 * Specifically deals with: &, <, >, ", and '.
\r
282 * $quote_style can be set to ENT_COMPAT to encode " to
\r
283 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
\r
287 * @param string $string The text which is to be encoded.
\r
288 * @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
289 * @param string $charset Optional. The character encoding of the string. Default is false.
\r
290 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
\r
291 * @return string The encoded text with HTML entities.
\r
293 function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
\r
294 $string = (string) $string;
\r
296 if ( 0 === strlen( $string ) )
\r
299 // Don't bother if there are no specialchars - saves some processing
\r
300 if ( ! preg_match( '/[&<>"\']/', $string ) )
\r
303 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
\r
304 if ( empty( $quote_style ) )
\r
305 $quote_style = ENT_NOQUOTES;
\r
306 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
\r
307 $quote_style = ENT_QUOTES;
\r
309 $charset = 'UTF-8';
\r
311 $_quote_style = $quote_style;
\r
313 if ( $quote_style === 'double' ) {
\r
314 $quote_style = ENT_COMPAT;
\r
315 $_quote_style = ENT_COMPAT;
\r
316 } elseif ( $quote_style === 'single' ) {
\r
317 $quote_style = ENT_NOQUOTES;
\r
320 // Handle double encoding ourselves
\r
321 if ( $double_encode ) {
\r
322 $string = @htmlspecialchars( $string, $quote_style, $charset );
\r
324 // Decode & into &
\r
325 $string = yourls_specialchars_decode( $string, $_quote_style );
\r
327 // Guarantee every &entity; is valid or re-encode the &
\r
328 $string = yourls_kses_normalize_entities( $string );
\r
330 // Now re-encode everything except &entity;
\r
331 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
\r
333 for ( $i = 0; $i < count( $string ); $i += 2 )
\r
334 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
\r
336 $string = implode( '', $string );
\r
339 // Backwards compatibility
\r
340 if ( 'single' === $_quote_style )
\r
341 $string = str_replace( "'", ''', $string );
\r
347 * Converts a number of HTML entities into their special characters. Stolen from WP.
\r
349 * Specifically deals with: &, <, >, ", and '.
\r
351 * $quote_style can be set to ENT_COMPAT to decode " entities,
\r
352 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
\r
356 * @param string $string The text which is to be decoded.
\r
357 * @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
358 * @return string The decoded text without HTML entities.
\r
360 function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
\r
361 $string = (string) $string;
\r
363 if ( 0 === strlen( $string ) ) {
\r
367 // Don't bother if there are no entities - saves a lot of processing
\r
368 if ( strpos( $string, '&' ) === false ) {
\r
372 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
\r
373 if ( empty( $quote_style ) ) {
\r
374 $quote_style = ENT_NOQUOTES;
\r
375 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
\r
376 $quote_style = ENT_QUOTES;
\r
379 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
\r
380 $single = array( ''' => '\'', ''' => '\'' );
\r
381 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
\r
382 $double = array( '"' => '"', '"' => '"', '"' => '"' );
\r
383 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
\r
384 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
\r
385 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
\r
387 if ( $quote_style === ENT_QUOTES ) {
\r
388 $translation = array_merge( $single, $double, $others );
\r
389 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
\r
390 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
\r
391 $translation = array_merge( $double, $others );
\r
392 $translation_preg = array_merge( $double_preg, $others_preg );
\r
393 } elseif ( $quote_style === 'single' ) {
\r
394 $translation = array_merge( $single, $others );
\r
395 $translation_preg = array_merge( $single_preg, $others_preg );
\r
396 } elseif ( $quote_style === ENT_NOQUOTES ) {
\r
397 $translation = $others;
\r
398 $translation_preg = $others_preg;
\r
401 // Remove zero padding on numeric entities
\r
402 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
\r
404 // Replace characters according to translation table
\r
405 return strtr( $string, $translation );
\r
410 * Escaping for HTML blocks. Stolen from WP
\r
414 * @param string $text
\r
417 function yourls_esc_html( $text ) {
\r
418 $safe_text = yourls_check_invalid_utf8( $text );
\r
419 $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
\r
420 return yourls_apply_filters( 'esc_html', $safe_text, $text );
\r
424 * Escaping for HTML attributes. Stolen from WP
\r
428 * @param string $text
\r
431 function yourls_esc_attr( $text ) {
\r
432 $safe_text = yourls_check_invalid_utf8( $text );
\r
433 $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
\r
434 return yourls_apply_filters( 'esc_attr', $safe_text, $text );
\r
438 * Checks and cleans a URL before printing it. Stolen from WP.
\r
440 * A number of characters are removed from the URL. If the URL is for displaying
\r
441 * (the default behaviour) ampersands are also replaced.
\r
445 * @param string $url The URL to be cleaned.
\r
446 * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.
\r
447 * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols
\r
448 * @return string The cleaned $url
\r
450 function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {
\r
451 // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
\r
452 $url = str_replace(
\r
453 array( 'http://http://', 'http://https://' ),
\r
454 array( 'http://', 'https://' ),
\r
461 // make sure there's a protocol, add http:// if not
\r
462 if ( ! yourls_get_protocol( $url ) )
\r
463 $url = 'http://'.$url;
\r
465 // force scheme and domain to lowercase - see issue 591
\r
466 preg_match( '!^([a-zA-Z]+://([^/]+))(.*)$!', $url, $matches );
\r
467 if( isset( $matches[1] ) && isset( $matches[3] ) )
\r
468 $url = strtolower( $matches[1] ) . $matches[3];
\r
470 $original_url = $url;
\r
472 $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url );
\r
473 // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'
\r
474 // TODO: check if that was it too destructive
\r
475 $strip = array( '%0d', '%0a', '%0D', '%0A' );
\r
476 $url = yourls_deep_replace( $strip, $url );
\r
477 $url = str_replace( ';//', '://', $url );
\r
479 // Replace ampersands and single quotes only when displaying.
\r
480 if ( 'display' == $context ) {
\r
481 $url = yourls_kses_normalize_entities( $url );
\r
482 $url = str_replace( '&', '&', $url );
\r
483 $url = str_replace( "'", ''', $url );
\r
486 if ( ! is_array( $protocols ) or ! $protocols ) {
\r
487 global $yourls_allowedprotocols;
\r
488 $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );
\r
489 // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()
\r
492 if ( !yourls_is_allowed_protocol( $url, $protocols ) )
\r
495 // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)
\r
497 $url = substr( $url, 0, 1999 );
\r
499 return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
\r
503 * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
\r
505 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
\r
506 * (in a tag attribute, for example onclick="..."). Note that the strings have to
\r
507 * be in single quotes. The filter 'js_escape' is also applied here.
\r
511 * @param string $text The text to be escaped.
\r
512 * @return string Escaped text.
\r
514 function yourls_esc_js( $text ) {
\r
515 $safe_text = yourls_check_invalid_utf8( $text );
\r
516 $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );
\r
517 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
\r
518 $safe_text = str_replace( "\r", '', $safe_text );
\r
519 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
\r
520 return yourls_apply_filters( 'esc_js', $safe_text, $text );
\r
524 * Escaping for textarea values. Stolen from WP.
\r
528 * @param string $text
\r
531 function yourls_esc_textarea( $text ) {
\r
532 $safe_text = htmlspecialchars( $text, ENT_QUOTES );
\r
533 return yourls_apply_filters( 'esc_textarea', $safe_text, $text );
\r
538 * PHP emulation of JS's encodeURI
\r
540 * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
\r
544 function yourls_encodeURI( $url ) {
\r
545 return strtr( rawurlencode( $url ), array (
\r
546 '%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':', '%40' => '@',
\r
547 '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$', '%21' => '!', '%2A' => '*',
\r
548 '%27' => '\'', '%28' => '(', '%29' => ')', '%23' => '#',
\r
553 * Adds backslashes before letters and before a number at the start of a string. Stolen from WP.
\r
557 * @param string $string Value to which backslashes will be added.
\r
558 * @return string String with backslashes inserted.
\r
560 function yourls_backslashit($string) {
\r
561 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
\r
562 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
\r