]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-formatting.php
yourls_get_protocol() can return '', not false
[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 "http://sho.rt/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  * @since 1.5
78  * @param string $unsafe_title  Title, potentially unsafe
79  * @param string $fallback      Optional fallback if after sanitization nothing remains
80  * @return string               Safe title
81  */
82 function yourls_sanitize_title( $unsafe_title, $fallback = '' ) {
83         $title = $unsafe_title;
84         $title = strip_tags( $title );
85         $title = preg_replace( "/\s+/", ' ', trim( $title ) );
86     
87     if ( '' === $title || false === $title ) {
88         $title = $fallback;
89     }
90     
91         return yourls_apply_filter( 'sanitize_title', $title, $unsafe_title, $fallback );
92 }
93
94 /**
95  * A few sanity checks on the URL. Used for redirection or DB. For display purpose, see yourls_esc_url()
96  *
97  * @param string $unsafe_url unsafe URL
98  * @param array $protocols Optional allowed protocols, default to global $yourls_allowedprotocols
99  * @return string Safe URL
100  */
101 function yourls_sanitize_url( $unsafe_url, $protocols = array() ) {
102         $url = yourls_esc_url( $unsafe_url, 'redirection', $protocols );
103         return yourls_apply_filter( 'sanitize_url', $url, $unsafe_url );
104 }
105
106 /**
107  * Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''
108  *
109  * Stolen from WP's _deep_replace
110  *
111  */
112 function yourls_deep_replace( $search, $subject ){
113         $found = true;
114         while($found) {
115                 $found = false;
116                 foreach( (array) $search as $val ) {
117                         while( strpos( $subject, $val ) !== false ) {
118                                 $found = true;
119                                 $subject = str_replace( $val, '', $subject );
120                         }
121                 }
122         }
123         
124         return $subject;
125 }
126
127 /**
128  * Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)
129  *
130  */
131 function yourls_sanitize_int( $in ) {
132         return ( substr( preg_replace( '/[^0-9]/', '', strval( $in ) ), 0, 20 ) );
133 }
134
135 /**
136  * Escape a string or an array of strings before DB usage. ALWAYS escape before using in a SQL query. Thanks.
137  *
138  * @param string|array $data string or array of strings to be escaped
139  * @return string|array escaped data
140  */
141 function yourls_escape( $data ) {
142         if( is_array( $data ) ) {
143                 foreach( $data as $k => $v ) {
144                         if( is_array( $v ) ) {
145                                 $data[ $k ] = yourls_escape( $v );
146                         } else {
147                                 $data[ $k ] = yourls_escape_real( $v );
148                         }
149                 }
150         } else {
151                 $data = yourls_escape_real( $data );
152         }
153         
154         return $data;
155 }
156
157 /**
158  * "Real" escape. This function should NOT be called directly. Use yourls_escape() instead. 
159  *
160  * This function uses a "real" escape if possible, using PDO, MySQL or MySQLi functions,
161  * with a fallback to a "simple" addslashes
162  * If you're implementing a custom DB engine or a custom cache system, you can define an
163  * escape function using filter 'custom_escape_real'
164  *
165  * @since 1.7
166  * @param string $a string to be escaped
167  * @return string escaped string
168  */
169 function yourls_escape_real( $string ) {
170         global $ydb;
171         if( isset( $ydb ) && ( $ydb instanceof ezSQLcore ) )
172                 return $ydb->escape( $string );
173         
174         // YOURLS DB classes have been bypassed by a custom DB engine or a custom cache layer
175         return yourls_apply_filter( 'custom_escape_real', addslashes( $string ), $string );     
176 }
177
178 /**
179  * Sanitize an IP address
180  *
181  */
182 function yourls_sanitize_ip( $ip ) {
183         return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
184 }
185
186 /**
187  * Make sure a date is m(m)/d(d)/yyyy, return false otherwise
188  *
189  */
190 function yourls_sanitize_date( $date ) {
191         if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {
192                 return false;
193         }
194         return $date;
195 }
196
197 /**
198  * Sanitize a date for SQL search. Return false if malformed input.
199  *
200  */
201 function yourls_sanitize_date_for_sql( $date ) {
202         if( !yourls_sanitize_date( $date ) )
203                 return false;
204         return date( 'Y-m-d', strtotime( $date ) );
205 }
206
207 /**
208  * Return trimmed string
209  *
210  */
211 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {
212         $newstring = $string;
213         if( function_exists( 'mb_substr' ) ) {
214                 if ( mb_strlen( $newstring ) > $length ) {
215                         $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;     
216                 }
217         } else {
218                 if ( strlen( $newstring ) > $length ) {
219                         $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;    
220                 }
221         }
222         return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );
223 }
224
225 /**
226  * Sanitize a version number (1.4.1-whatever-RC1 -> 1.4.1)
227  *
228  * @since 1.4.1
229  * @param string $ver Version number
230  * @return string Sanitized version number
231  */
232 function yourls_sanitize_version( $ver ) {
233         preg_match( '/(^[0-9.]+).*$/', $ver, $matches );
234     return isset( $matches[1] ) ? trim( $matches[1], '.' ) : '';
235 }
236
237 /**
238  * Sanitize a filename (no Win32 stuff)
239  *
240  */
241 function yourls_sanitize_filename( $file ) {
242         $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs
243         $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash
244         return $file;
245 }
246
247 /**
248  * Check if a string seems to be UTF-8. Stolen from WP.
249  *
250  */
251 function yourls_seems_utf8( $str ) {
252         $length = strlen( $str );
253         for ( $i=0; $i < $length; $i++ ) {
254                 $c = ord( $str[ $i ] );
255                 if ( $c < 0x80 ) $n = 0; # 0bbbbbbb
256                 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
257                 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
258                 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
259                 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
260                 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
261                 else return false; # Does not match any model
262                 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
263                         if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
264                                 return false;
265                 }
266         }
267         return true;
268 }
269
270 /**
271  * Checks for invalid UTF8 in a string. Stolen from WP
272  *
273  * @since 1.6
274  *
275  * @param string $string The text which is to be checked.
276  * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
277  * @return string The checked text.
278  */
279 function yourls_check_invalid_utf8( $string, $strip = false ) {
280         $string = (string) $string;
281
282         if ( 0 === strlen( $string ) ) {
283                 return '';
284         }
285
286         // Check for support for utf8 in the installed PCRE library once and store the result in a static
287         static $utf8_pcre;
288         if ( !isset( $utf8_pcre ) ) {
289                 $utf8_pcre = @preg_match( '/^./u', 'a' );
290         }
291         // We can't demand utf8 in the PCRE installation, so just return the string in those cases
292         if ( !$utf8_pcre ) {
293                 return $string;
294         }
295
296         // preg_match fails when it encounters invalid UTF8 in $string
297         if ( 1 === @preg_match( '/^./us', $string ) ) {
298                 return $string;
299         }
300
301         // Attempt to strip the bad chars if requested (not recommended)
302         if ( $strip && function_exists( 'iconv' ) ) {
303                 return iconv( 'utf-8', 'utf-8', $string );
304         }
305
306         return '';
307 }
308
309 /**
310  * Converts a number of special characters into their HTML entities. Stolen from WP.
311  *
312  * Specifically deals with: &, <, >, ", and '.
313  *
314  * $quote_style can be set to ENT_COMPAT to encode " to
315  * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
316  *
317  * @since 1.6
318  *
319  * @param string $string The text which is to be encoded.
320  * @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.
321  * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
322  * @return string The encoded text with HTML entities.
323  */
324 function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
325         $string = (string) $string;
326
327         if ( 0 === strlen( $string ) )
328                 return '';
329
330         // Don't bother if there are no specialchars - saves some processing
331         if ( ! preg_match( '/[&<>"\']/', $string ) )
332                 return $string;
333
334         // Account for the previous behaviour of the function when the $quote_style is not an accepted value
335         if ( empty( $quote_style ) )
336                 $quote_style = ENT_NOQUOTES;
337         elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
338                 $quote_style = ENT_QUOTES;
339
340         $charset = 'UTF-8';
341
342         $_quote_style = $quote_style;
343
344         if ( $quote_style === 'double' ) {
345                 $quote_style = ENT_COMPAT;
346                 $_quote_style = ENT_COMPAT;
347         } elseif ( $quote_style === 'single' ) {
348                 $quote_style = ENT_NOQUOTES;
349         }
350
351         // Handle double encoding ourselves
352         if ( $double_encode ) {
353                 $string = @htmlspecialchars( $string, $quote_style, $charset );
354         } else {
355                 // Decode &amp; into &
356                 $string = yourls_specialchars_decode( $string, $_quote_style );
357
358                 // Guarantee every &entity; is valid or re-encode the &
359                 $string = yourls_kses_normalize_entities( $string );
360
361                 // Now re-encode everything except &entity;
362                 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
363
364                 for ( $i = 0; $i < count( $string ); $i += 2 )
365                         $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
366
367                 $string = implode( '', $string );
368         }
369
370         // Backwards compatibility
371         if ( 'single' === $_quote_style )
372                 $string = str_replace( "'", '&#039;', $string );
373
374         return $string;
375 }
376
377 /**
378  * Converts a number of HTML entities into their special characters. Stolen from WP.
379  *
380  * Specifically deals with: &, <, >, ", and '.
381  *
382  * $quote_style can be set to ENT_COMPAT to decode " entities,
383  * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
384  *
385  * @since 1.6
386  *
387  * @param string $string The text which is to be decoded.
388  * @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.
389  * @return string The decoded text without HTML entities.
390  */
391 function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
392         $string = (string) $string;
393
394         if ( 0 === strlen( $string ) ) {
395                 return '';
396         }
397
398         // Don't bother if there are no entities - saves a lot of processing
399         if ( strpos( $string, '&' ) === false ) {
400                 return $string;
401         }
402
403         // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
404         if ( empty( $quote_style ) ) {
405                 $quote_style = ENT_NOQUOTES;
406         } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
407                 $quote_style = ENT_QUOTES;
408         }
409
410         // More complete than get_html_translation_table( HTML_SPECIALCHARS )
411         $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
412         $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
413         $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
414         $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
415         $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
416         $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
417
418         if ( $quote_style === ENT_QUOTES ) {
419                 $translation = array_merge( $single, $double, $others );
420                 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
421         } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
422                 $translation = array_merge( $double, $others );
423                 $translation_preg = array_merge( $double_preg, $others_preg );
424         } elseif ( $quote_style === 'single' ) {
425                 $translation = array_merge( $single, $others );
426                 $translation_preg = array_merge( $single_preg, $others_preg );
427         } elseif ( $quote_style === ENT_NOQUOTES ) {
428                 $translation = $others;
429                 $translation_preg = $others_preg;
430         }
431
432         // Remove zero padding on numeric entities
433         $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
434
435         // Replace characters according to translation table
436         return strtr( $string, $translation );
437 }
438
439
440 /**
441  * Escaping for HTML blocks. Stolen from WP
442  *
443  * @since 1.6
444  *
445  * @param string $text
446  * @return string
447  */
448 function yourls_esc_html( $text ) {
449         $safe_text = yourls_check_invalid_utf8( $text );
450         $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
451         return yourls_apply_filter( 'esc_html', $safe_text, $text );
452 }
453
454 /**
455  * Escaping for HTML attributes.  Stolen from WP
456  *
457  * @since 1.6
458  *
459  * @param string $text
460  * @return string
461  */
462 function yourls_esc_attr( $text ) {
463         $safe_text = yourls_check_invalid_utf8( $text );
464         $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
465         return yourls_apply_filter( 'esc_attr', $safe_text, $text );
466 }
467
468 /**
469  * Checks and cleans a URL before printing it. Stolen from WP.
470  *
471  * A number of characters are removed from the URL. If the URL is for displaying
472  * (the default behaviour) ampersands are also replaced.
473  *
474  * @since 1.6
475  *
476  * @param string $url The URL to be cleaned.
477  * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.
478  * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols
479  * @return string The cleaned $url
480  */
481 function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {
482         // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
483         $url = str_replace( 
484                 array( 'http://http://', 'http://https://' ),
485                 array( 'http://',        'https://'        ),
486                 $url
487         );
488
489         if ( '' == $url )
490                 return $url;
491
492         // make sure there's a protocol, add http:// if not
493         if ( ! yourls_get_protocol( $url ) )
494                 $url = 'http://'.$url;
495
496         $original_url = $url;
497
498         // force scheme and domain to lowercase - see issues 591 and 1630
499     $url = yourls_lowercase_scheme_domain( $url );
500
501         $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
502         // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'
503         // TODO: check if that was it too destructive
504         $strip = array( '%0d', '%0a', '%0D', '%0A' );
505         $url = yourls_deep_replace( $strip, $url );
506         $url = str_replace( ';//', '://', $url );
507
508         // Replace ampersands and single quotes only when displaying.
509         if ( 'display' == $context ) {
510                 $url = yourls_kses_normalize_entities( $url );
511                 $url = str_replace( '&amp;', '&#038;', $url );
512                 $url = str_replace( "'", '&#039;', $url );
513         }
514         
515         if ( ! is_array( $protocols ) or ! $protocols ) {
516                 global $yourls_allowedprotocols;
517                 $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );
518                 // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()
519         }
520
521         if ( !yourls_is_allowed_protocol( $url, $protocols ) )
522                 return '';
523         
524         // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)
525
526         return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
527 }
528
529
530 /**
531  * Lowercase scheme and domain of an URI - see issues 591, 1630, 1889
532  *
533  * This function is trickier than what seems to be needed at first
534  * 
535  * First, we need to handle several URI types: http://example.com, mailto:ozh@ozh.ozh, facetime:user@example.com, and so on, see
536  * yourls_kses_allowed_protocols() in functions-kses.php
537  * The general rule is that the scheme ("stuff://" or "stuff:") is case insensitive and should be lowercase. But then, depending on the
538  * scheme, parts of what follows the scheme may or may not be case sensitive.
539  *
540  * Second, simply using parse_url() and its opposite http_build_url() (see functions-compat.php) is a pretty unsafe process:
541  *  - parse_url() can easily trip up on malformed or weird URLs
542  *  - exploding a URL with parse_url(), lowercasing some stuff, and glueing things back with http_build_url() does not handle well
543  *    "stuff:"-like URI [1] and can result in URLs ending modified [2][3]. We don't want to *validate* URI, we just want to lowercase
544  *    what is supposed to be lowercased.
545  *
546  * So, to be conservative, this functions:
547  *  - lowercases the scheme
548  *  - does not lowercase anything else on "stuff:" URI
549  *  - tries to lowercase only scheme and domain of "stuff://" URI
550  *
551  * [1] http_build_url(parse_url("mailto:ozh")) == "mailto:///ozh"
552  * [2] http_build_url(parse_url("http://blah#omg")) == "http://blah/#omg"
553  * [3] http_build_url(parse_url("http://blah?#")) == "http://blah/"
554  *
555  * @since 1.7.1
556  * @param string $url URL
557  * @return string URL with lowercase scheme and protocol
558  */
559 function yourls_lowercase_scheme_domain( $url ) {
560     $scheme = yourls_get_protocol( $url );
561
562     if( '' == $scheme ) {
563         // Scheme not found, malformed URL? Something else? Not sure.
564         return $url;
565     }
566
567     // Case 1 : scheme like "stuff://" (eg "http://example.com/" or "ssh://joe@joe.com")
568     if( substr( $scheme, -2, 2 ) == '//' ) {
569
570         $parts = parse_url( $url );
571
572         // Most likely malformed stuff, could not parse : we'll just lowercase the scheme and leave the rest untouched
573         if( false == $parts ) {
574             $url = str_replace( $scheme, strtolower( $scheme ), $url );
575
576         // URL seems parsable, let's do the best we can
577         } else {
578
579             $lower = array();
580
581             $lower['scheme'] = strtolower( $parts['scheme'] );
582
583             if( isset( $parts['host'] ) ) { 
584                 $lower['host'] = strtolower( $parts['host'] );
585             } else {
586                 $parts['host'] = '***';
587             }
588
589             // We're not going to glue back things that could be modified in the process            
590             unset( $parts['path'] );
591             unset( $parts['query'] );
592             unset( $parts['fragment'] );
593
594             // original beginning of the URL and its lowercase-where-needed counterpart
595             // We trim the / after the domain to avoid avoid "http://example.com" being reconstructed as "http://example.com/"
596             $partial_original_url       = trim( http_build_url( $parts ), '/' );
597             $partial_lower_original_url = trim( http_build_url( $parts, $lower ), '/' );
598
599             $url = str_replace( $partial_original_url , $partial_lower_original_url, $url );
600
601         }
602
603     // Case 2 : scheme like "stuff:" (eg "mailto:joe@joe.com" or "bitcoin:15p1o8vnWqNkJBJGgwafNgR1GCCd6EGtQR?amount=1&label=Ozh")
604     // In this case, we only lowercase the scheme, because depending on it, things after should or should not be lowercased
605     } else {
606
607         $url = str_replace( $scheme, strtolower( $scheme ), $url );
608
609     }
610
611     return $url;
612 }
613
614
615 /**
616  * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
617  *
618  * Escapes text strings for echoing in JS. It is intended to be used for inline JS
619  * (in a tag attribute, for example onclick="..."). Note that the strings have to
620  * be in single quotes. The filter 'js_escape' is also applied here.
621  *
622  * @since 1.6
623  *
624  * @param string $text The text to be escaped.
625  * @return string Escaped text.
626  */
627 function yourls_esc_js( $text ) {
628         $safe_text = yourls_check_invalid_utf8( $text );
629         $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );
630         $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
631         $safe_text = str_replace( "\r", '', $safe_text );
632         $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
633         return yourls_apply_filter( 'esc_js', $safe_text, $text );
634 }
635
636 /**
637  * Escaping for textarea values. Stolen from WP.
638  *
639  * @since 1.6
640  *
641  * @param string $text
642  * @return string
643  */
644 function yourls_esc_textarea( $text ) {
645         $safe_text = htmlspecialchars( $text, ENT_QUOTES );
646         return yourls_apply_filter( 'esc_textarea', $safe_text, $text );
647 }
648
649
650 /**
651 * PHP emulation of JS's encodeURI
652 *
653 * @link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
654 * @param $url
655 * @return string
656 */
657 function yourls_encodeURI( $url ) {
658         // Decode URL all the way
659         $result = yourls_rawurldecode_while_encoded( $url );
660         // Encode once
661         $result = strtr( rawurlencode( $result ), array (
662         '%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':', '%40' => '@',
663                 '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$', '%21' => '!', '%2A' => '*',
664                 '%27' => '\'', '%28' => '(', '%29' => ')', '%23' => '#',
665     ) );
666         // @TODO:
667         // Known limit: this will most likely break IDN URLs such as http://www.académie-française.fr/
668         // To fully support IDN URLs, advocate use of a plugin.
669         return yourls_apply_filter( 'encodeURI', $result, $url );
670 }
671
672 /**
673  * Adds backslashes before letters and before a number at the start of a string. Stolen from WP.
674  *
675  * @since 1.6
676  *
677  * @param string $string Value to which backslashes will be added.
678  * @return string String with backslashes inserted.
679  */
680 function yourls_backslashit($string) {
681     $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
682     $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
683     return $string;
684 }
685
686 /**
687  * Check if a string seems to be urlencoded
688  *
689  * We use rawurlencode instead of urlencode to avoid messing with '+'
690  *
691  * @since 1.7
692  * @param string $string
693  * @return bool
694  */
695 function yourls_is_rawurlencoded( $string ) {
696         return rawurldecode( $string ) != $string;
697 }
698
699 /**
700  * rawurldecode a string till it's not encoded anymore
701  *
702  * Deals with multiple encoding (eg "%2521" => "%21" => "!").
703  * See https://github.com/YOURLS/YOURLS/issues/1303
704  *
705  * @since 1.7
706  * @param string $string
707  * @return string
708  */
709 function yourls_rawurldecode_while_encoded( $string ) {
710         $string = rawurldecode( $string );
711         if( yourls_is_rawurlencoded( $string ) ) {
712                 $string = yourls_rawurldecode_while_encoded( $string );
713         }
714         return $string;
715 }
716
717 /**
718  * Converts readable Javascript code into a valid bookmarklet link
719  *
720  * Uses https://github.com/ozh/bookmarkletgen
721  *
722  * @since 1.7.1
723  * @param  string $code  Javascript code
724  * @return string        Bookmarklet link
725  */
726 function yourls_make_bookmarklet( $code ) {
727     if ( !class_exists( 'BookmarkletGen', false ) ) {
728         require_once YOURLS_INC . '/BookmarkletGen/BookmarkletGen.php';
729     }
730
731     $book = new BookmarkletGen;
732     return $book->crunch( $code );
733 }