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