]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions.php
More filters to redirects.
[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, $num, $chars );\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 \r
60         return yourls_apply_filter( 'string2int', $integer, $string, $chars );\r
61 }\r
62 \r
63 // return a unique(ish) hash for a string to be used as a valid HTML id\r
64 function yourls_string2htmlid( $string ) {\r
65         return yourls_apply_filter( 'string2htmlid', 'y'.abs( crc32( $string ) ) );\r
66 }\r
67 \r
68 // Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.\r
69 function yourls_sanitize_string( $string ) {\r
70         // make a regexp pattern with the shorturl charset, and remove everything but this\r
71         $pattern = yourls_make_regexp_pattern( yourls_get_shorturl_charset() );\r
72         $valid = substr(preg_replace('![^'.$pattern.']!', '', $string ), 0, 199);\r
73         \r
74         return yourls_apply_filter( 'sanitize_string', $valid, $string );\r
75 }\r
76 \r
77 // Make an optimized regexp pattern from a string of characters\r
78 function yourls_make_regexp_pattern( $string ) {\r
79         $pattern = preg_quote( $string, '-' ); // add - as an escaped characters -- this is fixed in PHP 5.3\r
80         // TODO: replace char sequences by smart sequences such as 0-9, a-z, A-Z ... ?\r
81         return $pattern;\r
82 }\r
83 \r
84 // Alias function. I was always getting it wrong.\r
85 function yourls_sanitize_keyword( $keyword ) {\r
86         return yourls_sanitize_string( $keyword );\r
87 }\r
88 \r
89 // Sanitize a page title. No HTML per W3C http://www.w3.org/TR/html401/struct/global.html#h-7.4.2\r
90 function yourls_sanitize_title( $title ) {\r
91         // TODO: make stronger Implement KSES?\r
92         $title = strip_tags( $title );\r
93         // Remove extra white space\r
94         $title = preg_replace( "/\s+/", ' ', trim( $title ) );\r
95         return $title;\r
96 }\r
97 \r
98 // Is an URL a short URL?\r
99 function yourls_is_shorturl( $shorturl ) {\r
100         // TODO: make sure this function evolves with the feature set.\r
101         \r
102         $is_short = false;\r
103         $keyword = preg_replace( '!^'.YOURLS_SITE.'/!', '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
104         if( $keyword && $keyword == yourls_sanitize_string( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {\r
105                 $is_short = true;\r
106         }\r
107         \r
108         return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );\r
109 }\r
110 \r
111 // A few sanity checks on the URL\r
112 function yourls_sanitize_url($url) {\r
113         // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')\r
114         $url = str_replace('http://http://', 'http://', $url);\r
115 \r
116         // make sure there's a protocol, add http:// if not\r
117         if ( !preg_match('!^([a-zA-Z]+://)!', $url ) )\r
118                 $url = 'http://'.$url;\r
119         \r
120         $url = yourls_clean_url($url);\r
121         \r
122         return substr( $url, 0, 1999 );\r
123 }\r
124 \r
125 // Function to filter all invalid characters from a URL. Stolen from WP's clean_url()\r
126 function yourls_clean_url( $url ) {\r
127         $url = preg_replace('|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*\'"()\\x80-\\xff]|i', '', $url );\r
128         $strip = array('%0d', '%0a', '%0D', '%0A');\r
129         $url = yourls_deep_replace($strip, $url);\r
130         $url = str_replace(';//', '://', $url);\r
131         $url = str_replace('&amp;', '&', $url); // Revert & not to break query strings\r
132         \r
133         return $url;\r
134 }\r
135 \r
136 // Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''\r
137 // Stolen from WP's _deep_replace\r
138 function yourls_deep_replace($search, $subject){\r
139         $found = true;\r
140         while($found) {\r
141                 $found = false;\r
142                 foreach( (array) $search as $val ) {\r
143                         while(strpos($subject, $val) !== false) {\r
144                                 $found = true;\r
145                                 $subject = str_replace($val, '', $subject);\r
146                         }\r
147                 }\r
148         }\r
149         \r
150         return $subject;\r
151 }\r
152 \r
153 // Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)\r
154 // TODO FIXME FFS: unused ?\r
155 function yourls_sanitize_int($in) {\r
156         return ( substr(preg_replace('/[^0-9]/', '', strval($in) ), 0, 20) );\r
157 }\r
158 \r
159 // Make sure a integer is safe\r
160 // Note: this is not checking for integers, since integers on 32bits system are way too limited\r
161 // TODO: find a way to validate as integer\r
162 function yourls_intval($in) {\r
163         return yourls_escape($in);\r
164 }\r
165 \r
166 // Escape a string\r
167 function yourls_escape( $in ) {\r
168         return mysql_real_escape_string($in);\r
169 }\r
170 \r
171 // Check to see if a given keyword is reserved (ie reserved URL or an existing page)\r
172 // Returns bool\r
173 function yourls_keyword_is_reserved( $keyword ) {\r
174         global $yourls_reserved_URL;\r
175         $keyword = yourls_sanitize_keyword( $keyword );\r
176         $reserved = false;\r
177         \r
178         if ( in_array( $keyword, $yourls_reserved_URL)\r
179                 or file_exists( YOURLS_ABSPATH ."/pages/$keyword.php" )\r
180                 or is_dir( YOURLS_ABSPATH ."/$keyword" )\r
181         )\r
182                 $reserved = true;\r
183         \r
184         return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );\r
185 }\r
186 \r
187 // Function: Get IP Address. Returns a DB safe string.\r
188 function yourls_get_IP() {\r
189         if( !empty( $_SERVER['REMOTE_ADDR'] ) ) {\r
190                 $ip = $_SERVER['REMOTE_ADDR'];\r
191         } else {\r
192                 if(!empty($_SERVER['HTTP_CLIENT_IP'])) {\r
193                         $ip = $_SERVER['HTTP_CLIENT_IP'];\r
194                 } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {\r
195                         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];\r
196                 } else if(!empty($_SERVER['HTTP_VIA '])) {\r
197                         $ip = $_SERVER['HTTP_VIA '];\r
198                 }\r
199         }\r
200 \r
201         return yourls_apply_filter( 'get_IP', yourls_sanitize_ip( $ip ) );\r
202 }\r
203 \r
204 // Sanitize an IP address\r
205 function yourls_sanitize_ip( $ip ) {\r
206         return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );\r
207 }\r
208 \r
209 // Make sure a date is m(m)/d(d)/yyyy, return false otherwise\r
210 function yourls_sanitize_date( $date ) {\r
211         if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {\r
212                 return false;\r
213         }\r
214         return $date;\r
215 }\r
216 \r
217 // Sanitize a date for SQL search. Return false if malformed input.\r
218 function yourls_sanitize_date_for_sql( $date ) {\r
219         if( !yourls_sanitize_date( $date ) )\r
220                 return false;\r
221         return date('Y-m-d', strtotime( $date ) );\r
222 }\r
223 \r
224 // Add the "Edit" row\r
225 function yourls_table_edit_row( $keyword ) {\r
226         global $ydb;\r
227         \r
228         $table = YOURLS_DB_TABLE_URL;\r
229         $keyword = yourls_sanitize_string( $keyword );\r
230         $id = yourls_string2htmlid( $keyword ); // used as HTML #id\r
231         $url = yourls_get_keyword_longurl( $keyword );\r
232         $title = htmlspecialchars( yourls_get_keyword_title( $keyword ) );\r
233         $safe_url = stripslashes( $url );\r
234         $safe_title = stripslashes( $title );\r
235         $www = YOURLS_SITE;\r
236         \r
237         $save_link = yourls_nonce_url( 'save-link_'.$id,\r
238                 yourls_add_query_arg( array( 'id' => $id, 'action' => 'edit_save', 'keyword' => $keyword ), yourls_admin_url( 'admin-ajax.php' ) ) \r
239         );\r
240         \r
241         $nonce = yourls_create_nonce( 'edit-save_'.$id );\r
242         \r
243         if( $url ) {\r
244                 $return = <<<RETURN\r
245 <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"/><input type="hidden" id="nonce_$id" value="$nonce"/></td></tr>\r
246 RETURN;\r
247         } else {\r
248                 $return = '<tr><td colspan="6">Error, URL not found</td></tr>';\r
249         }\r
250         \r
251         $return = yourls_apply_filter( 'table_edit_row', $return, $keyword, $url, $title );\r
252 \r
253         return $return;\r
254 }\r
255 \r
256 // Add a link row\r
257 function yourls_table_add_row( $keyword, $url, $title = '', $ip, $clicks, $timestamp ) {\r
258         $keyword  = yourls_sanitize_string( $keyword );\r
259         $display_keyword = htmlentities( $keyword );\r
260 \r
261         $url = yourls_sanitize_url( $url );\r
262         $display_url = htmlentities( yourls_trim_long_string( $url ) );\r
263         $title_url = htmlspecialchars( $url );\r
264         \r
265         $title = yourls_sanitize_title( $title ) ;\r
266         $display_title   = yourls_trim_long_string( $title );\r
267         $title = htmlspecialchars( $title );\r
268 \r
269         $id      = yourls_string2htmlid( $keyword ); // used as HTML #id\r
270         $date    = date( 'M d, Y H:i', $timestamp+( YOURLS_HOURS_OFFSET * 3600) );\r
271         $clicks  = number_format($clicks, 0, '', '');\r
272 \r
273         $shorturl = YOURLS_SITE.'/'.$keyword;\r
274         $statlink = $shorturl.'+';\r
275         if( yourls_is_ssl() )\r
276                 $statlink = str_replace( 'http://', 'https://', $statlink );\r
277         \r
278         if( $title ) {\r
279                 $display_link = "<a href=\"$url\" title=\"$title\">$display_title</a><br/><small><a href=\"$url\" title=\"$title_url\">$display_url</a></small>";\r
280         } else {\r
281                 $display_link = "<a href=\"$url\" title=\"$title_url\">$display_url</a>";\r
282         }\r
283         \r
284         $delete_link = yourls_nonce_url( 'delete-link_'.$id,\r
285                 yourls_add_query_arg( array( 'id' => $id, 'action' => 'delete', 'keyword' => $keyword ), yourls_admin_url( 'admin-ajax.php' ) ) \r
286         );\r
287         \r
288         $edit_link = yourls_nonce_url( 'edit-link_'.$id,\r
289                 yourls_add_query_arg( array( 'id' => $id, 'action' => 'edit', 'keyword' => $keyword ), yourls_admin_url( 'admin-ajax.php' ) ) \r
290         );\r
291         \r
292         \r
293         \r
294         $actions = <<<ACTION\r
295 <a href="$statlink" id="statlink-$id" title="Stats" class="button button_stats">Stats</a><a href="" id="share-button-$id" name="share-button" title="Share" class="button button_share" onclick="toggle_share('$id');return false;">Share</a><a href="$edit_link" id="edit-button-$id" name="edit-button" title="Edit" class="button button_edit" onclick="edit('$id');return false;">Edit</a><a href="$delete_link" id="delete-button-$id" name="delete-button" title="Delete" class="button button_delete" onclick="remove('$id');return false;">Delete</a>\r
296 ACTION;\r
297         $actions = yourls_apply_filter( 'action_links', $actions, $keyword, $url, $ip, $clicks, $timestamp );\r
298         \r
299         $row = <<<ROW\r
300 <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
301 ROW;\r
302         $row = yourls_apply_filter( 'table_add_row', $row, $keyword, $url, $title, $ip, $clicks, $timestamp );\r
303         \r
304         return $row;\r
305 }\r
306 \r
307 // Get next id a new link will have if no custom keyword provided\r
308 function yourls_get_next_decimal() {\r
309         return yourls_apply_filter( 'get_next_decimal', (int)yourls_get_option( 'next_id' ) );\r
310 }\r
311 \r
312 // Update id for next link with no custom keyword\r
313 function yourls_update_next_decimal( $int = '' ) {\r
314         $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;\r
315         $update = yourls_update_option( 'next_id', $int );\r
316         yourls_do_action( 'update_next_decimal', $int, $update );\r
317         return $update;\r
318 }\r
319 \r
320 // Delete a link in the DB\r
321 function yourls_delete_link_by_keyword( $keyword ) {\r
322         global $ydb;\r
323 \r
324         $table = YOURLS_DB_TABLE_URL;\r
325         $keyword = yourls_sanitize_string( $keyword );\r
326         $delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");\r
327         yourls_do_action( 'delete_link', $keyword, $delete );\r
328         return $delete;\r
329 }\r
330 \r
331 // SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting\r
332 function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {\r
333         global $ydb;\r
334         \r
335         $url     = addslashes( yourls_sanitize_url( $url ) );\r
336         $keyword = addslashes( yourls_sanitize_keyword( $keyword ) );\r
337         $title   = addslashes( yourls_sanitize_title( $title ) );\r
338 \r
339         $table = YOURLS_DB_TABLE_URL;\r
340         $timestamp = date('Y-m-d H:i:s');\r
341         $ip = yourls_get_IP();\r
342         $insert = $ydb->query("INSERT INTO `$table` VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");\r
343         \r
344         yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );\r
345         \r
346         return (bool)$insert;\r
347 }\r
348 \r
349 // Add a new link in the DB, either with custom keyword, or find one\r
350 function yourls_add_new_link( $url, $keyword = '', $title = '' ) {\r
351         global $ydb;\r
352 \r
353         // Allow plugins to short-circuit the whole function\r
354         $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );\r
355         if ( false !== $pre )\r
356                 return $pre;\r
357 \r
358         if ( !$url || $url == 'http://' || $url == 'https://' ) {\r
359                 $return['status'] = 'fail';\r
360                 $return['code'] = 'error:nourl';\r
361                 $return['message'] = 'Missing URL input';\r
362                 $return['errorCode'] = '400';\r
363                 return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );\r
364         }\r
365         \r
366         // Prevent DB flood\r
367         $ip = yourls_get_IP();\r
368         yourls_check_IP_flood( $ip );\r
369         \r
370         // Prevent internal redirection loops: cannot shorten a shortened URL\r
371         $url = yourls_escape( yourls_sanitize_url($url) );\r
372         if( preg_match( '!^'.YOURLS_SITE.'/!', $url ) ) {\r
373                 if( yourls_is_shorturl( $url ) ) {\r
374                         $return['status'] = 'fail';\r
375                         $return['code'] = 'error:noloop';\r
376                         $return['message'] = 'URL is a short URL';\r
377                         $return['errorCode'] = '400';\r
378                         return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );\r
379                 }\r
380         }\r
381 \r
382         yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );\r
383         \r
384         $table = YOURLS_DB_TABLE_URL;\r
385         $strip_url = stripslashes($url);\r
386         $url_exists = $ydb->get_row("SELECT * FROM `$table` WHERE `url` = '".$strip_url."';");\r
387         $return = array();\r
388 \r
389         // New URL : store it -- or: URL exists, but duplicates allowed\r
390         if( !$url_exists || yourls_allow_duplicate_longurls() ) {\r
391         \r
392                 if( isset( $title ) && !empty( $title ) ) {\r
393                         $title = yourls_sanitize_title( $title );\r
394                 } else {\r
395                         $title = yourls_get_remote_title( $url );\r
396                 }\r
397                 $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );\r
398 \r
399                 // Custom keyword provided\r
400                 if ( $keyword ) {\r
401                         \r
402                         yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );\r
403                 \r
404                         $keyword = yourls_escape( yourls_sanitize_string($keyword) );\r
405                         $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );\r
406                         if ( !yourls_keyword_is_free($keyword) ) {\r
407                                 // This shorturl either reserved or taken already\r
408                                 $return['status'] = 'fail';\r
409                                 $return['code'] = 'error:keyword';\r
410                                 $return['message'] = 'Short URL '.$keyword.' already exists in database or is reserved';\r
411                         } else {\r
412                                 // all clear, store !\r
413                                 yourls_insert_link_in_db( $url, $keyword, $title );\r
414                                 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );\r
415                                 $return['status'] = 'success';\r
416                                 $return['message'] = yourls_trim_long_string( $strip_url ).' added to database';\r
417                                 $return['title'] = $title;\r
418                                 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\r
419                                 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
420                         }\r
421 \r
422                 // Create random keyword        \r
423                 } else {\r
424                         \r
425                         yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );\r
426                 \r
427                         $timestamp = date('Y-m-d H:i:s');\r
428                         $id = yourls_get_next_decimal();\r
429                         $ok = false;\r
430                         do {\r
431                                 $keyword = yourls_int2string( $id );\r
432                                 $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );\r
433                                 $free = yourls_keyword_is_free($keyword);\r
434                                 $add_url = @yourls_insert_link_in_db( $url, $keyword, $title );\r
435                                 $ok = ($free && $add_url);\r
436                                 if ( $ok === false && $add_url === 1 ) {\r
437                                         // we stored something, but shouldn't have (ie reserved id)\r
438                                         $delete = yourls_delete_link_by_keyword( $keyword );\r
439                                         $return['extra_info'] .= '(deleted '.$keyword.')';\r
440                                 } else {\r
441                                         // everything ok, populate needed vars\r
442                                         $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );\r
443                                         $return['status'] = 'success';\r
444                                         $return['message'] = yourls_trim_long_string( $strip_url ).' added to database';\r
445                                         $return['title'] = $title;\r
446                                         $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\r
447                                         $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
448                                 }\r
449                                 $id++;\r
450                         } while (!$ok);\r
451                         @yourls_update_next_decimal($id);\r
452                 }\r
453 \r
454         // URL was already stored\r
455         } else {\r
456                         \r
457                 yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );\r
458                 \r
459                 $return['status'] = 'fail';\r
460                 $return['code'] = 'error:url';\r
461                 $return['url'] = array( 'keyword' => $keyword, 'url' => $strip_url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );\r
462                 $return['message'] = yourls_trim_long_string( $strip_url ).' already exists in database';\r
463                 $return['title'] = $url_exists->title; \r
464                 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;\r
465         }\r
466         \r
467         yourls_do_action( 'post_add_new_link', $url, $keyword, $title );\r
468 \r
469         $return['statusCode'] = 200; // regardless of result, this is still a valid request\r
470         return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );\r
471 }\r
472 \r
473 \r
474 // Edit a link\r
475 function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {\r
476         global $ydb;\r
477 \r
478         $table = YOURLS_DB_TABLE_URL;\r
479         $url = yourls_escape(yourls_sanitize_url($url));\r
480         $keyword = yourls_escape(yourls_sanitize_string( $keyword ));\r
481         $title = yourls_escape(yourls_sanitize_title( $title ));\r
482         $newkeyword = yourls_escape(yourls_sanitize_string( $newkeyword ));\r
483         $strip_url = stripslashes($url);\r
484         $strip_title = stripslashes($title);\r
485         $old_url = $ydb->get_var("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");\r
486         \r
487         // Check if new URL is not here already\r
488         if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {\r
489                 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));\r
490         } else {\r
491                 $new_url_already_there = false;\r
492         }\r
493         \r
494         // Check if the new keyword is not here already\r
495         if ( $newkeyword != $keyword ) {\r
496                 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );\r
497         } else {\r
498                 $keyword_is_ok = true;\r
499         }\r
500         \r
501         yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );\r
502         \r
503         // All clear, update\r
504         if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {\r
505                         $update_url = $ydb->query("UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';");\r
506                 if( $update_url ) {\r
507                         $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'title' => $strip_title, 'display_title' => yourls_trim_long_string( $strip_title ) );\r
508                         $return['status'] = 'success';\r
509                         $return['message'] = 'Link updated in database';\r
510                 } else {\r
511                         $return['status'] = 'fail';\r
512                         $return['message'] = 'Error updating '. yourls_trim_long_string( $strip_url ).' (Short URL: '.$keyword.') to database';\r
513                 }\r
514         \r
515         // Nope\r
516         } else {\r
517                 $return['status'] = 'fail';\r
518                 $return['message'] = 'URL or keyword already exists in database';\r
519         }\r
520         \r
521         return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );\r
522 }\r
523 \r
524 // Update a title link (no checks for duplicates etc..)\r
525 function yourls_edit_link_title( $keyword, $title ) {\r
526         global $ydb;\r
527         \r
528         $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );\r
529         $title = yourls_escape( yourls_sanitize_title( $title ) );\r
530         \r
531         $table = YOURLS_DB_TABLE_URL;\r
532         $update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");\r
533 \r
534         return $update;\r
535 }\r
536 \r
537 \r
538 // Check if keyword id is free (ie not already taken, and not reserved). Return bool.\r
539 function yourls_keyword_is_free( $keyword ) {\r
540         $free = true;\r
541         if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )\r
542                 $free = false;\r
543                 \r
544         return yourls_apply_filter( 'keyword_is_free', $free, $keyword );\r
545 }\r
546 \r
547 // Check if a keyword is taken (ie there is already a short URL with this id). Return bool.             \r
548 function yourls_keyword_is_taken( $keyword ) {\r
549         global $ydb;\r
550         $keyword = yourls_sanitize_keyword( $keyword );\r
551         $taken = false;\r
552         $table = YOURLS_DB_TABLE_URL;\r
553         $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");\r
554         if ( $already_exists )\r
555                 $taken = true;\r
556 \r
557         return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );\r
558 }\r
559 \r
560 \r
561 // Display a page\r
562 function yourls_page( $page ) {\r
563         $include = YOURLS_ABSPATH . "/pages/$page.php";\r
564         if (!file_exists($include)) {\r
565                 yourls_die("Page '$page' not found", 'Not found', 404);\r
566         }\r
567         yourls_do_action( 'pre_page', $page );\r
568         include($include);\r
569         yourls_do_action( 'post_page', $page );\r
570         die();  \r
571 }\r
572 \r
573 // Connect to DB\r
574 function yourls_db_connect() {\r
575         global $ydb;\r
576 \r
577         if (!defined('YOURLS_DB_USER')\r
578                 or !defined('YOURLS_DB_PASS')\r
579                 or !defined('YOURLS_DB_NAME')\r
580                 or !defined('YOURLS_DB_HOST')\r
581                 or !class_exists('ezSQL_mysql')\r
582         ) yourls_die ('DB config missing, or could not find DB class', 'Fatal error', 503);\r
583         \r
584         // Are we standalone or in the WordPress environment?\r
585         if ( class_exists('wpdb') ) {\r
586                 $ydb =  new wpdb(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
587         } else {\r
588                 $ydb =  new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
589         }\r
590         if ( $ydb->last_error )\r
591                 yourls_die( $ydb->last_error, 'Fatal error', 503 );\r
592         \r
593         if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )\r
594                 $ydb->show_errors = true;\r
595         \r
596         return $ydb;\r
597 }\r
598 \r
599 // Return XML output.\r
600 function yourls_xml_encode($array) {\r
601         require_once(YOURLS_INC.'/functions-xml.php');\r
602         $converter= new yourls_array2xml;\r
603         return $converter->array2xml($array);\r
604 }\r
605 \r
606 // 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
607 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {\r
608         global $ydb;\r
609         $keyword = yourls_sanitize_string( $keyword );\r
610 \r
611         yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );\r
612 \r
613         if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {\r
614                 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );\r
615         }\r
616         \r
617         yourls_do_action( 'get_keyword_not_cached', $keyword );\r
618         \r
619         $table = YOURLS_DB_TABLE_URL;\r
620         $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");\r
621         \r
622         if( $infos ) {\r
623                 $infos = (array)$infos;\r
624                 $ydb->infos[$keyword] = $infos;\r
625         } else {\r
626                 $ydb->infos[$keyword] = false;\r
627         }\r
628                 \r
629         return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );\r
630 }\r
631 \r
632 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\r
633 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {\r
634 \r
635         // Allow plugins to short-circuit the whole function\r
636         $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );\r
637         if ( false !== $pre )\r
638                 return $pre;\r
639 \r
640         $keyword = yourls_sanitize_string( $keyword );\r
641         $infos = yourls_get_keyword_infos( $keyword );\r
642         \r
643         $return = $notfound;\r
644         if ( isset($infos[$field]) && $infos[$field] !== false )\r
645                 $return = $infos[$field];\r
646 \r
647         return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound ); \r
648 }\r
649 \r
650 // Return title associated with keyword. Optional $notfound = string default message if nothing found\r
651 function yourls_get_keyword_title( $keyword, $notfound = false ) {\r
652         return yourls_get_keyword_info( $keyword, 'title', $notfound );\r
653 }\r
654 \r
655 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found\r
656 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {\r
657         return yourls_get_keyword_info( $keyword, 'url', $notfound );\r
658 }\r
659 \r
660 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\r
661 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {\r
662         return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\r
663 }\r
664 \r
665 // Return IP that added a keyword. Optional $notfound = string default message if nothing found\r
666 function yourls_get_keyword_IP( $keyword, $notfound = false ) {\r
667         return yourls_get_keyword_info( $keyword, 'ip', $notfound );\r
668 }\r
669 \r
670 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\r
671 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\r
672         return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\r
673 }\r
674 \r
675 // Update click count on a short URL. Return 0/1 for error/success.\r
676 function yourls_update_clicks( $keyword ) {\r
677         // Allow plugins to short-circuit the whole function\r
678         $pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword );\r
679         if ( false !== $pre )\r
680                 return $pre;\r
681 \r
682         global $ydb;\r
683         $keyword = yourls_sanitize_string( $keyword );\r
684         $table = YOURLS_DB_TABLE_URL;\r
685         $update = $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");\r
686         yourls_do_action( 'update_clicks', $keyword, $update );\r
687         return $update;\r
688 }\r
689 \r
690 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return\r
691 function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {\r
692         global $ydb;\r
693 \r
694         switch( $filter ) {\r
695                 case 'bottom':\r
696                         $sort_by = 'clicks';\r
697                         $sort_order = 'asc';\r
698                         break;\r
699                 case 'last':\r
700                         $sort_by = 'timestamp';\r
701                         $sort_order = 'desc';\r
702                         break;\r
703                 case 'rand':\r
704                 case 'random':\r
705                         $sort_by = 'RAND()';\r
706                         $sort_order = '';\r
707                         break;\r
708                 case 'top':\r
709                 default:\r
710                         $sort_by = 'clicks';\r
711                         $sort_order = 'desc';\r
712                         break;\r
713         }\r
714         \r
715         // Fetch links\r
716         $limit = intval( $limit );\r
717         $start = intval( $start );\r
718         if ( $limit > 0 ) {\r
719 \r
720                 $table_url = YOURLS_DB_TABLE_URL;\r
721                 $results = $ydb->get_results("SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;");\r
722                 \r
723                 $return = array();\r
724                 $i = 1;\r
725                 \r
726                 foreach ( (array)$results as $res) {\r
727                         $return['links']['link_'.$i++] = array(\r
728                                 'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
729                                 'url'      => $res->url,\r
730                                 'title'    => $res->title,\r
731                                 'timestamp'=> $res->timestamp,\r
732                                 'ip'       => $res->ip,\r
733                                 'clicks'   => $res->clicks,\r
734                         );\r
735                 }\r
736         }\r
737 \r
738         $return['stats'] = yourls_get_db_stats();\r
739         \r
740         $return['statusCode'] = 200;\r
741 \r
742         return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );\r
743 }\r
744 \r
745 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return\r
746 function yourls_get_link_stats( $shorturl ) {\r
747         global $ydb;\r
748 \r
749         $table_url = YOURLS_DB_TABLE_URL;\r
750         $res = $ydb->get_row("SELECT * FROM `$table_url` WHERE keyword = '$shorturl';");\r
751         $return = array();\r
752 \r
753         if( !$res ) {\r
754                 // non existent link\r
755                 $return = array(\r
756                         'statusCode' => 404,\r
757                         'message'    => 'Error: short URL not found',\r
758                 );\r
759         } else {\r
760                 $return = array(\r
761                         'statusCode' => 200,\r
762                         'message'    => 'success',\r
763                         'link'       => array(\r
764                         'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
765                         'url'      => $res->url,\r
766                         'title'    => $res->title,\r
767                         'timestamp'=> $res->timestamp,\r
768                         'ip'       => $res->ip,\r
769                         'clicks'   => $res->clicks,\r
770                         )\r
771                 );\r
772         }\r
773 \r
774         return yourls_apply_filter( 'get_link_stats', $return, $shorturl );\r
775 }\r
776 \r
777 // Return array for API stat requests\r
778 function yourls_api_stats( $filter = 'top', $limit = 10, $start = 0 ) {\r
779         $return = yourls_get_stats( $filter, $limit, $start );\r
780         $return['simple']  = 'Need either XML or JSON format for stats';\r
781         $return['message'] = 'success';\r
782         return yourls_apply_filter( 'api_stats', $return, $filter, $limit, $start );\r
783 }\r
784 \r
785 // Return array for counts of shorturls and clicks\r
786 function yourls_api_db_stats() {\r
787         $return = yourls_get_db_stats();\r
788         $return['simple']  = 'Need either XML or JSON format for stats';\r
789         $return['message'] = 'success';\r
790         return yourls_apply_filter( 'api_db_stats', $return );\r
791 }\r
792 \r
793 // Return array for API stat requests\r
794 function yourls_api_url_stats($shorturl) {\r
795         $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
796         $keyword = yourls_sanitize_string( $keyword );\r
797 \r
798         $return = yourls_get_link_stats( $keyword );\r
799         $return['simple']  = 'Need either XML or JSON format for stats';\r
800         return yourls_apply_filter( 'api_url_stats', $return, $shorturl );\r
801 }\r
802 \r
803 // Expand short url to long url\r
804 function yourls_api_expand( $shorturl ) {\r
805         $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'\r
806         $keyword = yourls_sanitize_string( $keyword );\r
807         \r
808         $longurl = yourls_get_keyword_longurl( $keyword );\r
809         \r
810         if( $longurl ) {\r
811                 $return = array(\r
812                         'keyword'  => $keyword,\r
813                         'shorturl' => YOURLS_SITE . "/$keyword",\r
814                         'longurl'  => $longurl,\r
815                         'simple'   => $longurl,\r
816                         'message'  => 'success',\r
817                         'statusCode' => 200,\r
818                 );\r
819         } else {\r
820                 $return = array(\r
821                         'keyword'  => $keyword,\r
822                         'simple'   => 'not found',\r
823                         'message'  => 'Error: short URL not found',\r
824                         'errorCode' => 404,\r
825                 );\r
826         }\r
827         \r
828         return yourls_apply_filter( 'api_expand', $return, $shorturl );\r
829 }\r
830 \r
831 \r
832 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array\r
833 function yourls_get_db_stats( $where = '' ) {\r
834         global $ydb;\r
835         $table_url = YOURLS_DB_TABLE_URL;\r
836 \r
837         $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");\r
838         $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );\r
839         \r
840         return yourls_apply_filter( 'get_db_stats', $return, $where );\r
841 }\r
842 \r
843 // Return API result. Dies after this\r
844 function yourls_api_output( $mode, $return ) {\r
845         if( isset( $return['simple'] ) ) {\r
846                 $simple = $return['simple'];\r
847                 unset( $return['simple'] );\r
848         }\r
849         \r
850         yourls_do_action( 'pre_api_output', $mode, $return );\r
851         \r
852         switch ( $mode ) {\r
853                 case 'json':\r
854                         header('Content-type: application/json');\r
855                         echo json_encode($return);\r
856                         break;\r
857                 \r
858                 case 'xml':\r
859                         header('Content-type: application/xml');\r
860                         echo yourls_xml_encode($return);\r
861                         break;\r
862                         \r
863                 case 'simple':\r
864                 default:\r
865                         if( isset( $simple ) )\r
866                                 echo $simple;\r
867                         break;\r
868         }\r
869 \r
870         yourls_do_action( 'api_output', $mode, $return );\r
871         \r
872         die();\r
873 }\r
874 \r
875 // Get number of SQL queries performed\r
876 function yourls_get_num_queries() {\r
877         global $ydb;\r
878 \r
879         return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );\r
880 }\r
881 \r
882 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.\r
883 function yourls_get_user_agent() {\r
884         if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )\r
885                 return '-';\r
886         \r
887         $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));\r
888         $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );\r
889                 \r
890         return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );\r
891 }\r
892 \r
893 // Redirect to another page\r
894 function yourls_redirect( $location, $code = 301 ) {\r
895         yourls_do_action( 'pre_redirect', $location, $code );\r
896         $location = yourls_apply_filter( 'redirect', $location, $code );\r
897         // Redirect, either properly if possible, or via Javascript otherwise\r
898         if( !headers_sent() ) {\r
899                 yourls_status_header( $code );\r
900                 header( "Location: $location" );\r
901         } else {\r
902                 yourls_redirect_javascript( $location );\r
903         }\r
904         die();\r
905 }\r
906 \r
907 // Set HTTP status header\r
908 function yourls_status_header( $code = 200 ) {\r
909         if( headers_sent() )\r
910                 return;\r
911                 \r
912         $protocol = $_SERVER["SERVER_PROTOCOL"];\r
913         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )\r
914                 $protocol = 'HTTP/1.0';\r
915 \r
916         $code = intval( $code );\r
917         $desc = yourls_get_HTTP_status( $code );\r
918 \r
919         @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups\r
920         yourls_do_action( 'status_header', $code );\r
921 }\r
922 \r
923 // 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
924 function yourls_redirect_javascript( $location, $dontwait = true ) {\r
925         yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );\r
926         $location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );\r
927         if( $dontwait ) {\r
928                 echo <<<REDIR\r
929                 <script type="text/javascript">\r
930                 window.location="$location";\r
931                 </script>\r
932                 <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>\r
933 REDIR;\r
934         } else {\r
935                 echo <<<MANUAL\r
936                 <p>Please <a href="$location">click here</a></p>\r
937 MANUAL;\r
938         }\r
939         yourls_do_action( 'post_redirect_javascript', $location );\r
940 }\r
941 \r
942 // Return a HTTP status code\r
943 function yourls_get_HTTP_status( $code ) {\r
944         $code = intval( $code );\r
945         $headers_desc = array(\r
946                 100 => 'Continue',\r
947                 101 => 'Switching Protocols',\r
948                 102 => 'Processing',\r
949 \r
950                 200 => 'OK',\r
951                 201 => 'Created',\r
952                 202 => 'Accepted',\r
953                 203 => 'Non-Authoritative Information',\r
954                 204 => 'No Content',\r
955                 205 => 'Reset Content',\r
956                 206 => 'Partial Content',\r
957                 207 => 'Multi-Status',\r
958                 226 => 'IM Used',\r
959 \r
960                 300 => 'Multiple Choices',\r
961                 301 => 'Moved Permanently',\r
962                 302 => 'Found',\r
963                 303 => 'See Other',\r
964                 304 => 'Not Modified',\r
965                 305 => 'Use Proxy',\r
966                 306 => 'Reserved',\r
967                 307 => 'Temporary Redirect',\r
968 \r
969                 400 => 'Bad Request',\r
970                 401 => 'Unauthorized',\r
971                 402 => 'Payment Required',\r
972                 403 => 'Forbidden',\r
973                 404 => 'Not Found',\r
974                 405 => 'Method Not Allowed',\r
975                 406 => 'Not Acceptable',\r
976                 407 => 'Proxy Authentication Required',\r
977                 408 => 'Request Timeout',\r
978                 409 => 'Conflict',\r
979                 410 => 'Gone',\r
980                 411 => 'Length Required',\r
981                 412 => 'Precondition Failed',\r
982                 413 => 'Request Entity Too Large',\r
983                 414 => 'Request-URI Too Long',\r
984                 415 => 'Unsupported Media Type',\r
985                 416 => 'Requested Range Not Satisfiable',\r
986                 417 => 'Expectation Failed',\r
987                 422 => 'Unprocessable Entity',\r
988                 423 => 'Locked',\r
989                 424 => 'Failed Dependency',\r
990                 426 => 'Upgrade Required',\r
991 \r
992                 500 => 'Internal Server Error',\r
993                 501 => 'Not Implemented',\r
994                 502 => 'Bad Gateway',\r
995                 503 => 'Service Unavailable',\r
996                 504 => 'Gateway Timeout',\r
997                 505 => 'HTTP Version Not Supported',\r
998                 506 => 'Variant Also Negotiates',\r
999                 507 => 'Insufficient Storage',\r
1000                 510 => 'Not Extended'\r
1001         );\r
1002 \r
1003         if ( isset( $headers_desc[$code] ) )\r
1004                 return $headers_desc[$code];\r
1005         else\r
1006                 return '';\r
1007 }\r
1008 \r
1009 \r
1010 // Log a redirect (for stats)\r
1011 function yourls_log_redirect( $keyword ) {\r
1012         // Allow plugins to short-circuit the whole function\r
1013         $pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );\r
1014         if ( false !== $pre )\r
1015                 return $pre;\r
1016 \r
1017         if ( !yourls_do_log_redirect() )\r
1018                 return true;\r
1019 \r
1020         global $ydb;\r
1021         $table = YOURLS_DB_TABLE_LOG;\r
1022         \r
1023         $keyword = yourls_sanitize_string( $keyword );\r
1024         $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );\r
1025         $ua = yourls_get_user_agent();\r
1026         $ip = yourls_get_IP();\r
1027         $location = yourls_geo_ip_to_countrycode( $ip );\r
1028         \r
1029         return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );\r
1030 }\r
1031 \r
1032 // Check if we want to not log redirects (for stats)\r
1033 function yourls_do_log_redirect() {\r
1034         return ( !defined('YOURLS_NOSTATS') || YOURLS_NOSTATS != true );\r
1035 }\r
1036 \r
1037 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/\r
1038 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {\r
1039         // Allow plugins to short-circuit the Geo IP API\r
1040         $location = yourls_apply_filter( 'shunt_geo_ip_to_countrycode', false, $ip, $default ); // at this point $ip can be '', check if your plugin hooks in here\r
1041         if ( false !== $location )\r
1042                 return $location;\r
1043 \r
1044         if ( !file_exists( YOURLS_INC.'/geo/GeoIP.dat') || !file_exists( YOURLS_INC.'/geo/geoip.inc') )\r
1045                 return $default;\r
1046 \r
1047         if ( $ip == '' )\r
1048                 $ip = yourls_get_IP();\r
1049         \r
1050         require_once( YOURLS_INC.'/geo/geoip.inc') ;\r
1051         $gi = geoip_open( YOURLS_INC.'/geo/GeoIP.dat', GEOIP_STANDARD);\r
1052         $location = geoip_country_code_by_addr($gi, $ip);\r
1053         geoip_close($gi);\r
1054 \r
1055         return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );\r
1056 }\r
1057 \r
1058 // Converts a 2 letter country code to long name (ie AU -> Australia)\r
1059 function yourls_geo_countrycode_to_countryname( $code ) {\r
1060         // Allow plugins to short-circuit the Geo IP API\r
1061         $country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );\r
1062         if ( false !== $country )\r
1063                 return $country;\r
1064 \r
1065         // Load the Geo class if not already done\r
1066         if( !class_exists('GeoIP') ) {\r
1067                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
1068         }\r
1069         \r
1070         if( class_exists('GeoIP') ) {\r
1071                 $geo = new GeoIP;\r
1072                 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];\r
1073                 $long = $geo->GEOIP_COUNTRY_NAMES[$id];\r
1074                 return $long;\r
1075         } else {\r
1076                 return false;\r
1077         }\r
1078 }\r
1079 \r
1080 // Return flag URL from 2 letter country code\r
1081 function yourls_geo_get_flag( $code ) {\r
1082         if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {\r
1083                 $img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif' );\r
1084         } else {\r
1085                 $img = false;\r
1086         }\r
1087         return yourls_apply_filter( 'geo_get_flag', $img, $code );\r
1088 }\r
1089 \r
1090 \r
1091 // Check if an upgrade is needed\r
1092 function yourls_upgrade_is_needed() {\r
1093         // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS\r
1094         list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();\r
1095         if( $currentsql < YOURLS_DB_VERSION )\r
1096                 return true;\r
1097                 \r
1098         return false;\r
1099 }\r
1100 \r
1101 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.\r
1102 function yourls_get_current_version_from_sql() {\r
1103         $currentver = yourls_get_option( 'version' );\r
1104         $currentsql = yourls_get_option( 'db_version' );\r
1105 \r
1106         // Values if version is 1.3\r
1107         if( !$currentver )\r
1108                 $currentver = '1.3';\r
1109         if( !$currentsql )\r
1110                 $currentsql = '100';\r
1111                 \r
1112         return array( $currentver, $currentsql);\r
1113 }\r
1114 \r
1115 // Read an option from DB (or from cache if available). Return value or $default if not found\r
1116 function yourls_get_option( $option_name, $default = false ) {\r
1117         global $ydb;\r
1118         \r
1119         // Allow plugins to short-circuit options\r
1120         $pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );\r
1121         if ( false !== $pre )\r
1122                 return $pre;\r
1123 \r
1124         if ( !isset( $ydb->option[$option_name] ) ) {\r
1125                 $table = YOURLS_DB_TABLE_OPTIONS;\r
1126                 $option_name = yourls_escape( $option_name );\r
1127                 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );\r
1128                 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values\r
1129                         $value = $row->option_value;\r
1130                 } else { // option does not exist, so we must cache its non-existence\r
1131                         $value = $default;\r
1132                 }\r
1133                 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );\r
1134         }\r
1135 \r
1136         return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );\r
1137 }\r
1138 \r
1139 // Read all options from DB at once\r
1140 function yourls_get_all_options() {\r
1141         global $ydb;\r
1142         $table = YOURLS_DB_TABLE_OPTIONS;\r
1143         \r
1144         $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");\r
1145         \r
1146         foreach( (array)$allopt as $option ) {\r
1147                 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );\r
1148         }\r
1149 }\r
1150 \r
1151 // Update (add if doesn't exist) an option to DB\r
1152 function yourls_update_option( $option_name, $newvalue ) {\r
1153         global $ydb;\r
1154         $table = YOURLS_DB_TABLE_OPTIONS;\r
1155 \r
1156         $safe_option_name = yourls_escape( $option_name );\r
1157 \r
1158         $oldvalue = yourls_get_option( $safe_option_name );\r
1159 \r
1160         // If the new and old values are the same, no need to update.\r
1161         if ( $newvalue === $oldvalue )\r
1162                 return false;\r
1163 \r
1164         if ( false === $oldvalue ) {\r
1165                 yourls_add_option( $option_name, $newvalue );\r
1166                 return true;\r
1167         }\r
1168 \r
1169         $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );\r
1170         \r
1171         yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );\r
1172 \r
1173         $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");\r
1174 \r
1175         if ( $ydb->rows_affected == 1 ) {\r
1176                 $ydb->option[$option_name] = $newvalue;\r
1177                 return true;\r
1178         }\r
1179         return false;\r
1180 }\r
1181 \r
1182 // Add an option to the DB\r
1183 function yourls_add_option( $name, $value = '' ) {\r
1184         global $ydb;\r
1185         $table = YOURLS_DB_TABLE_OPTIONS;\r
1186         $safe_name = yourls_escape( $name );\r
1187 \r
1188         // Make sure the option doesn't already exist\r
1189         if ( false !== yourls_get_option( $safe_name ) )\r
1190                 return;\r
1191 \r
1192         $_value = yourls_escape( yourls_maybe_serialize( $value ) );\r
1193 \r
1194         yourls_do_action( 'add_option', $safe_name, $_value );\r
1195 \r
1196         $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );\r
1197         $ydb->option[$name] = $value;\r
1198         return;\r
1199 }\r
1200 \r
1201 \r
1202 // Delete an option from the DB\r
1203 function yourls_delete_option( $name ) {\r
1204         global $ydb;\r
1205         $table = YOURLS_DB_TABLE_OPTIONS;\r
1206         $name = yourls_escape( $name );\r
1207 \r
1208         // Get the ID, if no ID then return\r
1209         $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );\r
1210         if ( is_null($option) || !$option->option_id )\r
1211                 return false;\r
1212                 \r
1213         yourls_do_action( 'delete_option', $option_name );\r
1214                 \r
1215         $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );\r
1216         return true;\r
1217 }\r
1218 \r
1219 \r
1220 \r
1221 // Serialize data if needed. Stolen from WordPress\r
1222 function yourls_maybe_serialize( $data ) {\r
1223         if ( is_array( $data ) || is_object( $data ) )\r
1224                 return serialize( $data );\r
1225 \r
1226         if ( yourls_is_serialized( $data ) )\r
1227                 return serialize( $data );\r
1228 \r
1229         return $data;\r
1230 }\r
1231 \r
1232 // Check value to find if it was serialized. Stolen from WordPress\r
1233 function yourls_is_serialized( $data ) {\r
1234         // if it isn't a string, it isn't serialized\r
1235         if ( !is_string( $data ) )\r
1236                 return false;\r
1237         $data = trim( $data );\r
1238         if ( 'N;' == $data )\r
1239                 return true;\r
1240         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )\r
1241                 return false;\r
1242         switch ( $badions[1] ) {\r
1243                 case 'a' :\r
1244                 case 'O' :\r
1245                 case 's' :\r
1246                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )\r
1247                                 return true;\r
1248                         break;\r
1249                 case 'b' :\r
1250                 case 'i' :\r
1251                 case 'd' :\r
1252                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )\r
1253                                 return true;\r
1254                         break;\r
1255         }\r
1256         return false;\r
1257 }\r
1258 \r
1259 // Unserialize value only if it was serialized. Stolen from WP\r
1260 function yourls_maybe_unserialize( $original ) {\r
1261         if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in\r
1262                 return @unserialize( $original );\r
1263         return $original;\r
1264 }\r
1265 \r
1266 // Determine if the current page is private\r
1267 function yourls_is_private() {\r
1268         $private = false;\r
1269 \r
1270         if ( defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true ) {\r
1271 \r
1272                 // Allow overruling for particular pages:\r
1273                 \r
1274                 // API\r
1275                 if( yourls_is_API() ) {\r
1276                         if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )\r
1277                                 $private = true;                \r
1278 \r
1279                 // Infos\r
1280                 } elseif( yourls_is_infos() ) {\r
1281                         if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )\r
1282                                 $private = true;\r
1283                 \r
1284                 // Others\r
1285                 } else {\r
1286                         $private = true;\r
1287                 }\r
1288                 \r
1289         }\r
1290                         \r
1291         return yourls_apply_filter( 'is_private', $private );\r
1292 }\r
1293 \r
1294 // Show login form if required\r
1295 function yourls_maybe_require_auth() {\r
1296         if( yourls_is_private() )\r
1297                 require_once( YOURLS_INC.'/auth.php' );\r
1298 }\r
1299 \r
1300 // Return word or words if more than one\r
1301 function yourls_plural( $word, $count=1 ) {\r
1302         return $word . ($count > 1 ? 's' : '');\r
1303 }\r
1304 \r
1305 // Return trimmed string\r
1306 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {\r
1307         $newstring = $string;\r
1308         if( function_exists('mb_substr') ) {\r
1309                 if ( mb_strlen( $newstring ) > $length ) {\r
1310                         $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;     \r
1311                 }\r
1312         } else {\r
1313                 if ( strlen( $newstring ) > $length ) {\r
1314                         $newstring = substr( $newstring, 0, $length - strlen( $append ) ) . $append;    \r
1315                 }\r
1316         }\r
1317         return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );\r
1318 }\r
1319 \r
1320 // Allow several short URLs for the same long URL ?\r
1321 function yourls_allow_duplicate_longurls() {\r
1322         // special treatment if API to check for WordPress plugin requests\r
1323         if( yourls_is_API() ) {\r
1324                 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' ) \r
1325                         return false;\r
1326         }\r
1327         return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );\r
1328 }\r
1329 \r
1330 // Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.\r
1331 function yourls_get_duplicate_keywords( $longurl ) {\r
1332         if( !yourls_allow_duplicate_longurls() )\r
1333                 return NULL;\r
1334         \r
1335         global $ydb;\r
1336         $longurl = yourls_escape( yourls_sanitize_url($longurl) );\r
1337         $table = YOURLS_DB_TABLE_URL;\r
1338         \r
1339         $return = $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );\r
1340         return yourls_apply_filter( 'get_duplicate_keywords', $return, $longurl );\r
1341 }\r
1342 \r
1343 // Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.\r
1344 function yourls_check_IP_flood( $ip = '' ) {\r
1345 \r
1346         // Allow plugins to short-circuit the whole function\r
1347         $pre = yourls_apply_filter( 'shunt_check_IP_flood', false, $ip );\r
1348         if ( false !== $pre )\r
1349                 return $pre;\r
1350 \r
1351         yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here\r
1352 \r
1353         if(\r
1354                 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||\r
1355                 !defined('YOURLS_FLOOD_DELAY_SECONDS')\r
1356         )\r
1357                 return true;\r
1358 \r
1359         $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );\r
1360 \r
1361         // Don't throttle whitelist IPs\r
1362         if( defined('YOURLS_FLOOD_IP_WHITELIST' && YOURLS_FLOOD_IP_WHITELIST ) ) {\r
1363                 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );\r
1364                 foreach( (array)$whitelist_ips as $whitelist_ip ) {\r
1365                         $whitelist_ip = trim( $whitelist_ip );\r
1366                         if ( $whitelist_ip == $ip )\r
1367                                 return true;\r
1368                 }\r
1369         }\r
1370         \r
1371         // Don't throttle logged in users\r
1372         if( yourls_is_private() ) {\r
1373                  if( yourls_is_valid_user() === true )\r
1374                         return true;\r
1375         }\r
1376         \r
1377         yourls_do_action( 'check_ip_flood', $ip );\r
1378         \r
1379         global $ydb;\r
1380         $table = YOURLS_DB_TABLE_URL;\r
1381         \r
1382         $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );\r
1383         if( $lasttime ) {\r
1384                 $now = date( 'U' );\r
1385                 $then = date( 'U', strtotime( $lasttime ) );\r
1386                 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {\r
1387                         // Flood!\r
1388                         yourls_do_action( 'ip_flood', $ip, $now - $then );\r
1389                         yourls_die( 'Too many URLs added too fast. Slow down please.', 'Forbidden', 403 );\r
1390                 }\r
1391         }\r
1392         \r
1393         return true;\r
1394 }\r
1395 \r
1396 // Check if YOURLS is installed\r
1397 function yourls_is_installed() {\r
1398         static $is_installed = false;\r
1399         if ( $is_installed === false ) {\r
1400                 $check_14 = $check_13 = false;\r
1401                 global $ydb;\r
1402                 if( defined('YOURLS_DB_TABLE_NEXTDEC') )\r
1403                         $check_13 = $ydb->get_var('SELECT `next_id` FROM '.YOURLS_DB_TABLE_NEXTDEC);\r
1404                 $check_14 = yourls_get_option( 'version' );\r
1405                 $is_installed = $check_13 || $check_14;\r
1406         }\r
1407         return yourls_apply_filter( 'is_installed', $is_installed );\r
1408 }\r
1409 \r
1410 // Generate random string of (int)$length length and type $type (see function for details)\r
1411 function yourls_rnd_string ( $length = 5, $type = 0, $charlist = '' ) {\r
1412         $str = '';\r
1413         $length = intval( $length );\r
1414 \r
1415         // define possible characters\r
1416         switch ( $type ) {\r
1417 \r
1418                 // custom char list, or comply to charset as defined in config\r
1419                 case '0':\r
1420                         $possible = $charlist ? $charlist : yourls_get_shorturl_charset() ;\r
1421                         break;\r
1422         \r
1423                 // no vowels to make no offending word, no 0/1/o/l to avoid confusion between letters & digits. Perfect for passwords.\r
1424                 case '1':\r
1425                         $possible = "23456789bcdfghjkmnpqrstvwxyz";\r
1426                         break;\r
1427                 \r
1428                 // Same, with lower + upper\r
1429                 case '2':\r
1430                         $possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";\r
1431                         break;\r
1432                 \r
1433                 // all letters, lowercase\r
1434                 case '3':\r
1435                         $possible = "abcdefghijklmnopqrstuvwxyz";\r
1436                         break;\r
1437                 \r
1438                 // all letters, lowercase + uppercase\r
1439                 case '4':\r
1440                         $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\r
1441                         break;\r
1442                 \r
1443                 // all digits & letters lowercase \r
1444                 case '5':\r
1445                         $possible = "0123456789abcdefghijklmnopqrstuvwxyz";\r
1446                         break;\r
1447                 \r
1448                 // all digits & letters lowercase + uppercase\r
1449                 case '6':\r
1450                         $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\r
1451                         break;\r
1452                 \r
1453         }\r
1454 \r
1455         $i = 0;\r
1456         while ($i < $length) {\r
1457                 $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);\r
1458                 $i++;\r
1459         }\r
1460         \r
1461         return yourls_apply_filter( 'rnd_string', $str, $length, $type, $charlist );\r
1462 }\r
1463 \r
1464 // Return salted string\r
1465 function yourls_salt( $string ) {\r
1466         $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;\r
1467         return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt), $string );\r
1468 }\r
1469 \r
1470 // Add a query var to a URL and return URL. Completely stolen from WP.\r
1471 // Works with one of these parameter patterns:\r
1472 //     array( 'var' => 'value' )\r
1473 //     array( 'var' => 'value' ), $url\r
1474 //     'var', 'value'\r
1475 //     'var', 'value', $url\r
1476 // If $url ommited, uses $_SERVER['REQUEST_URI']\r
1477 function yourls_add_query_arg() {\r
1478         $ret = '';\r
1479         if ( is_array( func_get_arg(0) ) ) {\r
1480                 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )\r
1481                         $uri = $_SERVER['REQUEST_URI'];\r
1482                 else\r
1483                         $uri = @func_get_arg( 1 );\r
1484         } else {\r
1485                 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )\r
1486                         $uri = $_SERVER['REQUEST_URI'];\r
1487                 else\r
1488                         $uri = @func_get_arg( 2 );\r
1489         }\r
1490         \r
1491         $uri = str_replace( '&amp;', '&', $uri );\r
1492 \r
1493         \r
1494         if ( $frag = strstr( $uri, '#' ) )\r
1495                 $uri = substr( $uri, 0, -strlen( $frag ) );\r
1496         else\r
1497                 $frag = '';\r
1498 \r
1499         if ( preg_match( '|^https?://|i', $uri, $matches ) ) {\r
1500                 $protocol = $matches[0];\r
1501                 $uri = substr( $uri, strlen( $protocol ) );\r
1502         } else {\r
1503                 $protocol = '';\r
1504         }\r
1505 \r
1506         if ( strpos( $uri, '?' ) !== false ) {\r
1507                 $parts = explode( '?', $uri, 2 );\r
1508                 if ( 1 == count( $parts ) ) {\r
1509                         $base = '?';\r
1510                         $query = $parts[0];\r
1511                 } else {\r
1512                         $base = $parts[0] . '?';\r
1513                         $query = $parts[1];\r
1514                 }\r
1515         } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {\r
1516                 $base = $uri . '?';\r
1517                 $query = '';\r
1518         } else {\r
1519                 $base = '';\r
1520                 $query = $uri;\r
1521         }\r
1522 \r
1523         parse_str( $query, $qs );\r
1524         $qs = yourls_urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string\r
1525         if ( is_array( func_get_arg( 0 ) ) ) {\r
1526                 $kayvees = func_get_arg( 0 );\r
1527                 $qs = array_merge( $qs, $kayvees );\r
1528         } else {\r
1529                 $qs[func_get_arg( 0 )] = func_get_arg( 1 );\r
1530         }\r
1531 \r
1532         foreach ( (array) $qs as $k => $v ) {\r
1533                 if ( $v === false )\r
1534                         unset( $qs[$k] );\r
1535         }\r
1536 \r
1537         $ret = http_build_query( $qs );\r
1538         $ret = trim( $ret, '?' );\r
1539         $ret = preg_replace( '#=(&|$)#', '$1', $ret );\r
1540         $ret = $protocol . $base . $ret . $frag;\r
1541         $ret = rtrim( $ret, '?' );\r
1542         return $ret;\r
1543 }\r
1544 \r
1545 // Navigates through an array and encodes the values to be used in a URL. Stolen from WP, used in yourls_add_query_arg()\r
1546 function yourls_urlencode_deep($value) {\r
1547         $value = is_array($value) ? array_map('yourls_urlencode_deep', $value) : urlencode($value);\r
1548         return $value;\r
1549 }\r
1550 \r
1551 // Remove arg from query. Opposite of yourls_add_query_arg. Stolen from WP.\r
1552 function yourls_remove_query_arg( $key, $query = false ) {\r
1553         if ( is_array( $key ) ) { // removing multiple keys\r
1554                 foreach ( $key as $k )\r
1555                         $query = add_query_arg( $k, false, $query );\r
1556                 return $query;\r
1557         }\r
1558         return add_query_arg( $key, false, $query );\r
1559 }\r
1560 \r
1561 // Return a time-dependent string for nonce creation\r
1562 function yourls_tick() {\r
1563         return ceil( time() / YOURLS_NONCE_LIFE );\r
1564 }\r
1565 \r
1566 // Create a time limited, action limited and user limited token\r
1567 function yourls_create_nonce( $action, $user = false ) {\r
1568         if( false == $user )\r
1569                 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';\r
1570         $tick = yourls_tick();\r
1571         return substr( yourls_salt($tick . $action . $user), 0, 10 );\r
1572 }\r
1573 \r
1574 // Create a nonce field for inclusion into a form\r
1575 function yourls_nonce_field( $action, $name = 'nonce', $user = false, $echo = true ) {\r
1576         $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';\r
1577         if( $echo )\r
1578                 echo $field."\n";\r
1579         return $field;\r
1580 }\r
1581 \r
1582 // Add a nonce to a URL. If URL omitted, adds nonce to current URL\r
1583 function yourls_nonce_url( $action, $url = false, $name = 'nonce', $user = false ) {\r
1584         $nonce = yourls_create_nonce( $action, $user );\r
1585         return yourls_add_query_arg( $name, $nonce, $url );\r
1586 }\r
1587 \r
1588 // Check validity of a nonce (ie time span, user and action match).\r
1589 // Returns true if valid, dies otherwise (yourls_die() or die($return) if defined)\r
1590 // if $nonce is false or unspecified, it will use $_REQUEST['nonce']\r
1591 function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {\r
1592         // get user\r
1593         if( false == $user )\r
1594                 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';\r
1595                 \r
1596         // get current nonce value\r
1597         if( false == $nonce && isset( $_REQUEST['nonce'] ) )\r
1598                 $nonce = $_REQUEST['nonce'];\r
1599 \r
1600         // what nonce should be\r
1601         $valid = yourls_create_nonce( $action, $user );\r
1602         \r
1603         if( $nonce == $valid ) {\r
1604                 return true;\r
1605         } else {\r
1606                 if( $return )\r
1607                         die( $return );\r
1608                 yourls_die( 'Unauthorized action or expired link', 'Error', 403 );\r
1609         }\r
1610 }\r
1611 \r
1612 // Sanitize a version number (1.4.1-whatever -> 1.4.1)\r
1613 function yourls_sanitize_version( $ver ) {\r
1614         return preg_replace( '/[^0-9.]/', '', $ver );\r
1615 }\r
1616 \r
1617 // Converts keyword into short link (prepend with YOURLS base URL)\r
1618 function yourls_link( $keyword = '' ) {\r
1619         $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );\r
1620         return yourls_apply_filter( 'yourls_link', $link, $keyword );\r
1621 }\r
1622 \r
1623 // Check if we're in API mode. Returns bool\r
1624 function yourls_is_API() {\r
1625         if ( defined('YOURLS_API') && YOURLS_API == true )\r
1626                 return true;\r
1627         return false;\r
1628 }\r
1629 \r
1630 // Check if we're in Ajax mode. Returns bool\r
1631 function yourls_is_Ajax() {\r
1632         if ( defined('YOURLS_AJAX') && YOURLS_AJAX == true )\r
1633                 return true;\r
1634         return false;\r
1635 }\r
1636 \r
1637 // Check if we're in GO mode (yourls-go.php). Returns bool\r
1638 function yourls_is_GO() {\r
1639         if ( defined('YOURLS_GO') && YOURLS_GO == true )\r
1640                 return true;\r
1641         return false;\r
1642 }\r
1643 \r
1644 // Check if we're displaying stats infos (yourls-infos.php). Returns bool\r
1645 function yourls_is_infos() {\r
1646         if ( defined('YOURLS_INFOS') && YOURLS_INFOS == true )\r
1647                 return true;\r
1648         return false;\r
1649 }\r
1650 \r
1651 // Check if we'll need interface display function (ie not API or redirection)\r
1652 function yourls_has_interface() {\r
1653         if( yourls_is_API() or yourls_is_GO() )\r
1654                 return false;\r
1655         return true;\r
1656 }\r
1657 \r
1658 // Check if we're in the admin area. Returns bool\r
1659 function yourls_is_admin() {\r
1660         if ( defined('YOURLS_ADMIN') && YOURLS_ADMIN == true )\r
1661                 return true;\r
1662         return false;\r
1663 }\r
1664 \r
1665 // Check if the server seems to be running on Windows. Not exactly sure how reliable this is.\r
1666 function yourls_is_windows() {\r
1667         return defined( 'DIRECTORY_SEPARATOR' ) && DIRECTORY_SEPARATOR == '\\';\r
1668 }\r
1669 \r
1670 // Check if SSL is required. Returns bool.\r
1671 function yourls_needs_ssl() {\r
1672         if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )\r
1673                 return true;\r
1674         return false;\r
1675 }\r
1676 \r
1677 // Return admin link, with SSL preference if applicable.\r
1678 function yourls_admin_url( $page = '' ) {\r
1679         $admin = YOURLS_SITE . '/admin/' . $page;\r
1680         if( yourls_is_ssl() or yourls_needs_ssl() )\r
1681                 $admin = str_replace('http://', 'https://', $admin);\r
1682         return yourls_apply_filter( 'admin_url', $admin, $page );\r
1683 }\r
1684 \r
1685 // Return YOURLS_SITE, with SSL preference\r
1686 function yourls_site_url( $echo = true ) {\r
1687         $site = YOURLS_SITE;\r
1688         // Do not enforce (checking yourls_need_ssl() ) but check current usage so it won't force SSL on non-admin pages\r
1689         if( yourls_is_ssl() )\r
1690                 $site = str_replace( 'http://', 'https://', $site );\r
1691         $site = yourls_apply_filter( 'site_url', $site );\r
1692         if( $echo )\r
1693                 echo $site;\r
1694         return $site;\r
1695 }\r
1696 \r
1697 // Check if SSL is used, returns bool. Stolen from WP.\r
1698 function yourls_is_ssl() {\r
1699         $is_ssl = false;\r
1700         if ( isset($_SERVER['HTTPS']) ) {\r
1701                 if ( 'on' == strtolower($_SERVER['HTTPS']) )\r
1702                         $is_ssl = true;\r
1703                 if ( '1' == $_SERVER['HTTPS'] )\r
1704                         $is_ssl = true;\r
1705         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {\r
1706                 $is_ssl = true;\r
1707         }\r
1708         return yourls_apply_filter( 'is_ssl', $is_ssl );\r
1709 }\r
1710 \r
1711 \r
1712 // Get a remote page <title>, return a string (either title or url)\r
1713 function yourls_get_remote_title( $url ) {\r
1714         // Allow plugins to short-circuit the whole function\r
1715         $pre = yourls_apply_filter( 'shunt_get_remote_title', false, $url );\r
1716         if ( false !== $pre )\r
1717                 return $pre;\r
1718 \r
1719         require_once( YOURLS_INC.'/functions-http.php' );\r
1720 \r
1721         $url = yourls_sanitize_url( $url );\r
1722 \r
1723         $title = $charset = false;\r
1724         \r
1725         $content = yourls_get_remote_content( $url );\r
1726         \r
1727         // If false, return url as title.\r
1728         // Todo: improve this with temporary title when shorturl_meta available?\r
1729         if( false === $content )\r
1730                 return $url;\r
1731 \r
1732         if( $content !== false ) {\r
1733                 // look for <title>\r
1734                 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {\r
1735                         $title = $found[1];\r
1736                         unset( $found );\r
1737                 }\r
1738 \r
1739                 // look for charset\r
1740                 // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />\r
1741                 if ( preg_match('/<meta[^>]*?charset=([^>]*?)\/?>/is', $content, $found ) ) {\r
1742                         $charset = trim($found[1], '"\' ');\r
1743                         unset( $found );\r
1744                 }\r
1745         }\r
1746         \r
1747         // if title not found, guess if returned content was actually an error message\r
1748         if( $title == false && strpos( $content, 'Error' ) === 0 ) {\r
1749                 $title = $content;\r
1750         }\r
1751         \r
1752         if( $title == false )\r
1753                 $title = $url;\r
1754         \r
1755         /*\r
1756         if( !yourls_seems_utf8( $title ) )\r
1757                 $title = utf8_encode( $title );\r
1758         */\r
1759         \r
1760         // Charset conversion. We use @ to remove warnings (mb_ functions are easily bitching about illegal chars)\r
1761         if( function_exists( 'mb_convert_encoding' ) ) {\r
1762                 if( $charset ) {\r
1763                         $title = @mb_convert_encoding( $title, 'UTF-8', $charset );\r
1764                 } else {\r
1765                         $title = @mb_convert_encoding( $title, 'UTF-8' );\r
1766                 }\r
1767         }\r
1768         \r
1769         // Remove HTML entities\r
1770         $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' );\r
1771         \r
1772         // Strip out evil things\r
1773         $title = yourls_sanitize_title( $title );\r
1774         \r
1775         return yourls_apply_filter( 'get_remote_title', $title, $url );\r
1776 }\r
1777 \r
1778 // Sanitize a filename (no Win32 stuff)\r
1779 function yourls_sanitize_filename( $file ) {\r
1780         $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs\r
1781         $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash\r
1782         return $file;\r
1783 }\r
1784 \r
1785 // Check for maintenance mode that will shortcut everything\r
1786 function yourls_check_maintenance_mode() {\r
1787         \r
1788         // TODO: all cases that always display the sites (is_admin but not is_ajax?)\r
1789         if( 1 )\r
1790                 return;\r
1791 \r
1792         // first case: /user/maintenance.php file\r
1793         if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {\r
1794                 include( YOURLS_USERDIR.'/maintenance.php' );\r
1795                 die();  \r
1796         }\r
1797         \r
1798         // second case: option in DB\r
1799         if( yourls_get_option( 'maintenance_mode' ) !== false ) {\r
1800                 require_once( YOURLS_INC.'/functions-html.php' );\r
1801                 $title = 'Service temporarily unavailable';\r
1802                 $message = 'Our service is currently undergoing scheduled maintenance.</p>\r
1803                 <p>Things should not last very long, thank you for your patience and please excuse the inconvenience';\r
1804                 yourls_die( $message, $title , 503 );\r
1805         }\r
1806         \r
1807 }\r
1808 \r
1809 // Toggle maintenance mode\r
1810 function yourls_maintenance_mode( $maintenance = true ) {\r
1811         yourls_update_option( 'maintenance_mode', (bool)$maintenance );\r
1812 }\r
1813 \r
1814 // Check if a string seems to be UTF-8. Stolen from WP.\r
1815 function yourls_seems_utf8($str) {\r
1816         $length = strlen($str);\r
1817         for ($i=0; $i < $length; $i++) {\r
1818                 $c = ord($str[$i]);\r
1819                 if ($c < 0x80) $n = 0; # 0bbbbbbb\r
1820                 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb\r
1821                 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb\r
1822                 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb\r
1823                 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb\r
1824                 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b\r
1825                 else return false; # Does not match any model\r
1826                 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?\r
1827                         if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))\r
1828                                 return false;\r
1829                 }\r
1830         }\r
1831         return true;\r
1832 }\r
1833 \r
1834 // Quick UA check for mobile devices. Return boolean.\r
1835 function yourls_is_mobile_device() {\r
1836         // Strings searched\r
1837         $mobiles = array(\r
1838                 'android', 'blackberry', 'blazer',\r
1839                 'compal', 'elaine', 'fennec', 'hiptop',\r
1840                 'iemobile', 'iphone', 'ipod', 'ipad',\r
1841                 'iris', 'kindle', 'opera mobi', 'opera mini',\r
1842                 'palm', 'phone', 'pocket', 'psp', 'symbian',\r
1843                 'treo', 'wap', 'windows ce', 'windows phone'\r
1844         );\r
1845         \r
1846         // Current user-agent\r
1847         $current = strtolower( $_SERVER['HTTP_USER_AGENT'] );\r
1848         \r
1849         // Check and return\r
1850         $is_mobile = ( str_replace( $mobiles, '', $current ) != $current );\r
1851         return yourls_apply_filter( 'is_mobile_device', $is_mobile );\r
1852 }\r
1853 \r
1854 // Get request in YOURLS base (eg in 'http://site.com/yourls/abcd' get 'abdc')\r
1855 function yourls_get_request() {\r
1856         // Cover all cases: YOURLS_SITE https or not * current URL https or not\r
1857         $base = str_replace( array( 'https', 'http' ), '', YOURLS_SITE );\r
1858         $scheme = yourls_is_ssl() ? 'https' : 'http' ;\r
1859 \r
1860         // Extract the 'abdc' from the requested URL\r
1861         $request = str_replace(\r
1862                 $scheme . $base.'/',\r
1863                 '',\r
1864                 $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']\r
1865         );\r
1866 \r
1867         return yourls_apply_filter( 'get_request', $request );\r
1868 }\r
1869 \r
1870 // Change protocol to match current scheme used (http or https)\r
1871 function yourls_match_current_protocol( $url, $normal = 'http', $ssl = 'https' ) {\r
1872         if( yourls_is_ssl() )\r
1873                 $url = str_replace( $normal, $ssl, $url );\r
1874         return $url;\r
1875 }\r
1876 \r
1877 // Fix $_SERVER['REQUEST_URI'] variable for various setups. Stolen from WP.\r
1878 function yourls_fix_request_uri() {\r
1879 \r
1880         $default_server_values = array(\r
1881                 'SERVER_SOFTWARE' => '',\r
1882                 'REQUEST_URI' => '',\r
1883         );\r
1884         $_SERVER = array_merge( $default_server_values, $_SERVER );\r
1885 \r
1886         // Fix for IIS when running with PHP ISAPI\r
1887         if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {\r
1888 \r
1889                 // IIS Mod-Rewrite\r
1890                 if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {\r
1891                         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];\r
1892                 }\r
1893                 // IIS Isapi_Rewrite\r
1894                 else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {\r
1895                         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];\r
1896                 } else {\r
1897                         // Use ORIG_PATH_INFO if there is no PATH_INFO\r
1898                         if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )\r
1899                                 $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];\r
1900 \r
1901                         // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)\r
1902                         if ( isset( $_SERVER['PATH_INFO'] ) ) {\r
1903                                 if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )\r
1904                                         $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];\r
1905                                 else\r
1906                                         $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];\r
1907                         }\r
1908 \r
1909                         // Append the query string if it exists and isn't null\r
1910                         if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {\r
1911                                 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];\r
1912                         }\r
1913                 }\r
1914         }\r
1915 }\r