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