]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions.php
Merge pull request #1359 from adigitalife/master
[Github/YOURLS.git] / includes / functions.php
1 <?php
2 /*
3  * YOURLS
4  * Function library
5  */
6
7 /**
8  * Determine the allowed character set in short URLs
9  * 
10  */
11 function yourls_get_shorturl_charset() {
12         static $charset = null;
13         if( $charset !== null )
14                 return $charset;
15                 
16         if( !defined('YOURLS_URL_CONVERT') ) {
17                 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
18         } else {
19                 switch( YOURLS_URL_CONVERT ) {
20                         case 36:
21                                 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
22                                 break;
23                         case 62:
24                         case 64: // just because some people get this wrong in their config.php
25                                 $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
26                                 break;
27                 }
28         }
29         
30         $charset = yourls_apply_filter( 'get_shorturl_charset', $charset );
31         return $charset;
32 }
33  
34 /**
35  * Make an optimized regexp pattern from a string of characters
36  * 
37  */
38 function yourls_make_regexp_pattern( $string ) {
39         $pattern = preg_quote( $string, '-' ); // add - as an escaped characters -- this is fixed in PHP 5.3
40         // TODO: replace char sequences by smart sequences such as 0-9, a-z, A-Z ... ?
41         return $pattern;
42 }
43
44 /**
45  * Is a URL a short URL?
46  * 
47  */
48 function yourls_is_shorturl( $shorturl ) {
49         // TODO: make sure this function evolves with the feature set.
50         
51         $is_short = false;
52         $keyword = yourls_get_relative_url( $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'
53         if( $keyword && $keyword == yourls_sanitize_string( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {
54                 $is_short = true;
55         }
56         
57         return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );
58 }
59
60 /**
61  * Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool
62  *
63  */
64 function yourls_keyword_is_reserved( $keyword ) {
65         global $yourls_reserved_URL;
66         $keyword = yourls_sanitize_keyword( $keyword );
67         $reserved = false;
68         
69         if ( in_array( $keyword, $yourls_reserved_URL)
70                 or file_exists( YOURLS_ABSPATH ."/pages/$keyword.php" )
71                 or is_dir( YOURLS_ABSPATH ."/$keyword" )
72         )
73                 $reserved = true;
74         
75         return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );
76 }
77
78 /**
79  * Function: Get client IP Address. Returns a DB safe string.
80  *
81  */
82 function yourls_get_IP() {
83         // Precedence: if set, X-Forwarded-For > HTTP_X_FORWARDED_FOR > HTTP_CLIENT_IP > HTTP_VIA > REMOTE_ADDR
84         $headers = array( 'X-Forwarded-For', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_VIA', 'REMOTE_ADDR' );
85         foreach( $headers as $header ) {
86                 if ( !empty( $_SERVER[ $header ] ) ) {
87                         $ip = $_SERVER[ $header ];
88                         break;
89                 }
90         }
91         
92         // headers can contain multiple IPs (X-Forwarded-For = client, proxy1, proxy2). Take first one.
93         if ( strpos( $ip, ',' ) !== false )
94                 $ip = substr( $ip, 0, strpos( $ip, ',' ) );
95         
96         return yourls_apply_filter( 'get_IP', yourls_sanitize_ip( $ip ) );
97 }
98
99 /**
100  * Get next id a new link will have if no custom keyword provided
101  *
102  */
103 function yourls_get_next_decimal() {
104         return yourls_apply_filter( 'get_next_decimal', (int)yourls_get_option( 'next_id' ) );
105 }
106
107 /**
108  * Update id for next link with no custom keyword
109  *
110  */
111 function yourls_update_next_decimal( $int = '' ) {
112         $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
113         $update = yourls_update_option( 'next_id', $int );
114         yourls_do_action( 'update_next_decimal', $int, $update );
115         return $update;
116 }
117
118 /**
119  * Delete a link in the DB
120  *
121  */
122 function yourls_delete_link_by_keyword( $keyword ) {
123         global $ydb;
124
125         $table = YOURLS_DB_TABLE_URL;
126         $keyword = yourls_sanitize_string( $keyword );
127         $delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
128         yourls_do_action( 'delete_link', $keyword, $delete );
129         return $delete;
130 }
131
132 /**
133  * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting
134  *
135  */
136 function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {
137         global $ydb;
138         
139         $url     = yourls_escape( yourls_sanitize_url( $url ) );
140         $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
141         $title   = yourls_escape( yourls_sanitize_title( $title ) );
142
143         $table = YOURLS_DB_TABLE_URL;
144         $timestamp = date('Y-m-d H:i:s');
145         $ip = yourls_get_IP();
146         $insert = $ydb->query("INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");
147         
148         yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );
149         
150         return (bool)$insert;
151 }
152
153 /**
154  * Check if a URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.
155  *
156  */
157 function yourls_url_exists( $url ) {
158         // Allow plugins to short-circuit the whole function
159         $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );
160         if ( false !== $pre )
161                 return $pre;
162
163         global $ydb;
164         $table = YOURLS_DB_TABLE_URL;
165         $strip_url = stripslashes($url);
166         $url_exists = $ydb->get_row("SELECT * FROM `$table` WHERE `url` = '".$strip_url."';");
167         
168         return yourls_apply_filter( 'url_exists', $url_exists, $url );
169 }
170
171 /**
172  * Add a new link in the DB, either with custom keyword, or find one
173  *
174  */
175 function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
176         global $ydb;
177
178         // Allow plugins to short-circuit the whole function
179         $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
180         if ( false !== $pre )
181                 return $pre;
182                 
183         $url = yourls_encodeURI( $url );
184         $url = yourls_escape( yourls_sanitize_url( $url ) );
185         if ( !$url || $url == 'http://' || $url == 'https://' ) {
186                 $return['status']    = 'fail';
187                 $return['code']      = 'error:nourl';
188                 $return['message']   = yourls__( 'Missing or malformed URL' );
189                 $return['errorCode'] = '400';
190                 return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
191         }
192         
193         // Prevent DB flood
194         $ip = yourls_get_IP();
195         yourls_check_IP_flood( $ip );
196         
197         // Prevent internal redirection loops: cannot shorten a shortened URL
198         if( yourls_get_relative_url( $url ) ) {
199                 if( yourls_is_shorturl( $url ) ) {
200                         $return['status']    = 'fail';
201                         $return['code']      = 'error:noloop';
202                         $return['message']   = yourls__( 'URL is a short URL' );
203                         $return['errorCode'] = '400';
204                         return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );
205                 }
206         }
207
208         yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );
209         
210         $strip_url = stripslashes( $url );
211         $return = array();
212
213         // duplicates allowed or new URL => store it
214         if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_url_exists( $url ) ) ) {
215         
216                 if( isset( $title ) && !empty( $title ) ) {
217                         $title = yourls_sanitize_title( $title );
218                 } else {
219                         $title = yourls_get_remote_title( $url );
220                 }
221                 $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );
222
223                 // Custom keyword provided
224                 if ( $keyword ) {
225                         
226                         yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );
227                 
228                         $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
229                         $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );
230                         if ( !yourls_keyword_is_free( $keyword ) ) {
231                                 // This shorturl either reserved or taken already
232                                 $return['status']  = 'fail';
233                                 $return['code']    = 'error:keyword';
234                                 $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );
235                         } else {
236                                 // all clear, store !
237                                 yourls_insert_link_in_db( $url, $keyword, $title );
238                                 $return['url']      = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
239                                 $return['status']   = 'success';
240                                 $return['message']  = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
241                                 $return['title']    = $title;
242                                 $return['html']     = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
243                                 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
244                         }
245
246                 // Create random keyword        
247                 } else {
248                         
249                         yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );
250                 
251                         $timestamp = date( 'Y-m-d H:i:s' );
252                         $id = yourls_get_next_decimal();
253                         $ok = false;
254                         do {
255                                 $keyword = yourls_int2string( $id );
256                                 $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );
257                                 $free = yourls_keyword_is_free($keyword);
258                                 $add_url = @yourls_insert_link_in_db( $url, $keyword, $title );
259                                 $ok = ($free && $add_url);
260                                 if ( $ok === false && $add_url === 1 ) {
261                                         // we stored something, but shouldn't have (ie reserved id)
262                                         $delete = yourls_delete_link_by_keyword( $keyword );
263                                         $return['extra_info'] .= '(deleted '.$keyword.')';
264                                 } else {
265                                         // everything ok, populate needed vars
266                                         $return['url']      = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );
267                                         $return['status']   = 'success';
268                                         $return['message']  = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
269                                         $return['title']    = $title;
270                                         $return['html']     = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
271                                         $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
272                                 }
273                                 $id++;
274                         } while ( !$ok );
275                         @yourls_update_next_decimal( $id );
276                 }
277
278         // URL was already stored
279         } else {
280                         
281                 yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );
282                 
283                 $return['status']   = 'fail';
284                 $return['code']     = 'error:url';
285                 $return['url']      = array( 'keyword' => $url_exists->keyword, 'url' => $strip_url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );
286                 $return['message']  = /* //translators: eg "http://someurl/ already exists" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $strip_url ) );
287                 $return['title']    = $url_exists->title; 
288                 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
289         }
290         
291         yourls_do_action( 'post_add_new_link', $url, $keyword, $title );
292
293         $return['statusCode'] = 200; // regardless of result, this is still a valid request
294         return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );
295 }
296
297
298 /**
299  * Edit a link
300  *
301  */
302 function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {
303         global $ydb;
304
305         $table = YOURLS_DB_TABLE_URL;
306         $url = yourls_escape (yourls_sanitize_url( $url ) );
307         $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
308         $title = yourls_escape( yourls_sanitize_title( $title ) );
309         $newkeyword = yourls_escape( yourls_sanitize_string( $newkeyword ) );
310         $strip_url = stripslashes( $url );
311         $strip_title = stripslashes( $title );
312         $old_url = $ydb->get_var( "SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';" );
313         
314         // Check if new URL is not here already
315         if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {
316                 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
317         } else {
318                 $new_url_already_there = false;
319         }
320         
321         // Check if the new keyword is not here already
322         if ( $newkeyword != $keyword ) {
323                 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
324         } else {
325                 $keyword_is_ok = true;
326         }
327         
328         yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );
329         
330         // All clear, update
331         if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
332                         $update_url = $ydb->query( "UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';" );
333                 if( $update_url ) {
334                         $return['url']     = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'title' => $strip_title, 'display_title' => yourls_trim_long_string( $strip_title ) );
335                         $return['status']  = 'success';
336                         $return['message'] = yourls__( 'Link updated in database' );
337                 } else {
338                         $return['status']  = 'fail';
339                         $return['message'] = /* //translators: "Error updating http://someurl/ (Shorturl: http://sho.rt/blah)" */ yourls_s( 'Error updating %s (Short URL: %s)', yourls_trim_long_string( $strip_url ), $keyword ) ;
340                 }
341         
342         // Nope
343         } else {
344                 $return['status']  = 'fail';
345                 $return['message'] = yourls__( 'URL or keyword already exists in database' );
346         }
347         
348         return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );
349 }
350
351 /**
352  * Update a title link (no checks for duplicates etc..)
353  *
354  */
355 function yourls_edit_link_title( $keyword, $title ) {
356         global $ydb;
357         
358         $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
359         $title = yourls_escape( yourls_sanitize_title( $title ) );
360         
361         $table = YOURLS_DB_TABLE_URL;
362         $update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");
363
364         return $update;
365 }
366
367
368 /**
369  * Check if keyword id is free (ie not already taken, and not reserved). Return bool.
370  *
371  */
372 function yourls_keyword_is_free( $keyword ) {
373         $free = true;
374         if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
375                 $free = false;
376                 
377         return yourls_apply_filter( 'keyword_is_free', $free, $keyword );
378 }
379
380 /**
381  * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.             
382  *
383  */
384 function yourls_keyword_is_taken( $keyword ) {
385
386         // Allow plugins to short-circuit the whole function
387         $pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );
388         if ( false !== $pre )
389                 return $pre;
390         
391         global $ydb;
392         $keyword = yourls_sanitize_keyword( $keyword );
393         $taken = false;
394         $table = YOURLS_DB_TABLE_URL;
395         $already_exists = $ydb->get_var( "SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';" );
396         if ( $already_exists )
397                 $taken = true;
398
399         return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );
400 }
401
402
403 /**
404  * Connect to DB
405  *
406  */
407 function yourls_db_connect() {
408         global $ydb;
409
410         if (   !defined( 'YOURLS_DB_USER' )
411                 or !defined( 'YOURLS_DB_PASS' )
412                 or !defined( 'YOURLS_DB_NAME' )
413                 or !defined( 'YOURLS_DB_HOST' )
414                 or !class_exists( 'ezSQL_mysql', false )
415         ) yourls_die ( yourls__( 'DB config missing, or could not find DB class' ), yourls__( 'Fatal error' ), 503 );
416         
417         // Are we standalone or in the WordPress environment?
418         if ( class_exists( 'wpdb', false ) ) {
419                 $ydb =  new wpdb( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
420         } else {
421                 $ydb =  new ezSQL_mysql( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
422         }
423         if ( $ydb->last_error )
424                 yourls_die( $ydb->last_error, yourls__( 'Fatal error' ), 503 );
425         
426         if ( defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG === true )
427                 $ydb->show_errors = true;
428         
429         return $ydb;
430 }
431
432 /**
433  * Return XML output.
434  *
435  */
436 function yourls_xml_encode( $array ) {
437         require_once( YOURLS_INC.'/functions-xml.php' );
438         $converter= new yourls_array2xml;
439         return $converter->array2xml( $array );
440 }
441
442 /**
443  * Return array of all informations associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB
444  *
445  */
446 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
447         global $ydb;
448         $keyword = yourls_sanitize_string( $keyword );
449
450         yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );
451
452         if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
453                 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
454         }
455         
456         yourls_do_action( 'get_keyword_not_cached', $keyword );
457         
458         $table = YOURLS_DB_TABLE_URL;
459         $infos = $ydb->get_row( "SELECT * FROM `$table` WHERE `keyword` = '$keyword'" );
460         
461         if( $infos ) {
462                 $infos = (array)$infos;
463                 $ydb->infos[ $keyword ] = $infos;
464         } else {
465                 $ydb->infos[ $keyword ] = false;
466         }
467                 
468         return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
469 }
470
471 /**
472  * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
473  *
474  */
475 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
476
477         // Allow plugins to short-circuit the whole function
478         $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );
479         if ( false !== $pre )
480                 return $pre;
481
482         $keyword = yourls_sanitize_string( $keyword );
483         $infos = yourls_get_keyword_infos( $keyword );
484         
485         $return = $notfound;
486         if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )
487                 $return = $infos[ $field ];
488
489         return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound ); 
490 }
491
492 /**
493  * Return title associated with keyword. Optional $notfound = string default message if nothing found
494  *
495  */
496 function yourls_get_keyword_title( $keyword, $notfound = false ) {
497         return yourls_get_keyword_info( $keyword, 'title', $notfound );
498 }
499
500 /**
501  * Return long URL associated with keyword. Optional $notfound = string default message if nothing found
502  *
503  */
504 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
505         return yourls_get_keyword_info( $keyword, 'url', $notfound );
506 }
507
508 /**
509  * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
510  *
511  */
512 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
513         return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
514 }
515
516 /**
517  * Return IP that added a keyword. Optional $notfound = string default message if nothing found
518  *
519  */
520 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
521         return yourls_get_keyword_info( $keyword, 'ip', $notfound );
522 }
523
524 /**
525  * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
526  *
527  */
528 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
529         return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
530 }
531
532 /**
533  * Update click count on a short URL. Return 0/1 for error/success.
534  *
535  */
536 function yourls_update_clicks( $keyword, $clicks = false ) {
537         // Allow plugins to short-circuit the whole function
538         $pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword, $clicks );
539         if ( false !== $pre )
540                 return $pre;
541
542         global $ydb;
543         $keyword = yourls_sanitize_string( $keyword );
544         $table = YOURLS_DB_TABLE_URL;
545         if ( $clicks !== false && is_int( $clicks ) && $clicks >= 0 )
546                 $update = $ydb->query( "UPDATE `$table` SET `clicks` = $clicks WHERE `keyword` = '$keyword'" );
547         else
548                 $update = $ydb->query( "UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'" );
549
550         yourls_do_action( 'update_clicks', $keyword, $update, $clicks );
551         return $update;
552 }
553
554 /**
555  * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
556  *
557  */
558 function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {
559         global $ydb;
560
561         switch( $filter ) {
562                 case 'bottom':
563                         $sort_by    = 'clicks';
564                         $sort_order = 'asc';
565                         break;
566                 case 'last':
567                         $sort_by    = 'timestamp';
568                         $sort_order = 'desc';
569                         break;
570                 case 'rand':
571                 case 'random':
572                         $sort_by    = 'RAND()';
573                         $sort_order = '';
574                         break;
575                 case 'top':
576                 default:
577                         $sort_by    = 'clicks';
578                         $sort_order = 'desc';
579                         break;
580         }
581         
582         // Fetch links
583         $limit = intval( $limit );
584         $start = intval( $start );
585         if ( $limit > 0 ) {
586
587                 $table_url = YOURLS_DB_TABLE_URL;
588                 $results = $ydb->get_results( "SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;" );
589                 
590                 $return = array();
591                 $i = 1;
592                 
593                 foreach ( (array)$results as $res ) {
594                         $return['links']['link_'.$i++] = array(
595                                 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
596                                 'url'      => $res->url,
597                                 'title'    => $res->title,
598                                 'timestamp'=> $res->timestamp,
599                                 'ip'       => $res->ip,
600                                 'clicks'   => $res->clicks,
601                         );
602                 }
603         }
604
605         $return['stats'] = yourls_get_db_stats();
606         
607         $return['statusCode'] = 200;
608
609         return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );
610 }
611
612 /**
613  * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
614  *
615  */
616 function yourls_get_link_stats( $shorturl ) {
617         global $ydb;
618
619         $table_url = YOURLS_DB_TABLE_URL;
620         $res = $ydb->get_row( "SELECT * FROM `$table_url` WHERE keyword = '$shorturl';" );
621         $return = array();
622
623         if( !$res ) {
624                 // non existent link
625                 $return = array(
626                         'statusCode' => 404,
627                         'message'    => 'Error: short URL not found',
628                 );
629         } else {
630                 $return = array(
631                         'statusCode' => 200,
632                         'message'    => 'success',
633                         'link'       => array(
634                                 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
635                                 'url'      => $res->url,
636                                 'title'    => $res->title,
637                                 'timestamp'=> $res->timestamp,
638                                 'ip'       => $res->ip,
639                                 'clicks'   => $res->clicks,
640                         )
641                 );
642         }
643
644         return yourls_apply_filter( 'get_link_stats', $return, $shorturl );
645 }
646
647 /**
648  * Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
649  *
650  */
651 function yourls_get_db_stats( $where = '' ) {
652         global $ydb;
653         $table_url = YOURLS_DB_TABLE_URL;
654
655         $totals = $ydb->get_row( "SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where" );
656         $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
657         
658         return yourls_apply_filter( 'get_db_stats', $return, $where );
659 }
660
661 /**
662  * Get number of SQL queries performed
663  *
664  */
665 function yourls_get_num_queries() {
666         global $ydb;
667
668         return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );
669 }
670
671 /**
672  * Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
673  *
674  */
675 function yourls_get_user_agent() {
676         if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
677                 return '-';
678         
679         $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
680         $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
681                 
682         return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );
683 }
684
685 /**
686  * Redirect to another page
687  *
688  */
689 function yourls_redirect( $location, $code = 301 ) {
690         yourls_do_action( 'pre_redirect', $location, $code );
691         $location = yourls_apply_filter( 'redirect_location', $location, $code );
692         $code     = yourls_apply_filter( 'redirect_code', $code, $location );
693         // Redirect, either properly if possible, or via Javascript otherwise
694         if( !headers_sent() ) {
695                 yourls_status_header( $code );
696                 header( "Location: $location" );
697         } else {
698                 yourls_redirect_javascript( $location );
699         }
700         die();
701 }
702
703 /**
704  * Set HTTP status header
705  *
706  */
707 function yourls_status_header( $code = 200 ) {
708         if( headers_sent() )
709                 return;
710                 
711         $protocol = $_SERVER["SERVER_PROTOCOL"];
712         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
713                 $protocol = 'HTTP/1.0';
714
715         $code = intval( $code );
716         $desc = yourls_get_HTTP_status( $code );
717
718         @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
719         yourls_do_action( 'status_header', $code );
720 }
721
722 /**
723  * Redirect to another page using Javascript. Set optional (bool)$dontwait to false to force manual redirection (make sure a message has been read by user)
724  *
725  */
726 function yourls_redirect_javascript( $location, $dontwait = true ) {
727         yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );
728         $location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );
729         if( $dontwait ) {
730                 $message = yourls_s( 'if you are not redirected after 10 seconds, please <a href="%s">click here</a>', $location );
731                 echo <<<REDIR
732                 <script type="text/javascript">
733                 window.location="$location";
734                 </script>
735                 <small>($message)</small>
736 REDIR;
737         } else {
738                 echo '<p>' . yourls_s( 'Please <a href="%s">click here</a>', $location ) . '</p>';
739         }
740         yourls_do_action( 'post_redirect_javascript', $location );
741 }
742
743 /**
744  * Return a HTTP status code
745  *
746  */
747 function yourls_get_HTTP_status( $code ) {
748         $code = intval( $code );
749         $headers_desc = array(
750                 100 => 'Continue',
751                 101 => 'Switching Protocols',
752                 102 => 'Processing',
753
754                 200 => 'OK',
755                 201 => 'Created',
756                 202 => 'Accepted',
757                 203 => 'Non-Authoritative Information',
758                 204 => 'No Content',
759                 205 => 'Reset Content',
760                 206 => 'Partial Content',
761                 207 => 'Multi-Status',
762                 226 => 'IM Used',
763
764                 300 => 'Multiple Choices',
765                 301 => 'Moved Permanently',
766                 302 => 'Found',
767                 303 => 'See Other',
768                 304 => 'Not Modified',
769                 305 => 'Use Proxy',
770                 306 => 'Reserved',
771                 307 => 'Temporary Redirect',
772
773                 400 => 'Bad Request',
774                 401 => 'Unauthorized',
775                 402 => 'Payment Required',
776                 403 => 'Forbidden',
777                 404 => 'Not Found',
778                 405 => 'Method Not Allowed',
779                 406 => 'Not Acceptable',
780                 407 => 'Proxy Authentication Required',
781                 408 => 'Request Timeout',
782                 409 => 'Conflict',
783                 410 => 'Gone',
784                 411 => 'Length Required',
785                 412 => 'Precondition Failed',
786                 413 => 'Request Entity Too Large',
787                 414 => 'Request-URI Too Long',
788                 415 => 'Unsupported Media Type',
789                 416 => 'Requested Range Not Satisfiable',
790                 417 => 'Expectation Failed',
791                 422 => 'Unprocessable Entity',
792                 423 => 'Locked',
793                 424 => 'Failed Dependency',
794                 426 => 'Upgrade Required',
795
796                 500 => 'Internal Server Error',
797                 501 => 'Not Implemented',
798                 502 => 'Bad Gateway',
799                 503 => 'Service Unavailable',
800                 504 => 'Gateway Timeout',
801                 505 => 'HTTP Version Not Supported',
802                 506 => 'Variant Also Negotiates',
803                 507 => 'Insufficient Storage',
804                 510 => 'Not Extended'
805         );
806
807         if ( isset( $headers_desc[$code] ) )
808                 return $headers_desc[$code];
809         else
810                 return '';
811 }
812
813
814 /**
815  * Log a redirect (for stats)
816  *
817  */
818 function yourls_log_redirect( $keyword ) {
819         // Allow plugins to short-circuit the whole function
820         $pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );
821         if ( false !== $pre )
822                 return $pre;
823
824         if ( !yourls_do_log_redirect() )
825                 return true;
826
827         global $ydb;
828         $table = YOURLS_DB_TABLE_LOG;
829         
830         $keyword = yourls_sanitize_string( $keyword );
831         $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
832         $ua = yourls_get_user_agent();
833         $ip = yourls_get_IP();
834         $location = yourls_geo_ip_to_countrycode( $ip );
835         
836         return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
837 }
838
839 /**
840  * Check if we want to not log redirects (for stats)
841  *
842  */
843 function yourls_do_log_redirect() {
844         return ( !defined( 'YOURLS_NOSTATS' ) || YOURLS_NOSTATS != true );
845 }
846
847 /**
848  * Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
849  *
850  */
851 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
852         // Allow plugins to short-circuit the Geo IP API
853         $location = yourls_apply_filter( 'shunt_geo_ip_to_countrycode', false, $ip, $default ); // at this point $ip can be '', check if your plugin hooks in here
854         if ( false !== $location )
855                 return $location;
856
857         if ( !file_exists( YOURLS_INC.'/geo/GeoIP.dat') || !file_exists( YOURLS_INC.'/geo/geoip.inc') )
858                 return $default;
859
860         if ( $ip == '' )
861                 $ip = yourls_get_IP();
862         
863         require_once( YOURLS_INC.'/geo/geoip.inc') ;
864         $gi = geoip_open( YOURLS_INC.'/geo/GeoIP.dat', GEOIP_STANDARD);
865         $location = geoip_country_code_by_addr($gi, $ip);
866         geoip_close($gi);
867
868         return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );
869 }
870
871 /**
872  * Converts a 2 letter country code to long name (ie AU -> Australia)
873  *
874  */
875 function yourls_geo_countrycode_to_countryname( $code ) {
876         // Allow plugins to short-circuit the Geo IP API
877         $country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );
878         if ( false !== $country )
879                 return $country;
880
881         // Load the Geo class if not already done
882         if( !class_exists( 'GeoIP', false ) ) {
883                 $temp = yourls_geo_ip_to_countrycode( '127.0.0.1' );
884         }
885         
886         if( class_exists( 'GeoIP', false ) ) {
887                 $geo  = new GeoIP;
888                 $id   = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[ $code ];
889                 $long = $geo->GEOIP_COUNTRY_NAMES[ $id ];
890                 return $long;
891         } else {
892                 return false;
893         }
894 }
895
896 /**
897  * Return flag URL from 2 letter country code
898  *
899  */
900 function yourls_geo_get_flag( $code ) {
901         if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {
902                 $img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.( strtolower( $code ) ).'.gif' );
903         } else {
904                 $img = false;
905         }
906         return yourls_apply_filter( 'geo_get_flag', $img, $code );
907 }
908
909
910 /**
911  * Check if an upgrade is needed
912  *
913  */
914 function yourls_upgrade_is_needed() {
915         // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
916         list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
917         if( $currentsql < YOURLS_DB_VERSION )
918                 return true;
919                 
920         return false;
921 }
922
923 /**
924  * Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
925  *
926  */
927 function yourls_get_current_version_from_sql() {
928         $currentver = yourls_get_option( 'version' );
929         $currentsql = yourls_get_option( 'db_version' );
930
931         // Values if version is 1.3
932         if( !$currentver )
933                 $currentver = '1.3';
934         if( !$currentsql )
935                 $currentsql = '100';
936                 
937         return array( $currentver, $currentsql);
938 }
939
940 /**
941  * Read an option from DB (or from cache if available). Return value or $default if not found
942  *
943  */
944 function yourls_get_option( $option_name, $default = false ) {
945         global $ydb;
946         
947         // Allow plugins to short-circuit options
948         $pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );
949         if ( false !== $pre )
950                 return $pre;
951
952         // If option not cached already, get its value from the DB
953         if ( !isset( $ydb->option[$option_name] ) ) {
954                 $table = YOURLS_DB_TABLE_OPTIONS;
955                 $option_name = yourls_escape( $option_name );
956                 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
957                 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
958                         $value = $row->option_value;
959                 } else { // option does not exist, so we must cache its non-existence
960                         $value = $default;
961                 }
962                 $ydb->option[ $option_name ] = yourls_maybe_unserialize( $value );
963         }
964
965         return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );
966 }
967
968 /**
969  * Read all options from DB at once
970  *
971  */
972 function yourls_get_all_options() {
973         global $ydb;
974
975         // Allow plugins to short-circuit all options. (Note: regular plugins are loaded after all options)
976         $pre = yourls_apply_filter( 'shunt_all_options', false );
977         if ( false !== $pre )
978                 return $pre;
979
980         $table = YOURLS_DB_TABLE_OPTIONS;
981         
982         $allopt = $ydb->get_results( "SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1" );
983         
984         foreach( (array)$allopt as $option ) {
985                 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );
986         }
987         
988         $ydb->option = yourls_apply_filter( 'get_all_options', $ydb->option );
989 }
990
991 /**
992  * Update (add if doesn't exist) an option to DB
993  *
994  */
995 function yourls_update_option( $option_name, $newvalue ) {
996         global $ydb;
997         $table = YOURLS_DB_TABLE_OPTIONS;
998
999         $safe_option_name = yourls_escape( $option_name );
1000
1001         $oldvalue = yourls_get_option( $safe_option_name );
1002
1003         // If the new and old values are the same, no need to update.
1004         if ( $newvalue === $oldvalue )
1005                 return false;
1006
1007         if ( false === $oldvalue ) {
1008                 yourls_add_option( $option_name, $newvalue );
1009                 return true;
1010         }
1011
1012         $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
1013         
1014         yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );
1015
1016         $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'" );
1017
1018         if ( $ydb->rows_affected == 1 ) {
1019                 $ydb->option[ $option_name ] = $newvalue;
1020                 return true;
1021         }
1022         return false;
1023 }
1024
1025 /**
1026  * Add an option to the DB
1027  *
1028  */
1029 function yourls_add_option( $name, $value = '' ) {
1030         global $ydb;
1031         $table = YOURLS_DB_TABLE_OPTIONS;
1032         $safe_name = yourls_escape( $name );
1033
1034         // Make sure the option doesn't already exist
1035         if ( false !== yourls_get_option( $safe_name ) )
1036                 return;
1037
1038         $_value = yourls_escape( yourls_maybe_serialize( $value ) );
1039
1040         yourls_do_action( 'add_option', $safe_name, $_value );
1041
1042         $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
1043         $ydb->option[ $name ] = $value;
1044         return;
1045 }
1046
1047
1048 /**
1049  * Delete an option from the DB
1050  *
1051  */
1052 function yourls_delete_option( $name ) {
1053         global $ydb;
1054         $table = YOURLS_DB_TABLE_OPTIONS;
1055         $name = yourls_escape( $name );
1056
1057         // Get the ID, if no ID then return
1058         $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
1059         if ( is_null( $option ) || !$option->option_id )
1060                 return false;
1061                 
1062         yourls_do_action( 'delete_option', $option_name );
1063                 
1064         $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
1065         return true;
1066 }
1067
1068
1069
1070 /**
1071  * Serialize data if needed. Stolen from WordPress
1072  *
1073  */
1074 function yourls_maybe_serialize( $data ) {
1075         if ( is_array( $data ) || is_object( $data ) )
1076                 return serialize( $data );
1077
1078         if ( yourls_is_serialized( $data ) )
1079                 return serialize( $data );
1080
1081         return $data;
1082 }
1083
1084 /**
1085  * Check value to find if it was serialized. Stolen from WordPress
1086  *
1087  */
1088 function yourls_is_serialized( $data ) {
1089         // if it isn't a string, it isn't serialized
1090         if ( !is_string( $data ) )
1091                 return false;
1092         $data = trim( $data );
1093         if ( 'N;' == $data )
1094                 return true;
1095         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
1096                 return false;
1097         switch ( $badions[1] ) {
1098                 case 'a' :
1099                 case 'O' :
1100                 case 's' :
1101                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
1102                                 return true;
1103                         break;
1104                 case 'b' :
1105                 case 'i' :
1106                 case 'd' :
1107                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
1108                                 return true;
1109                         break;
1110         }
1111         return false;
1112 }
1113
1114 /**
1115  * Unserialize value only if it was serialized. Stolen from WP
1116  *
1117  */
1118 function yourls_maybe_unserialize( $original ) {
1119         if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
1120                 return @unserialize( $original );
1121         return $original;
1122 }
1123
1124 /**
1125  * Determine if the current page is private
1126  *
1127  */
1128 function yourls_is_private() {
1129         $private = false;
1130
1131         if ( defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true ) {
1132
1133                 // Allow overruling for particular pages:
1134                 
1135                 // API
1136                 if( yourls_is_API() ) {
1137                         if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
1138                                 $private = true;                
1139
1140                 // Infos
1141                 } elseif( yourls_is_infos() ) {
1142                         if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
1143                                 $private = true;
1144                 
1145                 // Others
1146                 } else {
1147                         $private = true;
1148                 }
1149                 
1150         }
1151                         
1152         return yourls_apply_filter( 'is_private', $private );
1153 }
1154
1155 /**
1156  * Show login form if required
1157  *
1158  */
1159 function yourls_maybe_require_auth() {
1160         if( yourls_is_private() ) {
1161                 yourls_do_action( 'require_auth' );
1162                 require_once( YOURLS_INC.'/auth.php' );
1163         } else {
1164                 yourls_do_action( 'require_no_auth' );
1165         }
1166 }
1167
1168 /**
1169  * Allow several short URLs for the same long URL ?
1170  *
1171  */
1172 function yourls_allow_duplicate_longurls() {
1173         // special treatment if API to check for WordPress plugin requests
1174         if( yourls_is_API() ) {
1175                 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' ) 
1176                         return false;
1177         }
1178         return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
1179 }
1180
1181 /**
1182  * Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.
1183  *
1184  */
1185 function yourls_get_duplicate_keywords( $longurl ) {
1186         if( !yourls_allow_duplicate_longurls() )
1187                 return NULL;
1188         
1189         global $ydb;
1190         $longurl = yourls_escape( yourls_sanitize_url($longurl) );
1191         $table = YOURLS_DB_TABLE_URL;
1192         
1193         $return = $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );
1194         return yourls_apply_filter( 'get_duplicate_keywords', $return, $longurl );
1195 }
1196
1197 /**
1198  * Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
1199  *
1200  */
1201 function yourls_check_IP_flood( $ip = '' ) {
1202
1203         // Allow plugins to short-circuit the whole function
1204         $pre = yourls_apply_filter( 'shunt_check_IP_flood', false, $ip );
1205         if ( false !== $pre )
1206                 return $pre;
1207
1208         yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here
1209
1210         if(
1211                 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
1212                 !defined('YOURLS_FLOOD_DELAY_SECONDS')
1213         )
1214                 return true;
1215
1216         $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
1217
1218         // Don't throttle whitelist IPs
1219         if( defined( 'YOURLS_FLOOD_IP_WHITELIST' ) && YOURLS_FLOOD_IP_WHITELIST ) {
1220                 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
1221                 foreach( (array)$whitelist_ips as $whitelist_ip ) {
1222                         $whitelist_ip = trim( $whitelist_ip );
1223                         if ( $whitelist_ip == $ip )
1224                                 return true;
1225                 }
1226         }
1227         
1228         // Don't throttle logged in users
1229         if( yourls_is_private() ) {
1230                  if( yourls_is_valid_user() === true )
1231                         return true;
1232         }
1233         
1234         yourls_do_action( 'check_ip_flood', $ip );
1235         
1236         global $ydb;
1237         $table = YOURLS_DB_TABLE_URL;
1238         
1239         $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
1240         if( $lasttime ) {
1241                 $now = date( 'U' );
1242                 $then = date( 'U', strtotime( $lasttime ) );
1243                 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
1244                         // Flood!
1245                         yourls_do_action( 'ip_flood', $ip, $now - $then );
1246                         yourls_die( yourls__( 'Too many URLs added too fast. Slow down please.' ), yourls__( 'Forbidden' ), 403 );
1247                 }
1248         }
1249         
1250         return true;
1251 }
1252
1253 /**
1254  * Check if YOURLS is installing
1255  *
1256  * @return bool
1257  * @since 1.6
1258  */
1259 function yourls_is_installing() {
1260         $installing = defined( 'YOURLS_INSTALLING' ) && YOURLS_INSTALLING == true;
1261         return yourls_apply_filter( 'is_installing', $installing );
1262 }
1263
1264 /**
1265  * Check if YOURLS is upgrading
1266  *
1267  * @return bool
1268  * @since 1.6
1269  */
1270 function yourls_is_upgrading() {
1271         $upgrading = defined( 'YOURLS_UPGRADING' ) && YOURLS_UPGRADING == true;
1272         return yourls_apply_filter( 'is_upgrading', $upgrading );
1273 }
1274
1275
1276 /**
1277  * Check if YOURLS is installed
1278  *
1279  */
1280 function yourls_is_installed() {
1281         static $is_installed = false;
1282         if ( $is_installed === false ) {
1283                 $check_14 = $check_13 = false;
1284                 global $ydb;
1285                 if( defined('YOURLS_DB_TABLE_NEXTDEC') )
1286                         $check_13 = $ydb->get_var('SELECT `next_id` FROM '.YOURLS_DB_TABLE_NEXTDEC);
1287                 $check_14 = yourls_get_option( 'version' );
1288                 $is_installed = $check_13 || $check_14;
1289         }
1290         return yourls_apply_filter( 'is_installed', $is_installed );
1291 }
1292
1293 /**
1294  * Generate random string of (int)$length length and type $type (see function for details)
1295  *
1296  */
1297 function yourls_rnd_string ( $length = 5, $type = 0, $charlist = '' ) {
1298         $str = '';
1299         $length = intval( $length );
1300
1301         // define possible characters
1302         switch ( $type ) {
1303
1304                 // custom char list, or comply to charset as defined in config
1305                 case '0':
1306                         $possible = $charlist ? $charlist : yourls_get_shorturl_charset() ;
1307                         break;
1308         
1309                 // no vowels to make no offending word, no 0/1/o/l to avoid confusion between letters & digits. Perfect for passwords.
1310                 case '1':
1311                         $possible = "23456789bcdfghjkmnpqrstvwxyz";
1312                         break;
1313                 
1314                 // Same, with lower + upper
1315                 case '2':
1316                         $possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
1317                         break;
1318                 
1319                 // all letters, lowercase
1320                 case '3':
1321                         $possible = "abcdefghijklmnopqrstuvwxyz";
1322                         break;
1323                 
1324                 // all letters, lowercase + uppercase
1325                 case '4':
1326                         $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1327                         break;
1328                 
1329                 // all digits & letters lowercase 
1330                 case '5':
1331                         $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
1332                         break;
1333                 
1334                 // all digits & letters lowercase + uppercase
1335                 case '6':
1336                         $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1337                         break;
1338                 
1339         }
1340
1341         $i = 0;
1342         while ($i < $length) {
1343                 $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
1344                 $i++;
1345         }
1346         
1347         return yourls_apply_filter( 'rnd_string', $str, $length, $type, $charlist );
1348 }
1349
1350 /**
1351  * Return salted string
1352  *
1353  */
1354 function yourls_salt( $string ) {
1355         $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
1356         return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt), $string );
1357 }
1358
1359 /**
1360  * Add a query var to a URL and return URL. Completely stolen from WP.
1361  * 
1362  * Works with one of these parameter patterns:
1363  *     array( 'var' => 'value' )
1364  *     array( 'var' => 'value' ), $url
1365  *     'var', 'value'
1366  *     'var', 'value', $url 
1367  * If $url ommited, uses $_SERVER['REQUEST_URI']
1368  *
1369  */
1370 function yourls_add_query_arg() {
1371         $ret = '';
1372         if ( is_array( func_get_arg(0) ) ) {
1373                 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
1374                         $uri = $_SERVER['REQUEST_URI'];
1375                 else
1376                         $uri = @func_get_arg( 1 );
1377         } else {
1378                 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
1379                         $uri = $_SERVER['REQUEST_URI'];
1380                 else
1381                         $uri = @func_get_arg( 2 );
1382         }
1383         
1384         $uri = str_replace( '&amp;', '&', $uri );
1385
1386         
1387         if ( $frag = strstr( $uri, '#' ) )
1388                 $uri = substr( $uri, 0, -strlen( $frag ) );
1389         else
1390                 $frag = '';
1391
1392         if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
1393                 $protocol = $matches[0];
1394                 $uri = substr( $uri, strlen( $protocol ) );
1395         } else {
1396                 $protocol = '';
1397         }
1398
1399         if ( strpos( $uri, '?' ) !== false ) {
1400                 $parts = explode( '?', $uri, 2 );
1401                 if ( 1 == count( $parts ) ) {
1402                         $base = '?';
1403                         $query = $parts[0];
1404                 } else {
1405                         $base = $parts[0] . '?';
1406                         $query = $parts[1];
1407                 }
1408         } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
1409                 $base = $uri . '?';
1410                 $query = '';
1411         } else {
1412                 $base = '';
1413                 $query = $uri;
1414         }
1415
1416         parse_str( $query, $qs );
1417         $qs = yourls_urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
1418         if ( is_array( func_get_arg( 0 ) ) ) {
1419                 $kayvees = func_get_arg( 0 );
1420                 $qs = array_merge( $qs, $kayvees );
1421         } else {
1422                 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1423         }
1424
1425         foreach ( (array) $qs as $k => $v ) {
1426                 if ( $v === false )
1427                         unset( $qs[$k] );
1428         }
1429
1430         $ret = http_build_query( $qs );
1431         $ret = trim( $ret, '?' );
1432         $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1433         $ret = $protocol . $base . $ret . $frag;
1434         $ret = rtrim( $ret, '?' );
1435         return $ret;
1436 }
1437
1438 /**
1439  * Navigates through an array and encodes the values to be used in a URL. Stolen from WP, used in yourls_add_query_arg()
1440  *
1441  */
1442 function yourls_urlencode_deep( $value ) {
1443         $value = is_array( $value ) ? array_map( 'yourls_urlencode_deep', $value ) : urlencode( $value );
1444         return $value;
1445 }
1446
1447 /**
1448  * Remove arg from query. Opposite of yourls_add_query_arg. Stolen from WP.
1449  *
1450  */
1451 function yourls_remove_query_arg( $key, $query = false ) {
1452         if ( is_array( $key ) ) { // removing multiple keys
1453                 foreach ( $key as $k )
1454                         $query = yourls_add_query_arg( $k, false, $query );
1455                 return $query;
1456         }
1457         return yourls_add_query_arg( $key, false, $query );
1458 }
1459
1460 /**
1461  * Return a time-dependent string for nonce creation
1462  *
1463  */
1464 function yourls_tick() {
1465         return ceil( time() / YOURLS_NONCE_LIFE );
1466 }
1467
1468 /**
1469  * Create a time limited, action limited and user limited token
1470  *
1471  */
1472 function yourls_create_nonce( $action, $user = false ) {
1473         if( false == $user )
1474                 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1475         $tick = yourls_tick();
1476         return substr( yourls_salt($tick . $action . $user), 0, 10 );
1477 }
1478
1479 /**
1480  * Create a nonce field for inclusion into a form
1481  *
1482  */
1483 function yourls_nonce_field( $action, $name = 'nonce', $user = false, $echo = true ) {
1484         $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';
1485         if( $echo )
1486                 echo $field."\n";
1487         return $field;
1488 }
1489
1490 /**
1491  * Add a nonce to a URL. If URL omitted, adds nonce to current URL
1492  *
1493  */
1494 function yourls_nonce_url( $action, $url = false, $name = 'nonce', $user = false ) {
1495         $nonce = yourls_create_nonce( $action, $user );
1496         return yourls_add_query_arg( $name, $nonce, $url );
1497 }
1498
1499 /**
1500  * Check validity of a nonce (ie time span, user and action match).
1501  * 
1502  * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined)
1503  * if $nonce is false or unspecified, it will use $_REQUEST['nonce']
1504  *
1505  */
1506 function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {
1507         // get user
1508         if( false == $user )
1509                 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1510                 
1511         // get current nonce value
1512         if( false == $nonce && isset( $_REQUEST['nonce'] ) )
1513                 $nonce = $_REQUEST['nonce'];
1514
1515         // what nonce should be
1516         $valid = yourls_create_nonce( $action, $user );
1517         
1518         if( $nonce == $valid ) {
1519                 return true;
1520         } else {
1521                 if( $return )
1522                         die( $return );
1523                 yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );
1524         }
1525 }
1526
1527 /**
1528  * Converts keyword into short link (prepend with YOURLS base URL)
1529  *
1530  */
1531 function yourls_link( $keyword = '' ) {
1532         $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
1533         return yourls_apply_filter( 'yourls_link', $link, $keyword );
1534 }
1535
1536 /**
1537  * Converts keyword into stat link (prepend with YOURLS base URL, append +)
1538  *
1539  */
1540 function yourls_statlink( $keyword = '' ) {
1541         $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword ) . '+';
1542         if( yourls_is_ssl() )
1543                 $link = str_replace( 'http://', 'https://', $link );
1544         return yourls_apply_filter( 'yourls_statlink', $link, $keyword );
1545 }
1546
1547 /**
1548  * Check if we're in API mode. Returns bool
1549  *
1550  */
1551 function yourls_is_API() {
1552         if ( defined( 'YOURLS_API' ) && YOURLS_API == true )
1553                 return true;
1554         return false;
1555 }
1556
1557 /**
1558  * Check if we're in Ajax mode. Returns bool
1559  *
1560  */
1561 function yourls_is_Ajax() {
1562         if ( defined( 'YOURLS_AJAX' ) && YOURLS_AJAX == true )
1563                 return true;
1564         return false;
1565 }
1566
1567 /**
1568  * Check if we're in GO mode (yourls-go.php). Returns bool
1569  *
1570  */
1571 function yourls_is_GO() {
1572         if ( defined( 'YOURLS_GO' ) && YOURLS_GO == true )
1573                 return true;
1574         return false;
1575 }
1576
1577 /**
1578  * Check if we're displaying stats infos (yourls-infos.php). Returns bool
1579  *
1580  */
1581 function yourls_is_infos() {
1582         if ( defined( 'YOURLS_INFOS' ) && YOURLS_INFOS == true )
1583                 return true;
1584         return false;
1585 }
1586
1587 /**
1588  * Check if we'll need interface display function (ie not API or redirection)
1589  *
1590  */
1591 function yourls_has_interface() {
1592         if( yourls_is_API() or yourls_is_GO() )
1593                 return false;
1594         return true;
1595 }
1596
1597 /**
1598  * Check if we're in the admin area. Returns bool
1599  *
1600  */
1601 function yourls_is_admin() {
1602         if ( defined( 'YOURLS_ADMIN' ) && YOURLS_ADMIN == true )
1603                 return true;
1604         return false;
1605 }
1606
1607 /**
1608  * Check if the server seems to be running on Windows. Not exactly sure how reliable this is.
1609  *
1610  */
1611 function yourls_is_windows() {
1612         return defined( 'DIRECTORY_SEPARATOR' ) && DIRECTORY_SEPARATOR == '\\';
1613 }
1614
1615 /**
1616  * Check if SSL is required. Returns bool.
1617  *
1618  */
1619 function yourls_needs_ssl() {
1620         if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
1621                 return true;
1622         return false;
1623 }
1624
1625 /**
1626  * Return admin link, with SSL preference if applicable.
1627  *
1628  */
1629 function yourls_admin_url( $page = '' ) {
1630         $admin = YOURLS_SITE . '/admin/' . $page;
1631         if( yourls_is_ssl() or yourls_needs_ssl() )
1632                 $admin = str_replace('http://', 'https://', $admin);
1633         return yourls_apply_filter( 'admin_url', $admin, $page );
1634 }
1635
1636 /**
1637  * Return YOURLS_SITE or URL under YOURLS setup, with SSL preference
1638  *
1639  */
1640 function yourls_site_url( $echo = true, $url = '' ) {
1641         $url = yourls_get_relative_url( $url );
1642         $url = trim( YOURLS_SITE . '/' . $url, '/' );
1643         
1644         // Do not enforce (checking yourls_need_ssl() ) but check current usage so it won't force SSL on non-admin pages
1645         if( yourls_is_ssl() )
1646                 $url = str_replace( 'http://', 'https://', $url );
1647         $url = yourls_apply_filter( 'site_url', $url );
1648         if( $echo )
1649                 echo $url;
1650         return $url;
1651 }
1652
1653 /**
1654  * Check if SSL is used, returns bool. Stolen from WP.
1655  *
1656  */
1657 function yourls_is_ssl() {
1658         $is_ssl = false;
1659         if ( isset( $_SERVER['HTTPS'] ) ) {
1660                 if ( 'on' == strtolower( $_SERVER['HTTPS'] ) )
1661                         $is_ssl = true;
1662                 if ( '1' == $_SERVER['HTTPS'] )
1663                         $is_ssl = true;
1664         } elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
1665                 $is_ssl = true;
1666         }
1667         return yourls_apply_filter( 'is_ssl', $is_ssl );
1668 }
1669
1670
1671 /**
1672  * Get a remote page <title>, return a string (either title or url)
1673  *
1674  */
1675 function yourls_get_remote_title( $url ) {
1676         // Allow plugins to short-circuit the whole function
1677         $pre = yourls_apply_filter( 'shunt_get_remote_title', false, $url );
1678         if ( false !== $pre )
1679                 return $pre;
1680
1681         require_once( YOURLS_INC.'/functions-http.php' );
1682
1683         $url = yourls_sanitize_url( $url );
1684
1685         $title = $charset = false;
1686         
1687         $content = yourls_get_remote_content( $url );
1688         
1689         // If false, return url as title.
1690         // Todo: improve this with temporary title when shorturl_meta available?
1691         if( false === $content )
1692                 return $url;
1693
1694         if( $content !== false ) {
1695                 // look for <title>
1696                 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {
1697                         $title = $found[1];
1698                         unset( $found );
1699                 }
1700
1701                 // look for charset
1702                 // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1703                 if ( preg_match('/<meta[^>]*?charset=([^>]*?)\/?>/is', $content, $found ) ) {
1704                         $charset = trim($found[1], '"\' ');
1705                         unset( $found );
1706                 }
1707         }
1708         
1709         // if title not found, guess if returned content was actually an error message
1710         if( $title == false && strpos( $content, 'Error' ) === 0 ) {
1711                 $title = $content;
1712         }
1713         
1714         if( $title == false )
1715                 $title = $url;
1716         
1717         /*
1718         if( !yourls_seems_utf8( $title ) )
1719                 $title = utf8_encode( $title );
1720         */
1721         
1722         // Charset conversion. We use @ to remove warnings (mb_ functions are easily bitching about illegal chars)
1723         if( function_exists( 'mb_convert_encoding' ) ) {
1724                 if( $charset ) {
1725                         $title = @mb_convert_encoding( $title, 'UTF-8', $charset );
1726                 } else {
1727                         $title = @mb_convert_encoding( $title, 'UTF-8' );
1728                 }
1729         }
1730         
1731         // Remove HTML entities
1732         $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' );
1733         
1734         // Strip out evil things
1735         $title = yourls_sanitize_title( $title );
1736         
1737         return yourls_apply_filter( 'get_remote_title', $title, $url );
1738 }
1739
1740 /**
1741  * Quick UA check for mobile devices. Return boolean.
1742  *
1743  */
1744 function yourls_is_mobile_device() {
1745         // Strings searched
1746         $mobiles = array(
1747                 'android', 'blackberry', 'blazer',
1748                 'compal', 'elaine', 'fennec', 'hiptop',
1749                 'iemobile', 'iphone', 'ipod', 'ipad',
1750                 'iris', 'kindle', 'opera mobi', 'opera mini',
1751                 'palm', 'phone', 'pocket', 'psp', 'symbian',
1752                 'treo', 'wap', 'windows ce', 'windows phone'
1753         );
1754         
1755         // Current user-agent
1756         $current = strtolower( $_SERVER['HTTP_USER_AGENT'] );
1757         
1758         // Check and return
1759         $is_mobile = ( str_replace( $mobiles, '', $current ) != $current );
1760         return yourls_apply_filter( 'is_mobile_device', $is_mobile );
1761 }
1762
1763 /**
1764  * Get request in YOURLS base (eg in 'http://site.com/yourls/abcd' get 'abdc')
1765  *
1766  */
1767 function yourls_get_request() {
1768         // Allow plugins to short-circuit the whole function
1769         $pre = yourls_apply_filter( 'shunt_get_request', false );
1770         if ( false !== $pre )
1771                 return $pre;
1772                 
1773         static $request = null;
1774
1775         yourls_do_action( 'pre_get_request', $request );
1776         
1777         if( $request !== null )
1778                 return $request;
1779         
1780         // Ignore protocol & www. prefix
1781         $root = str_replace( array( 'https://', 'http://', 'https://www.', 'http://www.' ), '', YOURLS_SITE );
1782         // Case insensitive comparison of the YOURLS root to match both http://Sho.rt/blah and http://sho.rt/blah
1783         $request = preg_replace( "!$root/!i", '', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 1 );
1784
1785         // Unless request looks like a full URL (ie request is a simple keyword) strip query string
1786         if( !preg_match( "@^[a-zA-Z]+://.+@", $request ) ) {
1787                 $request = current( explode( '?', $request ) );
1788         }
1789         
1790         return yourls_apply_filter( 'get_request', $request );
1791 }
1792
1793 /**
1794  * Change protocol to match current scheme used (http or https)
1795  *
1796  */
1797 function yourls_match_current_protocol( $url, $normal = 'http', $ssl = 'https' ) {
1798         if( yourls_is_ssl() )
1799                 $url = str_replace( $normal, $ssl, $url );
1800         return yourls_apply_filter( 'match_current_protocol', $url );
1801 }
1802
1803 /**
1804  * Fix $_SERVER['REQUEST_URI'] variable for various setups. Stolen from WP.
1805  *
1806  */
1807 function yourls_fix_request_uri() {
1808
1809         $default_server_values = array(
1810                 'SERVER_SOFTWARE' => '',
1811                 'REQUEST_URI' => '',
1812         );
1813         $_SERVER = array_merge( $default_server_values, $_SERVER );
1814
1815         // Fix for IIS when running with PHP ISAPI
1816         if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {
1817
1818                 // IIS Mod-Rewrite
1819                 if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
1820                         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
1821                 }
1822                 // IIS Isapi_Rewrite
1823                 else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {
1824                         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
1825                 } else {
1826                         // Use ORIG_PATH_INFO if there is no PATH_INFO
1827                         if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )
1828                                 $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
1829
1830                         // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
1831                         if ( isset( $_SERVER['PATH_INFO'] ) ) {
1832                                 if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
1833                                         $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
1834                                 else
1835                                         $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
1836                         }
1837
1838                         // Append the query string if it exists and isn't null
1839                         if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
1840                                 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
1841                         }
1842                 }
1843         }
1844 }
1845
1846 /**
1847  * Shutdown function, runs just before PHP shuts down execution. Stolen from WP
1848  *
1849  */
1850 function yourls_shutdown() {
1851         yourls_do_action( 'shutdown' );
1852 }
1853
1854 /**
1855  * Auto detect custom favicon in /user directory, fallback to YOURLS favicon, and echo/return its URL
1856  *
1857  */
1858 function yourls_favicon( $echo = true ) {
1859         static $favicon = null;
1860         if( $favicon !== null )
1861                 return $favicon;
1862         
1863         $custom = null;
1864         // search for favicon.(gif|ico|png|jpg|svg)
1865         foreach( array( 'gif', 'ico', 'png', 'jpg', 'svg' ) as $ext ) {
1866                 if( file_exists( YOURLS_USERDIR. '/favicon.' . $ext ) ) {
1867                         $custom = 'favicon.' . $ext;
1868                         break;
1869                 }
1870         }
1871         
1872         if( $custom ) {
1873                 $favicon = yourls_site_url( false, YOURLS_USERURL . '/' . $custom );
1874         } else {
1875                 $favicon = yourls_site_url( false ) . '/images/favicon.gif';
1876         }
1877         if( $echo )
1878                 echo $favicon;
1879         return $favicon;
1880 }
1881
1882 /**
1883  * Check for maintenance mode. If yes, die. See yourls_maintenance_mode(). Stolen from WP.
1884  *
1885  */
1886 function yourls_check_maintenance_mode() {
1887
1888         $file = YOURLS_ABSPATH . '/.maintenance' ;
1889         if ( !file_exists( $file ) || yourls_is_upgrading() || yourls_is_installing() )
1890                 return;
1891         
1892         global $maintenance_start;
1893
1894         include( $file );
1895         // If the $maintenance_start timestamp is older than 10 minutes, don't die.
1896         if ( ( time() - $maintenance_start ) >= 600 )
1897                 return;
1898
1899         // Use any /user/maintenance.php file
1900         if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {
1901                 include( YOURLS_USERDIR.'/maintenance.php' );
1902                 die();
1903         }
1904         
1905         // https://www.youtube.com/watch?v=Xw-m4jEY-Ns
1906         $title   = yourls__( 'Service temporarily unavailable' );
1907         $message = yourls__( 'Our service is currently undergoing scheduled maintenance.' ) . "</p>\n<p>" .
1908         yourls__( 'Things should not last very long, thank you for your patience and please excuse the inconvenience' );
1909         yourls_die( $message, $title , 503 );
1910
1911 }
1912
1913 /**
1914  * Return current admin page, or null if not an admin page
1915  *
1916  * @return mixed string if admin page, null if not an admin page
1917  * @since 1.6
1918  */
1919 function yourls_current_admin_page() {
1920         if( yourls_is_admin() ) {
1921                 $current = substr( yourls_get_request(), 6 );
1922                 if( $current === false ) 
1923                         $current = 'index.php'; // if current page is http://sho.rt/admin/ instead of http://sho.rt/admin/index.php
1924                         
1925                 return $current;
1926         }
1927         return null;
1928 }
1929
1930 /**
1931  * Check if a URL protocol is allowed
1932  *
1933  * Checks a URL against a list of whitelisted protocols. Protocols must be defined with
1934  * their complete scheme name, ie 'stuff:' or 'stuff://' (for instance, 'mailto:' is a valid
1935  * protocol, 'mailto://' isn't, and 'http:' with no double slashed isn't either
1936  *
1937  * @since 1.6
1938  *
1939  * @param string $url URL to be check
1940  * @param array $protocols Optional. Array of protocols, defaults to global $yourls_allowedprotocols
1941  * @return boolean true if protocol allowed, false otherwise
1942  */
1943 function yourls_is_allowed_protocol( $url, $protocols = array() ) {
1944         if( ! $protocols ) {
1945                 global $yourls_allowedprotocols;
1946                 $protocols = $yourls_allowedprotocols;
1947         }
1948         
1949         $protocol = yourls_get_protocol( $url );
1950         return yourls_apply_filter( 'is_allowed_protocol', in_array( $protocol, $protocols ), $url, $protocols );
1951 }
1952
1953 /**
1954  * Get protocol from a URL (eg mailto:, http:// ...)
1955  *
1956  * @since 1.6
1957  *
1958  * @param string $url URL to be check
1959  * @return string Protocol, with slash slash if applicable. Empty string if no protocol
1960  */
1961 function yourls_get_protocol( $url ) {
1962         preg_match( '!^[a-zA-Z0-9\+\.-]+:(//)?!', $url, $matches );
1963         /*
1964         http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
1965         The scheme name consists of a sequence of characters beginning with a letter and followed by any
1966         combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). Although schemes are
1967         case-insensitive, the canonical form is lowercase and documents that specify schemes must do so
1968         with lowercase letters. It is followed by a colon (":").
1969         */
1970         $protocol = ( isset( $matches[0] ) ? $matches[0] : '' );
1971         return yourls_apply_filter( 'get_protocol', $protocol, $url );
1972 }
1973
1974 /**
1975  * Get relative URL (eg 'abc' from 'http://sho.rt/abc')
1976  *
1977  * Treat indifferently http & https. If a URL isn't relative to the YOURLS install, return it as is
1978  * or return empty string if $strict is true
1979  *
1980  * @since 1.6
1981  * @param string $url URL to relativize
1982  * @param bool $strict if true and if URL isn't relative to YOURLS install, return empty string
1983  * @return string URL 
1984  */
1985 function yourls_get_relative_url( $url, $strict = true ) {
1986         $url = yourls_sanitize_url( $url );
1987
1988         // Remove protocols to make it easier
1989         $noproto_url  = str_replace( 'https:', 'http:', $url );
1990         $noproto_site = str_replace( 'https:', 'http:', YOURLS_SITE );
1991         
1992         // Trim URL from YOURLS root URL : if no modification made, URL wasn't relative
1993         $_url = str_replace( $noproto_site . '/', '', $noproto_url );
1994         if( $_url == $noproto_url )
1995                 $_url = ( $strict ? '' : $url );
1996
1997         return yourls_apply_filter( 'get_relative_url', $_url, $url );
1998 }
1999
2000 /**
2001  * Marks a function as deprecated and informs when it has been used. Stolen from WP.
2002  *
2003  * There is a hook deprecated_function that will be called that can be used
2004  * to get the backtrace up to what file and function called the deprecated
2005  * function.
2006  *
2007  * The current behavior is to trigger a user error if YOURLS_DEBUG is true.
2008  *
2009  * This function is to be used in every function that is deprecated.
2010  *
2011  * @since 1.6
2012  * @uses yourls_do_action() Calls 'deprecated_function' and passes the function name, what to use instead,
2013  *   and the version the function was deprecated in.
2014  * @uses yourls_apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2015  *   trigger or false to not trigger error.
2016  *
2017  * @param string $function The function that was called
2018  * @param string $version The version of WordPress that deprecated the function
2019  * @param string $replacement Optional. The function that should have been called
2020  */
2021 function yourls_deprecated_function( $function, $version, $replacement = null ) {
2022
2023         yourls_do_action( 'deprecated_function', $function, $replacement, $version );
2024
2025         // Allow plugin to filter the output error trigger
2026         if ( YOURLS_DEBUG && yourls_apply_filters( 'deprecated_function_trigger_error', true ) ) {
2027                 if ( ! is_null( $replacement ) )
2028                         trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2029                 else
2030                         trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2031         }
2032 }
2033
2034 /**
2035  * Return the value if not an empty string
2036  *
2037  * Used with array_filter(), to remove empty keys but not keys with value 0 or false
2038  *
2039  * @since 1.6
2040  * @param mixed $val Value to test against ''
2041  * @return bool True if not an empty string
2042  */
2043 function yourls_return_if_not_empty_string( $val ) {
2044         return( $val !== '' );
2045 }