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