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