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