7 if (defined('YOURLS_DEBUG') && YOURLS_DEBUG == true) {
\r
8 error_reporting(E_ALL);
\r
10 error_reporting(E_ERROR | E_PARSE);
\r
13 // function to convert an integer (1337) to a string (3jk). Input integer processed as a string to beat PHP's int max value
\r
14 function yourls_int2string( $id ) {
\r
15 $str = yourls_base2base(trim(strval($id)), 10, YOURLS_URL_CONVERT);
\r
16 if (YOURLS_URL_CONVERT <= 37)
\r
17 $str = strtolower($str);
\r
21 // function to convert a string (3jk) to an integer (1337)
\r
22 function yourls_string2int( $str ) {
\r
23 if (YOURLS_URL_CONVERT <= 37)
\r
24 $str = strtolower($str);
\r
25 return yourls_base2base(trim($str), YOURLS_URL_CONVERT, 10);
\r
28 // Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.
\r
29 function yourls_sanitize_string($in) {
\r
30 if (YOURLS_URL_CONVERT <= 37)
\r
31 $in = strtolower($in);
\r
32 return substr(preg_replace('/[^a-zA-Z0-9]/', '', $in), 0, 199);
\r
35 // Alias function. I was always getting it wrong.
\r
36 function yourls_sanitize_keyword( $keyword ) {
\r
37 return yourls_sanitize_string( $keyword );
\r
40 // A few sanity checks on the URL
\r
41 function yourls_sanitize_url($url) {
\r
42 // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
\r
43 $url = str_replace('http://http://', 'http://', $url);
\r
45 // make sure there's a protocol, add http:// if not
\r
46 if ( !preg_match('!^([a-zA-Z]+://)!', $url ) )
\r
47 $url = 'http://'.$url;
\r
49 $url = yourls_clean_url($url);
\r
51 return substr( $url, 0, 1999 );
\r
54 // Function to filter all invalid characters from a URL. Stolen from WP's clean_url()
\r
55 function yourls_clean_url( $url ) {
\r
56 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'"()\\x80-\\xff]|i', '', $url );
\r
57 $strip = array('%0d', '%0a', '%0D', '%0A');
\r
58 $url = yourls_deep_replace($strip, $url);
\r
59 $url = str_replace(';//', '://', $url);
\r
60 $url = str_replace('&', '&', $url); // Revert & not to break query strings
\r
65 // Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''
\r
66 // Stolen from WP's _deep_replace
\r
67 function yourls_deep_replace($search, $subject){
\r
71 foreach( (array) $search as $val ) {
\r
72 while(strpos($subject, $val) !== false) {
\r
74 $subject = str_replace($val, '', $subject);
\r
82 // Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)
\r
83 // TODO FIXME FFS: unused ?
\r
84 function yourls_sanitize_int($in) {
\r
85 return ( substr(preg_replace('/[^0-9]/', '', strval($in) ), 0, 20) );
\r
88 // Make sure a integer is safe
\r
89 // Note: this is not checking for integers, since integers on 32bits system are way too limited
\r
90 // TODO: find a way to validate as integer
\r
91 function yourls_intval($in) {
\r
92 return mysql_real_escape_string($in);
\r
96 function yourls_escape( $in ) {
\r
97 return mysql_real_escape_string($in);
\r
100 // Check to see if a given keyword is reserved (ie reserved URL or an existing page)
\r
102 function yourls_keyword_is_reserved( $keyword ) {
\r
103 global $yourls_reserved_URL;
\r
105 if ( in_array( $keyword, $yourls_reserved_URL)
\r
106 or file_exists(dirname(dirname(__FILE__))."/pages/$keyword.php")
\r
107 or is_dir(dirname(dirname(__FILE__))."/$keyword")
\r
114 // Function: Get IP Address. Returns a DB safe string.
\r
115 function yourls_get_IP() {
\r
116 if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
\r
117 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
\r
118 } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
\r
119 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
\r
120 } else if(!empty($_SERVER['REMOTE_ADDR'])) {
\r
121 $ip_address = $_SERVER['REMOTE_ADDR'];
\r
125 if(strpos($ip_address, ',') !== false) {
\r
126 $ip_address = explode(',', $ip_address);
\r
127 $ip_address = $ip_address[0];
\r
130 $ip_address = yourls_sanitize_ip( $ip_address );
\r
132 return $ip_address;
\r
135 // Sanitize an IP address
\r
136 function yourls_sanitize_ip( $ip ) {
\r
137 return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
\r
140 // Add the "Edit" row
\r
141 function yourls_table_edit_row( $keyword ) {
\r
144 $table = YOURLS_DB_TABLE_URL;
\r
145 $keyword = yourls_sanitize_string( $keyword );
\r
146 $id = yourls_string2int( $keyword ); // used as HTML #id
\r
147 $url = $ydb->get_row("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");
\r
148 $safe_url = stripslashes( $url->url );
\r
149 $www = YOURLS_SITE;
\r
152 $return = <<<RETURN
\r
153 <tr id="edit-$id" class="edit-row"><td colspan="5"><strong>Original URL</strong>:<input type="text" id="edit-url-$id" name="edit-url-$id" value="$safe_url" class="text" size="70" /> <strong>Short URL</strong>: $www/<input type="text" id="edit-keyword-$id" name="edit-keyword-$id" value="$keyword" class="text" size="10" /></td><td colspan="1"><input type="button" id="edit-submit-$id" name="edit-submit-$id" value="Save" title="Save new values" class="button" onclick="edit_save('$id');" /> <input type="button" id="edit-close-$id" name="edit-close-$id" value="X" title="Cancel editing" class="button" onclick="hide_edit('$id');" /><input type="hidden" id="old_keyword_$id" value="$keyword"/></td></tr>
\r
156 $return = '<tr><td colspan="6">Error, URL not found</td></tr>';
\r
163 function yourls_table_add_row( $keyword, $url, $ip, $clicks, $timestamp ) {
\r
164 $keyword = yourls_sanitize_string( $keyword );
\r
165 $id = yourls_string2int( $keyword ); // used as HTML #id
\r
166 $date = date( 'M d, Y H:i', $timestamp+( YOURLS_HOURS_OFFSET * 3600) );
\r
167 $clicks = number_format($clicks, 0, '', '');
\r
168 $shorturl = YOURLS_SITE.'/'.$keyword;
\r
169 $display_url = htmlentities( yourls_trim_long_string( $url ) );
\r
170 $statlink = $shorturl.'+';
\r
171 $url = htmlentities( $url );
\r
174 <tr id="id-$id"><td id="keyword-$id"><a href="$shorturl">$keyword</a></td><td id="url-$id"><a href="$url" title="$url">$display_url</a></td><td id="timestamp-$id">$date</td><td id="ip-$id">$ip</td><td id="clicks-$id">$clicks</td><td class="actions" id="actions-$id"><a href="$statlink" id="statlink-$id" class="button button_stats"> </a> <input type="button" id="edit-button-$id" name="edit-button" value="" title="Edit" class="button button_edit" onclick="edit('$id');" /> <input type="button" id="delete-button-$id" name="delete-button" value="" title="Delete" class="button button_delete" onclick="remove('$id');" /><input type="hidden" id="keyword_$id" value="$keyword"/></td></tr>
\r
178 // Get next id a new link will have if no custom keyword provided
\r
179 function yourls_get_next_decimal() {
\r
180 return (int)yourls_get_option( 'next_id' );
\r
183 // Update id for next link with no custom keyword
\r
184 function yourls_update_next_decimal( $int = '' ) {
\r
185 $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
\r
186 return yourls_update_option( 'next_id', $int );
\r
189 // Delete a link in the DB
\r
190 function yourls_delete_link_by_keyword( $keyword ) {
\r
193 $table = YOURLS_DB_TABLE_URL;
\r
194 $keyword = yourls_sanitize_string( $keyword );
\r
195 return $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
\r
198 // SQL query to insert a new link in the DB. Needs sanitized data. Returns boolean for success or failure of the inserting
\r
199 function yourls_insert_link_in_db($url, $keyword) {
\r
202 $table = YOURLS_DB_TABLE_URL;
\r
203 $timestamp = date('Y-m-d H:i:s');
\r
204 $ip = yourls_get_IP();
\r
205 $insert = $ydb->query("INSERT INTO `$table` VALUES('$keyword', '$url', '$timestamp', '$ip', 0);");
\r
207 return (bool)$insert;
\r
210 // Add a new link in the DB, either with custom keyword, or find one
\r
211 function yourls_add_new_link( $url, $keyword = '' ) {
\r
214 if ( !$url || $url == 'http://' || $url == 'https://' ) {
\r
215 $return['status'] = 'fail';
\r
216 $return['code'] = 'error:nourl';
\r
217 $return['message'] = 'Missing URL input';
\r
218 $return['errorCode'] = '400';
\r
222 // Prevent DB flood
\r
223 $ip = yourls_get_IP();
\r
224 yourls_check_IP_flood( $ip );
\r
226 $table = YOURLS_DB_TABLE_URL;
\r
227 $url = mysql_real_escape_string( yourls_sanitize_url($url) );
\r
228 $strip_url = stripslashes($url);
\r
229 $url_exists = $ydb->get_row("SELECT keyword,url FROM `$table` WHERE `url` = '".$strip_url."';");
\r
232 // New URL : store it -- or: URL exists, but duplicates allowed
\r
233 if( !$url_exists || yourls_allow_duplicate_longurls() ) {
\r
235 // Custom keyword provided
\r
237 $keyword = mysql_real_escape_string(yourls_sanitize_string($keyword));
\r
238 if ( !yourls_keyword_is_free($keyword) ) {
\r
239 // This shorturl either reserved or taken already
\r
240 $return['status'] = 'fail';
\r
241 $return['code'] = 'error:keyword';
\r
242 $return['message'] = 'Short URL '.$keyword.' already exists in database or is reserved';
\r
244 // all clear, store !
\r
245 yourls_insert_link_in_db($url, $keyword);
\r
246 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
\r
247 $return['status'] = 'success';
\r
248 $return['message'] = $strip_url.' added to database';
\r
249 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );
\r
250 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
253 // Create random keyword
\r
255 $timestamp = date('Y-m-d H:i:s');
\r
256 $id = yourls_get_next_decimal();
\r
259 $keyword = yourls_int2string( $id );
\r
260 $free = yourls_keyword_is_free($keyword);
\r
261 $add_url = @yourls_insert_link_in_db($url, $keyword);
\r
262 $ok = ($free && $add_url);
\r
263 if ( $ok === false && $add_url === 1 ) {
\r
264 // we stored something, but shouldn't have (ie reserved id)
\r
265 $delete = yourls_delete_link_by_keyword( $keyword );
\r
266 $return['extra_info'] .= '(deleted '.$keyword.')';
\r
268 // everything ok, populate needed vars
\r
269 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => $timestamp, 'ip' => $ip );
\r
270 $return['status'] = 'success';
\r
271 $return['message'] = $strip_url.' added to database';
\r
272 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );
\r
273 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
277 @yourls_update_next_decimal($id);
\r
280 // URL was already stored
\r
281 $return['status'] = 'fail';
\r
282 $return['code'] = 'error:url';
\r
283 $return['message'] = $strip_url.' already exists in database';
\r
284 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
\r
287 $return['statusCode'] = 200; // regardless of result, this is still a valid request
\r
293 function yourls_edit_link($url, $keyword, $newkeyword='') {
\r
296 $table = YOURLS_DB_TABLE_URL;
\r
297 $url = mysql_real_escape_string(yourls_sanitize_url($url));
\r
298 $keyword = yourls_sanitize_string( $keyword );
\r
299 $newkeyword = yourls_sanitize_string( $newkeyword );
\r
300 $strip_url = stripslashes($url);
\r
301 $old_url = $ydb->get_var("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");
\r
302 $old_id = $id = yourls_string2int( $keyword );
\r
303 $new_id = ( $newkeyword == '' ? $old_id : yourls_string2int( $newkeyword ) );
\r
305 // Check if new URL is not here already
\r
306 if ($old_url != $url) {
\r
307 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
\r
309 $new_url_already_there = false;
\r
312 // Check if the new keyword is not here already
\r
313 if ( $newkeyword != $keyword ) {
\r
314 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
\r
316 $keyword_is_ok = true;
\r
319 // All clear, update
\r
320 if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
\r
321 $update_url = $ydb->query("UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword' WHERE `keyword` = '$keyword';");
\r
322 if( $update_url ) {
\r
323 $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'new_id' => $new_id );
\r
324 $return['status'] = 'success';
\r
325 $return['message'] = 'Link updated in database';
\r
327 $return['status'] = 'fail';
\r
328 $return['message'] = 'Error updating '.$strip_url.' (Short URL: '.$keyword.') to database';
\r
333 $return['status'] = 'fail';
\r
334 $return['message'] = 'URL or keyword already exists in database';
\r
341 // Check if keyword id is free (ie not already taken, and not reserved)
\r
342 function yourls_keyword_is_free( $keyword ) {
\r
345 if ( yourls_keyword_is_reserved($keyword) )
\r
348 $table = YOURLS_DB_TABLE_URL;
\r
349 $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");
\r
350 if ( $already_exists )
\r
358 function yourls_page( $page ) {
\r
359 $include = dirname(dirname(__FILE__))."/pages/$page.php";
\r
360 if (!file_exists($include)) {
\r
361 yourls_die("Page '$page' not found", 'Not found', 404);
\r
368 function yourls_db_connect() {
\r
371 if (!defined('YOURLS_DB_USER')
\r
372 or !defined('YOURLS_DB_PASS')
\r
373 or !defined('YOURLS_DB_NAME')
\r
374 or !defined('YOURLS_DB_HOST')
\r
375 or !class_exists('ezSQL_mysql')
\r
376 ) yourls_die ('DB config missigin, or could not find DB class', 'Fatal error', 503);
\r
378 // Are we standalone or in the WordPress environment?
\r
379 if ( class_exists('wpdb') ) {
\r
380 $ydb = new wpdb(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);
\r
382 $ydb = new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);
\r
384 if ( $ydb->last_error )
\r
385 yourls_die( $ydb->last_error, 'Fatal error', 503 );
\r
387 if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )
\r
388 $ydb->show_errors = true;
\r
393 // Return JSON output. Compatible with PHP prior to 5.2
\r
394 function yourls_json_encode($array) {
\r
395 if (function_exists('json_encode')) {
\r
396 return json_encode($array);
\r
398 require_once(dirname(__FILE__).'/functions-json.php');
\r
399 return yourls_array_to_json($array);
\r
403 // Return XML output.
\r
404 function yourls_xml_encode($array) {
\r
405 require_once(dirname(__FILE__).'/functions-xml.php');
\r
406 $converter= new yourls_array2xml;
\r
407 return $converter->array2xml($array);
\r
410 // 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
411 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
\r
413 $keyword = yourls_sanitize_string( $keyword );
\r
415 if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
\r
416 return $ydb->infos[$keyword];
\r
419 $table = YOURLS_DB_TABLE_URL;
\r
420 $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");
\r
423 $infos = (array)$infos;
\r
424 $ydb->infos[$keyword] = $infos;
\r
426 $ydb->infos[$keyword] = false;
\r
429 return $ydb->infos[$keyword];
\r
432 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
\r
433 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
\r
436 $keyword = yourls_sanitize_string( $keyword );
\r
437 $infos = yourls_get_keyword_infos( $keyword );
\r
439 if ( isset($infos[$field]) && $infos[$field] !== false )
\r
440 return $infos[$field];
\r
445 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found
\r
446 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
\r
447 return yourls_get_keyword_info( $keyword, 'url', $notfound );
\r
450 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
\r
451 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
\r
452 return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
\r
455 // Return IP that added a keyword. Optional $notfound = string default message if nothing found
\r
456 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
\r
457 return yourls_get_keyword_info( $keyword, 'ip', $notfound );
\r
460 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
\r
461 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
\r
462 return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
\r
465 // Update click count on a short URL
\r
466 function yourls_update_clicks( $keyword ) {
\r
468 $keyword = yourls_sanitize_string( $keyword );
\r
469 $table = YOURLS_DB_TABLE_URL;
\r
470 return $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");
\r
473 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
\r
474 function yourls_get_links_stats( $filter = 'top', $limit = 10 ) {
\r
477 switch( $filter ) {
\r
479 $sort_by = 'clicks';
\r
480 $sort_order = 'asc';
\r
483 $sort_by = 'timestamp';
\r
484 $sort_order = 'desc';
\r
488 $sort_by = 'RAND()';
\r
493 $sort_by = 'clicks';
\r
494 $sort_order = 'desc';
\r
498 $limit = intval( $limit );
\r
501 $table_url = YOURLS_DB_TABLE_URL;
\r
502 $results = $ydb->get_results("SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT 0, $limit;");
\r
507 foreach ($results as $res) {
\r
508 $return['links']['link_'.$i++] = array(
\r
509 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
\r
510 'url' => $res->url,
\r
511 'timestamp' => $res->timestamp,
\r
513 'clicks' => $res->clicks,
\r
517 $return['stats'] = yourls_get_db_stats();
\r
519 $return['statusCode'] = 200;
\r
525 // Return array for API stat requests
\r
526 function yourls_api_stats( $filter = 'top', $limit = 10 ) {
\r
527 $return = yourls_get_links_stats( $filter, $limit );
\r
528 $return['simple'] = 'Need either XML or JSON format for stats';
\r
529 $return['message'] = 'success';
\r
533 // Expand short url to long url
\r
534 function yourls_api_expand( $shorturl ) {
\r
535 $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'
\r
536 $keyword = yourls_sanitize_string( $keyword );
\r
538 $longurl = yourls_get_keyword_longurl( $keyword );
\r
542 'keyword' => $keyword,
\r
543 'shorturl' => YOURLS_SITE . "/$keyword",
\r
544 'longurl' => $longurl,
\r
545 'simple' => $longurl,
\r
546 'message' => 'success',
\r
547 'statusCode' => 200,
\r
551 'keyword' => $keyword,
\r
552 'simple' => 'not found',
\r
553 'message' => 'Error: short URL not found',
\r
554 'errorCode' => 404,
\r
560 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
\r
561 function yourls_get_db_stats( $where = '' ) {
\r
563 $table_url = YOURLS_DB_TABLE_URL;
\r
565 $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");
\r
566 return array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
\r
569 // Return API result. Dies after this
\r
570 function yourls_api_output( $mode, $return ) {
\r
571 if( isset( $return['simple'] ) ) {
\r
572 $simple = $return['simple'];
\r
573 unset( $return['simple'] );
\r
577 header('Content-type: application/json');
\r
578 echo yourls_json_encode($return);
\r
582 header('Content-type: application/xml');
\r
583 echo yourls_xml_encode($return);
\r
588 if( isset( $simple ) )
\r
595 // Get number of SQL queries performed
\r
596 function yourls_get_num_queries() {
\r
599 return $ydb->num_queries;
\r
602 // Compat http_build_query for PHP4
\r
603 if (!function_exists('http_build_query')) {
\r
604 function http_build_query($data, $prefix=null, $sep=null) {
\r
605 return yourls_http_build_query($data, $prefix, $sep);
\r
609 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
\r
610 function yourls_http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
\r
613 foreach ( (array) $data as $k => $v ) {
\r
615 $k = urlencode($k);
\r
616 if ( is_int($k) && $prefix != null )
\r
618 if ( !empty($key) )
\r
619 $k = $key . '%5B' . $k . '%5D';
\r
622 elseif ( $v === FALSE )
\r
625 if ( is_array($v) || is_object($v) )
\r
626 array_push($ret,yourls_http_build_query($v, '', $sep, $k, $urlencode));
\r
627 elseif ( $urlencode )
\r
628 array_push($ret, $k.'='.urlencode($v));
\r
630 array_push($ret, $k.'='.$v);
\r
633 if ( NULL === $sep )
\r
634 $sep = ini_get('arg_separator.output');
\r
636 return implode($sep, $ret);
\r
639 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
\r
640 function yourls_get_user_agent() {
\r
641 if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
\r
644 $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
\r
645 $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
\r
647 return substr( $ua, 0, 254 );
\r
650 // Redirect to another page
\r
651 function yourls_redirect( $location, $code = 301 ) {
\r
652 // Redirect, either properly if possible, or via Javascript otherwise
\r
653 if( !headers_sent() ) {
\r
654 yourls_status_header( $code );
\r
655 header("Location: $location");
\r
657 yourls_redirect_javascript( $location );
\r
662 // Set HTTP status header
\r
663 function yourls_status_header( $code = 200 ) {
\r
664 if( headers_sent() )
\r
667 $protocol = $_SERVER["SERVER_PROTOCOL"];
\r
668 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
\r
669 $protocol = 'HTTP/1.0';
\r
671 $code = intval( $code );
\r
672 $desc = yourls_get_HTTP_status($code);
\r
674 @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
\r
677 // 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
678 function yourls_redirect_javascript( $location, $dontwait = true ) {
\r
681 <script type="text/javascript">
\r
682 window.location="$location";
\r
684 <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>
\r
688 <p>Please <a href="$location">click here</a></p>
\r
693 // Return a HTTP status code
\r
694 function yourls_get_HTTP_status( $code ) {
\r
695 $code = intval( $code );
\r
696 $headers_desc = array(
\r
698 101 => 'Switching Protocols',
\r
699 102 => 'Processing',
\r
704 203 => 'Non-Authoritative Information',
\r
705 204 => 'No Content',
\r
706 205 => 'Reset Content',
\r
707 206 => 'Partial Content',
\r
708 207 => 'Multi-Status',
\r
711 300 => 'Multiple Choices',
\r
712 301 => 'Moved Permanently',
\r
714 303 => 'See Other',
\r
715 304 => 'Not Modified',
\r
716 305 => 'Use Proxy',
\r
718 307 => 'Temporary Redirect',
\r
720 400 => 'Bad Request',
\r
721 401 => 'Unauthorized',
\r
722 402 => 'Payment Required',
\r
723 403 => 'Forbidden',
\r
724 404 => 'Not Found',
\r
725 405 => 'Method Not Allowed',
\r
726 406 => 'Not Acceptable',
\r
727 407 => 'Proxy Authentication Required',
\r
728 408 => 'Request Timeout',
\r
731 411 => 'Length Required',
\r
732 412 => 'Precondition Failed',
\r
733 413 => 'Request Entity Too Large',
\r
734 414 => 'Request-URI Too Long',
\r
735 415 => 'Unsupported Media Type',
\r
736 416 => 'Requested Range Not Satisfiable',
\r
737 417 => 'Expectation Failed',
\r
738 422 => 'Unprocessable Entity',
\r
740 424 => 'Failed Dependency',
\r
741 426 => 'Upgrade Required',
\r
743 500 => 'Internal Server Error',
\r
744 501 => 'Not Implemented',
\r
745 502 => 'Bad Gateway',
\r
746 503 => 'Service Unavailable',
\r
747 504 => 'Gateway Timeout',
\r
748 505 => 'HTTP Version Not Supported',
\r
749 506 => 'Variant Also Negotiates',
\r
750 507 => 'Insufficient Storage',
\r
751 510 => 'Not Extended'
\r
754 if ( isset( $headers_desc[$code] ) )
\r
755 return $headers_desc[$code];
\r
761 // Log a redirect (for stats)
\r
762 function yourls_log_redirect( $keyword ) {
\r
763 if ( !yourls_do_log_redirect() )
\r
767 $table = YOURLS_DB_TABLE_LOG;
\r
769 $keyword = yourls_sanitize_string( $keyword );
\r
770 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
\r
771 $ua = yourls_get_user_agent();
\r
772 $ip = yourls_get_IP();
\r
773 $location = yourls_geo_ip_to_countrycode( $ip );
\r
775 return $ydb->query( "INSERT INTO `$table` VALUES ('', NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
\r
778 // Check if we want to not log redirects (for stats)
\r
779 function yourls_do_log_redirect() {
\r
780 return ( !defined('YOURLS_NOSTATS') || YOURLS_NOSTATS != true );
\r
783 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
\r
784 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
\r
785 if ( !file_exists( dirname(__FILE__).'/geo/GeoIP.dat') || !file_exists( dirname(__FILE__).'/geo/geoip.inc') )
\r
789 $ip = yourls_get_IP();
\r
791 require_once( dirname(__FILE__).'/geo/geoip.inc') ;
\r
792 $gi = geoip_open( dirname(__FILE__).'/geo/GeoIP.dat', GEOIP_STANDARD);
\r
793 $location = geoip_country_code_by_addr($gi, $ip);
\r
799 // Converts a 2 letter country code to long name (ie AU -> Australia)
\r
800 function yourls_geo_countrycode_to_countryname( $code ) {
\r
801 // Load the Geo class if not already done
\r
802 if( !class_exists('GeoIP') ) {
\r
803 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');
\r
806 if( class_exists('GeoIP') ) {
\r
808 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];
\r
809 $long = $geo->GEOIP_COUNTRY_NAMES[$id];
\r
816 // Return flag URL from 2 letter country code
\r
817 function yourls_geo_get_flag( $code ) {
\r
818 // Load the Geo class if not already done
\r
819 if( !class_exists('GeoIP') ) {
\r
820 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');
\r
823 if( class_exists('GeoIP') ) {
\r
824 return YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif';
\r
831 // Check if an upgrade is needed
\r
832 function yourls_upgrade_is_needed() {
\r
833 // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
\r
834 list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
\r
835 if( $currentsql < YOURLS_DB_VERSION )
\r
841 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
\r
842 function yourls_get_current_version_from_sql() {
\r
843 $currentver = yourls_get_option( 'version' );
\r
844 $currentsql = yourls_get_option( 'db_version' );
\r
846 // Values if version is 1.3
\r
848 $currentver = '1.3';
\r
850 $currentsql = '100';
\r
852 return array( $currentver, $currentsql);
\r
855 // Read an option from DB (or from cache if available). Return value or $default if not found
\r
856 function yourls_get_option( $option_name, $default = false ) {
\r
858 if ( !isset( $ydb->option[$option_name] ) ) {
\r
859 $table = YOURLS_DB_TABLE_OPTIONS;
\r
860 $option_name = yourls_escape( $option_name );
\r
861 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
\r
862 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
\r
863 $value = $row->option_value;
\r
864 } else { // option does not exist, so we must cache its non-existence
\r
867 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );
\r
870 return $ydb->option[$option_name];
\r
873 // Read all options from DB at once
\r
874 function yourls_get_all_options() {
\r
876 $table = YOURLS_DB_TABLE_OPTIONS;
\r
878 $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");
\r
880 foreach( (array)$allopt as $option ) {
\r
881 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );
\r
885 // Update (add if doesn't exist) an option to DB
\r
886 function yourls_update_option( $option_name, $newvalue ) {
\r
888 $table = YOURLS_DB_TABLE_OPTIONS;
\r
890 $safe_option_name = yourls_escape( $option_name );
\r
892 $oldvalue = yourls_get_option( $safe_option_name );
\r
894 // If the new and old values are the same, no need to update.
\r
895 if ( $newvalue === $oldvalue )
\r
898 if ( false === $oldvalue ) {
\r
899 yourls_add_option( $option_name, $newvalue );
\r
903 $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
\r
905 $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");
\r
907 if ( $ydb->rows_affected == 1 ) {
\r
908 $ydb->option[$option_name] = $newvalue;
\r
914 // Add an option to the DB
\r
915 function yourls_add_option( $name, $value = '' ) {
\r
917 $table = YOURLS_DB_TABLE_OPTIONS;
\r
918 $safe_name = yourls_escape( $name );
\r
920 // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
\r
921 if ( false !== yourls_get_option( $safe_name ) )
\r
924 $_value = yourls_escape( yourls_maybe_serialize( $value ) );
\r
926 $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
\r
927 $ydb->option[$name] = $value;
\r
932 // Delete an option from the DB
\r
933 function yourls_delete_option( $name ) {
\r
935 $table = YOURLS_DB_TABLE_OPTIONS;
\r
936 $name = yourls_escape( $name );
\r
938 // Get the ID, if no ID then return
\r
939 $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
\r
940 if ( is_null($option) || !$option->option_id )
\r
942 $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
\r
948 // Serialize data if needed. Stolen from WordPress
\r
949 function yourls_maybe_serialize( $data ) {
\r
950 if ( is_array( $data ) || is_object( $data ) )
\r
951 return serialize( $data );
\r
953 if ( yourls_is_serialized( $data ) )
\r
954 return serialize( $data );
\r
959 // Check value to find if it was serialized. Stolen from WordPress
\r
960 function yourls_is_serialized( $data ) {
\r
961 // if it isn't a string, it isn't serialized
\r
962 if ( !is_string( $data ) )
\r
964 $data = trim( $data );
\r
965 if ( 'N;' == $data )
\r
967 if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
\r
969 switch ( $badions[1] ) {
\r
973 if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
\r
979 if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
\r
986 // Unserialize value only if it was serialized. Stolen from WP
\r
987 function yourls_maybe_unserialize( $original ) {
\r
988 if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
\r
989 return @unserialize( $original );
\r
993 // Determine if the current page is private
\r
994 function yourls_is_private() {
\r
995 if (defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true) {
\r
997 // Allow overruling of particular pages
\r
998 $current = basename( $_SERVER["SCRIPT_NAME"] );
\r
1000 switch( $current ) {
\r
1002 case 'yourls-api.php':
\r
1003 if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
\r
1007 case 'yourls-infos.php':
\r
1008 if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
\r
1021 // Show login form if required
\r
1022 function yourls_maybe_require_auth() {
\r
1023 if( yourls_is_private() )
\r
1024 require_once( dirname(__FILE__).'/auth.php' );
\r
1027 // Return word or words if more than one
\r
1028 function yourls_plural( $word, $count=1 ) {
\r
1029 return $word . ($count > 1 ? 's' : '');
\r
1032 // Return trimmed string
\r
1033 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {
\r
1034 if ( strlen( $string ) > $length ) {
\r
1035 $string = substr( $string, 0, $length - strlen( $append ) ) . $append;
\r
1040 // Allow several short URLs for the same long URL ?
\r
1041 function yourls_allow_duplicate_longurls() {
\r
1042 return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
\r
1045 // Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.
\r
1046 function yourls_get_duplicate_keywords( $longurl ) {
\r
1047 if( !yourls_allow_duplicate_longurls() )
\r
1051 $longurl = mysql_real_escape_string( yourls_sanitize_url($longurl) );
\r
1052 $table = YOURLS_DB_TABLE_URL;
\r
1054 return $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );
\r
1057 // Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
\r
1058 function yourls_check_IP_flood( $ip = '' ) {
\r
1060 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
\r
1061 !defined('YOURLS_FLOOD_DELAY_SECONDS')
\r
1065 $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
\r
1067 // Don't throttle whitelist IPs
\r
1068 if( defined('YOURLS_FLOOD_IP_WHITELIST' && YOURLS_FLOOD_IP_WHITELIST ) ) {
\r
1069 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
\r
1070 foreach( $whitelist_ips as $whitelist_ip ) {
\r
1071 $whitelist_ip = trim( $whitelist_ip );
\r
1072 if ( $whitelist_ip == $ip )
\r
1077 // Don't throttle logged in users
\r
1078 if( yourls_is_private() ) {
\r
1079 if( yourls_is_valid_user() === true )
\r
1084 $table = YOURLS_DB_TABLE_URL;
\r
1086 $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
\r
1088 $now = date( 'U' );
\r
1089 $then = date( 'U', strtotime( $lasttime ) );
\r
1090 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
\r
1092 yourls_die( 'Too many URLs added too fast. Slow down please.', 'Forbidden', 403 );
\r
1099 // Check if YOURLS is installed
\r
1100 function yourls_is_installed() {
\r
1101 static $is_installed = false;
\r
1102 if ( $is_installed === false ) {
\r
1103 $check_14 = $check_13 = false;
\r
1105 if( defined('YOURLS_DB_TABLE_NEXTDEC') )
\r
1106 $check_13 = $ydb->get_var('SELECT next_id FROM '.YOURLS_DB_TABLE_NEXTDEC);
\r
1107 $check_14 = yourls_get_option( 'version' );
\r
1108 $is_installed = $check_13 || $check_14;
\r
1110 return $is_installed;
\r
1113 // Compat for PHP < 5.1
\r
1114 if ( !function_exists('htmlspecialchars_decode') ) {
\r
1115 function htmlspecialchars_decode($text) {
\r
1116 return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
\r
1120 // Generate random string of (int)$lenght length and type $type (see function for details)
\r
1121 function yourls_rnd_string ( $length = 5, $type = 1 ) {
\r
1123 $length = intval( $length );
\r
1125 // define possible characters
\r
1126 switch ( $type ) {
\r
1127 // no vowels to make no offending word, no 0 or 1 to avoid confusion betwee letters & digits. Perfect for passwords.
\r
1129 $possible = "23456789bcdfghjkmnpqrstvwxyz";
\r
1132 // all letters, lowercase
\r
1134 $possible = "abcdefghijklmnopqrstuvwxyz";
\r
1137 // all letters, lowercase + uppercase
\r
1139 $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1142 // all digits & letters lowercase
\r
1144 $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
\r
1147 // all digits & letters lowercase + uppercase
\r
1149 $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1155 while ($i < $length) {
\r
1156 $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
\r
1163 // Return salted string
\r
1164 function yourls_salt( $string ) {
\r
1165 $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
\r
1166 return md5 ($string . $salt);
\r
1169 // Return a time-dependent string for nonce creation
\r
1170 function yourls_tick() {
\r
1171 return ceil( time() / YOURLS_NONCE_LIFE );
\r
1174 // Create a time limited, action limited and user limited token
\r
1175 function yourls_create_nonce( $action = '-1', $user = false ) {
\r
1176 if( false == $user )
\r
1177 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
\r
1178 $tick = yourls_tick();
\r
1179 return substr( yourls_salt($tick . $action . $user), 0, 10 );
\r
1182 // Check validity of a nonce (ie time span, user and action match)
\r
1183 function yourls_verify_nonce( $nonce, $action = -1, $user = false ) {
\r
1184 if( false == $user )
\r
1185 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
\r
1186 $valid = yourls_create_nonce( $action, $user );
\r
1188 return $nonce == $valid ;
\r
1191 // Sanitize a version number
\r
1192 function yourls_sanitize_version( $ver ) {
\r
1193 return preg_replace( '/[^0-9a-zA-Z-.]/', '', $ver );
\r
1196 // Converts keyword into short link
\r
1197 function yourls_link( $keyword = '' ) {
\r
1198 return YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
\r
1201 // Check if we're in API mode. Returns bool
\r
1202 function yourls_is_API() {
\r
1203 if ( defined('YOURLS_API') && YOURLS_API == true )
\r
1208 // Check if we're in Ajax mode. Returns bool
\r
1209 function yourls_is_Ajax() {
\r
1210 if ( defined('YOURLS_AJAX') && YOURLS_AJAX == true )
\r
1215 // Check if we're in GO mode. Returns bool
\r
1216 function yourls_is_GO() {
\r
1217 if ( defined('YOURLS_GO') && YOURLS_GO == true )
\r
1222 // Check if we'll need interface display function (ie not API or redirection)
\r
1223 function yourls_has_interface() {
\r
1224 if( yourls_is_API() or yourls_is_GO() or yourls_is_Ajax() )
\r
1229 // Check if we're in the admin area. Returns bool
\r
1230 function yourls_is_admin() {
\r
1231 if ( defined('YOURLS_ADMIN') && YOURLS_ADMIN == true )
\r
1236 // Check if SSL is required. Returns bool.
\r
1237 function yourls_needs_ssl() {
\r
1238 if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
\r
1243 // Return admin link, with SSL preference if applicable.
\r
1244 function yourls_admin_url( $page = '' ) {
\r
1245 $admin = YOURLS_SITE . '/admin/' . $page;
\r
1246 if( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
\r
1247 $admin = str_replace('http://', 'https://', $admin);
\r
1251 // Check if SSL is used, returns bool. Stolen from WP.
\r
1252 function yourls_is_ssl() {
\r
1253 if ( isset($_SERVER['HTTPS']) ) {
\r
1254 if ( 'on' == strtolower($_SERVER['HTTPS']) )
\r
1256 if ( '1' == $_SERVER['HTTPS'] )
\r
1258 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
\r