]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions.php
Save title in database
[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 \r
488 // Check if keyword id is free (ie not already taken, and not reserved). Return bool.\r
489 function yourls_keyword_is_free( $keyword ) {\r
490         $free = true;\r
491         if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )\r
492                 $free = false;\r
493                 \r
494         return yourls_apply_filter( 'keyword_is_free', $free, $keyword );\r
495 }\r
496 \r
497 // Check if a keyword is taken (ie there is already a short URL with this id). Return bool.             \r
498 function yourls_keyword_is_taken( $keyword ) {\r
499         global $ydb;\r
500         $keyword = yourls_sanitize_keyword( $keyword );\r
501         $taken = false;\r
502         $table = YOURLS_DB_TABLE_URL;\r
503         $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");\r
504         if ( $already_exists )\r
505                 $taken = true;\r
506 \r
507         return yourls_apply_filter( 'keyword_is_taken', $taken );\r
508 }\r
509 \r
510 \r
511 // Display a page\r
512 function yourls_page( $page ) {\r
513         $include = YOURLS_ABSPATH . "/pages/$page.php";\r
514         if (!file_exists($include)) {\r
515                 yourls_die("Page '$page' not found", 'Not found', 404);\r
516         }\r
517         yourls_do_action( 'pre_page', $page );\r
518         include($include);\r
519         yourls_do_action( 'post_page', $page );\r
520         die();  \r
521 }\r
522 \r
523 // Connect to DB\r
524 function yourls_db_connect() {\r
525         global $ydb;\r
526 \r
527         if (!defined('YOURLS_DB_USER')\r
528                 or !defined('YOURLS_DB_PASS')\r
529                 or !defined('YOURLS_DB_NAME')\r
530                 or !defined('YOURLS_DB_HOST')\r
531                 or !class_exists('ezSQL_mysql')\r
532         ) yourls_die ('DB config missing, or could not find DB class', 'Fatal error', 503);\r
533         \r
534         // Are we standalone or in the WordPress environment?\r
535         if ( class_exists('wpdb') ) {\r
536                 $ydb =  new wpdb(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
537         } else {\r
538                 $ydb =  new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
539         }\r
540         if ( $ydb->last_error )\r
541                 yourls_die( $ydb->last_error, 'Fatal error', 503 );\r
542         \r
543         if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )\r
544                 $ydb->show_errors = true;\r
545         \r
546         return $ydb;\r
547 }\r
548 \r
549 // Return XML output.\r
550 function yourls_xml_encode($array) {\r
551         require_once(YOURLS_INC.'/functions-xml.php');\r
552         $converter= new yourls_array2xml;\r
553         return $converter->array2xml($array);\r
554 }\r
555 \r
556 // 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
557 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {\r
558         global $ydb;\r
559         $keyword = yourls_sanitize_string( $keyword );\r
560 \r
561         if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {\r
562                 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );\r
563         }\r
564         \r
565         $table = YOURLS_DB_TABLE_URL;\r
566         $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");\r
567         \r
568         if( $infos ) {\r
569                 $infos = (array)$infos;\r
570                 $ydb->infos[$keyword] = $infos;\r
571         } else {\r
572                 $ydb->infos[$keyword] = false;\r
573         }\r
574                 \r
575         return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );\r
576 }\r
577 \r
578 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\r
579 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {\r
580         $keyword = yourls_sanitize_string( $keyword );\r
581         $infos = yourls_get_keyword_infos( $keyword );\r
582         \r
583         $return = $notfound;\r
584         if ( isset($infos[$field]) && $infos[$field] !== false )\r
585                 $return = $infos[$field];\r
586 \r
587         return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound ); \r
588 }\r
589 \r
590 // Return title associated with keyword. Optional $notfound = string default message if nothing found\r
591 function yourls_get_keyword_title( $keyword, $notfound = false ) {\r
592         return yourls_get_keyword_info( $keyword, 'title', $notfound );\r
593 }\r
594 \r
595 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found\r
596 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {\r
597         return yourls_get_keyword_info( $keyword, 'url', $notfound );\r
598 }\r
599 \r
600 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\r
601 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {\r
602         return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\r
603 }\r
604 \r
605 // Return IP that added a keyword. Optional $notfound = string default message if nothing found\r
606 function yourls_get_keyword_IP( $keyword, $notfound = false ) {\r
607         return yourls_get_keyword_info( $keyword, 'ip', $notfound );\r
608 }\r
609 \r
610 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\r
611 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\r
612         return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\r
613 }\r
614 \r
615 // Update click count on a short URL. Return 0/1 for error/success.\r
616 function yourls_update_clicks( $keyword ) {\r
617         global $ydb;\r
618         $keyword = yourls_sanitize_string( $keyword );\r
619         $table = YOURLS_DB_TABLE_URL;\r
620         $update = $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");\r
621         yourls_do_action( 'update_clicks', $keyword, $update );\r
622         return $update;\r
623 }\r
624 \r
625 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return\r
626 function yourls_get_stats( $filter = 'top', $limit = 10 ) {\r
627         global $ydb;\r
628 \r
629         switch( $filter ) {\r
630                 case 'bottom':\r
631                         $sort_by = 'clicks';\r
632                         $sort_order = 'asc';\r
633                         break;\r
634                 case 'last':\r
635                         $sort_by = 'timestamp';\r
636                         $sort_order = 'desc';\r
637                         break;\r
638                 case 'rand':\r
639                 case 'random':\r
640                         $sort_by = 'RAND()';\r
641                         $sort_order = '';\r
642                         break;\r
643                 case 'top':\r
644                 default:\r
645                         $sort_by = 'clicks';\r
646                         $sort_order = 'desc';\r
647                         break;\r
648         }\r
649         \r
650         $limit = intval( $limit );\r
651         if ( $limit == 0 )\r
652                 $limit = 1;\r
653         $table_url = YOURLS_DB_TABLE_URL;\r
654         $results = $ydb->get_results("SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT 0, $limit;");\r
655         \r
656         $return = array();\r
657         $i = 1;\r
658         \r
659         foreach ($results as $res) {\r
660                 $return['links']['link_'.$i++] = array(\r
661                         'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
662                         'url' => $res->url,\r
663                         'timestamp' => $res->timestamp,\r
664                         'ip' => $res->ip,\r
665                         'clicks' => $res->clicks,\r
666                 );\r
667         }\r
668 \r
669         $return['stats'] = yourls_get_db_stats();\r
670         \r
671         $return['statusCode'] = 200;\r
672 \r
673         return yourls_apply_filter( 'get_stats', $return);\r
674 }\r
675 \r
676 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return\r
677 function yourls_get_link_stats( $shorturl ) {\r
678         global $ydb;\r
679 \r
680         $table_url = YOURLS_DB_TABLE_URL;\r
681         $res = $ydb->get_row("SELECT * FROM `$table_url` WHERE keyword = '$shorturl';");\r
682         $return = array();\r
683 \r
684         if( !$res ) {\r
685                 // non existent link\r
686                 $return = array(\r
687                         'statusCode' => 404,\r
688                         'message'    => 'Error: short URL not found',\r
689                 );\r
690         } else {\r
691                 $return = array(\r
692                         'statusCode' => 200,\r
693                         'message'    => 'success',\r
694                         'link'       => array(\r
695                         'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
696                         'url' => $res->url,\r
697                         'timestamp' => $res->timestamp,\r
698                         'ip' => $res->ip,\r
699                         'clicks' => $res->clicks,\r
700                         )\r
701                 );\r
702         }\r
703 \r
704         return yourls_apply_filter( 'get_link_stats', $return );\r
705 }\r
706 \r
707 // Return array for API stat requests\r
708 function yourls_api_stats( $filter = 'top', $limit = 10 ) {\r
709         $return = yourls_get_stats( $filter, $limit );\r
710         $return['simple']  = 'Need either XML or JSON format for stats';\r
711         $return['message'] = 'success';\r
712         return yourls_apply_filter( 'api_stats', $return );\r
713 }\r
714 \r
715 // Return array for API stat requests\r
716 function yourls_api_url_stats($shorturl) {\r
717         $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
718         $keyword = yourls_sanitize_string( $keyword );\r
719 \r
720         $return = yourls_get_link_stats( $keyword );\r
721         $return['simple']  = 'Need either XML or JSON format for stats';\r
722         return yourls_apply_filter( 'api_url_stats', $return );\r
723 }\r
724 \r
725 // Expand short url to long url\r
726 function yourls_api_expand( $shorturl ) {\r
727         $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
728         $keyword = yourls_sanitize_string( $keyword );\r
729         \r
730         $longurl = yourls_get_keyword_longurl( $keyword );\r
731         \r
732         if( $longurl ) {\r
733                 $return = array(\r
734                         'keyword'  => $keyword,\r
735                         'shorturl' => YOURLS_SITE . "/$keyword",\r
736                         'longurl'  => $longurl,\r
737                         'simple'   => $longurl,\r
738                         'message'  => 'success',\r
739                         'statusCode' => 200,\r
740                 );\r
741         } else {\r
742                 $return = array(\r
743                         'keyword'  => $keyword,\r
744                         'simple'   => 'not found',\r
745                         'message'  => 'Error: short URL not found',\r
746                         'errorCode' => 404,\r
747                 );\r
748         }\r
749         \r
750         return yourls_apply_filter( 'api_expand', $return );\r
751 }\r
752 \r
753 \r
754 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array\r
755 function yourls_get_db_stats( $where = '' ) {\r
756         global $ydb;\r
757         $table_url = YOURLS_DB_TABLE_URL;\r
758 \r
759         $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");\r
760         $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );\r
761         \r
762         return yourls_apply_filter( 'get_db_stats', $return );\r
763 }\r
764 \r
765 // Return API result. Dies after this\r
766 function yourls_api_output( $mode, $return ) {\r
767         if( isset( $return['simple'] ) ) {\r
768                 $simple = $return['simple'];\r
769                 unset( $return['simple'] );\r
770         }\r
771         \r
772         yourls_do_action( 'pre_api_output', $mode, $return );\r
773         \r
774         switch ( $mode ) {\r
775                 case 'json':\r
776                         header('Content-type: application/json');\r
777                         echo json_encode($return);\r
778                         break;\r
779                 \r
780                 case 'xml':\r
781                         header('Content-type: application/xml');\r
782                         echo yourls_xml_encode($return);\r
783                         break;\r
784                         \r
785                 case 'simple':\r
786                 default:\r
787                         if( isset( $simple ) )\r
788                                 echo $simple;\r
789                         break;\r
790         }\r
791 \r
792         yourls_do_action( 'api_output', $mode, $return );\r
793         \r
794         die();\r
795 }\r
796 \r
797 // Get number of SQL queries performed\r
798 function yourls_get_num_queries() {\r
799         global $ydb;\r
800 \r
801         return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );\r
802 }\r
803 \r
804 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.\r
805 function yourls_get_user_agent() {\r
806         if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )\r
807                 return '-';\r
808         \r
809         $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));\r
810         $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );\r
811                 \r
812         return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );\r
813 }\r
814 \r
815 // Redirect to another page\r
816 function yourls_redirect( $location, $code = 301 ) {\r
817         yourls_do_action( 'pre_redirect', $location, $code );\r
818         // Redirect, either properly if possible, or via Javascript otherwise\r
819         if( !headers_sent() ) {\r
820                 yourls_status_header( $code );\r
821                 header("Location: $location");\r
822         } else {\r
823                 yourls_redirect_javascript( $location );\r
824         }\r
825         die();\r
826 }\r
827 \r
828 // Set HTTP status header\r
829 function yourls_status_header( $code = 200 ) {\r
830         if( headers_sent() )\r
831                 return;\r
832                 \r
833         $protocol = $_SERVER["SERVER_PROTOCOL"];\r
834         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )\r
835                 $protocol = 'HTTP/1.0';\r
836 \r
837         $code = intval( $code );\r
838         $desc = yourls_get_HTTP_status($code);\r
839 \r
840         @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups\r
841         yourls_do_action( 'status_header', $code );\r
842 }\r
843 \r
844 // 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
845 function yourls_redirect_javascript( $location, $dontwait = true ) {\r
846         if( $dontwait ) {\r
847         echo <<<REDIR\r
848         <script type="text/javascript">\r
849         window.location="$location";\r
850         </script>\r
851         <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>\r
852 REDIR;\r
853         } else {\r
854         echo <<<MANUAL\r
855         <p>Please <a href="$location">click here</a></p>\r
856 MANUAL;\r
857         }\r
858         yourls_do_action( 'redirect_javascript', $location );\r
859 }\r
860 \r
861 // Return a HTTP status code\r
862 function yourls_get_HTTP_status( $code ) {\r
863         $code = intval( $code );\r
864         $headers_desc = array(\r
865                 100 => 'Continue',\r
866                 101 => 'Switching Protocols',\r
867                 102 => 'Processing',\r
868 \r
869                 200 => 'OK',\r
870                 201 => 'Created',\r
871                 202 => 'Accepted',\r
872                 203 => 'Non-Authoritative Information',\r
873                 204 => 'No Content',\r
874                 205 => 'Reset Content',\r
875                 206 => 'Partial Content',\r
876                 207 => 'Multi-Status',\r
877                 226 => 'IM Used',\r
878 \r
879                 300 => 'Multiple Choices',\r
880                 301 => 'Moved Permanently',\r
881                 302 => 'Found',\r
882                 303 => 'See Other',\r
883                 304 => 'Not Modified',\r
884                 305 => 'Use Proxy',\r
885                 306 => 'Reserved',\r
886                 307 => 'Temporary Redirect',\r
887 \r
888                 400 => 'Bad Request',\r
889                 401 => 'Unauthorized',\r
890                 402 => 'Payment Required',\r
891                 403 => 'Forbidden',\r
892                 404 => 'Not Found',\r
893                 405 => 'Method Not Allowed',\r
894                 406 => 'Not Acceptable',\r
895                 407 => 'Proxy Authentication Required',\r
896                 408 => 'Request Timeout',\r
897                 409 => 'Conflict',\r
898                 410 => 'Gone',\r
899                 411 => 'Length Required',\r
900                 412 => 'Precondition Failed',\r
901                 413 => 'Request Entity Too Large',\r
902                 414 => 'Request-URI Too Long',\r
903                 415 => 'Unsupported Media Type',\r
904                 416 => 'Requested Range Not Satisfiable',\r
905                 417 => 'Expectation Failed',\r
906                 422 => 'Unprocessable Entity',\r
907                 423 => 'Locked',\r
908                 424 => 'Failed Dependency',\r
909                 426 => 'Upgrade Required',\r
910 \r
911                 500 => 'Internal Server Error',\r
912                 501 => 'Not Implemented',\r
913                 502 => 'Bad Gateway',\r
914                 503 => 'Service Unavailable',\r
915                 504 => 'Gateway Timeout',\r
916                 505 => 'HTTP Version Not Supported',\r
917                 506 => 'Variant Also Negotiates',\r
918                 507 => 'Insufficient Storage',\r
919                 510 => 'Not Extended'\r
920         );\r
921 \r
922         if ( isset( $headers_desc[$code] ) )\r
923                 return $headers_desc[$code];\r
924         else\r
925                 return '';\r
926 }\r
927 \r
928 \r
929 // Log a redirect (for stats)\r
930 function yourls_log_redirect( $keyword ) {\r
931         if ( !yourls_do_log_redirect() )\r
932                 return true;\r
933 \r
934         global $ydb;\r
935         $table = YOURLS_DB_TABLE_LOG;\r
936         \r
937         $keyword = yourls_sanitize_string( $keyword );\r
938         $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );\r
939         $ua = yourls_get_user_agent();\r
940         $ip = yourls_get_IP();\r
941         $location = yourls_geo_ip_to_countrycode( $ip );\r
942         \r
943         return $ydb->query( "INSERT INTO `$table` VALUES ('', NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );\r
944 }\r
945 \r
946 // Check if we want to not log redirects (for stats)\r
947 function yourls_do_log_redirect() {\r
948         return ( !defined('YOURLS_NOSTATS') || YOURLS_NOSTATS != true );\r
949 }\r
950 \r
951 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/\r
952 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {\r
953         // allow a plugin to shortcircuit the Geo IP API\r
954         $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
955         if ( false !== $location )\r
956                 return $location;\r
957 \r
958         if ( !file_exists( YOURLS_INC.'/geo/GeoIP.dat') || !file_exists( YOURLS_INC.'/geo/geoip.inc') )\r
959                 return $default;\r
960 \r
961         if ( $ip == '' )\r
962                 $ip = yourls_get_IP();\r
963         \r
964         require_once( YOURLS_INC.'/geo/geoip.inc') ;\r
965         $gi = geoip_open( YOURLS_INC.'/geo/GeoIP.dat', GEOIP_STANDARD);\r
966         $location = geoip_country_code_by_addr($gi, $ip);\r
967         geoip_close($gi);\r
968 \r
969         return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );\r
970 }\r
971 \r
972 // Converts a 2 letter country code to long name (ie AU -> Australia)\r
973 function yourls_geo_countrycode_to_countryname( $code ) {\r
974         // Load the Geo class if not already done\r
975         if( !class_exists('GeoIP') ) {\r
976                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
977         }\r
978         \r
979         if( class_exists('GeoIP') ) {\r
980                 $geo = new GeoIP;\r
981                 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];\r
982                 $long = $geo->GEOIP_COUNTRY_NAMES[$id];\r
983                 return $long;\r
984         } else {\r
985                 return false;\r
986         }\r
987 }\r
988 \r
989 // Return flag URL from 2 letter country code\r
990 function yourls_geo_get_flag( $code ) {\r
991         // Load the Geo class if not already done\r
992         if( !class_exists('GeoIP') ) {\r
993                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
994         }\r
995         \r
996         if( class_exists('GeoIP') ) {\r
997                 return YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif';\r
998         } else {\r
999                 return false;\r
1000         }\r
1001 }\r
1002 \r
1003 \r
1004 // Check if an upgrade is needed\r
1005 function yourls_upgrade_is_needed() {\r
1006         // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS\r
1007         list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();\r
1008         if( $currentsql < YOURLS_DB_VERSION )\r
1009                 return true;\r
1010                 \r
1011         return false;\r
1012 }\r
1013 \r
1014 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.\r
1015 function yourls_get_current_version_from_sql() {\r
1016         $currentver = yourls_get_option( 'version' );\r
1017         $currentsql = yourls_get_option( 'db_version' );\r
1018 \r
1019         // Values if version is 1.3\r
1020         if( !$currentver )\r
1021                 $currentver = '1.3';\r
1022         if( !$currentsql )\r
1023                 $currentsql = '100';\r
1024                 \r
1025         return array( $currentver, $currentsql);\r
1026 }\r
1027 \r
1028 // Read an option from DB (or from cache if available). Return value or $default if not found\r
1029 function yourls_get_option( $option_name, $default = false ) {\r
1030         global $ydb;\r
1031         if ( !isset( $ydb->option[$option_name] ) ) {\r
1032                 $table = YOURLS_DB_TABLE_OPTIONS;\r
1033                 $option_name = yourls_escape( $option_name );\r
1034                 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );\r
1035                 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values\r
1036                         $value = $row->option_value;\r
1037                 } else { // option does not exist, so we must cache its non-existence\r
1038                         $value = $default;\r
1039                 }\r
1040                 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );\r
1041         }\r
1042 \r
1043         return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );\r
1044 }\r
1045 \r
1046 // Read all options from DB at once\r
1047 function yourls_get_all_options() {\r
1048         global $ydb;\r
1049         $table = YOURLS_DB_TABLE_OPTIONS;\r
1050         \r
1051         $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");\r
1052         \r
1053         foreach( (array)$allopt as $option ) {\r
1054                 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );\r
1055         }\r
1056 }\r
1057 \r
1058 // Update (add if doesn't exist) an option to DB\r
1059 function yourls_update_option( $option_name, $newvalue ) {\r
1060         global $ydb;\r
1061         $table = YOURLS_DB_TABLE_OPTIONS;\r
1062 \r
1063         $safe_option_name = yourls_escape( $option_name );\r
1064 \r
1065         $oldvalue = yourls_get_option( $safe_option_name );\r
1066 \r
1067         // If the new and old values are the same, no need to update.\r
1068         if ( $newvalue === $oldvalue )\r
1069                 return false;\r
1070 \r
1071         if ( false === $oldvalue ) {\r
1072                 yourls_add_option( $option_name, $newvalue );\r
1073                 return true;\r
1074         }\r
1075 \r
1076         $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );\r
1077         \r
1078         yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );\r
1079 \r
1080         $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");\r
1081 \r
1082         if ( $ydb->rows_affected == 1 ) {\r
1083                 $ydb->option[$option_name] = $newvalue;\r
1084                 return true;\r
1085         }\r
1086         return false;\r
1087 }\r
1088 \r
1089 // Add an option to the DB\r
1090 function yourls_add_option( $name, $value = '' ) {\r
1091         global $ydb;\r
1092         $table = YOURLS_DB_TABLE_OPTIONS;\r
1093         $safe_name = yourls_escape( $name );\r
1094 \r
1095         // Make sure the option doesn't already exist\r
1096         if ( false !== yourls_get_option( $safe_name ) )\r
1097                 return;\r
1098 \r
1099         $_value = yourls_escape( yourls_maybe_serialize( $value ) );\r
1100 \r
1101         yourls_do_action( 'add_option', $safe_name, $_value );\r
1102 \r
1103         $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );\r
1104         $ydb->option[$name] = $value;\r
1105         return;\r
1106 }\r
1107 \r
1108 \r
1109 // Delete an option from the DB\r
1110 function yourls_delete_option( $name ) {\r
1111         global $ydb;\r
1112         $table = YOURLS_DB_TABLE_OPTIONS;\r
1113         $name = yourls_escape( $name );\r
1114 \r
1115         // Get the ID, if no ID then return\r
1116         $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );\r
1117         if ( is_null($option) || !$option->option_id )\r
1118                 return false;\r
1119                 \r
1120         yourls_do_action( 'delete_option', $option_name );\r
1121                 \r
1122         $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );\r
1123         return true;\r
1124 }\r
1125 \r
1126 \r
1127 \r
1128 // Serialize data if needed. Stolen from WordPress\r
1129 function yourls_maybe_serialize( $data ) {\r
1130         if ( is_array( $data ) || is_object( $data ) )\r
1131                 return serialize( $data );\r
1132 \r
1133         if ( yourls_is_serialized( $data ) )\r
1134                 return serialize( $data );\r
1135 \r
1136         return $data;\r
1137 }\r
1138 \r
1139 // Check value to find if it was serialized. Stolen from WordPress\r
1140 function yourls_is_serialized( $data ) {\r
1141         // if it isn't a string, it isn't serialized\r
1142         if ( !is_string( $data ) )\r
1143                 return false;\r
1144         $data = trim( $data );\r
1145         if ( 'N;' == $data )\r
1146                 return true;\r
1147         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )\r
1148                 return false;\r
1149         switch ( $badions[1] ) {\r
1150                 case 'a' :\r
1151                 case 'O' :\r
1152                 case 's' :\r
1153                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )\r
1154                                 return true;\r
1155                         break;\r
1156                 case 'b' :\r
1157                 case 'i' :\r
1158                 case 'd' :\r
1159                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )\r
1160                                 return true;\r
1161                         break;\r
1162         }\r
1163         return false;\r
1164 }\r
1165 \r
1166 // Unserialize value only if it was serialized. Stolen from WP\r
1167 function yourls_maybe_unserialize( $original ) {\r
1168         if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in\r
1169                 return @unserialize( $original );\r
1170         return $original;\r
1171 }\r
1172 \r
1173 // Determine if the current page is private\r
1174 function yourls_is_private() {\r
1175         $private = false;\r
1176 \r
1177         if (defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true) {\r
1178 \r
1179                 // Allow overruling of particular pages\r
1180                 $current = basename( $_SERVER["SCRIPT_NAME"] );\r
1181 \r
1182                 switch( $current ) {\r
1183                 \r
1184                 case 'yourls-api.php':\r
1185                         if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )\r
1186                                 $private = true;\r
1187                         break;\r
1188                                 \r
1189                 case 'yourls-infos.php':\r
1190                         if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )\r
1191                                 $private = true;\r
1192                         break;\r
1193                 \r
1194                 default:\r
1195                         $private = true;\r
1196                         break;\r
1197                 }\r
1198         }\r
1199         \r
1200         return yourls_apply_filter( 'is_private', $private );\r
1201 }\r
1202 \r
1203 // Show login form if required\r
1204 function yourls_maybe_require_auth() {\r
1205         if( yourls_is_private() )\r
1206                 require_once( YOURLS_INC.'/auth.php' );\r
1207 }\r
1208 \r
1209 // Return word or words if more than one\r
1210 function yourls_plural( $word, $count=1 ) {\r
1211         return $word . ($count > 1 ? 's' : '');\r
1212 }\r
1213 \r
1214 // Return trimmed string\r
1215 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {\r
1216         $newstring = $string;\r
1217         if ( strlen( $newstring ) > $length ) {\r
1218                 $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;    \r
1219         }\r
1220         return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );\r
1221 }\r
1222 \r
1223 // Allow several short URLs for the same long URL ?\r
1224 function yourls_allow_duplicate_longurls() {\r
1225         // special treatment if API to check for WordPress plugin requests\r
1226         if( yourls_is_API() ) {\r
1227                 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' ) \r
1228                         return false;\r
1229         }\r
1230         return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );\r
1231 }\r
1232 \r
1233 // Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.\r
1234 function yourls_get_duplicate_keywords( $longurl ) {\r
1235         if( !yourls_allow_duplicate_longurls() )\r
1236                 return NULL;\r
1237         \r
1238         global $ydb;\r
1239         $longurl = yourls_escape( yourls_sanitize_url($longurl) );\r
1240         $table = YOURLS_DB_TABLE_URL;\r
1241         \r
1242         $return = $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );\r
1243         return yourls_apply_filter( 'get_duplicate_keywords', $return );\r
1244 }\r
1245 \r
1246 // Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.\r
1247 function yourls_check_IP_flood( $ip = '' ) {\r
1248 \r
1249         yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here\r
1250 \r
1251         if(\r
1252                 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||\r
1253                 !defined('YOURLS_FLOOD_DELAY_SECONDS')\r
1254         )\r
1255                 return true;\r
1256 \r
1257         $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );\r
1258 \r
1259         // Don't throttle whitelist IPs\r
1260         if( defined('YOURLS_FLOOD_IP_WHITELIST' && YOURLS_FLOOD_IP_WHITELIST ) ) {\r
1261                 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );\r
1262                 foreach( $whitelist_ips as $whitelist_ip ) {\r
1263                         $whitelist_ip = trim( $whitelist_ip );\r
1264                         if ( $whitelist_ip == $ip )\r
1265                                 return true;\r
1266                 }\r
1267         }\r
1268         \r
1269         // Don't throttle logged in users\r
1270         if( yourls_is_private() ) {\r
1271                  if( yourls_is_valid_user() === true )\r
1272                         return true;\r
1273         }\r
1274         \r
1275         yourls_do_action( 'check_ip_flood', $ip );\r
1276         \r
1277         global $ydb;\r
1278         $table = YOURLS_DB_TABLE_URL;\r
1279         \r
1280         $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );\r
1281         if( $lasttime ) {\r
1282                 $now = date( 'U' );\r
1283                 $then = date( 'U', strtotime( $lasttime ) );\r
1284                 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {\r
1285                         // Flood!\r
1286                         yourls_do_action( 'ip_flood', $ip, $now - $then );\r
1287                         yourls_die( 'Too many URLs added too fast. Slow down please.', 'Forbidden', 403 );\r
1288                 }\r
1289         }\r
1290         \r
1291         return true;\r
1292 }\r
1293 \r
1294 // Check if YOURLS is installed\r
1295 function yourls_is_installed() {\r
1296         static $is_installed = false;\r
1297         if ( $is_installed === false ) {\r
1298                 $check_14 = $check_13 = false;\r
1299                 global $ydb;\r
1300                 if( defined('YOURLS_DB_TABLE_NEXTDEC') )\r
1301                         $check_13 = $ydb->get_var('SELECT `next_id` FROM '.YOURLS_DB_TABLE_NEXTDEC);\r
1302                 $check_14 = yourls_get_option( 'version' );\r
1303                 $is_installed = $check_13 || $check_14;\r
1304         }\r
1305         return yourls_apply_filter( 'is_installed', $is_installed );\r
1306 }\r
1307 \r
1308 // Generate random string of (int)$lenght length and type $type (see function for details)\r
1309 function yourls_rnd_string ( $length = 5, $type = 1 ) {\r
1310         $str = '';\r
1311         $length = intval( $length );\r
1312 \r
1313         // define possible characters\r
1314         switch ( $type ) {\r
1315                 // no vowels to make no offending word, no 0 or 1 to avoid confusion betwee letters & digits. Perfect for passwords.\r
1316                 case '1':\r
1317                         $possible = "23456789bcdfghjkmnpqrstvwxyz";\r
1318                         break;\r
1319                 \r
1320                 // all letters, lowercase\r
1321                 case '2':\r
1322                         $possible = "abcdefghijklmnopqrstuvwxyz";\r
1323                         break;\r
1324                 \r
1325                 // all letters, lowercase + uppercase\r
1326                 case '3':\r
1327                         $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\r
1328                         break;\r
1329                 \r
1330                 // all digits & letters lowercase \r
1331                 case '4':\r
1332                         $possible = "0123456789abcdefghijklmnopqrstuvwxyz";\r
1333                         break;\r
1334                 \r
1335                 // all digits & letters lowercase + uppercase\r
1336                 case '5':\r
1337                         $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\r
1338                         break;\r
1339                 \r
1340         }\r
1341 \r
1342         $i = 0;\r
1343         while ($i < $length) {\r
1344         $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);\r
1345                 $i++;\r
1346         }\r
1347         \r
1348         return yourls_apply_filter( 'rnd_string', $str);\r
1349 }\r
1350 \r
1351 // Return salted string\r
1352 function yourls_salt( $string ) {\r
1353         $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;\r
1354         return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt) );\r
1355 }\r
1356 \r
1357 // Return a time-dependent string for nonce creation\r
1358 function yourls_tick() {\r
1359         return ceil( time() / YOURLS_NONCE_LIFE );\r
1360 }\r
1361 \r
1362 // Create a time limited, action limited and user limited token\r
1363 function yourls_create_nonce( $action = '-1', $user = false ) {\r
1364         if( false == $user )\r
1365                 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';\r
1366         $tick = yourls_tick();\r
1367         return substr( yourls_salt($tick . $action . $user), 0, 10 );\r
1368 }\r
1369 \r
1370 // Check validity of a nonce (ie time span, user and action match)\r
1371 function yourls_verify_nonce( $nonce, $action = -1, $user = false ) {\r
1372         if( false == $user )\r
1373                 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';\r
1374         $valid = yourls_create_nonce( $action, $user );\r
1375         \r
1376         return $nonce == $valid ;\r
1377 }\r
1378 \r
1379 // Sanitize a version number (1.4.1-whatever -> 1.4.1)\r
1380 function yourls_sanitize_version( $ver ) {\r
1381         return preg_replace( '/[^0-9.]/', '', $ver );\r
1382 }\r
1383 \r
1384 // Converts keyword into short link\r
1385 function yourls_link( $keyword = '' ) {\r
1386         return YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );\r
1387 }\r
1388 \r
1389 // Check if we're in API mode. Returns bool\r
1390 function yourls_is_API() {\r
1391         if ( defined('YOURLS_API') && YOURLS_API == true )\r
1392                 return true;\r
1393         return false;\r
1394 }\r
1395 \r
1396 // Check if we're in Ajax mode. Returns bool\r
1397 function yourls_is_Ajax() {\r
1398         if ( defined('YOURLS_AJAX') && YOURLS_AJAX == true )\r
1399                 return true;\r
1400         return false;\r
1401 }\r
1402 \r
1403 // Check if we're in GO mode (redirection on yourls-go.php). Returns bool\r
1404 function yourls_is_GO() {\r
1405         if ( defined('YOURLS_GO') && YOURLS_GO == true )\r
1406                 return true;\r
1407         return false;\r
1408 }\r
1409 \r
1410 // Check if we'll need interface display function (ie not API or redirection)\r
1411 function yourls_has_interface() {\r
1412         if( yourls_is_API() or yourls_is_GO() or yourls_is_Ajax() )\r
1413                 return false;\r
1414         return true;\r
1415 }\r
1416 \r
1417 // Check if we're in the admin area. Returns bool\r
1418 function yourls_is_admin() {\r
1419         if ( defined('YOURLS_ADMIN') && YOURLS_ADMIN == true )\r
1420                 return true;\r
1421         return false;\r
1422 }\r
1423 \r
1424 // Check if SSL is required. Returns bool.\r
1425 function yourls_needs_ssl() {\r
1426         if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )\r
1427                 return true;\r
1428         return false;\r
1429 }\r
1430 \r
1431 // Return admin link, with SSL preference if applicable.\r
1432 function yourls_admin_url( $page = '' ) {\r
1433         $admin = YOURLS_SITE . '/admin/' . $page;\r
1434         if( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )\r
1435                 $admin = str_replace('http://', 'https://', $admin);\r
1436         return yourls_apply_filter( 'admin_url', $admin, $page );\r
1437 }\r
1438 \r
1439 // Check if SSL is used, returns bool. Stolen from WP.\r
1440 function yourls_is_ssl() {\r
1441         $is_ssl = false;\r
1442         if ( isset($_SERVER['HTTPS']) ) {\r
1443                 if ( 'on' == strtolower($_SERVER['HTTPS']) )\r
1444                         $is_ssl = true;\r
1445                 if ( '1' == $_SERVER['HTTPS'] )\r
1446                         $is_ssl = true;\r
1447         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {\r
1448                 $is_ssl = true;\r
1449         }\r
1450         return yourls_apply_filter( 'is_ssl', $is_ssl );\r
1451 }\r
1452 \r
1453 \r
1454 // Get a remote page <title>, return a string (either title or url)\r
1455 function yourls_get_remote_title( $url ) {\r
1456         require_once( YOURLS_INC.'/functions-http.php' );\r
1457 \r
1458         $url = yourls_sanitize_url( $url );\r
1459 \r
1460         $title = false;\r
1461         \r
1462         $content = yourls_get_remote_content( $url );\r
1463 \r
1464         // look for <title>\r
1465         if( $content !== false ) {\r
1466                 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {\r
1467                         $title = $found[1];\r
1468                         unset( $found );\r
1469                 }\r
1470         }\r
1471         \r
1472         // if title not found, guess if returned content was actually an error message\r
1473         if( $title == false && strpos( $content, 'Error' ) === 0 ) {\r
1474                 $title = $content;\r
1475         }\r
1476 \r
1477         $title = yourls_sanitize_title( $title );\r
1478 \r
1479         return yourls_apply_filter( 'get_remote_title', $title );\r
1480 }\r
1481 \r
1482 // Sanitize a filename (no Win32 stuff)\r
1483 function yourls_sanitize_filename( $file ) {\r
1484         $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs\r
1485         $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash\r
1486         return $file;\r
1487 }\r
1488 \r
1489 // Check for maintenance mode that will shortcut everything\r
1490 function yourls_check_maintenance_mode() {\r
1491         \r
1492         // TODO: all cases that always display the sites (is_admin but not is_ajax?)\r
1493         if( 1 )\r
1494                 return;\r
1495 \r
1496         // first case: /user/maintenance.php file\r
1497         if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {\r
1498                 include( YOURLS_USERDIR.'/maintenance.php' );\r
1499                 die();  \r
1500         }\r
1501         \r
1502         // second case: option in DB\r
1503         if( yourls_get_option( 'maintenance_mode' ) !== false ) {\r
1504                 require_once( YOURLS_INC.'/functions-html.php' );\r
1505                 $title = 'Service temporarily unavailable';\r
1506                 $message = 'Our service is currently undergoing scheduled maintenance.</p>\r
1507                 <p>Things should not last very long, thank you for your patience and please excuse the inconvenience';\r
1508                 yourls_die( $message, $title , 503 );\r
1509         }\r
1510         \r
1511 }\r
1512 \r
1513 // Toggle maintenance mode\r
1514 function yourls_maintenance_mode( $maintenance = true ) {\r
1515         yourls_update_option( 'maintenance_mode', (bool)$maintenance );\r
1516 }\r
1517 \r