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 yourls_escape($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
104 $keyword = yourls_sanitize_keyword( $keyword );
\r
106 if ( in_array( $keyword, $yourls_reserved_URL)
\r
107 or file_exists(dirname(dirname(__FILE__))."/pages/$keyword.php")
\r
108 or is_dir(dirname(dirname(__FILE__))."/$keyword")
\r
115 // Function: Get IP Address. Returns a DB safe string.
\r
116 function yourls_get_IP() {
\r
117 if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
\r
118 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
\r
119 } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
\r
120 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
\r
121 } else if(!empty($_SERVER['REMOTE_ADDR'])) {
\r
122 $ip_address = $_SERVER['REMOTE_ADDR'];
\r
126 if(strpos($ip_address, ',') !== false) {
\r
127 $ip_address = explode(',', $ip_address);
\r
128 $ip_address = $ip_address[0];
\r
131 $ip_address = yourls_sanitize_ip( $ip_address );
\r
133 return $ip_address;
\r
136 // Sanitize an IP address
\r
137 function yourls_sanitize_ip( $ip ) {
\r
138 return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
\r
141 // Make sure a date is m(m)/d(d)/yyyy, return false otherwise
\r
142 function yourls_sanitize_date( $date ) {
\r
143 if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {
\r
149 // Sanitize a date for SQL search. Return false if malformed input.
\r
150 function yourls_sanitize_date_for_sql( $date ) {
\r
151 if( !yourls_sanitize_date( $date ) )
\r
153 return date('Y-m-d', strtotime( $date ) );
\r
156 // Add the "Edit" row
\r
157 function yourls_table_edit_row( $keyword ) {
\r
160 $table = YOURLS_DB_TABLE_URL;
\r
161 $keyword = yourls_sanitize_string( $keyword );
\r
162 $id = yourls_string2int( $keyword ); // used as HTML #id
\r
163 $url = $ydb->get_row("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");
\r
164 $safe_url = stripslashes( $url->url );
\r
165 $www = YOURLS_SITE;
\r
168 $return = <<<RETURN
\r
169 <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
172 $return = '<tr><td colspan="6">Error, URL not found</td></tr>';
\r
179 function yourls_table_add_row( $keyword, $url, $ip, $clicks, $timestamp ) {
\r
180 $keyword = yourls_sanitize_string( $keyword );
\r
181 $id = yourls_string2int( $keyword ); // used as HTML #id
\r
182 $date = date( 'M d, Y H:i', $timestamp+( YOURLS_HOURS_OFFSET * 3600) );
\r
183 $clicks = number_format($clicks, 0, '', '');
\r
184 $shorturl = YOURLS_SITE.'/'.$keyword;
\r
185 $display_url = htmlentities( yourls_trim_long_string( $url ) );
\r
186 $statlink = $shorturl.'+';
\r
187 $url = htmlentities( $url );
\r
190 <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
194 // Get next id a new link will have if no custom keyword provided
\r
195 function yourls_get_next_decimal() {
\r
196 return (int)yourls_get_option( 'next_id' );
\r
199 // Update id for next link with no custom keyword
\r
200 function yourls_update_next_decimal( $int = '' ) {
\r
201 $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
\r
202 return yourls_update_option( 'next_id', $int );
\r
205 // Delete a link in the DB
\r
206 function yourls_delete_link_by_keyword( $keyword ) {
\r
209 $table = YOURLS_DB_TABLE_URL;
\r
210 $keyword = yourls_sanitize_string( $keyword );
\r
211 return $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
\r
214 // SQL query to insert a new link in the DB. Needs sanitized data. Returns boolean for success or failure of the inserting
\r
215 function yourls_insert_link_in_db($url, $keyword) {
\r
218 $table = YOURLS_DB_TABLE_URL;
\r
219 $timestamp = date('Y-m-d H:i:s');
\r
220 $ip = yourls_get_IP();
\r
221 $insert = $ydb->query("INSERT INTO `$table` VALUES('$keyword', '$url', '$timestamp', '$ip', 0);");
\r
223 return (bool)$insert;
\r
226 // Add a new link in the DB, either with custom keyword, or find one
\r
227 function yourls_add_new_link( $url, $keyword = '' ) {
\r
230 if ( !$url || $url == 'http://' || $url == 'https://' ) {
\r
231 $return['status'] = 'fail';
\r
232 $return['code'] = 'error:nourl';
\r
233 $return['message'] = 'Missing URL input';
\r
234 $return['errorCode'] = '400';
\r
238 // Prevent DB flood
\r
239 $ip = yourls_get_IP();
\r
240 yourls_check_IP_flood( $ip );
\r
242 // TODO? Prevent internal redirection loops: cannot shorten a shortened URL
\r
243 // Could ban site.com/abc if 'abc' is already a taken keyword
\r
244 // and site.com/abc-def
\r
245 // Could allow site.com/abc+
\r
246 // and site.com/abc+all
\r
248 $url = yourls_escape( yourls_sanitize_url($url) );
\r
249 $table = YOURLS_DB_TABLE_URL;
\r
250 $strip_url = stripslashes($url);
\r
251 $url_exists = $ydb->get_row("SELECT keyword,url FROM `$table` WHERE `url` = '".$strip_url."';");
\r
254 // New URL : store it -- or: URL exists, but duplicates allowed
\r
255 if( !$url_exists || yourls_allow_duplicate_longurls() ) {
\r
257 // Custom keyword provided
\r
259 $keyword = yourls_escape( yourls_sanitize_string($keyword) );
\r
260 if ( !yourls_keyword_is_free($keyword) ) {
\r
261 // This shorturl either reserved or taken already
\r
262 $return['status'] = 'fail';
\r
263 $return['code'] = 'error:keyword';
\r
264 $return['message'] = 'Short URL '.$keyword.' already exists in database or is reserved';
\r
266 // all clear, store !
\r
267 yourls_insert_link_in_db($url, $keyword);
\r
268 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
\r
269 $return['status'] = 'success';
\r
270 $return['message'] = $strip_url.' added to database';
\r
271 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );
\r
272 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
275 // Create random keyword
\r
277 $timestamp = date('Y-m-d H:i:s');
\r
278 $id = yourls_get_next_decimal();
\r
281 $keyword = yourls_int2string( $id );
\r
282 $free = yourls_keyword_is_free($keyword);
\r
283 $add_url = @yourls_insert_link_in_db($url, $keyword);
\r
284 $ok = ($free && $add_url);
\r
285 if ( $ok === false && $add_url === 1 ) {
\r
286 // we stored something, but shouldn't have (ie reserved id)
\r
287 $delete = yourls_delete_link_by_keyword( $keyword );
\r
288 $return['extra_info'] .= '(deleted '.$keyword.')';
\r
290 // everything ok, populate needed vars
\r
291 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => $timestamp, 'ip' => $ip );
\r
292 $return['status'] = 'success';
\r
293 $return['message'] = $strip_url.' added to database';
\r
294 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );
\r
295 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
299 @yourls_update_next_decimal($id);
\r
302 // URL was already stored
\r
303 $return['status'] = 'fail';
\r
304 $return['code'] = 'error:url';
\r
305 $return['message'] = $strip_url.' already exists in database';
\r
306 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
\r
309 $return['statusCode'] = 200; // regardless of result, this is still a valid request
\r
315 function yourls_edit_link($url, $keyword, $newkeyword='') {
\r
318 $table = YOURLS_DB_TABLE_URL;
\r
319 $url = yourls_escape(yourls_sanitize_url($url));
\r
320 $keyword = yourls_sanitize_string( $keyword );
\r
321 $newkeyword = yourls_sanitize_string( $newkeyword );
\r
322 $strip_url = stripslashes($url);
\r
323 $old_url = $ydb->get_var("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");
\r
324 $old_id = $id = yourls_string2int( $keyword );
\r
325 $new_id = ( $newkeyword == '' ? $old_id : yourls_string2int( $newkeyword ) );
\r
327 // Check if new URL is not here already
\r
328 if ($old_url != $url) {
\r
329 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
\r
331 $new_url_already_there = false;
\r
334 // Check if the new keyword is not here already
\r
335 if ( $newkeyword != $keyword ) {
\r
336 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
\r
338 $keyword_is_ok = true;
\r
341 // All clear, update
\r
342 if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
\r
343 $update_url = $ydb->query("UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword' WHERE `keyword` = '$keyword';");
\r
344 if( $update_url ) {
\r
345 $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
346 $return['status'] = 'success';
\r
347 $return['message'] = 'Link updated in database';
\r
349 $return['status'] = 'fail';
\r
350 $return['message'] = 'Error updating '.$strip_url.' (Short URL: '.$keyword.') to database';
\r
355 $return['status'] = 'fail';
\r
356 $return['message'] = 'URL or keyword already exists in database';
\r
363 // Check if keyword id is free (ie not already taken, and not reserved). Return bool.
\r
364 function yourls_keyword_is_free( $keyword ) {
\r
365 if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
\r
371 // Check if a keyword is taken (ie there is already a short URL with this id). Return bool.
\r
372 function yourls_keyword_is_taken( $keyword ) {
\r
374 $keyword = yourls_sanitize_keyword( $keyword );
\r
376 $table = YOURLS_DB_TABLE_URL;
\r
377 $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");
\r
378 if ( $already_exists )
\r
386 function yourls_page( $page ) {
\r
387 $include = dirname(dirname(__FILE__))."/pages/$page.php";
\r
388 if (!file_exists($include)) {
\r
389 yourls_die("Page '$page' not found", 'Not found', 404);
\r
396 function yourls_db_connect() {
\r
399 if (!defined('YOURLS_DB_USER')
\r
400 or !defined('YOURLS_DB_PASS')
\r
401 or !defined('YOURLS_DB_NAME')
\r
402 or !defined('YOURLS_DB_HOST')
\r
403 or !class_exists('ezSQL_mysql')
\r
404 ) yourls_die ('DB config missigin, or could not find DB class', 'Fatal error', 503);
\r
406 // Are we standalone or in the WordPress environment?
\r
407 if ( class_exists('wpdb') ) {
\r
408 $ydb = new wpdb(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);
\r
410 $ydb = new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);
\r
412 if ( $ydb->last_error )
\r
413 yourls_die( $ydb->last_error, 'Fatal error', 503 );
\r
415 if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )
\r
416 $ydb->show_errors = true;
\r
421 // Return JSON output. Compatible with PHP prior to 5.2
\r
422 function yourls_json_encode($array) {
\r
423 if (function_exists('json_encode')) {
\r
424 return json_encode($array);
\r
426 require_once(dirname(__FILE__).'/functions-json.php');
\r
427 return yourls_array_to_json($array);
\r
431 // Return XML output.
\r
432 function yourls_xml_encode($array) {
\r
433 require_once(dirname(__FILE__).'/functions-xml.php');
\r
434 $converter= new yourls_array2xml;
\r
435 return $converter->array2xml($array);
\r
438 // 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
439 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
\r
441 $keyword = yourls_sanitize_string( $keyword );
\r
443 if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
\r
444 return $ydb->infos[$keyword];
\r
447 $table = YOURLS_DB_TABLE_URL;
\r
448 $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");
\r
451 $infos = (array)$infos;
\r
452 $ydb->infos[$keyword] = $infos;
\r
454 $ydb->infos[$keyword] = false;
\r
457 return $ydb->infos[$keyword];
\r
460 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
\r
461 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
\r
464 $keyword = yourls_sanitize_string( $keyword );
\r
465 $infos = yourls_get_keyword_infos( $keyword );
\r
467 if ( isset($infos[$field]) && $infos[$field] !== false )
\r
468 return $infos[$field];
\r
473 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found
\r
474 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
\r
475 return yourls_get_keyword_info( $keyword, 'url', $notfound );
\r
478 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
\r
479 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
\r
480 return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
\r
483 // Return IP that added a keyword. Optional $notfound = string default message if nothing found
\r
484 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
\r
485 return yourls_get_keyword_info( $keyword, 'ip', $notfound );
\r
488 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
\r
489 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
\r
490 return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
\r
493 // Update click count on a short URL
\r
494 function yourls_update_clicks( $keyword ) {
\r
496 $keyword = yourls_sanitize_string( $keyword );
\r
497 $table = YOURLS_DB_TABLE_URL;
\r
498 return $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");
\r
501 // Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
\r
502 function yourls_get_links_stats( $filter = 'top', $limit = 10 ) {
\r
505 switch( $filter ) {
\r
507 $sort_by = 'clicks';
\r
508 $sort_order = 'asc';
\r
511 $sort_by = 'timestamp';
\r
512 $sort_order = 'desc';
\r
516 $sort_by = 'RAND()';
\r
521 $sort_by = 'clicks';
\r
522 $sort_order = 'desc';
\r
526 $limit = intval( $limit );
\r
529 $table_url = YOURLS_DB_TABLE_URL;
\r
530 $results = $ydb->get_results("SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT 0, $limit;");
\r
535 foreach ($results as $res) {
\r
536 $return['links']['link_'.$i++] = array(
\r
537 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
\r
538 'url' => $res->url,
\r
539 'timestamp' => $res->timestamp,
\r
541 'clicks' => $res->clicks,
\r
545 $return['stats'] = yourls_get_db_stats();
\r
547 $return['statusCode'] = 200;
\r
553 // Return array for API stat requests
\r
554 function yourls_api_stats( $filter = 'top', $limit = 10 ) {
\r
555 $return = yourls_get_links_stats( $filter, $limit );
\r
556 $return['simple'] = 'Need either XML or JSON format for stats';
\r
557 $return['message'] = 'success';
\r
561 // Expand short url to long url
\r
562 function yourls_api_expand( $shorturl ) {
\r
563 $keyword = str_replace( YOURLS_SITE . '/' , '', $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'
\r
564 $keyword = yourls_sanitize_string( $keyword );
\r
566 $longurl = yourls_get_keyword_longurl( $keyword );
\r
570 'keyword' => $keyword,
\r
571 'shorturl' => YOURLS_SITE . "/$keyword",
\r
572 'longurl' => $longurl,
\r
573 'simple' => $longurl,
\r
574 'message' => 'success',
\r
575 'statusCode' => 200,
\r
579 'keyword' => $keyword,
\r
580 'simple' => 'not found',
\r
581 'message' => 'Error: short URL not found',
\r
582 'errorCode' => 404,
\r
588 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
\r
589 function yourls_get_db_stats( $where = '' ) {
\r
591 $table_url = YOURLS_DB_TABLE_URL;
\r
593 $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");
\r
594 return array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
\r
597 // Return API result. Dies after this
\r
598 function yourls_api_output( $mode, $return ) {
\r
599 if( isset( $return['simple'] ) ) {
\r
600 $simple = $return['simple'];
\r
601 unset( $return['simple'] );
\r
605 header('Content-type: application/json');
\r
606 echo yourls_json_encode($return);
\r
610 header('Content-type: application/xml');
\r
611 echo yourls_xml_encode($return);
\r
616 if( isset( $simple ) )
\r
623 // Get number of SQL queries performed
\r
624 function yourls_get_num_queries() {
\r
627 return $ydb->num_queries;
\r
630 // Compat http_build_query for PHP4
\r
631 if (!function_exists('http_build_query')) {
\r
632 function http_build_query($data, $prefix=null, $sep=null) {
\r
633 return yourls_http_build_query($data, $prefix, $sep);
\r
637 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
\r
638 function yourls_http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
\r
641 foreach ( (array) $data as $k => $v ) {
\r
643 $k = urlencode($k);
\r
644 if ( is_int($k) && $prefix != null )
\r
646 if ( !empty($key) )
\r
647 $k = $key . '%5B' . $k . '%5D';
\r
650 elseif ( $v === FALSE )
\r
653 if ( is_array($v) || is_object($v) )
\r
654 array_push($ret,yourls_http_build_query($v, '', $sep, $k, $urlencode));
\r
655 elseif ( $urlencode )
\r
656 array_push($ret, $k.'='.urlencode($v));
\r
658 array_push($ret, $k.'='.$v);
\r
661 if ( NULL === $sep )
\r
662 $sep = ini_get('arg_separator.output');
\r
664 return implode($sep, $ret);
\r
667 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
\r
668 function yourls_get_user_agent() {
\r
669 if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
\r
672 $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
\r
673 $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
\r
675 return substr( $ua, 0, 254 );
\r
678 // Redirect to another page
\r
679 function yourls_redirect( $location, $code = 301 ) {
\r
680 // Redirect, either properly if possible, or via Javascript otherwise
\r
681 if( !headers_sent() ) {
\r
682 yourls_status_header( $code );
\r
683 header("Location: $location");
\r
685 yourls_redirect_javascript( $location );
\r
690 // Set HTTP status header
\r
691 function yourls_status_header( $code = 200 ) {
\r
692 if( headers_sent() )
\r
695 $protocol = $_SERVER["SERVER_PROTOCOL"];
\r
696 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
\r
697 $protocol = 'HTTP/1.0';
\r
699 $code = intval( $code );
\r
700 $desc = yourls_get_HTTP_status($code);
\r
702 @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
\r
705 // 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
706 function yourls_redirect_javascript( $location, $dontwait = true ) {
\r
709 <script type="text/javascript">
\r
710 window.location="$location";
\r
712 <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>
\r
716 <p>Please <a href="$location">click here</a></p>
\r
721 // Return a HTTP status code
\r
722 function yourls_get_HTTP_status( $code ) {
\r
723 $code = intval( $code );
\r
724 $headers_desc = array(
\r
726 101 => 'Switching Protocols',
\r
727 102 => 'Processing',
\r
732 203 => 'Non-Authoritative Information',
\r
733 204 => 'No Content',
\r
734 205 => 'Reset Content',
\r
735 206 => 'Partial Content',
\r
736 207 => 'Multi-Status',
\r
739 300 => 'Multiple Choices',
\r
740 301 => 'Moved Permanently',
\r
742 303 => 'See Other',
\r
743 304 => 'Not Modified',
\r
744 305 => 'Use Proxy',
\r
746 307 => 'Temporary Redirect',
\r
748 400 => 'Bad Request',
\r
749 401 => 'Unauthorized',
\r
750 402 => 'Payment Required',
\r
751 403 => 'Forbidden',
\r
752 404 => 'Not Found',
\r
753 405 => 'Method Not Allowed',
\r
754 406 => 'Not Acceptable',
\r
755 407 => 'Proxy Authentication Required',
\r
756 408 => 'Request Timeout',
\r
759 411 => 'Length Required',
\r
760 412 => 'Precondition Failed',
\r
761 413 => 'Request Entity Too Large',
\r
762 414 => 'Request-URI Too Long',
\r
763 415 => 'Unsupported Media Type',
\r
764 416 => 'Requested Range Not Satisfiable',
\r
765 417 => 'Expectation Failed',
\r
766 422 => 'Unprocessable Entity',
\r
768 424 => 'Failed Dependency',
\r
769 426 => 'Upgrade Required',
\r
771 500 => 'Internal Server Error',
\r
772 501 => 'Not Implemented',
\r
773 502 => 'Bad Gateway',
\r
774 503 => 'Service Unavailable',
\r
775 504 => 'Gateway Timeout',
\r
776 505 => 'HTTP Version Not Supported',
\r
777 506 => 'Variant Also Negotiates',
\r
778 507 => 'Insufficient Storage',
\r
779 510 => 'Not Extended'
\r
782 if ( isset( $headers_desc[$code] ) )
\r
783 return $headers_desc[$code];
\r
789 // Log a redirect (for stats)
\r
790 function yourls_log_redirect( $keyword ) {
\r
791 if ( !yourls_do_log_redirect() )
\r
795 $table = YOURLS_DB_TABLE_LOG;
\r
797 $keyword = yourls_sanitize_string( $keyword );
\r
798 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
\r
799 $ua = yourls_get_user_agent();
\r
800 $ip = yourls_get_IP();
\r
801 $location = yourls_geo_ip_to_countrycode( $ip );
\r
803 return $ydb->query( "INSERT INTO `$table` VALUES ('', NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
\r
806 // Check if we want to not log redirects (for stats)
\r
807 function yourls_do_log_redirect() {
\r
808 return ( !defined('YOURLS_NOSTATS') || YOURLS_NOSTATS != true );
\r
811 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
\r
812 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
\r
813 if ( !file_exists( dirname(__FILE__).'/geo/GeoIP.dat') || !file_exists( dirname(__FILE__).'/geo/geoip.inc') )
\r
817 $ip = yourls_get_IP();
\r
819 require_once( dirname(__FILE__).'/geo/geoip.inc') ;
\r
820 $gi = geoip_open( dirname(__FILE__).'/geo/GeoIP.dat', GEOIP_STANDARD);
\r
821 $location = geoip_country_code_by_addr($gi, $ip);
\r
827 // Converts a 2 letter country code to long name (ie AU -> Australia)
\r
828 function yourls_geo_countrycode_to_countryname( $code ) {
\r
829 // Load the Geo class if not already done
\r
830 if( !class_exists('GeoIP') ) {
\r
831 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');
\r
834 if( class_exists('GeoIP') ) {
\r
836 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];
\r
837 $long = $geo->GEOIP_COUNTRY_NAMES[$id];
\r
844 // Return flag URL from 2 letter country code
\r
845 function yourls_geo_get_flag( $code ) {
\r
846 // Load the Geo class if not already done
\r
847 if( !class_exists('GeoIP') ) {
\r
848 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');
\r
851 if( class_exists('GeoIP') ) {
\r
852 return YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif';
\r
859 // Check if an upgrade is needed
\r
860 function yourls_upgrade_is_needed() {
\r
861 // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
\r
862 list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
\r
863 if( $currentsql < YOURLS_DB_VERSION )
\r
869 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
\r
870 function yourls_get_current_version_from_sql() {
\r
871 $currentver = yourls_get_option( 'version' );
\r
872 $currentsql = yourls_get_option( 'db_version' );
\r
874 // Values if version is 1.3
\r
876 $currentver = '1.3';
\r
878 $currentsql = '100';
\r
880 return array( $currentver, $currentsql);
\r
883 // Read an option from DB (or from cache if available). Return value or $default if not found
\r
884 function yourls_get_option( $option_name, $default = false ) {
\r
886 if ( !isset( $ydb->option[$option_name] ) ) {
\r
887 $table = YOURLS_DB_TABLE_OPTIONS;
\r
888 $option_name = yourls_escape( $option_name );
\r
889 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
\r
890 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
\r
891 $value = $row->option_value;
\r
892 } else { // option does not exist, so we must cache its non-existence
\r
895 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );
\r
898 return $ydb->option[$option_name];
\r
901 // Read all options from DB at once
\r
902 function yourls_get_all_options() {
\r
904 $table = YOURLS_DB_TABLE_OPTIONS;
\r
906 $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");
\r
908 foreach( (array)$allopt as $option ) {
\r
909 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );
\r
913 // Update (add if doesn't exist) an option to DB
\r
914 function yourls_update_option( $option_name, $newvalue ) {
\r
916 $table = YOURLS_DB_TABLE_OPTIONS;
\r
918 $safe_option_name = yourls_escape( $option_name );
\r
920 $oldvalue = yourls_get_option( $safe_option_name );
\r
922 // If the new and old values are the same, no need to update.
\r
923 if ( $newvalue === $oldvalue )
\r
926 if ( false === $oldvalue ) {
\r
927 yourls_add_option( $option_name, $newvalue );
\r
931 $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
\r
933 $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");
\r
935 if ( $ydb->rows_affected == 1 ) {
\r
936 $ydb->option[$option_name] = $newvalue;
\r
942 // Add an option to the DB
\r
943 function yourls_add_option( $name, $value = '' ) {
\r
945 $table = YOURLS_DB_TABLE_OPTIONS;
\r
946 $safe_name = yourls_escape( $name );
\r
948 // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
\r
949 if ( false !== yourls_get_option( $safe_name ) )
\r
952 $_value = yourls_escape( yourls_maybe_serialize( $value ) );
\r
954 $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
\r
955 $ydb->option[$name] = $value;
\r
960 // Delete an option from the DB
\r
961 function yourls_delete_option( $name ) {
\r
963 $table = YOURLS_DB_TABLE_OPTIONS;
\r
964 $name = yourls_escape( $name );
\r
966 // Get the ID, if no ID then return
\r
967 $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
\r
968 if ( is_null($option) || !$option->option_id )
\r
970 $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
\r
976 // Serialize data if needed. Stolen from WordPress
\r
977 function yourls_maybe_serialize( $data ) {
\r
978 if ( is_array( $data ) || is_object( $data ) )
\r
979 return serialize( $data );
\r
981 if ( yourls_is_serialized( $data ) )
\r
982 return serialize( $data );
\r
987 // Check value to find if it was serialized. Stolen from WordPress
\r
988 function yourls_is_serialized( $data ) {
\r
989 // if it isn't a string, it isn't serialized
\r
990 if ( !is_string( $data ) )
\r
992 $data = trim( $data );
\r
993 if ( 'N;' == $data )
\r
995 if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
\r
997 switch ( $badions[1] ) {
\r
1001 if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
\r
1007 if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
\r
1014 // Unserialize value only if it was serialized. Stolen from WP
\r
1015 function yourls_maybe_unserialize( $original ) {
\r
1016 if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
\r
1017 return @unserialize( $original );
\r
1021 // Determine if the current page is private
\r
1022 function yourls_is_private() {
\r
1023 if (defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true) {
\r
1025 // Allow overruling of particular pages
\r
1026 $current = basename( $_SERVER["SCRIPT_NAME"] );
\r
1028 switch( $current ) {
\r
1030 case 'yourls-api.php':
\r
1031 if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
\r
1035 case 'yourls-infos.php':
\r
1036 if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
\r
1049 // Show login form if required
\r
1050 function yourls_maybe_require_auth() {
\r
1051 if( yourls_is_private() )
\r
1052 require_once( dirname(__FILE__).'/auth.php' );
\r
1055 // Return word or words if more than one
\r
1056 function yourls_plural( $word, $count=1 ) {
\r
1057 return $word . ($count > 1 ? 's' : '');
\r
1060 // Return trimmed string
\r
1061 function yourls_trim_long_string( $string, $length = 60, $append = '[...]' ) {
\r
1062 if ( strlen( $string ) > $length ) {
\r
1063 $string = substr( $string, 0, $length - strlen( $append ) ) . $append;
\r
1068 // Allow several short URLs for the same long URL ?
\r
1069 function yourls_allow_duplicate_longurls() {
\r
1070 return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
\r
1073 // Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.
\r
1074 function yourls_get_duplicate_keywords( $longurl ) {
\r
1075 if( !yourls_allow_duplicate_longurls() )
\r
1079 $longurl = yourls_escape( yourls_sanitize_url($longurl) );
\r
1080 $table = YOURLS_DB_TABLE_URL;
\r
1082 return $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );
\r
1085 // Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
\r
1086 function yourls_check_IP_flood( $ip = '' ) {
\r
1088 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
\r
1089 !defined('YOURLS_FLOOD_DELAY_SECONDS')
\r
1093 $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
\r
1095 // Don't throttle whitelist IPs
\r
1096 if( defined('YOURLS_FLOOD_IP_WHITELIST' && YOURLS_FLOOD_IP_WHITELIST ) ) {
\r
1097 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
\r
1098 foreach( $whitelist_ips as $whitelist_ip ) {
\r
1099 $whitelist_ip = trim( $whitelist_ip );
\r
1100 if ( $whitelist_ip == $ip )
\r
1105 // Don't throttle logged in users
\r
1106 if( yourls_is_private() ) {
\r
1107 if( yourls_is_valid_user() === true )
\r
1112 $table = YOURLS_DB_TABLE_URL;
\r
1114 $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
\r
1116 $now = date( 'U' );
\r
1117 $then = date( 'U', strtotime( $lasttime ) );
\r
1118 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
\r
1120 yourls_die( 'Too many URLs added too fast. Slow down please.', 'Forbidden', 403 );
\r
1127 // Check if YOURLS is installed
\r
1128 function yourls_is_installed() {
\r
1129 static $is_installed = false;
\r
1130 if ( $is_installed === false ) {
\r
1131 $check_14 = $check_13 = false;
\r
1133 if( defined('YOURLS_DB_TABLE_NEXTDEC') )
\r
1134 $check_13 = $ydb->get_var('SELECT next_id FROM '.YOURLS_DB_TABLE_NEXTDEC);
\r
1135 $check_14 = yourls_get_option( 'version' );
\r
1136 $is_installed = $check_13 || $check_14;
\r
1138 return $is_installed;
\r
1141 // Compat for PHP < 5.1
\r
1142 if ( !function_exists('htmlspecialchars_decode') ) {
\r
1143 function htmlspecialchars_decode($text) {
\r
1144 return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
\r
1148 // Generate random string of (int)$lenght length and type $type (see function for details)
\r
1149 function yourls_rnd_string ( $length = 5, $type = 1 ) {
\r
1151 $length = intval( $length );
\r
1153 // define possible characters
\r
1154 switch ( $type ) {
\r
1155 // no vowels to make no offending word, no 0 or 1 to avoid confusion betwee letters & digits. Perfect for passwords.
\r
1157 $possible = "23456789bcdfghjkmnpqrstvwxyz";
\r
1160 // all letters, lowercase
\r
1162 $possible = "abcdefghijklmnopqrstuvwxyz";
\r
1165 // all letters, lowercase + uppercase
\r
1167 $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1170 // all digits & letters lowercase
\r
1172 $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
\r
1175 // all digits & letters lowercase + uppercase
\r
1177 $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1183 while ($i < $length) {
\r
1184 $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
\r
1191 // Return salted string
\r
1192 function yourls_salt( $string ) {
\r
1193 $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
\r
1194 return md5 ($string . $salt);
\r
1197 // Return a time-dependent string for nonce creation
\r
1198 function yourls_tick() {
\r
1199 return ceil( time() / YOURLS_NONCE_LIFE );
\r
1202 // Create a time limited, action limited and user limited token
\r
1203 function yourls_create_nonce( $action = '-1', $user = false ) {
\r
1204 if( false == $user )
\r
1205 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
\r
1206 $tick = yourls_tick();
\r
1207 return substr( yourls_salt($tick . $action . $user), 0, 10 );
\r
1210 // Check validity of a nonce (ie time span, user and action match)
\r
1211 function yourls_verify_nonce( $nonce, $action = -1, $user = false ) {
\r
1212 if( false == $user )
\r
1213 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
\r
1214 $valid = yourls_create_nonce( $action, $user );
\r
1216 return $nonce == $valid ;
\r
1219 // Sanitize a version number
\r
1220 function yourls_sanitize_version( $ver ) {
\r
1221 return preg_replace( '/[^0-9a-zA-Z-.]/', '', $ver );
\r
1224 // Converts keyword into short link
\r
1225 function yourls_link( $keyword = '' ) {
\r
1226 return YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
\r
1229 // Check if we're in API mode. Returns bool
\r
1230 function yourls_is_API() {
\r
1231 if ( defined('YOURLS_API') && YOURLS_API == true )
\r
1236 // Check if we're in Ajax mode. Returns bool
\r
1237 function yourls_is_Ajax() {
\r
1238 if ( defined('YOURLS_AJAX') && YOURLS_AJAX == true )
\r
1243 // Check if we're in GO mode. Returns bool
\r
1244 function yourls_is_GO() {
\r
1245 if ( defined('YOURLS_GO') && YOURLS_GO == true )
\r
1250 // Check if we'll need interface display function (ie not API or redirection)
\r
1251 function yourls_has_interface() {
\r
1252 if( yourls_is_API() or yourls_is_GO() or yourls_is_Ajax() )
\r
1257 // Check if we're in the admin area. Returns bool
\r
1258 function yourls_is_admin() {
\r
1259 if ( defined('YOURLS_ADMIN') && YOURLS_ADMIN == true )
\r
1264 // Check if SSL is required. Returns bool.
\r
1265 function yourls_needs_ssl() {
\r
1266 if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
\r
1271 // Return admin link, with SSL preference if applicable.
\r
1272 function yourls_admin_url( $page = '' ) {
\r
1273 $admin = YOURLS_SITE . '/admin/' . $page;
\r
1274 if( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
\r
1275 $admin = str_replace('http://', 'https://', $admin);
\r
1279 // Check if SSL is used, returns bool. Stolen from WP.
\r
1280 function yourls_is_ssl() {
\r
1281 if ( isset($_SERVER['HTTPS']) ) {
\r
1282 if ( 'on' == strtolower($_SERVER['HTTPS']) )
\r
1284 if ( '1' == $_SERVER['HTTPS'] )
\r
1286 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
\r