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