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