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