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