]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions.php
Allow quotes in URLs. Fixes issue 108.
[Github/YOURLS.git] / includes / functions.php
1 <?php\r
2 /*\r
3  * YOURLS\r
4  * Function library\r
5  */\r
6 \r
7 if (defined('YOURLS_DEBUG') && YOURLS_DEBUG == true) {\r
8         error_reporting(E_ALL);\r
9 } else {\r
10         error_reporting(E_ERROR | E_PARSE);\r
11 }\r
12 \r
13 // function to convert an integer (1337) to a string (3jk). Input integer processed as a string to beat PHP's int max value\r
14 function yourls_int2string( $id ) {\r
15         $str = yourls_base2base(trim(strval($id)), 10, YOURLS_URL_CONVERT);\r
16         if (YOURLS_URL_CONVERT <= 37)\r
17                 $str = strtolower($str);\r
18         return $str;\r
19 }\r
20 \r
21 // function to convert a string (3jk) to an integer (1337)\r
22 function yourls_string2int( $str ) {\r
23         if (YOURLS_URL_CONVERT <= 37)\r
24                 $str = strtolower($str);\r
25         return yourls_base2base(trim($str), YOURLS_URL_CONVERT, 10);\r
26 }\r
27 \r
28 // Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.\r
29 function yourls_sanitize_string($in) {\r
30         if (YOURLS_URL_CONVERT <= 37)\r
31                 $in = strtolower($in);\r
32         return substr(preg_replace('/[^a-zA-Z0-9]/', '', $in), 0, 199);\r
33 }\r
34 \r
35 // A few sanity checks on the URL\r
36 function yourls_sanitize_url($url) {\r
37         // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')\r
38         $url = str_replace('http://http://', 'http://', $url);\r
39 \r
40         // make sure there's a protocol, add http:// if not\r
41         if ( !preg_match('!^([a-zA-Z]+://)!', $url ) )\r
42                 $url = 'http://'.$url;\r
43         \r
44         $url = yourls_clean_url($url);\r
45         \r
46         return substr( $url, 0, 1999 );\r
47 }\r
48 \r
49 // Function to filter all invalid characters from a URL. Stolen from WP's clean_url()\r
50 function yourls_clean_url( $url ) {\r
51         $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'"()\\x80-\\xff]|i', '', $url );\r
52         $strip = array('%0d', '%0a', '%0D', '%0A');\r
53         $url = yourls_deep_replace($strip, $url);\r
54         $url = str_replace(';//', '://', $url);\r
55         $url = str_replace('&amp;', '&', $url); // Revert & not to break query strings\r
56         \r
57         return $url;\r
58 }\r
59 \r
60 // Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''\r
61 // Stolen from WP's _deep_replace\r
62 function yourls_deep_replace($search, $subject){\r
63         $found = true;\r
64         while($found) {\r
65                 $found = false;\r
66                 foreach( (array) $search as $val ) {\r
67                         while(strpos($subject, $val) !== false) {\r
68                                 $found = true;\r
69                                 $subject = str_replace($val, '', $subject);\r
70                         }\r
71                 }\r
72         }\r
73         \r
74         return $subject;\r
75 }\r
76 \r
77 \r
78 // Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)\r
79 // TODO FIXME FFS: unused ?\r
80 function yourls_sanitize_int($in) {\r
81         return ( substr(preg_replace('/[^0-9]/', '', strval($in) ), 0, 20) );\r
82 }\r
83 \r
84 // Make sure a integer is safe\r
85 // Note: this is not checking for integers, since integers on 32bits system are way too limited\r
86 // TODO: find a way to validate as integer\r
87 function yourls_intval($in) {\r
88         return mysql_real_escape_string($in);\r
89 }\r
90 \r
91 // Escape a string\r
92 function yourls_escape( $in ) {\r
93         return mysql_real_escape_string($in);\r
94 }\r
95 \r
96 // Check to see if a given keyword is reserved (ie reserved URL or an existing page)\r
97 // Returns bool\r
98 function yourls_keyword_is_reserved( $keyword ) {\r
99         global $yourls_reserved_URL;\r
100         \r
101         if ( in_array( $keyword, $yourls_reserved_URL)\r
102                 or file_exists(dirname(dirname(__FILE__))."/pages/$keyword.php")\r
103                 or is_dir(dirname(dirname(__FILE__))."/$keyword")\r
104         )\r
105                 return true;\r
106         \r
107         return false;\r
108 }\r
109 \r
110 // Function: Get IP Address. Returns a DB safe string.\r
111 function yourls_get_IP() {\r
112         if(!empty($_SERVER['HTTP_CLIENT_IP'])) {\r
113                 $ip_address = $_SERVER['HTTP_CLIENT_IP'];\r
114         } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {\r
115                 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];\r
116         } else if(!empty($_SERVER['REMOTE_ADDR'])) {\r
117                 $ip_address = $_SERVER['REMOTE_ADDR'];\r
118         } else {\r
119                 $ip_address = '';\r
120         }\r
121         if(strpos($ip_address, ',') !== false) {\r
122                 $ip_address = explode(',', $ip_address);\r
123                 $ip_address = $ip_address[0];\r
124         }\r
125         \r
126         $ip_address = yourls_sanitize_ip( $ip_address );\r
127 \r
128         return $ip_address;\r
129 }\r
130 \r
131 // Sanitize an IP address\r
132 function yourls_sanitize_ip( $ip ) {\r
133         return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );\r
134 }\r
135 \r
136 // Add the "Edit" row\r
137 function yourls_table_edit_row( $keyword ) {\r
138         global $ydb;\r
139         \r
140         $table = YOURLS_DB_TABLE_URL;\r
141         $keyword = yourls_sanitize_string( $keyword );\r
142         $id = yourls_string2int( $keyword ); // used as HTML #id\r
143         $url = $ydb->get_row("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");\r
144         $safe_url = stripslashes( $url->url );\r
145         $www = YOURLS_SITE;\r
146         \r
147         if( $url ) {\r
148                 $return = <<<RETURN\r
149 <tr id="edit-$id" class="edit-row"><td colspan="5"><strong>Original URL</strong>:<input type="text" id="edit-url-$id" name="edit-url-$id" value="$safe_url" class="text" size="70" /> <strong>Short URL</strong>: $www/<input type="text" id="edit-keyword-$id" name="edit-keyword-$id" value="$keyword" class="text" size="10" /></td><td colspan="1"><input type="button" id="edit-submit-$id" name="edit-submit-$id" value="Save" title="Save new values" class="button" onclick="edit_save('$id');" />&nbsp;<input type="button" id="edit-close-$id" name="edit-close-$id" value="X" title="Cancel editing" class="button" onclick="hide_edit('$id');" /><input type="hidden" id="old_keyword_$id" value="$keyword"/></td></tr>\r
150 RETURN;\r
151         } else {\r
152                 $return = '<tr><td colspan="6">Error, URL not found</td></tr>';\r
153         }\r
154         \r
155         return $return;\r
156 }\r
157 \r
158 // Add a link row\r
159 function yourls_table_add_row( $keyword, $url, $ip, $clicks, $timestamp ) {\r
160         $keyword = yourls_sanitize_string( $keyword );\r
161         $id = yourls_string2int( $keyword ); // used as HTML #id\r
162         $date = date( 'M d, Y H:i', $timestamp+( YOURLS_HOURS_OFFSET * 3600) );\r
163         $clicks = number_format($clicks, 0, '', '');\r
164         $shorturl = YOURLS_SITE.'/'.$keyword;\r
165         $display_url = htmlentities( yourls_trim_long_string( $url ) );\r
166         $statlink = $shorturl.'+';\r
167         $url = htmlentities( $url );\r
168         \r
169         return <<<ROW\r
170 <tr id="id-$id"><td id="keyword-$id"><a href="$shorturl">$keyword</a></td><td id="url-$id"><a href="$url" title="$url">$display_url</a></td><td id="timestamp-$id">$date</td><td id="ip-$id">$ip</td><td id="clicks-$id">$clicks</td><td class="actions" id="actions-$id"><a href="$statlink" id="statlink-$id" class="button button_stats">&nbsp;&nbsp;&nbsp;</a>&nbsp;<input type="button" id="edit-button-$id" name="edit-button" value="" title="Edit" class="button button_edit" onclick="edit('$id');" />&nbsp;<input type="button" id="delete-button-$id" name="delete-button" value="" title="Delete" class="button button_delete" onclick="remove('$id');" /><input type="hidden" id="keyword_$id" value="$keyword"/></td></tr>\r
171 ROW;\r
172 }\r
173 \r
174 // Get next id a new link will have if no custom keyword provided\r
175 function yourls_get_next_decimal() {\r
176         return (int)yourls_get_option( 'next_id' );\r
177 }\r
178 \r
179 // Update id for next link with no custom keyword\r
180 function yourls_update_next_decimal( $int = '' ) {\r
181         $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;\r
182         return yourls_update_option( 'next_id', $int );\r
183 }\r
184 \r
185 // Delete a link in the DB\r
186 function yourls_delete_link_by_keyword( $keyword ) {\r
187         global $ydb;\r
188 \r
189         $table = YOURLS_DB_TABLE_URL;\r
190         $keyword = yourls_sanitize_string( $keyword );\r
191         return $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");\r
192 }\r
193 \r
194 // SQL query to insert a new link in the DB. Needs sanitized data. Returns boolean for success or failure of the inserting\r
195 function yourls_insert_link_in_db($url, $keyword) {\r
196         global $ydb;\r
197 \r
198         $table = YOURLS_DB_TABLE_URL;\r
199         $timestamp = date('Y-m-d H:i:s');\r
200         $ip = yourls_get_IP();\r
201         $insert = $ydb->query("INSERT INTO `$table` VALUES('$keyword', '$url', '$timestamp', '$ip', 0);");\r
202         \r
203         return (bool)$insert;\r
204 }\r
205 \r
206 // Add a new link in the DB, either with custom keyword, or find one\r
207 function yourls_add_new_link( $url, $keyword = '' ) {\r
208         global $ydb;\r
209 \r
210         if ( !$url || $url == 'http://' || $url == 'https://' ) {\r
211                 $return['status'] = 'fail';\r
212                 $return['code'] = 'error:nourl';\r
213                 $return['message'] = 'Missing URL input';\r
214                 $return['errorCode'] = '400';\r
215                 return $return;\r
216         }\r
217 \r
218         // Prevent DB flood\r
219         $ip = yourls_get_IP();\r
220         yourls_check_IP_flood( $ip );\r
221 \r
222         $table = YOURLS_DB_TABLE_URL;\r
223         $url = mysql_real_escape_string( yourls_sanitize_url($url) );\r
224         $strip_url = stripslashes($url);\r
225         $url_exists = $ydb->get_row("SELECT keyword,url FROM `$table` WHERE `url` = '".$strip_url."';");\r
226         $return = array();\r
227 \r
228         // New URL : store it -- or: URL exists, but duplicates allowed\r
229         if( !$url_exists || yourls_allow_duplicate_longurls() ) {\r
230 \r
231                 // Custom keyword provided\r
232                 if ( $keyword ) {\r
233                         $keyword = mysql_real_escape_string(yourls_sanitize_string($keyword));\r
234                         if ( !yourls_keyword_is_free($keyword) ) {\r
235                                 // This shorturl either reserved or taken already\r
236                                 $return['status'] = 'fail';\r
237                                 $return['code'] = 'error:keyword';\r
238                                 $return['message'] = 'Short URL '.$keyword.' already exists in database or is reserved';\r
239                         } else {\r
240                                 // all clear, store !\r
241                                 yourls_insert_link_in_db($url, $keyword);\r
242                                 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );\r
243                                 $return['status'] = 'success';\r
244                                 $return['message'] = $strip_url.' added to database';\r
245                                 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );\r
246                                 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
247                         }\r
248 \r
249                 // Create random keyword        \r
250                 } else {\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                                 $free = yourls_keyword_is_free($keyword);\r
257                                 $add_url = @yourls_insert_link_in_db($url, $keyword);\r
258                                 $ok = ($free && $add_url);\r
259                                 if ( $ok === false && $add_url === 1 ) {\r
260                                         // we stored something, but shouldn't have (ie reserved id)\r
261                                         $delete = yourls_delete_link_by_keyword( $keyword );\r
262                                         $return['extra_info'] .= '(deleted '.$keyword.')';\r
263                                 } else {\r
264                                         // everything ok, populate needed vars\r
265                                         $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => $timestamp, 'ip' => $ip );\r
266                                         $return['status'] = 'success';\r
267                                         $return['message'] = $strip_url.' added to database';\r
268                                         $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );\r
269                                         $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
270                                 }\r
271                                 $id++;\r
272                         } while (!$ok);\r
273                         @yourls_update_next_decimal($id);\r
274                 }\r
275         } else {\r
276                 // URL was already stored\r
277                 $return['status'] = 'fail';\r
278                 $return['code'] = 'error:url';\r
279                 $return['message'] = $strip_url.' already exists in database';\r
280                 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;\r
281         }\r
282 \r
283         $return['statusCode'] = 200; // regardless of result, this is still a valid request\r
284         return $return;\r
285 }\r
286 \r
287 \r
288 // Edit a link\r
289 function yourls_edit_link($url, $keyword, $newkeyword='') {\r
290         global $ydb;\r
291 \r
292         $table = YOURLS_DB_TABLE_URL;\r
293         $url = mysql_real_escape_string(yourls_sanitize_url($url));\r
294         $keyword = yourls_sanitize_string( $keyword );\r
295         $newkeyword = yourls_sanitize_string( $newkeyword );\r
296         $strip_url = stripslashes($url);\r
297         $old_url = $ydb->get_var("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");\r
298         $old_id = $id = yourls_string2int( $keyword );\r
299         $new_id = ( $newkeyword == '' ? $old_id : yourls_string2int( $newkeyword ) );\r
300         \r
301         // Check if new URL is not here already\r
302         if ($old_url != $url) {\r
303                 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));\r
304         } else {\r
305                 $new_url_already_there = false;\r
306         }\r
307         \r
308         // Check if the new keyword is not here already\r
309         if ( $newkeyword != $keyword ) {\r
310                 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );\r
311         } else {\r
312                 $keyword_is_ok = true;\r
313         }\r
314         \r
315         // All clear, update\r
316         if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {\r
317                 //$timestamp4screen = date( 'Y M d H:i', time()+( YOURLS_HOURS_OFFSET * 3600) );\r
318                 //$timestamp4db = date('Y-m-d H:i:s', time()+( YOURLS_HOURS_OFFSET * 3600) );\r
319                 $update_url = $ydb->query("UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword' WHERE `keyword` = '$keyword';");\r
320                 if( $update_url ) {\r
321                         $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'new_id' => $new_id );\r
322                         $return['status'] = 'success';\r
323                         $return['message'] = 'Link updated in database';\r
324                 } else {\r
325                         $return['status'] = 'fail';\r
326                         $return['message'] = 'Error updating '.$strip_url.' (Short URL: '.$keyword.') to database';\r
327                 }\r
328         \r
329         // Nope\r
330         } else {\r
331                 $return['status'] = 'fail';\r
332                 $return['message'] = 'URL or keyword already exists in database';\r
333         }\r
334         \r
335         return $return;\r
336 }\r
337 \r
338 \r
339 // Check if keyword id is free (ie not already taken, and not reserved)\r
340 function yourls_keyword_is_free( $keyword ) {\r
341         global $ydb;\r
342 \r
343         $table = YOURLS_DB_TABLE_URL;\r
344         if ( yourls_keyword_is_reserved($keyword) )\r
345                 return false;\r
346                 \r
347         $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");\r
348         if ( $already_exists )\r
349                 return false;\r
350 \r
351         return true;\r
352 }\r
353 \r
354 \r
355 // Display a page\r
356 function yourls_page( $page ) {\r
357         $include = dirname(dirname(__FILE__))."/pages/$page.php";\r
358         if (!file_exists($include)) {\r
359                 yourls_die("Page '$page' not found", 'Not found', 404);\r
360         }\r
361         include($include);\r
362         die();  \r
363 }\r
364 \r
365 // Connect to DB\r
366 function yourls_db_connect() {\r
367         global $ydb;\r
368 \r
369         if (!defined('YOURLS_DB_USER')\r
370                 or !defined('YOURLS_DB_PASS')\r
371                 or !defined('YOURLS_DB_NAME')\r
372                 or !defined('YOURLS_DB_HOST')\r
373                 or !class_exists('ezSQL_mysql')\r
374         ) yourls_die ('DB config missigin, or could not find DB class', 'Fatal error', 503);\r
375         \r
376         // Are we standalone or in the WordPress environment?\r
377         if ( class_exists('wpdb') ) {\r
378                 $ydb =  new wpdb(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
379         } else {\r
380                 $ydb =  new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
381         }\r
382         if ( $ydb->last_error )\r
383                 yourls_die( $ydb->last_error, 'Fatal error', 503 );\r
384         \r
385         if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )\r
386                 $ydb->show_errors = true;\r
387         \r
388         return $ydb;\r
389 }\r
390 \r
391 // Return JSON output. Compatible with PHP prior to 5.2\r
392 function yourls_json_encode($array) {\r
393         if (function_exists('json_encode')) {\r
394                 return json_encode($array);\r
395         } else {\r
396                 require_once(dirname(__FILE__).'/functions-json.php');\r
397                 return yourls_array_to_json($array);\r
398         }\r
399 }\r
400 \r
401 // Return XML output.\r
402 function yourls_xml_encode($array) {\r
403         require_once(dirname(__FILE__).'/functions-xml.php');\r
404         $converter= new yourls_array2xml;\r
405         return $converter->array2xml($array);\r
406 }\r
407 \r
408 // 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
409 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {\r
410         global $ydb;\r
411         $keyword = yourls_sanitize_string( $keyword );\r
412 \r
413         if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {\r
414                 return $ydb->infos[$keyword];\r
415         }\r
416         \r
417         $table = YOURLS_DB_TABLE_URL;\r
418         $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");\r
419         \r
420         if( $infos ) {\r
421                 $infos = (array)$infos;\r
422                 $ydb->infos[$keyword] = $infos;\r
423         } else {\r
424                 $ydb->infos[$keyword] = false;\r
425         }\r
426                 \r
427         return $ydb->infos[$keyword];\r
428 }\r
429 \r
430 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\r
431 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {\r
432         global $ydb;\r
433         \r
434         $keyword = yourls_sanitize_string( $keyword );\r
435         $infos = yourls_get_keyword_infos( $keyword );\r
436         \r
437         if ( isset($infos[$field]) && $infos[$field] !== false )\r
438                 return $infos[$field];\r
439 \r
440         return $notfound;       \r
441 }\r
442 \r
443 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found\r
444 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {\r
445         return yourls_get_keyword_info( $keyword, 'url', $notfound );\r
446 }\r
447 \r
448 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\r
449 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {\r
450         return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\r
451 }\r
452 \r
453 // Return IP that added a keyword. Optional $notfound = string default message if nothing found\r
454 function yourls_get_keyword_IP( $keyword, $notfound = false ) {\r
455         return yourls_get_keyword_info( $keyword, 'ip', $notfound );\r
456 }\r
457 \r
458 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\r
459 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\r
460         return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\r
461 }\r
462 \r
463 // Update click count on a short URL\r
464 function yourls_update_clicks( $keyword ) {\r
465         global $ydb;\r
466         $keyword = yourls_sanitize_string( $keyword );\r
467         $table = YOURLS_DB_TABLE_URL;\r
468         return $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");\r
469 }\r
470 \r
471 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return\r
472 function yourls_get_links_stats( $filter = 'top', $limit = 10 ) {\r
473         global $ydb;\r
474 \r
475         switch( $filter ) {\r
476                 case 'bottom':\r
477                         $sort_by = 'clicks';\r
478                         $sort_order = 'asc';\r
479                         break;\r
480                 case 'last':\r
481                         $sort_by = 'timestamp';\r
482                         $sort_order = 'desc';\r
483                         break;\r
484                 case 'rand':\r
485                 case 'random':\r
486                         $sort_by = 'RAND()';\r
487                         $sort_order = '';\r
488                         break;\r
489                 case 'top':\r
490                 default:\r
491                         $sort_by = 'clicks';\r
492                         $sort_order = 'desc';\r
493                         break;\r
494         }\r
495         \r
496         $limit = intval( $limit );\r
497         if ( $limit == 0 )\r
498                 $limit = 1;\r
499         $table_url = YOURLS_DB_TABLE_URL;\r
500         $results = $ydb->get_results("SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT 0, $limit;");\r
501         \r
502         $return = array();\r
503         $i = 1;\r
504         \r
505         foreach ($results as $res) {\r
506                 $return['links']['link_'.$i++] = array(\r
507                         'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
508                         'url' => $res->url,\r
509                         'timestamp' => $res->timestamp,\r
510                         'ip' => $res->ip,\r
511                         'clicks' => $res->clicks,\r
512                 );\r
513         }\r
514 \r
515         $return['stats'] = yourls_get_db_stats();\r
516         \r
517         $return['statusCode'] = 200;\r
518 \r
519         return $return;\r
520 }\r
521 \r
522 \r
523 // Return array for API stat requests\r
524 function yourls_api_stats( $filter = 'top', $limit = 10 ) {\r
525         $return = yourls_get_links_stats( $filter, $limit );\r
526         $return['simple']  = 'Need either XML or JSON format for stats';\r
527         $return['message'] = 'success';\r
528         return $return;\r
529 }\r
530 \r
531 // Expand short url to long url\r
532 function yourls_api_expand( $shorturl ) {\r
533         $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
534         $keyword = yourls_sanitize_string( $keyword );\r
535         \r
536         $longurl = yourls_get_keyword_longurl( $keyword );\r
537         \r
538         if( $longurl ) {\r
539                 return array(\r
540                         'keyword'  => $keyword,\r
541                         'shorturl' => YOURLS_SITE . "/$keyword",\r
542                         'longurl'  => $longurl,\r
543                         'simple'   => $longurl,\r
544                         'message'  => 'success',\r
545                         'statusCode' => 200,\r
546                 );\r
547         } else {\r
548                 return array(\r
549                         'keyword'  => $keyword,\r
550                         'simple'   => 'not found',\r
551                         'message'  => 'Error: short URL not found',\r
552                         'errorCode' => 404,\r
553                 );\r
554         }\r
555 }\r
556 \r
557 \r
558 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array\r
559 function yourls_get_db_stats( $where = '' ) {\r
560         global $ydb;\r
561         $table_url = YOURLS_DB_TABLE_URL;\r
562 \r
563         $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");\r
564         return array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );\r
565 }\r
566 \r
567 // Return API result. Dies after this\r
568 function yourls_api_output( $mode, $return ) {\r
569         if( isset( $return['simple'] ) ) {\r
570                 $simple = $return['simple'];\r
571                 unset( $return['simple'] );\r
572         }\r
573         switch ( $mode ) {\r
574                 case 'json':\r
575                         header('Content-type: application/json');\r
576                         echo yourls_json_encode($return);\r
577                         break;\r
578                 \r
579                 case 'xml':\r
580                         header('Content-type: application/xml');\r
581                         echo yourls_xml_encode($return);\r
582                         break;\r
583                         \r
584                 case 'simple':\r
585                 default:\r
586                         if( isset( $simple ) )\r
587                                 echo $simple;\r
588                         break;\r
589         }\r
590         die();\r
591 }\r
592 \r
593 // Display HTML head and <body> tag\r
594 function yourls_html_head( $context = 'index' ) {\r
595         // All components to false, except when specified true\r
596         $share = $insert = $tablesorter = $tabs = false;\r
597         // Load components as needed\r
598         switch ( $context ) {\r
599                 case 'infos':\r
600                         $share = $tabs = true;\r
601                         break;\r
602                         \r
603                 case 'bookmark':\r
604                         $share = $insert = $tablesorter = true;\r
605                         break;\r
606                         \r
607                 case 'index':\r
608                         $insert = $tablesorter = true;\r
609                         break;\r
610                 \r
611                 case 'install':\r
612                 case 'login':\r
613                 case 'new':\r
614                 case 'tools':\r
615                 case 'upgrade':\r
616                         break;\r
617         }\r
618         \r
619         ?>\r
620 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r
621 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\r
622 <head>\r
623         <title>YOURLS &raquo; Your Own URL Shortener | <?php echo YOURLS_SITE; ?></title>\r
624         <link rel="icon" type="image/gif" href="<?php echo YOURLS_SITE; ?>/images/favicon.gif" />\r
625         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r
626         <meta http-equiv="X-UA-Compatible" content="chrome=1" />\r
627         <meta name="copyright" content="Copyright &copy; 2008-<?php echo date('Y'); ?> YOURS" />\r
628         <meta name="author" content="Ozh Richard, Lester Chan" />\r
629         <meta name="description" content="Insert URL &laquo; YOURLS &raquo; Your Own URL Shortener' | <?php echo YOURLS_SITE; ?>" />\r
630         <script src="<?php echo YOURLS_SITE; ?>/js/jquery-1.3.2.min.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>\r
631         <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/style.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />\r
632         <?php if ($tabs) { ?>\r
633                 <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/infos.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />\r
634                 <script src="<?php echo YOURLS_SITE; ?>/js/infos.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>\r
635         <?php } ?>\r
636         <?php if ($tablesorter) { ?>\r
637                 <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/tablesorter.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />\r
638                 <script src="<?php echo YOURLS_SITE; ?>/js/jquery.tablesorter.min.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>\r
639         <?php } ?>\r
640         <?php if ($insert) { ?>\r
641                 <script src="<?php echo YOURLS_SITE; ?>/js/insert.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>\r
642         <?php } ?>\r
643         <?php if ($share) { ?>\r
644                 <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/share.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />\r
645                 <script src="<?php echo YOURLS_SITE; ?>/js/share.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>\r
646         <?php } ?>\r
647 </head>\r
648 <body class="<?php echo $context; ?>">\r
649 <div id="wrap">\r
650         <?php\r
651 }\r
652 \r
653 // Display HTML footer (including closing body & html tags)\r
654 function yourls_html_footer() {\r
655         global $ydb;\r
656         \r
657         $num_queries = $ydb->num_queries > 1 ? $ydb->num_queries.' queries' : $ydb->num_queries.' query';\r
658         ?>\r
659         </div> <?php // wrap ?>\r
660         <div id="footer"><p>Powered by <a href="http://yourls.org/" title="YOURLS">YOURLS</a> v<?php echo YOURLS_VERSION; echo ' &ndash; '.$num_queries; ?></p></div>\r
661         <?php if( defined('YOURLS_DEBUG') && YOURLS_DEBUG == true ) {\r
662                 echo '<p>'. $ydb->all_queries .'<p>';\r
663         } ?>\r
664         </body>\r
665         </html>\r
666         <?php\r
667 }\r
668 \r
669 // Display "Add new URL" box\r
670 function yourls_html_addnew( $url = '', $keyword = '' ) {\r
671         $url = $url ? $url : 'http://';\r
672         ?>\r
673         <div id="new_url">\r
674                 <div>\r
675                         <form id="new_url_form" action="" method="get">\r
676                                 <div><strong>Enter the URL</strong>:<input type="text" id="add-url" name="url" value="<?php echo $url; ?>" class="text" size="80" />\r
677                                 Optional: <strong>Custom short URL</strong>:<input type="text" id="add-keyword" name="keyword" value="<?php echo $keyword; ?>" maxlength="12" class="text" size="8" />\r
678                                 <input type="button" id="add-button" name="add-button" value="Shorten The URL" class="button" onclick="add();" /></div>\r
679                         </form>\r
680                         <div id="feedback" style="display:none"></div>\r
681                 </div>\r
682         </div>\r
683         <?php\r
684 }\r
685 \r
686 // Display main table's footer\r
687 function yourls_html_tfooter( $params = array() ) {\r
688         extract( $params ); // extract $search_text, $page, $search_in_sql ...\r
689 \r
690         ?>\r
691         <tfoot>\r
692                 <tr>\r
693                         <th colspan="4" style="text-align: left;">\r
694                                 <form action="" method="get">\r
695                                         <div>\r
696                                                 <div style="float:right;">\r
697                                                         <input type="submit" id="submit-sort" value="Filter" class="button primary" />\r
698                                                         &nbsp;\r
699                                                         <input type="button" id="submit-clear-filter" value="Clear Filter" class="button" onclick="window.parent.location.href = 'index.php'" />\r
700                                                 </div>\r
701 \r
702                                                 Search&nbsp;for&nbsp;\r
703                                                 <input type="text" name="s_search" class="text" size="20" value="<?php echo $search_text; ?>" />\r
704                                                 &nbsp;in&nbsp;\r
705                                                 <select name="s_in" size="1">\r
706                                                         <!-- <option value="id"<?php if($search_in_sql == 'id') { echo ' selected="selected"'; } ?>>ID</option> -->\r
707                                                         <option value="url"<?php if($search_in_sql == 'url') { echo ' selected="selected"'; } ?>>URL</option>\r
708                                                         <option value="ip"<?php if($search_in_sql == 'ip') { echo ' selected="selected"'; } ?>>IP</option>\r
709                                                 </select>\r
710                                                 &ndash;&nbsp;Order&nbsp;by&nbsp;\r
711                                                 <select name="s_by" size="1">\r
712                                                         <option value="id"<?php if($sort_by_sql == 'id') { echo ' selected="selected"'; } ?>>ID</option>\r
713                                                         <option value="url"<?php if($sort_by_sql == 'url') { echo ' selected="selected"'; } ?>>URL</option>\r
714                                                         <option value="timestamp"<?php if($sort_by_sql == 'timestamp') { echo ' selected="selected"'; } ?>>Date</option>\r
715                                                         <option value="ip"<?php if($sort_by_sql == 'ip') { echo ' selected="selected"'; } ?>>IP</option>\r
716                                                         <option value="clicks"<?php if($sort_by_sql == 'clicks') { echo ' selected="selected"'; } ?>>Clicks</option>\r
717                                                 </select>\r
718                                                 <select name="s_order" size="1">\r
719                                                         <option value="asc"<?php if($sort_order_sql == 'asc') { echo ' selected="selected"'; } ?>>Ascending</option>\r
720                                                         <option value="desc"<?php if($sort_order_sql == 'desc') { echo ' selected="selected"'; } ?>>Descending</option>\r
721                                                 </select>\r
722                                                 &ndash;&nbsp;Show&nbsp;\r
723                                                 <input type="text" name="perpage" class="text" size="2" value="<?php echo $perpage; ?>" />&nbsp;rows<br/>\r
724                                                 \r
725                                                 Show links with\r
726                                                 <select name="link_filter" size="1">\r
727                                                         <option value="more"<?php if($link_filter === 'more') { echo ' selected="selected"'; } ?>>more</option>\r
728                                                         <option value="less"<?php if($link_filter === 'less') { echo ' selected="selected"'; } ?>>less</option>\r
729                                                 </select>\r
730                                                 than\r
731                                                 <input type="text" name="link_limit" class="text" size="4" value="<?php echo $link_limit; ?>" />clicks\r
732 \r
733                                                 \r
734                                         </div>\r
735                                 </form>\r
736                         </th>\r
737                         <th colspan="3" style="text-align: right;">\r
738                                 Pages (<?php echo $total_pages; ?>):\r
739                                 <?php\r
740                                         if ($page >= 4) {\r
741                                                 echo '<b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page=1'.'" title="Go to First Page">&laquo; First</a></b> ... ';\r
742                                         }\r
743                                         if($page > 1) {\r
744                                                 echo ' <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($page-1).'" title="&laquo; Go to Page '.($page-1).'">&laquo;</a></b> ';\r
745                                         }\r
746                                         for($i = $page - 2 ; $i  <= $page +2; $i++) {\r
747                                                 if ($i >= 1 && $i <= $total_pages) {\r
748                                                         if($i == $page) {\r
749                                                                 echo "<strong>[$i]</strong> ";\r
750                                                         } else {\r
751                                                                 echo '<a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($i).'" title="Page '.$i.'">'.$i.'</a> ';\r
752                                                         }\r
753                                                 }\r
754                                         }\r
755                                         if($page < $total_pages) {\r
756                                                 echo ' <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($page+1).'" title="Go to Page '.($page+1).' &raquo;">&raquo;</a></b> ';\r
757                                         }\r
758                                         if (($page+2) < $total_pages) {\r
759                                                 echo ' ... <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($total_pages).'" title="Go to Last Page">Last &raquo;</a></b>';\r
760                                         }\r
761                                 ?>\r
762                         </th>\r
763                 </tr>\r
764         </tfoot>\r
765         <?php\r
766 }\r
767 \r
768 // Display the Quick Share box of the tools.php page\r
769 function yourls_share_box( $longurl, $shorturl, $title='', $text='', $shortlink_title = '<h2>Your short link</h2>', $share_title = '<h2>Quick Share</h2>' ) {\r
770         $text = ( $text ? '"'.$text.'" ' : '' );\r
771         $title = ( $title ? "$title " : '' );\r
772         $share = htmlspecialchars_decode( $title.$text.$shorturl );\r
773         $_share = rawurlencode( $share );\r
774         $_url = rawurlencode( $shorturl );\r
775         $count = 140 - strlen( $share );\r
776         ?>\r
777         \r
778         <div id="shareboxes">\r
779 \r
780                 <div id="copybox" class="share">\r
781                 <?php echo $shortlink_title; ?>\r
782                         <p><input id="copylink" class="text" size="40" value="<?php echo $shorturl; ?>" /></p>\r
783                         <p><small>Original link: <a href="<?php echo $longurl; ?>"><?php echo $longurl; ?></a></small></p>\r
784                 </div>\r
785 \r
786                 <div id="sharebox" class="share">\r
787                         <?php echo $share_title; ?>\r
788                         <div id="tweet">\r
789                                 <span id="charcount"><?php echo $count; ?></span>\r
790                                 <textarea id="tweet_body"><?php echo $share; ?></textarea>\r
791                         </div>\r
792                         <p id="share_links">Share with \r
793                                 <a id="share_tw" href="http://twitter.com/home?status=<?php echo $_share; ?>" title="Tweet this!" onclick="share('tw');return false">Twitter</a>\r
794                                 <a id="share_fb" href="http://www.facebook.com/share.php?u=<?php echo $_url; ?>" title="Share on Facebook" onclick="share('fb');return false;">Facebook</a>\r
795                                 <a id="share_ff" href="http://friendfeed.com/share/bookmarklet/frame#title=<?php echo $_share; ?>" title="Share on Friendfeed" onclick="javascript:share('ff');return false;">FriendFeed</a>\r
796                         </p>\r
797                         </div>\r
798                 </div>\r
799         \r
800         </div>\r
801         \r
802         <?php\r
803 }\r
804 \r
805 // Get number of SQL queries performed\r
806 function yourls_get_num_queries() {\r
807         global $ydb;\r
808 \r
809         return $ydb->num_queries;\r
810 }\r
811 \r
812 // Compat http_build_query for PHP4\r
813 if (!function_exists('http_build_query')) {\r
814         function http_build_query($data, $prefix=null, $sep=null) {\r
815                 return yourls_http_build_query($data, $prefix, $sep);\r
816         }\r
817 }\r
818 \r
819 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)\r
820 function yourls_http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {\r
821         $ret = array();\r
822 \r
823         foreach ( (array) $data as $k => $v ) {\r
824                 if ( $urlencode)\r
825                         $k = urlencode($k);\r
826                 if ( is_int($k) && $prefix != null )\r
827                         $k = $prefix.$k;\r
828                 if ( !empty($key) )\r
829                         $k = $key . '%5B' . $k . '%5D';\r
830                 if ( $v === NULL )\r
831                         continue;\r
832                 elseif ( $v === FALSE )\r
833                         $v = '0';\r
834 \r
835                 if ( is_array($v) || is_object($v) )\r
836                         array_push($ret,yourls_http_build_query($v, '', $sep, $k, $urlencode));\r
837                 elseif ( $urlencode )\r
838                         array_push($ret, $k.'='.urlencode($v));\r
839                 else\r
840                         array_push($ret, $k.'='.$v);\r
841         }\r
842 \r
843         if ( NULL === $sep )\r
844                 $sep = ini_get('arg_separator.output');\r
845 \r
846         return implode($sep, $ret);\r
847 }\r
848 \r
849 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.\r
850 function yourls_get_user_agent() {\r
851         if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )\r
852                 return '-';\r
853         \r
854         $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));\r
855         $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );\r
856                 \r
857         return substr( $ua, 0, 254 );\r
858 }\r
859 \r
860 // Redirect to another page\r
861 function yourls_redirect( $location, $code = 301 ) {\r
862         // Anti fool check: cannot redirect to the URL we currently are on\r
863         if( preg_replace('!^[^:]+://!', '', $location) != $_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI'] ) {\r
864                 yourls_status_header( $code );\r
865                 header("Location: $location");\r
866                 die();\r
867         }\r
868 }\r
869 \r
870 // Set HTTP status header\r
871 function yourls_status_header( $code = 200 ) {\r
872         if( headers_sent() )\r
873                 return;\r
874                 \r
875         $protocol = $_SERVER["SERVER_PROTOCOL"];\r
876         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )\r
877                 $protocol = 'HTTP/1.0';\r
878 \r
879         $code = intval( $code );\r
880         $desc = yourls_get_HTTP_status($code);\r
881 \r
882         @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups\r
883 }\r
884 \r
885 // 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
886 function yourls_redirect_javascript( $location, $dontwait = true ) {\r
887         if( $dontwait ) {\r
888         echo <<<REDIR\r
889         <script type="text/javascript">\r
890         window.location="$location";\r
891         </script>\r
892         <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>\r
893 REDIR;\r
894         } else {\r
895         echo <<<MANUAL\r
896         <p>Please <a href="$location">click here</a></p>\r
897 MANUAL;\r
898         }\r
899 }\r
900 \r
901 // Return a HTTP status code\r
902 function yourls_get_HTTP_status( $code ) {\r
903         $code = intval( $code );\r
904         $headers_desc = array(\r
905                 100 => 'Continue',\r
906                 101 => 'Switching Protocols',\r
907                 102 => 'Processing',\r
908 \r
909                 200 => 'OK',\r
910                 201 => 'Created',\r
911                 202 => 'Accepted',\r
912                 203 => 'Non-Authoritative Information',\r
913                 204 => 'No Content',\r
914                 205 => 'Reset Content',\r
915                 206 => 'Partial Content',\r
916                 207 => 'Multi-Status',\r
917                 226 => 'IM Used',\r
918 \r
919                 300 => 'Multiple Choices',\r
920                 301 => 'Moved Permanently',\r
921                 302 => 'Found',\r
922                 303 => 'See Other',\r
923                 304 => 'Not Modified',\r
924                 305 => 'Use Proxy',\r
925                 306 => 'Reserved',\r
926                 307 => 'Temporary Redirect',\r
927 \r
928                 400 => 'Bad Request',\r
929                 401 => 'Unauthorized',\r
930                 402 => 'Payment Required',\r
931                 403 => 'Forbidden',\r
932                 404 => 'Not Found',\r
933                 405 => 'Method Not Allowed',\r
934                 406 => 'Not Acceptable',\r
935                 407 => 'Proxy Authentication Required',\r
936                 408 => 'Request Timeout',\r
937                 409 => 'Conflict',\r
938                 410 => 'Gone',\r
939                 411 => 'Length Required',\r
940                 412 => 'Precondition Failed',\r
941                 413 => 'Request Entity Too Large',\r
942                 414 => 'Request-URI Too Long',\r
943                 415 => 'Unsupported Media Type',\r
944                 416 => 'Requested Range Not Satisfiable',\r
945                 417 => 'Expectation Failed',\r
946                 422 => 'Unprocessable Entity',\r
947                 423 => 'Locked',\r
948                 424 => 'Failed Dependency',\r
949                 426 => 'Upgrade Required',\r
950 \r
951                 500 => 'Internal Server Error',\r
952                 501 => 'Not Implemented',\r
953                 502 => 'Bad Gateway',\r
954                 503 => 'Service Unavailable',\r
955                 504 => 'Gateway Timeout',\r
956                 505 => 'HTTP Version Not Supported',\r
957                 506 => 'Variant Also Negotiates',\r
958                 507 => 'Insufficient Storage',\r
959                 510 => 'Not Extended'\r
960         );\r
961 \r
962         if ( isset( $headers_desc[$code] ) )\r
963                 return $headers_desc[$code];\r
964         else\r
965                 return '';\r
966 }\r
967 \r
968 \r
969 // Log a redirect (for stats)\r
970 function yourls_log_redirect( $keyword ) {\r
971         if ( !yourls_do_log_redirect() )\r
972                 return true;\r
973 \r
974         global $ydb;\r
975         $table = YOURLS_DB_TABLE_LOG;\r
976         \r
977         $keyword = yourls_sanitize_string( $keyword );\r
978         $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );\r
979         $ua = yourls_get_user_agent();\r
980         $ip = yourls_get_IP();\r
981         $location = yourls_geo_ip_to_countrycode( $ip );\r
982         \r
983         return $ydb->query( "INSERT INTO `$table` VALUES ('', NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );\r
984 }\r
985 \r
986 // Check if we want to not log redirects (for stats)\r
987 function yourls_do_log_redirect() {\r
988         return ( !defined('YOURLS_NOSTATS') || YOURLS_NOSTATS != true );\r
989 }\r
990 \r
991 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/\r
992 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {\r
993         if ( !file_exists( dirname(__FILE__).'/geo/GeoIP.dat') || !file_exists( dirname(__FILE__).'/geo/geoip.inc') )\r
994                 return $default;\r
995 \r
996         if ( $ip == '' )\r
997                 $ip = yourls_get_IP();\r
998                 \r
999         require_once( dirname(__FILE__).'/geo/geoip.inc') ;\r
1000         $gi = geoip_open( dirname(__FILE__).'/geo/GeoIP.dat', GEOIP_STANDARD);\r
1001         $location = geoip_country_code_by_addr($gi, $ip);\r
1002         geoip_close($gi);\r
1003 \r
1004         return $location;\r
1005 }\r
1006 \r
1007 // Converts a 2 letter country code to long name (ie AU -> Australia)\r
1008 function yourls_geo_countrycode_to_countryname( $code ) {\r
1009         // Load the Geo class if not already done\r
1010         if( !class_exists('GeoIP') ) {\r
1011                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
1012         }\r
1013         \r
1014         if( class_exists('GeoIP') ) {\r
1015                 $geo = new GeoIP;\r
1016                 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];\r
1017                 $long = $geo->GEOIP_COUNTRY_NAMES[$id];\r
1018                 return $long;\r
1019         } else {\r
1020                 return false;\r
1021         }\r
1022 }\r
1023 \r
1024 // Return flag URL from 2 letter country code\r
1025 function yourls_geo_get_flag( $code ) {\r
1026         // Load the Geo class if not already done\r
1027         if( !class_exists('GeoIP') ) {\r
1028                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
1029         }\r
1030         \r
1031         if( class_exists('GeoIP') ) {\r
1032                 return YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif';\r
1033         } else {\r
1034                 return false;\r
1035         }\r
1036 }\r
1037 \r
1038 \r
1039 // Check if an upgrade is needed\r
1040 function yourls_upgrade_is_needed() {\r
1041         // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS\r
1042         list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();\r
1043         if( $currentsql < YOURLS_DB_VERSION )\r
1044                 return true;\r
1045                 \r
1046         return false;\r
1047 }\r
1048 \r
1049 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.\r
1050 function yourls_get_current_version_from_sql() {\r
1051         $currentver = yourls_get_option( 'version' );\r
1052         $currentsql = yourls_get_option( 'db_version' );\r
1053 \r
1054         // Values if version is 1.3\r
1055         if( !$currentver )\r
1056                 $currentver = '1.3';\r
1057         if( !$currentsql )\r
1058                 $currentsql = '100';\r
1059                 \r
1060         return array( $currentver, $currentsql);\r
1061 }\r
1062 \r
1063 // Read an option from DB (or from cache if available). Return value or $default if not found\r
1064 function yourls_get_option( $option_name, $default = false ) {\r
1065         global $ydb;\r
1066         if ( !isset( $ydb->option[$option_name] ) ) {\r
1067                 $table = YOURLS_DB_TABLE_OPTIONS;\r
1068                 $option_name = yourls_escape( $option_name );\r
1069                 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );\r
1070                 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values\r
1071                         $value = $row->option_value;\r
1072                 } else { // option does not exist, so we must cache its non-existence\r
1073                         $value = $default;\r
1074                 }\r
1075                 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );\r
1076         }\r
1077 \r
1078         return $ydb->option[$option_name];\r
1079 }\r
1080 \r
1081 // Read all options from DB at once\r
1082 function yourls_get_all_options() {\r
1083         global $ydb;\r
1084         $table = YOURLS_DB_TABLE_OPTIONS;\r
1085         \r
1086         $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");\r
1087         \r
1088         foreach( (array)$allopt as $option ) {\r
1089                 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );\r
1090         }\r
1091 }\r
1092 \r
1093 // Update (add if doesn't exist) an option to DB\r
1094 function yourls_update_option( $option_name, $newvalue ) {\r
1095         global $ydb;\r
1096         $table = YOURLS_DB_TABLE_OPTIONS;\r
1097 \r
1098         $safe_option_name = yourls_escape( $option_name );\r
1099 \r
1100         $oldvalue = yourls_get_option( $safe_option_name );\r
1101 \r
1102         // If the new and old values are the same, no need to update.\r
1103         if ( $newvalue === $oldvalue )\r
1104                 return false;\r
1105 \r
1106         if ( false === $oldvalue ) {\r
1107                 yourls_add_option( $option_name, $newvalue );\r
1108                 return true;\r
1109         }\r
1110 \r
1111         $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );\r
1112 \r
1113         $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");\r
1114 \r
1115         if ( $ydb->rows_affected == 1 ) {\r
1116                 $ydb->option[$option_name] = $newvalue;\r
1117                 return true;\r
1118         }\r
1119         return false;\r
1120 }\r
1121 \r
1122 // Add an option to the DB\r
1123 function yourls_add_option( $name, $value = '' ) {\r
1124         global $ydb;\r
1125         $table = YOURLS_DB_TABLE_OPTIONS;\r
1126         $safe_name = yourls_escape( $name );\r
1127 \r
1128         // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query\r
1129         if ( false !== yourls_get_option( $safe_name ) )\r
1130                 return;\r
1131 \r
1132         $_value = yourls_escape( yourls_maybe_serialize( $value ) );\r
1133 \r
1134         $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );\r
1135         $ydb->option[$name] = $value;\r
1136         return;\r
1137 }\r
1138 \r
1139 \r
1140 // Delete an option from the DB\r
1141 function yourls_delete_option( $name ) {\r
1142         global $ydb;\r
1143         $table = YOURLS_DB_TABLE_OPTIONS;\r
1144         $name = yourls_escape( $name );\r
1145 \r
1146         // Get the ID, if no ID then return\r
1147         $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );\r
1148         if ( is_null($option) || !$option->option_id )\r
1149                 return false;\r
1150         $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );\r
1151         return true;\r
1152 }\r
1153 \r
1154 \r
1155 \r
1156 // Serialize data if needed. Stolen from WordPress\r
1157 function yourls_maybe_serialize( $data ) {\r
1158         if ( is_array( $data ) || is_object( $data ) )\r
1159                 return serialize( $data );\r
1160 \r
1161         if ( yourls_is_serialized( $data ) )\r
1162                 return serialize( $data );\r
1163 \r
1164         return $data;\r
1165 }\r
1166 \r
1167 // Check value to find if it was serialized. Stolen from WordPress\r
1168 function yourls_is_serialized( $data ) {\r
1169         // if it isn't a string, it isn't serialized\r
1170         if ( !is_string( $data ) )\r
1171                 return false;\r
1172         $data = trim( $data );\r
1173         if ( 'N;' == $data )\r
1174                 return true;\r
1175         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )\r
1176                 return false;\r
1177         switch ( $badions[1] ) {\r
1178                 case 'a' :\r
1179                 case 'O' :\r
1180                 case 's' :\r
1181                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )\r
1182                                 return true;\r
1183                         break;\r
1184                 case 'b' :\r
1185                 case 'i' :\r
1186                 case 'd' :\r
1187                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )\r
1188                                 return true;\r
1189                         break;\r
1190         }\r
1191         return false;\r
1192 }\r
1193 \r
1194 // Unserialize value only if it was serialized. Stolen from WP\r
1195 function yourls_maybe_unserialize( $original ) {\r
1196         if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in\r
1197                 return @unserialize( $original );\r
1198         return $original;\r
1199 }\r
1200 \r
1201 // Determine if the current page is private\r
1202 function yourls_is_private() {\r
1203         if (defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true) {\r
1204 \r
1205                 // Allow overruling of particular pages\r
1206                 $current = basename( $_SERVER["SCRIPT_NAME"] );\r
1207 \r
1208                 switch( $current ) {\r
1209                 \r
1210                 case 'yourls-api.php':\r
1211                         if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )\r
1212                                 return true;\r
1213                         break;\r
1214                                 \r
1215                 case 'yourls-infos.php':\r
1216                         if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )\r
1217                                 return true;\r
1218                         break;\r
1219                 \r
1220                 default:\r
1221                         return true;\r
1222                         break;\r
1223                 }\r
1224         }\r
1225         \r
1226         return false;\r
1227 }\r
1228 \r
1229 // Show login form if required\r
1230 function yourls_maybe_require_auth() {\r
1231         if( yourls_is_private() )\r
1232                 require_once( dirname(__FILE__).'/auth.php' );\r
1233 }\r
1234 \r
1235 // Echo HTML tag for a link\r
1236 function yourls_html_link( $href, $title = '', $element = '' ) {\r
1237         if( !$title )\r
1238                 $title = $href;\r
1239         if( $element )\r
1240                 $element = "id='$element'";\r
1241         echo "<a href='$href' $element>$title</a>";\r
1242 }\r
1243 \r
1244 // Return word or words if more than one\r
1245 function yourls_plural( $word, $count=1 ) {\r
1246         return $word . ($count > 1 ? 's' : '');\r
1247 }\r
1248 \r
1249 // Return trimmed string\r
1250 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {\r
1251         if ( strlen( $string ) > $length ) {\r
1252                 $string = substr( $string, 0, $length - strlen( $append ) ) . $append;  \r
1253         }\r
1254         return $string;\r
1255 }\r
1256 \r
1257 // Allow several short URLs for the same long URL ?\r
1258 function yourls_allow_duplicate_longurls() {\r
1259         return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );\r
1260 }\r
1261 \r
1262 // Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.\r
1263 function yourls_get_duplicate_keywords( $longurl ) {\r
1264         if( !yourls_allow_duplicate_longurls() )\r
1265                 return NULL;\r
1266         \r
1267         global $ydb;\r
1268         $longurl = mysql_real_escape_string( yourls_sanitize_url($longurl) );\r
1269         $table = YOURLS_DB_TABLE_URL;\r
1270         \r
1271         return $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );\r
1272 }\r
1273 \r
1274 // Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.\r
1275 function yourls_check_IP_flood( $ip = '' ) {\r
1276         if(\r
1277                 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||\r
1278                 !defined('YOURLS_FLOOD_DELAY_SECONDS')\r
1279         )\r
1280                 return true;\r
1281 \r
1282         $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );\r
1283 \r
1284         // Don't throttle whitelist IPs\r
1285         if( defined('YOURLS_FLOOD_IP_WHITELIST' && YOURLS_FLOOD_IP_WHITELIST ) ) {\r
1286                 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );\r
1287                 foreach( $whitelist_ips as $whitelist_ip ) {\r
1288                         $whitelist_ip = trim( $whitelist_ip );\r
1289                         if ( $whitelist_ip == $ip )\r
1290                                 return true;\r
1291                 }\r
1292         }\r
1293         \r
1294         // Don't throttle logged in users\r
1295         if( yourls_is_private() ) {\r
1296                  if( yourls_is_valid_user() === true )\r
1297                         return true;\r
1298         }\r
1299 \r
1300         global $ydb;\r
1301         $table = YOURLS_DB_TABLE_URL;\r
1302         \r
1303         $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );\r
1304         if( $lasttime ) {\r
1305                 $now = date( 'U' );\r
1306                 $then = date( 'U', strtotime( $lasttime ) );\r
1307                 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {\r
1308                         // Flood!\r
1309                         yourls_die( 'Too many URLs added too fast. Slow down please.', 'Forbidden', 403 );\r
1310                 }\r
1311         }\r
1312         \r
1313         return true;\r
1314 }\r
1315 \r
1316 // Die die die\r
1317 function yourls_die( $message = '', $title = '', $header_code = 200 ) {\r
1318         yourls_status_header( $header_code );\r
1319         \r
1320         yourls_html_head();\r
1321         ?>\r
1322         <h1>\r
1323                 <a href="<?php echo $base_page; ?>" title="YOURLS"><span>YOURLS</span>: <span>Y</span>our <span>O</span>wn <span>URL</span> <span>S</span>hortener<br/>\r
1324                 <img src="<?php echo YOURLS_SITE; ?>/images/yourls-logo.png" alt="YOURLS" title="YOURLS" style="border: 0px;" /></a>\r
1325         </h1>\r
1326         <?php\r
1327         echo "<h2>$title</h2>";\r
1328         echo "<p>$message</p>";\r
1329         yourls_html_footer();\r
1330         die();\r
1331 }\r
1332 \r
1333 // Check if YOURLS is installed\r
1334 function yourls_is_installed() {\r
1335         static $is_installed = false;\r
1336         if ( $is_installed === false ) {\r
1337                 $check_14 = $check_13 = false;\r
1338                 global $ydb;\r
1339                 if( defined('YOURLS_DB_TABLE_NEXTDEC') )\r
1340                         $check_13 = $ydb->get_var('SELECT next_id FROM '.YOURLS_DB_TABLE_NEXTDEC);\r
1341                 $check_14 = yourls_get_option( 'version' );\r
1342                 $is_installed = $check_13 || $check_14;\r
1343         }\r
1344         return $is_installed;\r
1345 }\r