4 * Function library for anything related to formatting / validating / sanitizing
\r
7 // function to convert an integer (1337) to a string (3jk).
\r
8 function yourls_int2string( $num, $chars = null ) {
\r
10 $chars = yourls_get_shorturl_charset();
\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
18 $string = $chars[ $num ] . $string;
\r
20 return yourls_apply_filter( 'int2string', $string, $num, $chars );
\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
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
36 return yourls_apply_filter( 'string2int', $integer, $string, $chars );
\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
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
50 return yourls_apply_filter( 'sanitize_string', $valid, $string );
\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
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
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
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
78 foreach( (array) $search as $val ) {
\r
79 while( strpos( $subject, $val ) !== false ) {
\r
81 $subject = str_replace( $val, '', $subject );
\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
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
103 function yourls_escape( $in ) {
\r
104 return mysql_real_escape_string( $in );
\r
107 // Sanitize an IP address
\r
108 function yourls_sanitize_ip( $ip ) {
\r
109 return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
\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
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
124 return date( 'Y-m-d', strtotime( $date ) );
\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
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
140 if ( strlen( $newstring ) > $length ) {
\r
141 $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;
\r
144 return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );
\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
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
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
180 * Checks for invalid UTF8 in a string. Stolen from WP
\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
188 function yourls_check_invalid_utf8( $string, $strip = false ) {
\r
189 $string = (string) $string;
\r
191 if ( 0 === strlen( $string ) ) {
\r
195 // Check for support for utf8 in the installed PCRE library once and store the result in a static
\r
197 if ( !isset( $utf8_pcre ) ) {
\r
198 $utf8_pcre = @preg_match( '/^./u', 'a' );
\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
205 // preg_match fails when it encounters invalid UTF8 in $string
\r
206 if ( 1 === @preg_match( '/^./us', $string ) ) {
\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
219 * Converts a number of special characters into their HTML entities. Stolen from WP.
\r
221 * Specifically deals with: &, <, >, ", and '.
\r
223 * $quote_style can be set to ENT_COMPAT to encode " to
\r
224 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
\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
234 function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
\r
235 $string = (string) $string;
\r
237 if ( 0 === strlen( $string ) )
\r
240 // Don't bother if there are no specialchars - saves some processing
\r
241 if ( ! preg_match( '/[&<>"\']/', $string ) )
\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
250 $charset = 'UTF-8';
\r
252 $_quote_style = $quote_style;
\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
261 // Handle double encoding ourselves
\r
262 if ( $double_encode ) {
\r
263 $string = @htmlspecialchars( $string, $quote_style, $charset );
\r
265 // Decode & into &
\r
266 $string = yourls_specialchars_decode( $string, $_quote_style );
\r
268 // Guarantee every &entity; is valid or re-encode the &
\r
269 $string = yourls_kses_normalize_entities( $string );
\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
274 for ( $i = 0; $i < count( $string ); $i += 2 )
\r
275 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
\r
277 $string = implode( '', $string );
\r
280 // Backwards compatibility
\r
281 if ( 'single' === $_quote_style )
\r
282 $string = str_replace( "'", ''', $string );
\r
288 * Converts a number of HTML entities into their special characters. Stolen from WP.
\r
290 * Specifically deals with: &, <, >, ", and '.
\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
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
301 function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
\r
302 $string = (string) $string;
\r
304 if ( 0 === strlen( $string ) ) {
\r
308 // Don't bother if there are no entities - saves a lot of processing
\r
309 if ( strpos( $string, '&' ) === false ) {
\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
320 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
\r
321 $single = array( ''' => '\'', ''' => '\'' );
\r
322 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
\r
323 $double = array( '"' => '"', '"' => '"', '"' => '"' );
\r
324 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
\r
325 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
\r
326 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
\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
342 // Remove zero padding on numeric entities
\r
343 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
\r
345 // Replace characters according to translation table
\r
346 return strtr( $string, $translation );
\r
351 * Escaping for HTML blocks. Stolen from WP
\r
355 * @param string $text
\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
365 * Escaping for HTML attributes. Stolen from WP
\r
369 * @param string $text
\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
379 * Checks and cleans a URL before printing it. Stolen from WP.
\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
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
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
402 // make sure there's a protocol, add http:// if not
\r
403 if ( ! yourls_get_protocol( $url ) )
\r
404 $url = 'http://'.$url;
\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
411 $original_url = $url;
\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
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( '&', '&', $url );
\r
424 $url = str_replace( "'", ''', $url );
\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
433 if ( !yourls_is_allowed_protocol( $url, $protocols ) )
\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
438 $url = substr( $url, 0, 1999 );
\r
440 return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
\r
444 * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
\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
452 * @param string $text The text to be escaped.
\r
453 * @return string Escaped text.
\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
465 * Escaping for textarea values. Stolen from WP.
\r
469 * @param string $text
\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
479 * PHP emulation of JS's encodeURI
\r
481 * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
\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