8 * Determine the allowed character set in short URLs
11 function yourls_get_shorturl_charset() {
12 static $charset = null;
13 if( $charset !== null )
16 if( !defined('YOURLS_URL_CONVERT') ) {
17 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
19 switch( YOURLS_URL_CONVERT ) {
21 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
24 case 64: // just because some people get this wrong in their config.php
25 $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
30 $charset = yourls_apply_filter( 'get_shorturl_charset', $charset );
35 * Make an optimized regexp pattern from a string of characters
38 function yourls_make_regexp_pattern( $string ) {
39 $pattern = preg_quote( $string, '-' ); // add - as an escaped characters -- this is fixed in PHP 5.3
40 // TODO: replace char sequences by smart sequences such as 0-9, a-z, A-Z ... ?
45 * Is a URL a short URL? Accept either 'http://sho.rt/abc' or 'abc'
48 function yourls_is_shorturl( $shorturl ) {
49 // TODO: make sure this function evolves with the feature set.
53 // Is $shorturl a URL (http://sho.rt/abc) or a keyword (abc) ?
54 if( yourls_get_protocol( $shorturl ) ) {
55 $keyword = yourls_get_relative_url( $shorturl );
60 // Check if it's a valid && used keyword
61 if( $keyword && $keyword == yourls_sanitize_string( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {
65 return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );
69 * Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool
72 function yourls_keyword_is_reserved( $keyword ) {
73 global $yourls_reserved_URL;
74 $keyword = yourls_sanitize_keyword( $keyword );
77 if ( in_array( $keyword, $yourls_reserved_URL)
78 or file_exists( YOURLS_ABSPATH ."/pages/$keyword.php" )
79 or is_dir( YOURLS_ABSPATH ."/$keyword" )
83 return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );
87 * Function: Get client IP Address. Returns a DB safe string.
90 function yourls_get_IP() {
93 // Precedence: if set, X-Forwarded-For > HTTP_X_FORWARDED_FOR > HTTP_CLIENT_IP > HTTP_VIA > REMOTE_ADDR
94 $headers = array( 'X-Forwarded-For', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_VIA', 'REMOTE_ADDR' );
95 foreach( $headers as $header ) {
96 if ( !empty( $_SERVER[ $header ] ) ) {
97 $ip = $_SERVER[ $header ];
102 // headers can contain multiple IPs (X-Forwarded-For = client, proxy1, proxy2). Take first one.
103 if ( strpos( $ip, ',' ) !== false )
104 $ip = substr( $ip, 0, strpos( $ip, ',' ) );
106 return yourls_apply_filter( 'get_IP', yourls_sanitize_ip( $ip ) );
110 * Get next id a new link will have if no custom keyword provided
113 function yourls_get_next_decimal() {
114 return yourls_apply_filter( 'get_next_decimal', (int)yourls_get_option( 'next_id' ) );
118 * Update id for next link with no custom keyword
121 function yourls_update_next_decimal( $int = '' ) {
122 $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
123 $update = yourls_update_option( 'next_id', $int );
124 yourls_do_action( 'update_next_decimal', $int, $update );
129 * Delete a link in the DB
132 function yourls_delete_link_by_keyword( $keyword ) {
135 $table = YOURLS_DB_TABLE_URL;
136 $keyword = yourls_sanitize_string( $keyword );
137 $delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
138 yourls_do_action( 'delete_link', $keyword, $delete );
143 * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting
146 function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {
149 $url = yourls_escape( yourls_sanitize_url( $url ) );
150 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
151 $title = yourls_escape( yourls_sanitize_title( $title ) );
153 $table = YOURLS_DB_TABLE_URL;
154 $timestamp = date('Y-m-d H:i:s');
155 $ip = yourls_get_IP();
156 $insert = $ydb->query("INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");
158 yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );
160 return (bool)$insert;
164 * Check if a URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.
167 function yourls_url_exists( $url ) {
168 // Allow plugins to short-circuit the whole function
169 $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );
170 if ( false !== $pre )
174 $table = YOURLS_DB_TABLE_URL;
175 $strip_url = stripslashes($url);
176 $url_exists = $ydb->get_row("SELECT * FROM `$table` WHERE `url` = '".$strip_url."';");
178 return yourls_apply_filter( 'url_exists', $url_exists, $url );
182 * Add a new link in the DB, either with custom keyword, or find one
185 function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
186 // Allow plugins to short-circuit the whole function
187 $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
188 if ( false !== $pre )
191 $url = yourls_encodeURI( $url );
192 $url = yourls_escape( yourls_sanitize_url( $url ) );
193 if ( !$url || $url == 'http://' || $url == 'https://' ) {
194 $return['status'] = 'fail';
195 $return['code'] = 'error:nourl';
196 $return['message'] = yourls__( 'Missing or malformed URL' );
197 $return['errorCode'] = '400';
198 return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
202 $ip = yourls_get_IP();
203 yourls_check_IP_flood( $ip );
205 // Prevent internal redirection loops: cannot shorten a shortened URL
206 if( yourls_get_relative_url( $url ) ) {
207 if( yourls_is_shorturl( $url ) ) {
208 $return['status'] = 'fail';
209 $return['code'] = 'error:noloop';
210 $return['message'] = yourls__( 'URL is a short URL' );
211 $return['errorCode'] = '400';
212 return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );
216 yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );
218 $strip_url = stripslashes( $url );
221 // duplicates allowed or new URL => store it
222 if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_url_exists( $url ) ) ) {
224 if( isset( $title ) && !empty( $title ) ) {
225 $title = yourls_sanitize_title( $title );
227 $title = yourls_get_remote_title( $url );
229 $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );
231 // Custom keyword provided
234 yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );
236 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
237 $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );
238 if ( !yourls_keyword_is_free( $keyword ) ) {
239 // This shorturl either reserved or taken already
240 $return['status'] = 'fail';
241 $return['code'] = 'error:keyword';
242 $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );
244 // all clear, store !
245 yourls_insert_link_in_db( $url, $keyword, $title );
246 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
247 $return['status'] = 'success';
248 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
249 $return['title'] = $title;
250 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
251 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
254 // Create random keyword
257 yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );
259 $timestamp = date( 'Y-m-d H:i:s' );
260 $id = yourls_get_next_decimal();
263 $keyword = yourls_int2string( $id );
264 $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );
265 if ( yourls_keyword_is_free($keyword) ) {
266 if( @yourls_insert_link_in_db( $url, $keyword, $title ) ){
267 // everything ok, populate needed vars
268 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );
269 $return['status'] = 'success';
270 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
271 $return['title'] = $title;
272 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
273 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
275 // database error, couldnt store result
276 $return['status'] = 'fail';
277 $return['code'] = 'error:db';
278 $return['message'] = yourls_s( 'Error saving url to database' );
284 @yourls_update_next_decimal( $id );
287 // URL was already stored
290 yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );
292 $return['status'] = 'fail';
293 $return['code'] = 'error:url';
294 $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 );
295 $return['message'] = /* //translators: eg "http://someurl/ already exists" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $strip_url ) );
296 $return['title'] = $url_exists->title;
297 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
300 yourls_do_action( 'post_add_new_link', $url, $keyword, $title );
302 $return['statusCode'] = 200; // regardless of result, this is still a valid request
303 return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );
311 function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {
314 $table = YOURLS_DB_TABLE_URL;
315 $url = yourls_escape (yourls_sanitize_url( $url ) );
316 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
317 $title = yourls_escape( yourls_sanitize_title( $title ) );
318 $newkeyword = yourls_escape( yourls_sanitize_string( $newkeyword ) );
319 $strip_url = stripslashes( $url );
320 $strip_title = stripslashes( $title );
321 $old_url = $ydb->get_var( "SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';" );
323 // Check if new URL is not here already
324 if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {
325 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
327 $new_url_already_there = false;
330 // Check if the new keyword is not here already
331 if ( $newkeyword != $keyword ) {
332 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
334 $keyword_is_ok = true;
337 yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );
340 if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
341 $update_url = $ydb->query( "UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';" );
343 $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 ) );
344 $return['status'] = 'success';
345 $return['message'] = yourls__( 'Link updated in database' );
347 $return['status'] = 'fail';
348 $return['message'] = /* //translators: "Error updating http://someurl/ (Shorturl: http://sho.rt/blah)" */ yourls_s( 'Error updating %s (Short URL: %s)', yourls_trim_long_string( $strip_url ), $keyword ) ;
353 $return['status'] = 'fail';
354 $return['message'] = yourls__( 'URL or keyword already exists in database' );
357 return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );
361 * Update a title link (no checks for duplicates etc..)
364 function yourls_edit_link_title( $keyword, $title ) {
367 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
368 $title = yourls_escape( yourls_sanitize_title( $title ) );
370 $table = YOURLS_DB_TABLE_URL;
371 $update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");
378 * Check if keyword id is free (ie not already taken, and not reserved). Return bool.
381 function yourls_keyword_is_free( $keyword ) {
383 if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
386 return yourls_apply_filter( 'keyword_is_free', $free, $keyword );
390 * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.
393 function yourls_keyword_is_taken( $keyword ) {
395 // Allow plugins to short-circuit the whole function
396 $pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );
397 if ( false !== $pre )
401 $keyword = yourls_sanitize_keyword( $keyword );
403 $table = YOURLS_DB_TABLE_URL;
404 $already_exists = $ydb->get_var( "SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';" );
405 if ( $already_exists )
408 return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );
416 function yourls_db_connect() {
419 if ( !defined( 'YOURLS_DB_USER' )
420 or !defined( 'YOURLS_DB_PASS' )
421 or !defined( 'YOURLS_DB_NAME' )
422 or !defined( 'YOURLS_DB_HOST' )
423 ) yourls_die ( yourls__( 'Incorrect DB config, or could not connect to DB' ), yourls__( 'Fatal error' ), 503 );
425 // Are we standalone or in the WordPress environment?
426 if ( class_exists( 'wpdb', false ) ) {
427 /* TODO: should we deprecate this? Follow WP dev in that area */
428 $ydb = new wpdb( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
430 yourls_set_DB_driver();
433 // Check if connection attempt raised an error. It seems that only PDO does, though.
434 if ( $ydb->last_error )
435 yourls_die( $ydb->last_error, yourls__( 'Fatal error' ), 503 );
437 if ( defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG === true )
438 $ydb->show_errors = true;
447 function yourls_xml_encode( $array ) {
448 require_once( YOURLS_INC.'/functions-xml.php' );
449 $converter= new yourls_array2xml;
450 return $converter->array2xml( $array );
454 * Return array of all information associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB
457 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
459 $keyword = yourls_sanitize_string( $keyword );
461 yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );
463 if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
464 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
467 yourls_do_action( 'get_keyword_not_cached', $keyword );
469 $table = YOURLS_DB_TABLE_URL;
470 $infos = $ydb->get_row( "SELECT * FROM `$table` WHERE `keyword` = '$keyword'" );
473 $infos = (array)$infos;
474 $ydb->infos[ $keyword ] = $infos;
476 $ydb->infos[ $keyword ] = false;
479 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
483 * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
486 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
488 // Allow plugins to short-circuit the whole function
489 $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );
490 if ( false !== $pre )
493 $keyword = yourls_sanitize_string( $keyword );
494 $infos = yourls_get_keyword_infos( $keyword );
497 if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )
498 $return = $infos[ $field ];
500 return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );
504 * Return title associated with keyword. Optional $notfound = string default message if nothing found
507 function yourls_get_keyword_title( $keyword, $notfound = false ) {
508 return yourls_get_keyword_info( $keyword, 'title', $notfound );
512 * Return long URL associated with keyword. Optional $notfound = string default message if nothing found
515 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
516 return yourls_get_keyword_info( $keyword, 'url', $notfound );
520 * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
523 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
524 return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
528 * Return IP that added a keyword. Optional $notfound = string default message if nothing found
531 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
532 return yourls_get_keyword_info( $keyword, 'ip', $notfound );
536 * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
539 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
540 return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
544 * Update click count on a short URL. Return 0/1 for error/success.
547 function yourls_update_clicks( $keyword, $clicks = false ) {
548 // Allow plugins to short-circuit the whole function
549 $pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword, $clicks );
550 if ( false !== $pre )
554 $keyword = yourls_sanitize_string( $keyword );
555 $table = YOURLS_DB_TABLE_URL;
556 if ( $clicks !== false && is_int( $clicks ) && $clicks >= 0 )
557 $update = $ydb->query( "UPDATE `$table` SET `clicks` = $clicks WHERE `keyword` = '$keyword'" );
559 $update = $ydb->query( "UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'" );
561 yourls_do_action( 'update_clicks', $keyword, $update, $clicks );
566 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
569 function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {
578 $sort_by = 'timestamp';
579 $sort_order = 'desc';
589 $sort_order = 'desc';
594 $limit = intval( $limit );
595 $start = intval( $start );
598 $table_url = YOURLS_DB_TABLE_URL;
599 $results = $ydb->get_results( "SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;" );
604 foreach ( (array)$results as $res ) {
605 $return['links']['link_'.$i++] = array(
606 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
608 'title' => $res->title,
609 'timestamp'=> $res->timestamp,
611 'clicks' => $res->clicks,
616 $return['stats'] = yourls_get_db_stats();
618 $return['statusCode'] = 200;
620 return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );
624 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
627 function yourls_get_link_stats( $shorturl ) {
630 $table_url = YOURLS_DB_TABLE_URL;
631 $res = $ydb->get_row( "SELECT * FROM `$table_url` WHERE keyword = '$shorturl';" );
638 'message' => 'Error: short URL not found',
643 'message' => 'success',
645 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
647 'title' => $res->title,
648 'timestamp'=> $res->timestamp,
650 'clicks' => $res->clicks,
655 return yourls_apply_filter( 'get_link_stats', $return, $shorturl );
659 * Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
662 function yourls_get_db_stats( $where = '' ) {
664 $table_url = YOURLS_DB_TABLE_URL;
666 $totals = $ydb->get_row( "SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where" );
667 $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
669 return yourls_apply_filter( 'get_db_stats', $return, $where );
673 * Get number of SQL queries performed
676 function yourls_get_num_queries() {
679 return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );
683 * Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
686 function yourls_get_user_agent() {
687 if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
690 $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
691 $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
693 return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );
697 * Redirect to another page
700 function yourls_redirect( $location, $code = 301 ) {
701 yourls_do_action( 'pre_redirect', $location, $code );
702 $location = yourls_apply_filter( 'redirect_location', $location, $code );
703 $code = yourls_apply_filter( 'redirect_code', $code, $location );
704 // Redirect, either properly if possible, or via Javascript otherwise
705 if( !headers_sent() ) {
706 yourls_status_header( $code );
707 header( "Location: $location" );
709 yourls_redirect_javascript( $location );
715 * Set HTTP status header
718 function yourls_status_header( $code = 200 ) {
722 $protocol = $_SERVER['SERVER_PROTOCOL'];
723 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
724 $protocol = 'HTTP/1.0';
726 $code = intval( $code );
727 $desc = yourls_get_HTTP_status( $code );
729 @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
730 yourls_do_action( 'status_header', $code );
734 * 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)
737 function yourls_redirect_javascript( $location, $dontwait = true ) {
738 yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );
739 $location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );
741 $message = yourls_s( 'if you are not redirected after 10 seconds, please <a href="%s">click here</a>', $location );
743 <script type="text/javascript">
744 window.location="$location";
746 <small>($message)</small>
749 echo '<p>' . yourls_s( 'Please <a href="%s">click here</a>', $location ) . '</p>';
751 yourls_do_action( 'post_redirect_javascript', $location );
755 * Return a HTTP status code
758 function yourls_get_HTTP_status( $code ) {
759 $code = intval( $code );
760 $headers_desc = array(
762 101 => 'Switching Protocols',
768 203 => 'Non-Authoritative Information',
770 205 => 'Reset Content',
771 206 => 'Partial Content',
772 207 => 'Multi-Status',
775 300 => 'Multiple Choices',
776 301 => 'Moved Permanently',
779 304 => 'Not Modified',
782 307 => 'Temporary Redirect',
784 400 => 'Bad Request',
785 401 => 'Unauthorized',
786 402 => 'Payment Required',
789 405 => 'Method Not Allowed',
790 406 => 'Not Acceptable',
791 407 => 'Proxy Authentication Required',
792 408 => 'Request Timeout',
795 411 => 'Length Required',
796 412 => 'Precondition Failed',
797 413 => 'Request Entity Too Large',
798 414 => 'Request-URI Too Long',
799 415 => 'Unsupported Media Type',
800 416 => 'Requested Range Not Satisfiable',
801 417 => 'Expectation Failed',
802 422 => 'Unprocessable Entity',
804 424 => 'Failed Dependency',
805 426 => 'Upgrade Required',
807 500 => 'Internal Server Error',
808 501 => 'Not Implemented',
809 502 => 'Bad Gateway',
810 503 => 'Service Unavailable',
811 504 => 'Gateway Timeout',
812 505 => 'HTTP Version Not Supported',
813 506 => 'Variant Also Negotiates',
814 507 => 'Insufficient Storage',
815 510 => 'Not Extended'
818 if ( isset( $headers_desc[$code] ) )
819 return $headers_desc[$code];
826 * Log a redirect (for stats)
829 function yourls_log_redirect( $keyword ) {
830 // Allow plugins to short-circuit the whole function
831 $pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );
832 if ( false !== $pre )
835 if ( !yourls_do_log_redirect() )
839 $table = YOURLS_DB_TABLE_LOG;
841 $keyword = yourls_sanitize_string( $keyword );
842 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
843 $ua = yourls_get_user_agent();
844 $ip = yourls_get_IP();
845 $location = yourls_geo_ip_to_countrycode( $ip );
847 return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
851 * Check if we want to not log redirects (for stats)
854 function yourls_do_log_redirect() {
855 return ( !defined( 'YOURLS_NOSTATS' ) || YOURLS_NOSTATS != true );
859 * Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
862 * @param string $ip IP or, if empty string, will be current user IP
863 * @param string $defaut Default string to return if IP doesn't resolve to a country (malformed, private IP...)
864 * @return string 2 letter country code (eg 'US') or $default
866 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
867 // Allow plugins to short-circuit the Geo IP API
868 $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
869 if ( false !== $location )
873 $ip = yourls_get_IP();
875 // Use IPv4 or IPv6 DB & functions
876 if( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
878 $func = 'geoip_country_code_by_addr';
881 $func = 'geoip_country_code_by_addr_v6';
884 if ( !file_exists( YOURLS_INC . '/geo/' . $db ) || !file_exists( YOURLS_INC .'/geo/geoip.inc' ) )
887 require_once( YOURLS_INC . '/geo/geoip.inc' );
888 $gi = geoip_open( YOURLS_INC . '/geo/' . $db, GEOIP_STANDARD );
890 $location = call_user_func( $func, $gi, $ip );
891 } catch ( Exception $e ) {
896 if( '' == $location )
897 $location = $default;
899 return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );
903 * Converts a 2 letter country code to long name (ie AU -> Australia)
906 function yourls_geo_countrycode_to_countryname( $code ) {
907 // Allow plugins to short-circuit the Geo IP API
908 $country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );
909 if ( false !== $country )
912 // Load the Geo class if not already done
913 if( !class_exists( 'GeoIP', false ) ) {
914 $temp = yourls_geo_ip_to_countrycode( '127.0.0.1' );
917 if( class_exists( 'GeoIP', false ) ) {
919 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[ $code ];
920 $long = $geo->GEOIP_COUNTRY_NAMES[ $id ];
928 * Return flag URL from 2 letter country code
931 function yourls_geo_get_flag( $code ) {
932 if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {
933 $img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.( strtolower( $code ) ).'.gif' );
937 return yourls_apply_filter( 'geo_get_flag', $img, $code );
942 * Check if an upgrade is needed
945 function yourls_upgrade_is_needed() {
946 // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
947 list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
948 if( $currentsql < YOURLS_DB_VERSION )
955 * Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
958 function yourls_get_current_version_from_sql() {
959 $currentver = yourls_get_option( 'version' );
960 $currentsql = yourls_get_option( 'db_version' );
962 // Values if version is 1.3
968 return array( $currentver, $currentsql);
972 * Read an option from DB (or from cache if available). Return value or $default if not found
974 * Pretty much stolen from WordPress
977 * @param string $option Option name. Expected to not be SQL-escaped.
978 * @param mixed $default Optional value to return if option doesn't exist. Default false.
979 * @return mixed Value set for the option.
981 function yourls_get_option( $option_name, $default = false ) {
984 // Allow plugins to short-circuit options
985 $pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );
986 if ( false !== $pre )
989 // If option not cached already, get its value from the DB
990 if ( !isset( $ydb->option[$option_name] ) ) {
991 $table = YOURLS_DB_TABLE_OPTIONS;
992 $option_name = yourls_escape( $option_name );
993 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
994 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
995 $value = $row->option_value;
996 } else { // option does not exist, so we must cache its non-existence
999 $ydb->option[ $option_name ] = yourls_maybe_unserialize( $value );
1002 return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );
1006 * Read all options from DB at once
1008 * The goal is to read all option at once and then populate array $ydb->option, to prevent further
1009 * SQL queries if we need to read an option value later.
1010 * It's also a simple check whether YOURLS is installed or not (no option = assuming not installed)
1014 function yourls_get_all_options() {
1017 // Allow plugins to short-circuit all options. (Note: regular plugins are loaded after all options)
1018 $pre = yourls_apply_filter( 'shunt_all_options', false );
1019 if ( false !== $pre )
1022 $table = YOURLS_DB_TABLE_OPTIONS;
1024 $allopt = $ydb->get_results( "SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1" );
1026 foreach( (array)$allopt as $option ) {
1027 $ydb->option[ $option->option_name ] = yourls_maybe_unserialize( $option->option_value );
1030 if( property_exists( $ydb, 'option' ) ) {
1031 $ydb->option = yourls_apply_filter( 'get_all_options', $ydb->option );
1032 $ydb->installed = true;
1034 // Zero option found: assume YOURLS is not installed
1035 $ydb->installed = false;
1040 * Update (add if doesn't exist) an option to DB
1042 * Pretty much stolen from WordPress
1045 * @param string $option Option name. Expected to not be SQL-escaped.
1046 * @param mixed $newvalue Option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.
1047 * @return bool False if value was not updated, true otherwise.
1049 function yourls_update_option( $option_name, $newvalue ) {
1051 $table = YOURLS_DB_TABLE_OPTIONS;
1053 $option_name = trim( $option_name );
1054 if ( empty( $option_name ) )
1057 // Use clone to break object refs -- see commit 09b989d375bac65e692277f61a84fede2fb04ae3
1058 if ( is_object( $newvalue ) )
1059 $newvalue = clone $newvalue;
1061 $option_name = yourls_escape( $option_name );
1063 $oldvalue = yourls_get_option( $option_name );
1065 // If the new and old values are the same, no need to update.
1066 if ( $newvalue === $oldvalue )
1069 if ( false === $oldvalue ) {
1070 yourls_add_option( $option_name, $newvalue );
1074 $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
1076 yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );
1078 $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'" );
1080 if ( $ydb->rows_affected == 1 ) {
1081 $ydb->option[ $option_name ] = $newvalue;
1088 * Add an option to the DB
1090 * Pretty much stolen from WordPress
1093 * @param string $option Name of option to add. Expected to not be SQL-escaped.
1094 * @param mixed $value Optional option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.
1095 * @return bool False if option was not added and true otherwise.
1097 function yourls_add_option( $name, $value = '' ) {
1099 $table = YOURLS_DB_TABLE_OPTIONS;
1101 $name = trim( $name );
1102 if ( empty( $name ) )
1105 // Use clone to break object refs -- see commit 09b989d375bac65e692277f61a84fede2fb04ae3
1106 if ( is_object( $value ) )
1107 $value = clone $value;
1109 $name = yourls_escape( $name );
1111 // Make sure the option doesn't already exist
1112 if ( false !== yourls_get_option( $name ) )
1115 $_value = yourls_escape( yourls_maybe_serialize( $value ) );
1117 yourls_do_action( 'add_option', $name, $_value );
1119 $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
1120 $ydb->option[ $name ] = $value;
1126 * Delete an option from the DB
1128 * Pretty much stolen from WordPress
1131 * @param string $option Option name to delete. Expected to not be SQL-escaped.
1132 * @return bool True, if option is successfully deleted. False on failure.
1134 function yourls_delete_option( $name ) {
1136 $table = YOURLS_DB_TABLE_OPTIONS;
1137 $name = yourls_escape( $name );
1139 // Get the ID, if no ID then return
1140 $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
1141 if ( is_null( $option ) || !$option->option_id )
1144 yourls_do_action( 'delete_option', $name );
1146 $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
1147 unset( $ydb->option[ $name ] );
1153 * Serialize data if needed. Stolen from WordPress
1156 * @param mixed $data Data that might be serialized.
1157 * @return mixed A scalar data
1159 function yourls_maybe_serialize( $data ) {
1160 if ( is_array( $data ) || is_object( $data ) )
1161 return serialize( $data );
1163 if ( yourls_is_serialized( $data, false ) )
1164 return serialize( $data );
1170 * Check value to find if it was serialized. Stolen from WordPress
1173 * @param mixed $data Value to check to see if was serialized.
1174 * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
1175 * @return bool False if not serialized and true if it was.
1177 function yourls_is_serialized( $data, $strict = true ) {
1178 // if it isn't a string, it isn't serialized
1179 if ( ! is_string( $data ) )
1181 $data = trim( $data );
1182 if ( 'N;' == $data )
1184 $length = strlen( $data );
1187 if ( ':' !== $data[1] )
1190 $lastc = $data[ $length - 1 ];
1191 if ( ';' !== $lastc && '}' !== $lastc )
1194 $semicolon = strpos( $data, ';' );
1195 $brace = strpos( $data, '}' );
1196 // Either ; or } must exist.
1197 if ( false === $semicolon && false === $brace )
1199 // But neither must be in the first X characters.
1200 if ( false !== $semicolon && $semicolon < 3 )
1202 if ( false !== $brace && $brace < 4 )
1209 if ( '"' !== $data[ $length - 2 ] )
1211 } elseif ( false === strpos( $data, '"' ) ) {
1214 // or else fall through
1217 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
1221 $end = $strict ? '$' : '';
1222 return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
1228 * Unserialize value only if it was serialized. Stolen from WP
1231 * @param string $original Maybe unserialized original, if is needed.
1232 * @return mixed Unserialized data can be any type.
1234 function yourls_maybe_unserialize( $original ) {
1235 if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
1236 return @unserialize( $original );
1241 * Determine if the current page is private
1244 function yourls_is_private() {
1247 if ( defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true ) {
1249 // Allow overruling for particular pages:
1252 if( yourls_is_API() ) {
1253 if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
1257 } elseif( yourls_is_infos() ) {
1258 if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
1268 return yourls_apply_filter( 'is_private', $private );
1272 * Show login form if required
1275 function yourls_maybe_require_auth() {
1276 if( yourls_is_private() ) {
1277 yourls_do_action( 'require_auth' );
1278 require_once( YOURLS_INC.'/auth.php' );
1280 yourls_do_action( 'require_no_auth' );
1285 * Allow several short URLs for the same long URL ?
1288 function yourls_allow_duplicate_longurls() {
1289 // special treatment if API to check for WordPress plugin requests
1290 if( yourls_is_API() ) {
1291 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' )
1294 return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
1298 * @deprecated Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.
1301 function yourls_get_duplicate_keywords( $longurl ) {
1302 yourls_deprecated_function( __FUNCTION__, 1.7, 'yourls_get_longurl_keywords' );
1303 if( !yourls_allow_duplicate_longurls() )
1305 return yourls_apply_filter( 'get_duplicate_keywords', yourls_get_longurl_keywords ( $longurl ), $longurl );
1309 * Return array of keywords that redirect to the submitted long URL
1312 * @param string $longurl long url
1313 * @param string $sort Optional ORDER BY order (can be 'keyword', 'title', 'timestamp' or'clicks')
1314 * @param string $order Optional SORT order (can be 'ASC' or 'DESC')
1315 * @return array array of keywords
1317 function yourls_get_longurl_keywords( $longurl, $sort = 'none', $order = 'ASC' ) {
1319 $longurl = yourls_escape( yourls_sanitize_url( $longurl ) );
1320 $table = YOURLS_DB_TABLE_URL;
1321 $query = "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'";
1323 // Ensure sort is a column in database (@TODO: update verification array if database changes)
1324 if ( in_array( $sort, array('keyword','title','timestamp','clicks') ) ) {
1325 $query .= " ORDER BY '".$sort."'";
1326 if ( in_array( $order, array( 'ASC','DESC' ) ) ) {
1327 $query .= " ".$order;
1330 return yourls_apply_filter( 'get_longurl_keywords', $ydb->get_col( $query ), $longurl );
1334 * Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
1337 function yourls_check_IP_flood( $ip = '' ) {
1339 // Allow plugins to short-circuit the whole function
1340 $pre = yourls_apply_filter( 'shunt_check_IP_flood', false, $ip );
1341 if ( false !== $pre )
1344 yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here
1346 // Raise white flag if installing or if no flood delay defined
1348 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
1349 !defined('YOURLS_FLOOD_DELAY_SECONDS') ||
1350 yourls_is_installing()
1354 // Don't throttle logged in users
1355 if( yourls_is_private() ) {
1356 if( yourls_is_valid_user() === true )
1360 // Don't throttle whitelist IPs
1361 if( defined( 'YOURLS_FLOOD_IP_WHITELIST' ) && YOURLS_FLOOD_IP_WHITELIST ) {
1362 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
1363 foreach( (array)$whitelist_ips as $whitelist_ip ) {
1364 $whitelist_ip = trim( $whitelist_ip );
1365 if ( $whitelist_ip == $ip )
1370 $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
1372 yourls_do_action( 'check_ip_flood', $ip );
1375 $table = YOURLS_DB_TABLE_URL;
1377 $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
1380 $then = date( 'U', strtotime( $lasttime ) );
1381 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
1383 yourls_do_action( 'ip_flood', $ip, $now - $then );
1384 yourls_die( yourls__( 'Too many URLs added too fast. Slow down please.' ), yourls__( 'Forbidden' ), 403 );
1392 * Check if YOURLS is installing
1397 function yourls_is_installing() {
1398 $installing = defined( 'YOURLS_INSTALLING' ) && YOURLS_INSTALLING == true;
1399 return yourls_apply_filter( 'is_installing', $installing );
1403 * Check if YOURLS is upgrading
1408 function yourls_is_upgrading() {
1409 $upgrading = defined( 'YOURLS_UPGRADING' ) && YOURLS_UPGRADING == true;
1410 return yourls_apply_filter( 'is_upgrading', $upgrading );
1415 * Check if YOURLS is installed
1417 * Checks property $ydb->installed that is created by yourls_get_all_options()
1419 * See inline comment for updating from 1.3 or prior.
1422 function yourls_is_installed() {
1424 $is_installed = ( property_exists( $ydb, 'installed' ) && $ydb->installed == true );
1425 return yourls_apply_filter( 'is_installed', $is_installed );
1427 /* Note: this test won't work on YOURLS 1.3 or older (Aug 2009...)
1428 Should someone complain that they cannot upgrade directly from
1429 1.3 to 1.7: first, laugh at them, then ask them to install 1.6 first.
1434 * Generate random string of (int)$length length and type $type (see function for details)
1437 function yourls_rnd_string ( $length = 5, $type = 0, $charlist = '' ) {
1439 $length = intval( $length );
1441 // define possible characters
1444 // custom char list, or comply to charset as defined in config
1446 $possible = $charlist ? $charlist : yourls_get_shorturl_charset() ;
1449 // no vowels to make no offending word, no 0/1/o/l to avoid confusion between letters & digits. Perfect for passwords.
1451 $possible = "23456789bcdfghjkmnpqrstvwxyz";
1454 // Same, with lower + upper
1456 $possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
1459 // all letters, lowercase
1461 $possible = "abcdefghijklmnopqrstuvwxyz";
1464 // all letters, lowercase + uppercase
1466 $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1469 // all digits & letters lowercase
1471 $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
1474 // all digits & letters lowercase + uppercase
1476 $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1482 while ($i < $length) {
1483 $str .= substr( $possible, mt_rand( 0, strlen( $possible )-1 ), 1 );
1487 return yourls_apply_filter( 'rnd_string', $str, $length, $type, $charlist );
1491 * Return salted string
1494 function yourls_salt( $string ) {
1495 $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
1496 return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt), $string );
1500 * Add a query var to a URL and return URL. Completely stolen from WP.
1502 * Works with one of these parameter patterns:
1503 * array( 'var' => 'value' )
1504 * array( 'var' => 'value' ), $url
1506 * 'var', 'value', $url
1507 * If $url omitted, uses $_SERVER['REQUEST_URI']
1510 function yourls_add_query_arg() {
1512 if ( is_array( func_get_arg(0) ) ) {
1513 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
1514 $uri = $_SERVER['REQUEST_URI'];
1516 $uri = @func_get_arg( 1 );
1518 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
1519 $uri = $_SERVER['REQUEST_URI'];
1521 $uri = @func_get_arg( 2 );
1524 $uri = str_replace( '&', '&', $uri );
1527 if ( $frag = strstr( $uri, '#' ) )
1528 $uri = substr( $uri, 0, -strlen( $frag ) );
1532 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
1533 $protocol = $matches[0];
1534 $uri = substr( $uri, strlen( $protocol ) );
1539 if ( strpos( $uri, '?' ) !== false ) {
1540 $parts = explode( '?', $uri, 2 );
1541 if ( 1 == count( $parts ) ) {
1545 $base = $parts[0] . '?';
1548 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
1556 parse_str( $query, $qs );
1557 $qs = yourls_urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
1558 if ( is_array( func_get_arg( 0 ) ) ) {
1559 $kayvees = func_get_arg( 0 );
1560 $qs = array_merge( $qs, $kayvees );
1562 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1565 foreach ( (array) $qs as $k => $v ) {
1570 $ret = http_build_query( $qs );
1571 $ret = trim( $ret, '?' );
1572 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1573 $ret = $protocol . $base . $ret . $frag;
1574 $ret = rtrim( $ret, '?' );
1579 * Navigates through an array and encodes the values to be used in a URL. Stolen from WP, used in yourls_add_query_arg()
1582 function yourls_urlencode_deep( $value ) {
1583 $value = is_array( $value ) ? array_map( 'yourls_urlencode_deep', $value ) : urlencode( $value );
1588 * Remove arg from query. Opposite of yourls_add_query_arg. Stolen from WP.
1591 function yourls_remove_query_arg( $key, $query = false ) {
1592 if ( is_array( $key ) ) { // removing multiple keys
1593 foreach ( $key as $k )
1594 $query = yourls_add_query_arg( $k, false, $query );
1597 return yourls_add_query_arg( $key, false, $query );
1601 * Return a time-dependent string for nonce creation
1604 function yourls_tick() {
1605 return ceil( time() / YOURLS_NONCE_LIFE );
1609 * Create a time limited, action limited and user limited token
1612 function yourls_create_nonce( $action, $user = false ) {
1613 if( false == $user )
1614 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1615 $tick = yourls_tick();
1616 return substr( yourls_salt($tick . $action . $user), 0, 10 );
1620 * Create a nonce field for inclusion into a form
1623 function yourls_nonce_field( $action, $name = 'nonce', $user = false, $echo = true ) {
1624 $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';
1631 * Add a nonce to a URL. If URL omitted, adds nonce to current URL
1634 function yourls_nonce_url( $action, $url = false, $name = 'nonce', $user = false ) {
1635 $nonce = yourls_create_nonce( $action, $user );
1636 return yourls_add_query_arg( $name, $nonce, $url );
1640 * Check validity of a nonce (ie time span, user and action match).
1642 * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined)
1643 * if $nonce is false or unspecified, it will use $_REQUEST['nonce']
1646 function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {
1648 if( false == $user )
1649 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1651 // get current nonce value
1652 if( false == $nonce && isset( $_REQUEST['nonce'] ) )
1653 $nonce = $_REQUEST['nonce'];
1655 // what nonce should be
1656 $valid = yourls_create_nonce( $action, $user );
1658 if( $nonce == $valid ) {
1663 yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );
1668 * Converts keyword into short link (prepend with YOURLS base URL)
1671 function yourls_link( $keyword = '' ) {
1672 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
1673 return yourls_apply_filter( 'yourls_link', $link, $keyword );
1677 * Converts keyword into stat link (prepend with YOURLS base URL, append +)
1680 function yourls_statlink( $keyword = '' ) {
1681 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword ) . '+';
1682 if( yourls_is_ssl() )
1683 $link = str_replace( 'http://', 'https://', $link );
1684 return yourls_apply_filter( 'yourls_statlink', $link, $keyword );
1688 * Check if we're in API mode. Returns bool
1691 function yourls_is_API() {
1692 if ( defined( 'YOURLS_API' ) && YOURLS_API == true )
1698 * Check if we're in Ajax mode. Returns bool
1701 function yourls_is_Ajax() {
1702 if ( defined( 'YOURLS_AJAX' ) && YOURLS_AJAX == true )
1708 * Check if we're in GO mode (yourls-go.php). Returns bool
1711 function yourls_is_GO() {
1712 if ( defined( 'YOURLS_GO' ) && YOURLS_GO == true )
1718 * Check if we're displaying stats infos (yourls-infos.php). Returns bool
1721 function yourls_is_infos() {
1722 if ( defined( 'YOURLS_INFOS' ) && YOURLS_INFOS == true )
1728 * Check if we'll need interface display function (ie not API or redirection)
1731 function yourls_has_interface() {
1732 if( yourls_is_API() or yourls_is_GO() )
1738 * Check if we're in the admin area. Returns bool
1741 function yourls_is_admin() {
1742 if ( defined( 'YOURLS_ADMIN' ) && YOURLS_ADMIN == true )
1748 * Check if the server seems to be running on Windows. Not exactly sure how reliable this is.
1751 function yourls_is_windows() {
1752 return defined( 'DIRECTORY_SEPARATOR' ) && DIRECTORY_SEPARATOR == '\\';
1756 * Check if SSL is required. Returns bool.
1759 function yourls_needs_ssl() {
1760 if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
1766 * Return admin link, with SSL preference if applicable.
1769 function yourls_admin_url( $page = '' ) {
1770 $admin = YOURLS_SITE . '/admin/' . $page;
1771 if( yourls_is_ssl() or yourls_needs_ssl() )
1772 $admin = str_replace('http://', 'https://', $admin);
1773 return yourls_apply_filter( 'admin_url', $admin, $page );
1777 * Return YOURLS_SITE or URL under YOURLS setup, with SSL preference
1780 function yourls_site_url( $echo = true, $url = '' ) {
1781 $url = yourls_get_relative_url( $url );
1782 $url = trim( YOURLS_SITE . '/' . $url, '/' );
1784 // Do not enforce (checking yourls_need_ssl() ) but check current usage so it won't force SSL on non-admin pages
1785 if( yourls_is_ssl() )
1786 $url = str_replace( 'http://', 'https://', $url );
1787 $url = yourls_apply_filter( 'site_url', $url );
1794 * Check if SSL is used, returns bool. Stolen from WP.
1797 function yourls_is_ssl() {
1799 if ( isset( $_SERVER['HTTPS'] ) ) {
1800 if ( 'on' == strtolower( $_SERVER['HTTPS'] ) )
1802 if ( '1' == $_SERVER['HTTPS'] )
1804 } elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
1807 return yourls_apply_filter( 'is_ssl', $is_ssl );
1811 * Get a remote page title
1813 * This function returns a string: either the page title as defined in HTML, or the URL if not found
1814 * The function tries to convert funky characters found in titles to UTF8, from the detected charset.
1815 * Charset in use is guessed from HTML meta tag, or if not found, from server's 'content-type' response.
1817 * @param string $url URL
1818 * @return string Title (sanitized) or the URL if no title found
1820 function yourls_get_remote_title( $url ) {
1821 // Allow plugins to short-circuit the whole function
1822 $pre = yourls_apply_filter( 'shunt_get_remote_title', false, $url );
1823 if ( false !== $pre )
1826 $url = yourls_sanitize_url( $url );
1828 // Only deal with http(s)://
1829 if( !in_array( yourls_get_protocol( $url ), array( 'http://', 'https://' ) ) )
1832 $title = $charset = false;
1834 $response = yourls_http_get( $url ); // can be a Request object or an error string
1835 if( is_string( $response ) ) {
1839 // Page content. No content? Return the URL
1840 $content = $response->body;
1844 // look for <title>. No title found? Return the URL
1845 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {
1852 // Now we have a title. We'll try to get proper utf8 from it.
1854 // Get charset as (and if) defined by the HTML meta tag. We should match
1855 // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1856 // or <meta charset='utf-8'> and all possible variations: see https://gist.github.com/ozh/7951236
1857 if ( preg_match( '/<meta[^>]*charset\s*=["\' ]*([a-zA-Z0-9\-_]+)/is', $content, $found ) ) {
1858 $charset = $found[1];
1861 // No charset found in HTML. Get charset as (and if) defined by the server response
1862 $_charset = current( $response->headers->getValues( 'content-type' ) );
1863 if( preg_match( '/charset=(\S+)/', $_charset, $found ) ) {
1864 $charset = trim( $found[1], ';' );
1869 // Conversion to utf-8 if what we have is not utf8 already
1870 if( strtolower( $charset ) != 'utf-8' && function_exists( 'mb_convert_encoding' ) ) {
1871 // We use @ to remove warnings because mb_ functions are easily bitching about illegal chars
1873 $title = @mb_convert_encoding( $title, 'UTF-8', $charset );
1875 $title = @mb_convert_encoding( $title, 'UTF-8' );
1879 // Remove HTML entities
1880 $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' );
1882 // Strip out evil things
1883 $title = yourls_sanitize_title( $title );
1885 return yourls_apply_filter( 'get_remote_title', $title, $url );
1889 * Quick UA check for mobile devices. Return boolean.
1892 function yourls_is_mobile_device() {
1895 'android', 'blackberry', 'blazer',
1896 'compal', 'elaine', 'fennec', 'hiptop',
1897 'iemobile', 'iphone', 'ipod', 'ipad',
1898 'iris', 'kindle', 'opera mobi', 'opera mini',
1899 'palm', 'phone', 'pocket', 'psp', 'symbian',
1900 'treo', 'wap', 'windows ce', 'windows phone'
1903 // Current user-agent
1904 $current = strtolower( $_SERVER['HTTP_USER_AGENT'] );
1907 $is_mobile = ( str_replace( $mobiles, '', $current ) != $current );
1908 return yourls_apply_filter( 'is_mobile_device', $is_mobile );
1912 * Get request in YOURLS base (eg in 'http://site.com/yourls/abcd' get 'abdc')
1915 function yourls_get_request() {
1916 // Allow plugins to short-circuit the whole function
1917 $pre = yourls_apply_filter( 'shunt_get_request', false );
1918 if ( false !== $pre )
1921 static $request = null;
1923 yourls_do_action( 'pre_get_request', $request );
1925 if( $request !== null )
1928 // Ignore protocol & www. prefix
1929 $root = str_replace( array( 'https://', 'http://', 'https://www.', 'http://www.' ), '', YOURLS_SITE );
1930 // Case insensitive comparison of the YOURLS root to match both http://Sho.rt/blah and http://sho.rt/blah
1931 $request = preg_replace( "!$root/!i", '', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 1 );
1933 // Unless request looks like a full URL (ie request is a simple keyword) strip query string
1934 if( !preg_match( "@^[a-zA-Z]+://.+@", $request ) ) {
1935 $request = current( explode( '?', $request ) );
1938 return yourls_apply_filter( 'get_request', $request );
1942 * Change protocol to match current scheme used (http or https)
1945 function yourls_match_current_protocol( $url, $normal = 'http://', $ssl = 'https://' ) {
1946 if( yourls_is_ssl() )
1947 $url = str_replace( $normal, $ssl, $url );
1948 return yourls_apply_filter( 'match_current_protocol', $url );
1952 * Fix $_SERVER['REQUEST_URI'] variable for various setups. Stolen from WP.
1955 function yourls_fix_request_uri() {
1957 $default_server_values = array(
1958 'SERVER_SOFTWARE' => '',
1959 'REQUEST_URI' => '',
1961 $_SERVER = array_merge( $default_server_values, $_SERVER );
1963 // Fix for IIS when running with PHP ISAPI
1964 if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {
1967 if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
1968 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
1970 // IIS Isapi_Rewrite
1971 else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {
1972 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
1974 // Use ORIG_PATH_INFO if there is no PATH_INFO
1975 if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )
1976 $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
1978 // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
1979 if ( isset( $_SERVER['PATH_INFO'] ) ) {
1980 if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
1981 $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
1983 $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
1986 // Append the query string if it exists and isn't null
1987 if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
1988 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
1995 * Shutdown function, runs just before PHP shuts down execution. Stolen from WP
1998 function yourls_shutdown() {
1999 yourls_do_action( 'shutdown' );
2003 * Auto detect custom favicon in /user directory, fallback to YOURLS favicon, and echo/return its URL
2006 function yourls_favicon( $echo = true ) {
2007 static $favicon = null;
2008 if( $favicon !== null )
2012 // search for favicon.(gif|ico|png|jpg|svg)
2013 foreach( array( 'gif', 'ico', 'png', 'jpg', 'svg' ) as $ext ) {
2014 if( file_exists( YOURLS_USERDIR. '/favicon.' . $ext ) ) {
2015 $custom = 'favicon.' . $ext;
2021 $favicon = yourls_site_url( false, YOURLS_USERURL . '/' . $custom );
2023 $favicon = yourls_site_url( false ) . '/images/favicon.gif';
2031 * Check for maintenance mode. If yes, die. See yourls_maintenance_mode(). Stolen from WP.
2034 function yourls_check_maintenance_mode() {
2036 $file = YOURLS_ABSPATH . '/.maintenance' ;
2037 if ( !file_exists( $file ) || yourls_is_upgrading() || yourls_is_installing() )
2040 global $maintenance_start;
2042 include_once( $file );
2043 // If the $maintenance_start timestamp is older than 10 minutes, don't die.
2044 if ( ( time() - $maintenance_start ) >= 600 )
2047 // Use any /user/maintenance.php file
2048 if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {
2049 include_once( YOURLS_USERDIR.'/maintenance.php' );
2053 // https://www.youtube.com/watch?v=Xw-m4jEY-Ns
2054 $title = yourls__( 'Service temporarily unavailable' );
2055 $message = yourls__( 'Our service is currently undergoing scheduled maintenance.' ) . "</p>\n<p>" .
2056 yourls__( 'Things should not last very long, thank you for your patience and please excuse the inconvenience' );
2057 yourls_die( $message, $title , 503 );
2062 * Return current admin page, or null if not an admin page
2064 * @return mixed string if admin page, null if not an admin page
2067 function yourls_current_admin_page() {
2068 if( yourls_is_admin() ) {
2069 $current = substr( yourls_get_request(), 6 );
2070 if( $current === false )
2071 $current = 'index.php'; // if current page is http://sho.rt/admin/ instead of http://sho.rt/admin/index.php
2079 * Check if a URL protocol is allowed
2081 * Checks a URL against a list of whitelisted protocols. Protocols must be defined with
2082 * their complete scheme name, ie 'stuff:' or 'stuff://' (for instance, 'mailto:' is a valid
2083 * protocol, 'mailto://' isn't, and 'http:' with no double slashed isn't either
2087 * @param string $url URL to be check
2088 * @param array $protocols Optional. Array of protocols, defaults to global $yourls_allowedprotocols
2089 * @return boolean true if protocol allowed, false otherwise
2091 function yourls_is_allowed_protocol( $url, $protocols = array() ) {
2092 if( ! $protocols ) {
2093 global $yourls_allowedprotocols;
2094 $protocols = $yourls_allowedprotocols;
2097 $protocol = yourls_get_protocol( $url );
2098 return yourls_apply_filter( 'is_allowed_protocol', in_array( $protocol, $protocols ), $url, $protocols );
2102 * Get protocol from a URL (eg mailto:, http:// ...)
2106 * @param string $url URL to be check
2107 * @return string Protocol, with slash slash if applicable. Empty string if no protocol
2109 function yourls_get_protocol( $url ) {
2110 preg_match( '!^[a-zA-Z0-9\+\.-]+:(//)?!', $url, $matches );
2112 http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
2113 The scheme name consists of a sequence of characters beginning with a letter and followed by any
2114 combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). Although schemes are
2115 case-insensitive, the canonical form is lowercase and documents that specify schemes must do so
2116 with lowercase letters. It is followed by a colon (":").
2118 $protocol = ( isset( $matches[0] ) ? $matches[0] : '' );
2119 return yourls_apply_filter( 'get_protocol', $protocol, $url );
2123 * Get relative URL (eg 'abc' from 'http://sho.rt/abc')
2125 * Treat indifferently http & https. If a URL isn't relative to the YOURLS install, return it as is
2126 * or return empty string if $strict is true
2129 * @param string $url URL to relativize
2130 * @param bool $strict if true and if URL isn't relative to YOURLS install, return empty string
2131 * @return string URL
2133 function yourls_get_relative_url( $url, $strict = true ) {
2134 $url = yourls_sanitize_url( $url );
2136 // Remove protocols to make it easier
2137 $noproto_url = str_replace( 'https:', 'http:', $url );
2138 $noproto_site = str_replace( 'https:', 'http:', YOURLS_SITE );
2140 // Trim URL from YOURLS root URL : if no modification made, URL wasn't relative
2141 $_url = str_replace( $noproto_site . '/', '', $noproto_url );
2142 if( $_url == $noproto_url )
2143 $_url = ( $strict ? '' : $url );
2145 return yourls_apply_filter( 'get_relative_url', $_url, $url );
2149 * Marks a function as deprecated and informs when it has been used. Stolen from WP.
2151 * There is a hook deprecated_function that will be called that can be used
2152 * to get the backtrace up to what file and function called the deprecated
2155 * The current behavior is to trigger a user error if YOURLS_DEBUG is true.
2157 * This function is to be used in every function that is deprecated.
2160 * @uses yourls_do_action() Calls 'deprecated_function' and passes the function name, what to use instead,
2161 * and the version the function was deprecated in.
2162 * @uses yourls_apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2163 * trigger or false to not trigger error.
2165 * @param string $function The function that was called
2166 * @param string $version The version of WordPress that deprecated the function
2167 * @param string $replacement Optional. The function that should have been called
2169 function yourls_deprecated_function( $function, $version, $replacement = null ) {
2171 yourls_do_action( 'deprecated_function', $function, $replacement, $version );
2173 // Allow plugin to filter the output error trigger
2174 if ( YOURLS_DEBUG && yourls_apply_filters( 'deprecated_function_trigger_error', true ) ) {
2175 if ( ! is_null( $replacement ) )
2176 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2178 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2183 * Return the value if not an empty string
2185 * Used with array_filter(), to remove empty keys but not keys with value 0 or false
2188 * @param mixed $val Value to test against ''
2189 * @return bool True if not an empty string
2191 function yourls_return_if_not_empty_string( $val ) {
2192 return( $val !== '' );