4 * Function library for anything related to formatting / validating / sanitizing
8 * Convert an integer (1337) to a string (3jk).
11 function yourls_int2string( $num, $chars = null ) {
13 $chars = yourls_get_shorturl_charset();
15 $len = strlen( $chars );
16 while( $num >= $len ) {
17 $mod = bcmod( $num, $len );
18 $num = bcdiv( $num, $len );
19 $string = $chars[ $mod ] . $string;
21 $string = $chars[ intval( $num ) ] . $string;
23 return yourls_apply_filter( 'int2string', $string, $num, $chars );
27 * Convert a string (3jk) to an integer (1337)
30 function yourls_string2int( $string, $chars = null ) {
32 $chars = yourls_get_shorturl_charset();
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 ) ) );
42 return yourls_apply_filter( 'string2int', $integer, $string, $chars );
46 * Return a unique(ish) hash for a string to be used as a valid HTML id
49 function yourls_string2htmlid( $string ) {
50 return yourls_apply_filter( 'string2htmlid', 'y'.abs( crc32( $string ) ) );
54 * Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.
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 );
62 return yourls_apply_filter( 'sanitize_string', $valid, $string );
66 * Alias function. I was always getting it wrong.
69 function yourls_sanitize_keyword( $keyword ) {
70 return yourls_sanitize_string( $keyword );
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 ) {
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 );
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 ) {
89 $url = yourls_esc_url( $unsafe_url, 'redirection' );
90 return yourls_apply_filter( 'sanitize_url', $url, $unsafe_url );
94 * Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''
96 * Stolen from WP's _deep_replace
99 function yourls_deep_replace( $search, $subject ){
103 foreach( (array) $search as $val ) {
104 while( strpos( $subject, $val ) !== false ) {
106 $subject = str_replace( $val, '', $subject );
115 * Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)
118 function yourls_sanitize_int( $in ) {
119 return ( substr( preg_replace( '/[^0-9]/', '', strval( $in ) ), 0, 20 ) );
123 * Make sure a integer is safe
125 * Note: this is not checking for integers, since integers on 32bits system are way too limited
126 * TODO: find a way to validate as integer
129 function yourls_intval( $in ) {
130 return yourls_escape( $in );
137 function yourls_escape( $in ) {
139 return $ydb->escape( $in );
143 * Sanitize an IP address
146 function yourls_sanitize_ip( $ip ) {
147 return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
151 * Make sure a date is m(m)/d(d)/yyyy, return false otherwise
154 function yourls_sanitize_date( $date ) {
155 if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {
162 * Sanitize a date for SQL search. Return false if malformed input.
165 function yourls_sanitize_date_for_sql( $date ) {
166 if( !yourls_sanitize_date( $date ) )
168 return date( 'Y-m-d', strtotime( $date ) );
172 * Return word or words if more than one
175 function yourls_plural( $word, $count=1 ) {
176 yourls_deprecated_function( __FUNCTION__, '1.6', 'yourls_n' );
177 return $word . ($count > 1 ? 's' : '');
181 * Return trimmed string
184 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {
185 $newstring = $string;
186 if( function_exists( 'mb_substr' ) ) {
187 if ( mb_strlen( $newstring ) > $length ) {
188 $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;
191 if ( strlen( $newstring ) > $length ) {
192 $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;
195 return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );
199 * Sanitize a version number (1.4.1-whatever -> 1.4.1)
202 function yourls_sanitize_version( $ver ) {
203 return preg_replace( '/[^0-9.]/', '', $ver );
207 * Sanitize a filename (no Win32 stuff)
210 function yourls_sanitize_filename( $file ) {
211 $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs
212 $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash
217 * Check if a string seems to be UTF-8. Stolen from WP.
220 function yourls_seems_utf8( $str ) {
221 $length = strlen( $str );
222 for ( $i=0; $i < $length; $i++ ) {
223 $c = ord( $str[ $i ] );
224 if ( $c < 0x80 ) $n = 0; # 0bbbbbbb
225 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
226 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
227 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
228 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
229 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
230 else return false; # Does not match any model
231 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
232 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
240 * Checks for invalid UTF8 in a string. Stolen from WP
244 * @param string $string The text which is to be checked.
245 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
246 * @return string The checked text.
248 function yourls_check_invalid_utf8( $string, $strip = false ) {
249 $string = (string) $string;
251 if ( 0 === strlen( $string ) ) {
255 // Check for support for utf8 in the installed PCRE library once and store the result in a static
257 if ( !isset( $utf8_pcre ) ) {
258 $utf8_pcre = @preg_match( '/^./u', 'a' );
260 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
265 // preg_match fails when it encounters invalid UTF8 in $string
266 if ( 1 === @preg_match( '/^./us', $string ) ) {
270 // Attempt to strip the bad chars if requested (not recommended)
271 if ( $strip && function_exists( 'iconv' ) ) {
272 return iconv( 'utf-8', 'utf-8', $string );
279 * Converts a number of special characters into their HTML entities. Stolen from WP.
281 * Specifically deals with: &, <, >, ", and '.
283 * $quote_style can be set to ENT_COMPAT to encode " to
284 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
288 * @param string $string The text which is to be encoded.
289 * @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.
290 * @param string $charset Optional. The character encoding of the string. Default is false.
291 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
292 * @return string The encoded text with HTML entities.
294 function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
295 $string = (string) $string;
297 if ( 0 === strlen( $string ) )
300 // Don't bother if there are no specialchars - saves some processing
301 if ( ! preg_match( '/[&<>"\']/', $string ) )
304 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
305 if ( empty( $quote_style ) )
306 $quote_style = ENT_NOQUOTES;
307 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
308 $quote_style = ENT_QUOTES;
312 $_quote_style = $quote_style;
314 if ( $quote_style === 'double' ) {
315 $quote_style = ENT_COMPAT;
316 $_quote_style = ENT_COMPAT;
317 } elseif ( $quote_style === 'single' ) {
318 $quote_style = ENT_NOQUOTES;
321 // Handle double encoding ourselves
322 if ( $double_encode ) {
323 $string = @htmlspecialchars( $string, $quote_style, $charset );
325 // Decode & into &
326 $string = yourls_specialchars_decode( $string, $_quote_style );
328 // Guarantee every &entity; is valid or re-encode the &
329 $string = yourls_kses_normalize_entities( $string );
331 // Now re-encode everything except &entity;
332 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
334 for ( $i = 0; $i < count( $string ); $i += 2 )
335 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
337 $string = implode( '', $string );
340 // Backwards compatibility
341 if ( 'single' === $_quote_style )
342 $string = str_replace( "'", ''', $string );
348 * Converts a number of HTML entities into their special characters. Stolen from WP.
350 * Specifically deals with: &, <, >, ", and '.
352 * $quote_style can be set to ENT_COMPAT to decode " entities,
353 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
357 * @param string $string The text which is to be decoded.
358 * @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.
359 * @return string The decoded text without HTML entities.
361 function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
362 $string = (string) $string;
364 if ( 0 === strlen( $string ) ) {
368 // Don't bother if there are no entities - saves a lot of processing
369 if ( strpos( $string, '&' ) === false ) {
373 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
374 if ( empty( $quote_style ) ) {
375 $quote_style = ENT_NOQUOTES;
376 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
377 $quote_style = ENT_QUOTES;
380 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
381 $single = array( ''' => '\'', ''' => '\'' );
382 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
383 $double = array( '"' => '"', '"' => '"', '"' => '"' );
384 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
385 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
386 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
388 if ( $quote_style === ENT_QUOTES ) {
389 $translation = array_merge( $single, $double, $others );
390 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
391 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
392 $translation = array_merge( $double, $others );
393 $translation_preg = array_merge( $double_preg, $others_preg );
394 } elseif ( $quote_style === 'single' ) {
395 $translation = array_merge( $single, $others );
396 $translation_preg = array_merge( $single_preg, $others_preg );
397 } elseif ( $quote_style === ENT_NOQUOTES ) {
398 $translation = $others;
399 $translation_preg = $others_preg;
402 // Remove zero padding on numeric entities
403 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
405 // Replace characters according to translation table
406 return strtr( $string, $translation );
411 * Escaping for HTML blocks. Stolen from WP
415 * @param string $text
418 function yourls_esc_html( $text ) {
419 $safe_text = yourls_check_invalid_utf8( $text );
420 $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
421 return yourls_apply_filters( 'esc_html', $safe_text, $text );
425 * Escaping for HTML attributes. Stolen from WP
429 * @param string $text
432 function yourls_esc_attr( $text ) {
433 $safe_text = yourls_check_invalid_utf8( $text );
434 $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
435 return yourls_apply_filters( 'esc_attr', $safe_text, $text );
439 * Checks and cleans a URL before printing it. Stolen from WP.
441 * A number of characters are removed from the URL. If the URL is for displaying
442 * (the default behaviour) ampersands are also replaced.
446 * @param string $url The URL to be cleaned.
447 * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.
448 * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols
449 * @return string The cleaned $url
451 function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {
452 // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
454 array( 'http://http://', 'http://https://' ),
455 array( 'http://', 'https://' ),
462 // make sure there's a protocol, add http:// if not
463 if ( ! yourls_get_protocol( $url ) )
464 $url = 'http://'.$url;
466 // force scheme and domain to lowercase - see issue 591
467 preg_match( '!^([a-zA-Z]+://([^/]+))(.*)$!', $url, $matches );
468 if( isset( $matches[1] ) && isset( $matches[3] ) )
469 $url = strtolower( $matches[1] ) . $matches[3];
471 $original_url = $url;
473 $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url );
474 // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'
475 // TODO: check if that was it too destructive
476 $strip = array( '%0d', '%0a', '%0D', '%0A' );
477 $url = yourls_deep_replace( $strip, $url );
478 $url = str_replace( ';//', '://', $url );
480 // Replace ampersands and single quotes only when displaying.
481 if ( 'display' == $context ) {
482 $url = yourls_kses_normalize_entities( $url );
483 $url = str_replace( '&', '&', $url );
484 $url = str_replace( "'", ''', $url );
487 if ( ! is_array( $protocols ) or ! $protocols ) {
488 global $yourls_allowedprotocols;
489 $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );
490 // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()
493 if ( !yourls_is_allowed_protocol( $url, $protocols ) )
496 // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)
498 $url = substr( $url, 0, 1999 );
500 return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
504 * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
506 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
507 * (in a tag attribute, for example onclick="..."). Note that the strings have to
508 * be in single quotes. The filter 'js_escape' is also applied here.
512 * @param string $text The text to be escaped.
513 * @return string Escaped text.
515 function yourls_esc_js( $text ) {
516 $safe_text = yourls_check_invalid_utf8( $text );
517 $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );
518 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
519 $safe_text = str_replace( "\r", '', $safe_text );
520 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
521 return yourls_apply_filters( 'esc_js', $safe_text, $text );
525 * Escaping for textarea values. Stolen from WP.
529 * @param string $text
532 function yourls_esc_textarea( $text ) {
533 $safe_text = htmlspecialchars( $text, ENT_QUOTES );
534 return yourls_apply_filters( 'esc_textarea', $safe_text, $text );
539 * PHP emulation of JS's encodeURI
541 * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
545 function yourls_encodeURI( $url ) {
546 return strtr( rawurlencode( $url ), array (
547 '%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':', '%40' => '@',
548 '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$', '%21' => '!', '%2A' => '*',
549 '%27' => '\'', '%28' => '(', '%29' => ')', '%23' => '#',
554 * Adds backslashes before letters and before a number at the start of a string. Stolen from WP.
558 * @param string $string Value to which backslashes will be added.
559 * @return string String with backslashes inserted.
561 function yourls_backslashit($string) {
562 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
563 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);