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