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