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