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 ) {
133 // Allow plugins to short-circuit the whole function
134 $pre = yourls_apply_filter( 'shunt_delete_link_by_keyword', null, $keyword );
140 $table = YOURLS_DB_TABLE_URL;
141 $keyword = yourls_sanitize_string( $keyword );
142 $delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
143 yourls_do_action( 'delete_link', $keyword, $delete );
148 * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting
151 function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {
154 $url = yourls_escape( yourls_sanitize_url( $url ) );
155 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
156 $title = yourls_escape( yourls_sanitize_title( $title ) );
158 $table = YOURLS_DB_TABLE_URL;
159 $timestamp = date('Y-m-d H:i:s');
160 $ip = yourls_get_IP();
161 $insert = $ydb->query("INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");
163 yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );
165 return (bool)$insert;
169 * Check if a URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.
172 function yourls_url_exists( $url ) {
173 // Allow plugins to short-circuit the whole function
174 $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );
175 if ( false !== $pre )
179 $table = YOURLS_DB_TABLE_URL;
180 $strip_url = stripslashes($url);
181 $url_exists = $ydb->get_row("SELECT * FROM `$table` WHERE `url` = '".$strip_url."';");
183 return yourls_apply_filter( 'url_exists', $url_exists, $url );
187 * Add a new link in the DB, either with custom keyword, or find one
190 function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
191 // Allow plugins to short-circuit the whole function
192 $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
193 if ( false !== $pre )
196 $url = yourls_encodeURI( $url );
197 $url = yourls_escape( yourls_sanitize_url( $url ) );
198 if ( !$url || $url == 'http://' || $url == 'https://' ) {
199 $return['status'] = 'fail';
200 $return['code'] = 'error:nourl';
201 $return['message'] = yourls__( 'Missing or malformed URL' );
202 $return['errorCode'] = '400';
203 return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
207 $ip = yourls_get_IP();
208 yourls_check_IP_flood( $ip );
210 // Prevent internal redirection loops: cannot shorten a shortened URL
211 if( yourls_get_relative_url( $url ) ) {
212 if( yourls_is_shorturl( $url ) ) {
213 $return['status'] = 'fail';
214 $return['code'] = 'error:noloop';
215 $return['message'] = yourls__( 'URL is a short URL' );
216 $return['errorCode'] = '400';
217 return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );
221 yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );
223 $strip_url = stripslashes( $url );
226 // duplicates allowed or new URL => store it
227 if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_url_exists( $url ) ) ) {
229 if( isset( $title ) && !empty( $title ) ) {
230 $title = yourls_sanitize_title( $title );
232 $title = yourls_get_remote_title( $url );
234 $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );
236 // Custom keyword provided
239 yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );
241 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
242 $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );
243 if ( !yourls_keyword_is_free( $keyword ) ) {
244 // This shorturl either reserved or taken already
245 $return['status'] = 'fail';
246 $return['code'] = 'error:keyword';
247 $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );
249 // all clear, store !
250 yourls_insert_link_in_db( $url, $keyword, $title );
251 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
252 $return['status'] = 'success';
253 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
254 $return['title'] = $title;
255 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
256 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
259 // Create random keyword
262 yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );
264 $timestamp = date( 'Y-m-d H:i:s' );
265 $id = yourls_get_next_decimal();
268 $keyword = yourls_int2string( $id );
269 $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );
270 if ( yourls_keyword_is_free($keyword) ) {
271 if( @yourls_insert_link_in_db( $url, $keyword, $title ) ){
272 // everything ok, populate needed vars
273 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );
274 $return['status'] = 'success';
275 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
276 $return['title'] = $title;
277 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
278 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
280 // database error, couldnt store result
281 $return['status'] = 'fail';
282 $return['code'] = 'error:db';
283 $return['message'] = yourls_s( 'Error saving url to database' );
289 @yourls_update_next_decimal( $id );
292 // URL was already stored
295 yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );
297 $return['status'] = 'fail';
298 $return['code'] = 'error:url';
299 $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 );
300 $return['message'] = /* //translators: eg "http://someurl/ already exists" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $strip_url ) );
301 $return['title'] = $url_exists->title;
302 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
305 yourls_do_action( 'post_add_new_link', $url, $keyword, $title );
307 $return['statusCode'] = 200; // regardless of result, this is still a valid request
308 return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );
316 function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {
317 // Allow plugins to short-circuit the whole function
318 $pre = yourls_apply_filter( 'shunt_edit_link', null, $keyword, $url, $keyword, $newkeyword, $title );
324 $table = YOURLS_DB_TABLE_URL;
325 $url = yourls_escape (yourls_sanitize_url( $url ) );
326 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
327 $title = yourls_escape( yourls_sanitize_title( $title ) );
328 $newkeyword = yourls_escape( yourls_sanitize_string( $newkeyword ) );
329 $strip_url = stripslashes( $url );
330 $strip_title = stripslashes( $title );
331 $old_url = $ydb->get_var( "SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';" );
333 // Check if new URL is not here already
334 if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {
335 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
337 $new_url_already_there = false;
340 // Check if the new keyword is not here already
341 if ( $newkeyword != $keyword ) {
342 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
344 $keyword_is_ok = true;
347 yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );
350 if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
351 $update_url = $ydb->query( "UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';" );
353 $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 ) );
354 $return['status'] = 'success';
355 $return['message'] = yourls__( 'Link updated in database' );
357 $return['status'] = 'fail';
358 $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 ) ;
363 $return['status'] = 'fail';
364 $return['message'] = yourls__( 'URL or keyword already exists in database' );
367 return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );
371 * Update a title link (no checks for duplicates etc..)
374 function yourls_edit_link_title( $keyword, $title ) {
375 // Allow plugins to short-circuit the whole function
376 $pre = yourls_apply_filter( 'shunt_edit_link_title', null, $keyword, $title );
382 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
383 $title = yourls_escape( yourls_sanitize_title( $title ) );
385 $table = YOURLS_DB_TABLE_URL;
386 $update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");
393 * Check if keyword id is free (ie not already taken, and not reserved). Return bool.
396 function yourls_keyword_is_free( $keyword ) {
398 if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
401 return yourls_apply_filter( 'keyword_is_free', $free, $keyword );
405 * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.
408 function yourls_keyword_is_taken( $keyword ) {
410 // Allow plugins to short-circuit the whole function
411 $pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );
412 if ( false !== $pre )
416 $keyword = yourls_sanitize_keyword( $keyword );
418 $table = YOURLS_DB_TABLE_URL;
419 $already_exists = $ydb->get_var( "SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';" );
420 if ( $already_exists )
423 return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );
431 function yourls_db_connect() {
434 if ( !defined( 'YOURLS_DB_USER' )
435 or !defined( 'YOURLS_DB_PASS' )
436 or !defined( 'YOURLS_DB_NAME' )
437 or !defined( 'YOURLS_DB_HOST' )
438 ) yourls_die ( yourls__( 'Incorrect DB config, or could not connect to DB' ), yourls__( 'Fatal error' ), 503 );
440 // Are we standalone or in the WordPress environment?
441 if ( class_exists( 'wpdb', false ) ) {
442 /* TODO: should we deprecate this? Follow WP dev in that area */
443 $ydb = new wpdb( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
445 yourls_set_DB_driver();
448 // Check if connection attempt raised an error. It seems that only PDO does, though.
449 if ( $ydb->last_error )
450 yourls_die( $ydb->last_error, yourls__( 'Fatal error' ), 503 );
452 if ( defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG === true )
453 $ydb->show_errors = true;
462 function yourls_xml_encode( $array ) {
463 require_once( YOURLS_INC.'/functions-xml.php' );
464 $converter= new yourls_array2xml;
465 return $converter->array2xml( $array );
469 * 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
472 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
474 $keyword = yourls_sanitize_string( $keyword );
476 yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );
478 if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
479 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
482 yourls_do_action( 'get_keyword_not_cached', $keyword );
484 $table = YOURLS_DB_TABLE_URL;
485 $infos = $ydb->get_row( "SELECT * FROM `$table` WHERE `keyword` = '$keyword'" );
488 $infos = (array)$infos;
489 $ydb->infos[ $keyword ] = $infos;
491 $ydb->infos[ $keyword ] = false;
494 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
498 * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
501 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
503 // Allow plugins to short-circuit the whole function
504 $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );
505 if ( false !== $pre )
508 $keyword = yourls_sanitize_string( $keyword );
509 $infos = yourls_get_keyword_infos( $keyword );
512 if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )
513 $return = $infos[ $field ];
515 return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );
519 * Return title associated with keyword. Optional $notfound = string default message if nothing found
522 function yourls_get_keyword_title( $keyword, $notfound = false ) {
523 return yourls_get_keyword_info( $keyword, 'title', $notfound );
527 * Return long URL associated with keyword. Optional $notfound = string default message if nothing found
530 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
531 return yourls_get_keyword_info( $keyword, 'url', $notfound );
535 * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
538 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
539 return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
543 * Return IP that added a keyword. Optional $notfound = string default message if nothing found
546 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
547 return yourls_get_keyword_info( $keyword, 'ip', $notfound );
551 * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
554 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
555 return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
559 * Update click count on a short URL. Return 0/1 for error/success.
562 function yourls_update_clicks( $keyword, $clicks = false ) {
563 // Allow plugins to short-circuit the whole function
564 $pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword, $clicks );
565 if ( false !== $pre )
569 $keyword = yourls_sanitize_string( $keyword );
570 $table = YOURLS_DB_TABLE_URL;
571 if ( $clicks !== false && is_int( $clicks ) && $clicks >= 0 )
572 $update = $ydb->query( "UPDATE `$table` SET `clicks` = $clicks WHERE `keyword` = '$keyword'" );
574 $update = $ydb->query( "UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'" );
576 yourls_do_action( 'update_clicks', $keyword, $update, $clicks );
581 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
584 function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {
593 $sort_by = 'timestamp';
594 $sort_order = 'desc';
604 $sort_order = 'desc';
609 $limit = intval( $limit );
610 $start = intval( $start );
613 $table_url = YOURLS_DB_TABLE_URL;
614 $results = $ydb->get_results( "SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;" );
619 foreach ( (array)$results as $res ) {
620 $return['links']['link_'.$i++] = array(
621 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
623 'title' => $res->title,
624 'timestamp'=> $res->timestamp,
626 'clicks' => $res->clicks,
631 $return['stats'] = yourls_get_db_stats();
633 $return['statusCode'] = 200;
635 return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );
639 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
642 function yourls_get_link_stats( $shorturl ) {
645 $table_url = YOURLS_DB_TABLE_URL;
646 $res = $ydb->get_row( "SELECT * FROM `$table_url` WHERE keyword = '$shorturl';" );
653 'message' => 'Error: short URL not found',
658 'message' => 'success',
660 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
662 'title' => $res->title,
663 'timestamp'=> $res->timestamp,
665 'clicks' => $res->clicks,
670 return yourls_apply_filter( 'get_link_stats', $return, $shorturl );
674 * Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
677 function yourls_get_db_stats( $where = '' ) {
679 $table_url = YOURLS_DB_TABLE_URL;
681 $totals = $ydb->get_row( "SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where" );
682 $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
684 return yourls_apply_filter( 'get_db_stats', $return, $where );
688 * Get number of SQL queries performed
691 function yourls_get_num_queries() {
694 return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );
698 * Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
701 function yourls_get_user_agent() {
702 if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
705 $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
706 $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
708 return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );
712 * Redirect to another page
715 function yourls_redirect( $location, $code = 301 ) {
716 yourls_do_action( 'pre_redirect', $location, $code );
717 $location = yourls_apply_filter( 'redirect_location', $location, $code );
718 $code = yourls_apply_filter( 'redirect_code', $code, $location );
719 // Redirect, either properly if possible, or via Javascript otherwise
720 if( !headers_sent() ) {
721 yourls_status_header( $code );
722 header( "Location: $location" );
724 yourls_redirect_javascript( $location );
730 * Set HTTP status header
733 function yourls_status_header( $code = 200 ) {
737 $protocol = $_SERVER['SERVER_PROTOCOL'];
738 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
739 $protocol = 'HTTP/1.0';
741 $code = intval( $code );
742 $desc = yourls_get_HTTP_status( $code );
744 @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
745 yourls_do_action( 'status_header', $code );
749 * 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)
752 function yourls_redirect_javascript( $location, $dontwait = true ) {
753 yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );
754 $location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );
756 $message = yourls_s( 'if you are not redirected after 10 seconds, please <a href="%s">click here</a>', $location );
758 <script type="text/javascript">
759 window.location="$location";
761 <small>($message)</small>
764 echo '<p>' . yourls_s( 'Please <a href="%s">click here</a>', $location ) . '</p>';
766 yourls_do_action( 'post_redirect_javascript', $location );
770 * Return a HTTP status code
773 function yourls_get_HTTP_status( $code ) {
774 $code = intval( $code );
775 $headers_desc = array(
777 101 => 'Switching Protocols',
783 203 => 'Non-Authoritative Information',
785 205 => 'Reset Content',
786 206 => 'Partial Content',
787 207 => 'Multi-Status',
790 300 => 'Multiple Choices',
791 301 => 'Moved Permanently',
794 304 => 'Not Modified',
797 307 => 'Temporary Redirect',
799 400 => 'Bad Request',
800 401 => 'Unauthorized',
801 402 => 'Payment Required',
804 405 => 'Method Not Allowed',
805 406 => 'Not Acceptable',
806 407 => 'Proxy Authentication Required',
807 408 => 'Request Timeout',
810 411 => 'Length Required',
811 412 => 'Precondition Failed',
812 413 => 'Request Entity Too Large',
813 414 => 'Request-URI Too Long',
814 415 => 'Unsupported Media Type',
815 416 => 'Requested Range Not Satisfiable',
816 417 => 'Expectation Failed',
817 422 => 'Unprocessable Entity',
819 424 => 'Failed Dependency',
820 426 => 'Upgrade Required',
822 500 => 'Internal Server Error',
823 501 => 'Not Implemented',
824 502 => 'Bad Gateway',
825 503 => 'Service Unavailable',
826 504 => 'Gateway Timeout',
827 505 => 'HTTP Version Not Supported',
828 506 => 'Variant Also Negotiates',
829 507 => 'Insufficient Storage',
830 510 => 'Not Extended'
833 if ( isset( $headers_desc[$code] ) )
834 return $headers_desc[$code];
841 * Log a redirect (for stats)
844 function yourls_log_redirect( $keyword ) {
845 // Allow plugins to short-circuit the whole function
846 $pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );
847 if ( false !== $pre )
850 if ( !yourls_do_log_redirect() )
854 $table = YOURLS_DB_TABLE_LOG;
856 $keyword = yourls_sanitize_string( $keyword );
857 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
858 $ua = yourls_get_user_agent();
859 $ip = yourls_get_IP();
860 $location = yourls_geo_ip_to_countrycode( $ip );
862 return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
866 * Check if we want to not log redirects (for stats)
869 function yourls_do_log_redirect() {
870 return ( !defined( 'YOURLS_NOSTATS' ) || YOURLS_NOSTATS != true );
874 * Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
877 * @param string $ip IP or, if empty string, will be current user IP
878 * @param string $defaut Default string to return if IP doesn't resolve to a country (malformed, private IP...)
879 * @return string 2 letter country code (eg 'US') or $default
881 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
882 // Allow plugins to short-circuit the Geo IP API
883 $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
884 if ( false !== $location )
888 $ip = yourls_get_IP();
890 // Use IPv4 or IPv6 DB & functions
891 if( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
893 $func = 'geoip_country_code_by_addr';
896 $func = 'geoip_country_code_by_addr_v6';
899 if ( !file_exists( YOURLS_INC . '/geo/' . $db ) || !file_exists( YOURLS_INC .'/geo/geoip.inc' ) )
902 require_once( YOURLS_INC . '/geo/geoip.inc' );
903 $gi = geoip_open( YOURLS_INC . '/geo/' . $db, GEOIP_STANDARD );
905 $location = call_user_func( $func, $gi, $ip );
906 } catch ( Exception $e ) {
911 if( '' == $location )
912 $location = $default;
914 return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );
918 * Converts a 2 letter country code to long name (ie AU -> Australia)
921 function yourls_geo_countrycode_to_countryname( $code ) {
922 // Allow plugins to short-circuit the Geo IP API
923 $country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );
924 if ( false !== $country )
927 // Load the Geo class if not already done
928 if( !class_exists( 'GeoIP', false ) ) {
929 $temp = yourls_geo_ip_to_countrycode( '127.0.0.1' );
932 if( class_exists( 'GeoIP', false ) ) {
934 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[ $code ];
935 $long = $geo->GEOIP_COUNTRY_NAMES[ $id ];
943 * Return flag URL from 2 letter country code
946 function yourls_geo_get_flag( $code ) {
947 if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {
948 $img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.( strtolower( $code ) ).'.gif' );
952 return yourls_apply_filter( 'geo_get_flag', $img, $code );
957 * Check if an upgrade is needed
960 function yourls_upgrade_is_needed() {
961 // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
962 list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
963 if( $currentsql < YOURLS_DB_VERSION )
970 * Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
973 function yourls_get_current_version_from_sql() {
974 $currentver = yourls_get_option( 'version' );
975 $currentsql = yourls_get_option( 'db_version' );
977 // Values if version is 1.3
983 return array( $currentver, $currentsql);
987 * Read an option from DB (or from cache if available). Return value or $default if not found
989 * Pretty much stolen from WordPress
992 * @param string $option Option name. Expected to not be SQL-escaped.
993 * @param mixed $default Optional value to return if option doesn't exist. Default false.
994 * @return mixed Value set for the option.
996 function yourls_get_option( $option_name, $default = false ) {
999 // Allow plugins to short-circuit options
1000 $pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );
1001 if ( false !== $pre )
1004 // If option not cached already, get its value from the DB
1005 if ( !isset( $ydb->option[$option_name] ) ) {
1006 $table = YOURLS_DB_TABLE_OPTIONS;
1007 $option_name = yourls_escape( $option_name );
1008 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
1009 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
1010 $value = $row->option_value;
1011 } else { // option does not exist, so we must cache its non-existence
1014 $ydb->option[ $option_name ] = yourls_maybe_unserialize( $value );
1017 return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );
1021 * Read all options from DB at once
1023 * The goal is to read all option at once and then populate array $ydb->option, to prevent further
1024 * SQL queries if we need to read an option value later.
1025 * It's also a simple check whether YOURLS is installed or not (no option = assuming not installed)
1029 function yourls_get_all_options() {
1032 // Allow plugins to short-circuit all options. (Note: regular plugins are loaded after all options)
1033 $pre = yourls_apply_filter( 'shunt_all_options', false );
1034 if ( false !== $pre )
1037 $table = YOURLS_DB_TABLE_OPTIONS;
1039 $allopt = $ydb->get_results( "SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1" );
1041 foreach( (array)$allopt as $option ) {
1042 $ydb->option[ $option->option_name ] = yourls_maybe_unserialize( $option->option_value );
1045 if( property_exists( $ydb, 'option' ) ) {
1046 $ydb->option = yourls_apply_filter( 'get_all_options', $ydb->option );
1047 $ydb->installed = true;
1049 // Zero option found: assume YOURLS is not installed
1050 $ydb->installed = false;
1055 * Update (add if doesn't exist) an option to DB
1057 * Pretty much stolen from WordPress
1060 * @param string $option Option name. Expected to not be SQL-escaped.
1061 * @param mixed $newvalue Option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.
1062 * @return bool False if value was not updated, true otherwise.
1064 function yourls_update_option( $option_name, $newvalue ) {
1066 $table = YOURLS_DB_TABLE_OPTIONS;
1068 $option_name = trim( $option_name );
1069 if ( empty( $option_name ) )
1072 // Use clone to break object refs -- see commit 09b989d375bac65e692277f61a84fede2fb04ae3
1073 if ( is_object( $newvalue ) )
1074 $newvalue = clone $newvalue;
1076 $option_name = yourls_escape( $option_name );
1078 $oldvalue = yourls_get_option( $option_name );
1080 // If the new and old values are the same, no need to update.
1081 if ( $newvalue === $oldvalue )
1084 if ( false === $oldvalue ) {
1085 yourls_add_option( $option_name, $newvalue );
1089 $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
1091 yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );
1093 $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'" );
1095 if ( $ydb->rows_affected == 1 ) {
1096 $ydb->option[ $option_name ] = $newvalue;
1103 * Add an option to the DB
1105 * Pretty much stolen from WordPress
1108 * @param string $option Name of option to add. Expected to not be SQL-escaped.
1109 * @param mixed $value Optional option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.
1110 * @return bool False if option was not added and true otherwise.
1112 function yourls_add_option( $name, $value = '' ) {
1114 $table = YOURLS_DB_TABLE_OPTIONS;
1116 $name = trim( $name );
1117 if ( empty( $name ) )
1120 // Use clone to break object refs -- see commit 09b989d375bac65e692277f61a84fede2fb04ae3
1121 if ( is_object( $value ) )
1122 $value = clone $value;
1124 $name = yourls_escape( $name );
1126 // Make sure the option doesn't already exist
1127 if ( false !== yourls_get_option( $name ) )
1130 $_value = yourls_escape( yourls_maybe_serialize( $value ) );
1132 yourls_do_action( 'add_option', $name, $_value );
1134 $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
1135 $ydb->option[ $name ] = $value;
1141 * Delete an option from the DB
1143 * Pretty much stolen from WordPress
1146 * @param string $option Option name to delete. Expected to not be SQL-escaped.
1147 * @return bool True, if option is successfully deleted. False on failure.
1149 function yourls_delete_option( $name ) {
1151 $table = YOURLS_DB_TABLE_OPTIONS;
1152 $name = yourls_escape( $name );
1154 // Get the ID, if no ID then return
1155 $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
1156 if ( is_null( $option ) || !$option->option_id )
1159 yourls_do_action( 'delete_option', $name );
1161 $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
1162 unset( $ydb->option[ $name ] );
1168 * Serialize data if needed. Stolen from WordPress
1171 * @param mixed $data Data that might be serialized.
1172 * @return mixed A scalar data
1174 function yourls_maybe_serialize( $data ) {
1175 if ( is_array( $data ) || is_object( $data ) )
1176 return serialize( $data );
1178 if ( yourls_is_serialized( $data, false ) )
1179 return serialize( $data );
1185 * Check value to find if it was serialized. Stolen from WordPress
1188 * @param mixed $data Value to check to see if was serialized.
1189 * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
1190 * @return bool False if not serialized and true if it was.
1192 function yourls_is_serialized( $data, $strict = true ) {
1193 // if it isn't a string, it isn't serialized
1194 if ( ! is_string( $data ) )
1196 $data = trim( $data );
1197 if ( 'N;' == $data )
1199 $length = strlen( $data );
1202 if ( ':' !== $data[1] )
1205 $lastc = $data[ $length - 1 ];
1206 if ( ';' !== $lastc && '}' !== $lastc )
1209 $semicolon = strpos( $data, ';' );
1210 $brace = strpos( $data, '}' );
1211 // Either ; or } must exist.
1212 if ( false === $semicolon && false === $brace )
1214 // But neither must be in the first X characters.
1215 if ( false !== $semicolon && $semicolon < 3 )
1217 if ( false !== $brace && $brace < 4 )
1224 if ( '"' !== $data[ $length - 2 ] )
1226 } elseif ( false === strpos( $data, '"' ) ) {
1229 // or else fall through
1232 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
1236 $end = $strict ? '$' : '';
1237 return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
1243 * Unserialize value only if it was serialized. Stolen from WP
1246 * @param string $original Maybe unserialized original, if is needed.
1247 * @return mixed Unserialized data can be any type.
1249 function yourls_maybe_unserialize( $original ) {
1250 if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
1251 return @unserialize( $original );
1256 * Determine if the current page is private
1259 function yourls_is_private() {
1262 if ( defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true ) {
1264 // Allow overruling for particular pages:
1267 if( yourls_is_API() ) {
1268 if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
1272 } elseif( yourls_is_infos() ) {
1273 if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
1283 return yourls_apply_filter( 'is_private', $private );
1287 * Show login form if required
1290 function yourls_maybe_require_auth() {
1291 if( yourls_is_private() ) {
1292 yourls_do_action( 'require_auth' );
1293 require_once( YOURLS_INC.'/auth.php' );
1295 yourls_do_action( 'require_no_auth' );
1300 * Allow several short URLs for the same long URL ?
1303 function yourls_allow_duplicate_longurls() {
1304 // special treatment if API to check for WordPress plugin requests
1305 if( yourls_is_API() ) {
1306 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' )
1309 return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
1313 * Return array of keywords that redirect to the submitted long URL
1316 * @param string $longurl long url
1317 * @param string $sort Optional ORDER BY order (can be 'keyword', 'title', 'timestamp' or'clicks')
1318 * @param string $order Optional SORT order (can be 'ASC' or 'DESC')
1319 * @return array array of keywords
1321 function yourls_get_longurl_keywords( $longurl, $sort = 'none', $order = 'ASC' ) {
1323 $longurl = yourls_escape( yourls_sanitize_url( $longurl ) );
1324 $table = YOURLS_DB_TABLE_URL;
1325 $query = "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'";
1327 // Ensure sort is a column in database (@TODO: update verification array if database changes)
1328 if ( in_array( $sort, array('keyword','title','timestamp','clicks') ) ) {
1329 $query .= " ORDER BY '".$sort."'";
1330 if ( in_array( $order, array( 'ASC','DESC' ) ) ) {
1331 $query .= " ".$order;
1334 return yourls_apply_filter( 'get_longurl_keywords', $ydb->get_col( $query ), $longurl );
1338 * Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
1341 function yourls_check_IP_flood( $ip = '' ) {
1343 // Allow plugins to short-circuit the whole function
1344 $pre = yourls_apply_filter( 'shunt_check_IP_flood', false, $ip );
1345 if ( false !== $pre )
1348 yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here
1350 // Raise white flag if installing or if no flood delay defined
1352 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
1353 !defined('YOURLS_FLOOD_DELAY_SECONDS') ||
1354 yourls_is_installing()
1358 // Don't throttle logged in users
1359 if( yourls_is_private() ) {
1360 if( yourls_is_valid_user() === true )
1364 // Don't throttle whitelist IPs
1365 if( defined( 'YOURLS_FLOOD_IP_WHITELIST' ) && YOURLS_FLOOD_IP_WHITELIST ) {
1366 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
1367 foreach( (array)$whitelist_ips as $whitelist_ip ) {
1368 $whitelist_ip = trim( $whitelist_ip );
1369 if ( $whitelist_ip == $ip )
1374 $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
1376 yourls_do_action( 'check_ip_flood', $ip );
1379 $table = YOURLS_DB_TABLE_URL;
1381 $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
1384 $then = date( 'U', strtotime( $lasttime ) );
1385 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
1387 yourls_do_action( 'ip_flood', $ip, $now - $then );
1388 yourls_die( yourls__( 'Too many URLs added too fast. Slow down please.' ), yourls__( 'Forbidden' ), 403 );
1396 * Check if YOURLS is installing
1401 function yourls_is_installing() {
1402 $installing = defined( 'YOURLS_INSTALLING' ) && YOURLS_INSTALLING == true;
1403 return yourls_apply_filter( 'is_installing', $installing );
1407 * Check if YOURLS is upgrading
1412 function yourls_is_upgrading() {
1413 $upgrading = defined( 'YOURLS_UPGRADING' ) && YOURLS_UPGRADING == true;
1414 return yourls_apply_filter( 'is_upgrading', $upgrading );
1419 * Check if YOURLS is installed
1421 * Checks property $ydb->installed that is created by yourls_get_all_options()
1423 * See inline comment for updating from 1.3 or prior.
1426 function yourls_is_installed() {
1428 $is_installed = ( property_exists( $ydb, 'installed' ) && $ydb->installed == true );
1429 return yourls_apply_filter( 'is_installed', $is_installed );
1431 /* Note: this test won't work on YOURLS 1.3 or older (Aug 2009...)
1432 Should someone complain that they cannot upgrade directly from
1433 1.3 to 1.7: first, laugh at them, then ask them to install 1.6 first.
1438 * Generate random string of (int)$length length and type $type (see function for details)
1441 function yourls_rnd_string ( $length = 5, $type = 0, $charlist = '' ) {
1443 $length = intval( $length );
1445 // define possible characters
1448 // custom char list, or comply to charset as defined in config
1450 $possible = $charlist ? $charlist : yourls_get_shorturl_charset() ;
1453 // no vowels to make no offending word, no 0/1/o/l to avoid confusion between letters & digits. Perfect for passwords.
1455 $possible = "23456789bcdfghjkmnpqrstvwxyz";
1458 // Same, with lower + upper
1460 $possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
1463 // all letters, lowercase
1465 $possible = "abcdefghijklmnopqrstuvwxyz";
1468 // all letters, lowercase + uppercase
1470 $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1473 // all digits & letters lowercase
1475 $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
1478 // all digits & letters lowercase + uppercase
1480 $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1486 while ($i < $length) {
1487 $str .= substr( $possible, mt_rand( 0, strlen( $possible )-1 ), 1 );
1491 return yourls_apply_filter( 'rnd_string', $str, $length, $type, $charlist );
1495 * Return salted string
1498 function yourls_salt( $string ) {
1499 $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
1500 return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt), $string );
1504 * Add a query var to a URL and return URL. Completely stolen from WP.
1506 * Works with one of these parameter patterns:
1507 * array( 'var' => 'value' )
1508 * array( 'var' => 'value' ), $url
1510 * 'var', 'value', $url
1511 * If $url omitted, uses $_SERVER['REQUEST_URI']
1514 function yourls_add_query_arg() {
1516 if ( is_array( func_get_arg(0) ) ) {
1517 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
1518 $uri = $_SERVER['REQUEST_URI'];
1520 $uri = @func_get_arg( 1 );
1522 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
1523 $uri = $_SERVER['REQUEST_URI'];
1525 $uri = @func_get_arg( 2 );
1528 $uri = str_replace( '&', '&', $uri );
1531 if ( $frag = strstr( $uri, '#' ) )
1532 $uri = substr( $uri, 0, -strlen( $frag ) );
1536 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
1537 $protocol = $matches[0];
1538 $uri = substr( $uri, strlen( $protocol ) );
1543 if ( strpos( $uri, '?' ) !== false ) {
1544 $parts = explode( '?', $uri, 2 );
1545 if ( 1 == count( $parts ) ) {
1549 $base = $parts[0] . '?';
1552 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
1560 parse_str( $query, $qs );
1561 $qs = yourls_urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
1562 if ( is_array( func_get_arg( 0 ) ) ) {
1563 $kayvees = func_get_arg( 0 );
1564 $qs = array_merge( $qs, $kayvees );
1566 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1569 foreach ( (array) $qs as $k => $v ) {
1574 $ret = http_build_query( $qs );
1575 $ret = trim( $ret, '?' );
1576 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1577 $ret = $protocol . $base . $ret . $frag;
1578 $ret = rtrim( $ret, '?' );
1583 * Navigates through an array and encodes the values to be used in a URL. Stolen from WP, used in yourls_add_query_arg()
1586 function yourls_urlencode_deep( $value ) {
1587 $value = is_array( $value ) ? array_map( 'yourls_urlencode_deep', $value ) : urlencode( $value );
1592 * Remove arg from query. Opposite of yourls_add_query_arg. Stolen from WP.
1595 function yourls_remove_query_arg( $key, $query = false ) {
1596 if ( is_array( $key ) ) { // removing multiple keys
1597 foreach ( $key as $k )
1598 $query = yourls_add_query_arg( $k, false, $query );
1601 return yourls_add_query_arg( $key, false, $query );
1605 * Return a time-dependent string for nonce creation
1608 function yourls_tick() {
1609 return ceil( time() / YOURLS_NONCE_LIFE );
1613 * Create a time limited, action limited and user limited token
1616 function yourls_create_nonce( $action, $user = false ) {
1617 if( false == $user )
1618 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1619 $tick = yourls_tick();
1620 return substr( yourls_salt($tick . $action . $user), 0, 10 );
1624 * Create a nonce field for inclusion into a form
1627 function yourls_nonce_field( $action, $name = 'nonce', $user = false, $echo = true ) {
1628 $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';
1635 * Add a nonce to a URL. If URL omitted, adds nonce to current URL
1638 function yourls_nonce_url( $action, $url = false, $name = 'nonce', $user = false ) {
1639 $nonce = yourls_create_nonce( $action, $user );
1640 return yourls_add_query_arg( $name, $nonce, $url );
1644 * Check validity of a nonce (ie time span, user and action match).
1646 * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined)
1647 * if $nonce is false or unspecified, it will use $_REQUEST['nonce']
1650 function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {
1652 if( false == $user )
1653 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
1655 // get current nonce value
1656 if( false == $nonce && isset( $_REQUEST['nonce'] ) )
1657 $nonce = $_REQUEST['nonce'];
1659 // what nonce should be
1660 $valid = yourls_create_nonce( $action, $user );
1662 if( $nonce == $valid ) {
1667 yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );
1672 * Converts keyword into short link (prepend with YOURLS base URL)
1675 function yourls_link( $keyword = '' ) {
1676 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
1677 return yourls_apply_filter( 'yourls_link', $link, $keyword );
1681 * Converts keyword into stat link (prepend with YOURLS base URL, append +)
1684 function yourls_statlink( $keyword = '' ) {
1685 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword ) . '+';
1686 if( yourls_is_ssl() )
1687 $link = str_replace( 'http://', 'https://', $link );
1688 return yourls_apply_filter( 'yourls_statlink', $link, $keyword );
1692 * Check if we're in API mode. Returns bool
1695 function yourls_is_API() {
1696 if ( defined( 'YOURLS_API' ) && YOURLS_API == true )
1702 * Check if we're in Ajax mode. Returns bool
1705 function yourls_is_Ajax() {
1706 if ( defined( 'YOURLS_AJAX' ) && YOURLS_AJAX == true )
1712 * Check if we're in GO mode (yourls-go.php). Returns bool
1715 function yourls_is_GO() {
1716 if ( defined( 'YOURLS_GO' ) && YOURLS_GO == true )
1722 * Check if we're displaying stats infos (yourls-infos.php). Returns bool
1725 function yourls_is_infos() {
1726 if ( defined( 'YOURLS_INFOS' ) && YOURLS_INFOS == true )
1732 * Check if we're in the admin area. Returns bool
1735 function yourls_is_admin() {
1736 if ( defined( 'YOURLS_ADMIN' ) && YOURLS_ADMIN == true )
1742 * Check if the server seems to be running on Windows. Not exactly sure how reliable this is.
1745 function yourls_is_windows() {
1746 return defined( 'DIRECTORY_SEPARATOR' ) && DIRECTORY_SEPARATOR == '\\';
1750 * Check if SSL is required. Returns bool.
1753 function yourls_needs_ssl() {
1754 if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
1760 * Return admin link, with SSL preference if applicable.
1763 function yourls_admin_url( $page = '' ) {
1764 $admin = YOURLS_SITE . '/admin/' . $page;
1765 if( yourls_is_ssl() or yourls_needs_ssl() )
1766 $admin = str_replace('http://', 'https://', $admin);
1767 return yourls_apply_filter( 'admin_url', $admin, $page );
1771 * Return YOURLS_SITE or URL under YOURLS setup, with SSL preference
1774 function yourls_site_url( $echo = true, $url = '' ) {
1775 $url = yourls_get_relative_url( $url );
1776 $url = trim( YOURLS_SITE . '/' . $url, '/' );
1778 // Do not enforce (checking yourls_need_ssl() ) but check current usage so it won't force SSL on non-admin pages
1779 if( yourls_is_ssl() )
1780 $url = str_replace( 'http://', 'https://', $url );
1781 $url = yourls_apply_filter( 'site_url', $url );
1788 * Check if SSL is used, returns bool. Stolen from WP.
1791 function yourls_is_ssl() {
1793 if ( isset( $_SERVER['HTTPS'] ) ) {
1794 if ( 'on' == strtolower( $_SERVER['HTTPS'] ) )
1796 if ( '1' == $_SERVER['HTTPS'] )
1798 } elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
1801 return yourls_apply_filter( 'is_ssl', $is_ssl );
1806 * Get a remote page <title>, return a string (either title or url)
1809 function yourls_get_remote_title( $url ) {
1810 // Allow plugins to short-circuit the whole function
1811 $pre = yourls_apply_filter( 'shunt_get_remote_title', false, $url );
1812 if ( false !== $pre )
1815 require_once( YOURLS_INC.'/functions-http.php' );
1817 $url = yourls_sanitize_url( $url );
1819 $title = $charset = false;
1821 $content = yourls_get_remote_content( $url );
1823 // If false, return url as title.
1824 // Todo: improve this with temporary title when shorturl_meta available?
1825 if( false === $content )
1828 if( $content !== false ) {
1830 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {
1836 // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1837 if ( preg_match('/<meta[^>]*?charset=([^>]*?)\/?>/is', $content, $found ) ) {
1838 $charset = trim($found[1], '"\' ');
1843 // if title not found, guess if returned content was actually an error message
1844 if( $title == false && strpos( $content, 'Error' ) === 0 ) {
1848 if( $title == false )
1852 if( !yourls_seems_utf8( $title ) )
1853 $title = utf8_encode( $title );
1856 // Charset conversion. We use @ to remove warnings (mb_ functions are easily bitching about illegal chars)
1857 if( function_exists( 'mb_convert_encoding' ) ) {
1859 $title = @mb_convert_encoding( $title, 'UTF-8', $charset );
1861 $title = @mb_convert_encoding( $title, 'UTF-8' );
1865 // Remove HTML entities
1866 $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' );
1868 // Strip out evil things
1869 $title = yourls_sanitize_title( $title );
1871 return yourls_apply_filter( 'get_remote_title', $title, $url );
1875 * Quick UA check for mobile devices. Return boolean.
1878 function yourls_is_mobile_device() {
1881 'android', 'blackberry', 'blazer',
1882 'compal', 'elaine', 'fennec', 'hiptop',
1883 'iemobile', 'iphone', 'ipod', 'ipad',
1884 'iris', 'kindle', 'opera mobi', 'opera mini',
1885 'palm', 'phone', 'pocket', 'psp', 'symbian',
1886 'treo', 'wap', 'windows ce', 'windows phone'
1889 // Current user-agent
1890 $current = strtolower( $_SERVER['HTTP_USER_AGENT'] );
1893 $is_mobile = ( str_replace( $mobiles, '', $current ) != $current );
1894 return yourls_apply_filter( 'is_mobile_device', $is_mobile );
1898 * Get request in YOURLS base (eg in 'http://site.com/yourls/abcd' get 'abdc')
1901 function yourls_get_request() {
1902 // Allow plugins to short-circuit the whole function
1903 $pre = yourls_apply_filter( 'shunt_get_request', false );
1904 if ( false !== $pre )
1907 static $request = null;
1909 yourls_do_action( 'pre_get_request', $request );
1911 if( $request !== null )
1914 // Ignore protocol & www. prefix
1915 $root = str_replace( array( 'https://', 'http://', 'https://www.', 'http://www.' ), '', YOURLS_SITE );
1916 // Case insensitive comparison of the YOURLS root to match both http://Sho.rt/blah and http://sho.rt/blah
1917 $request = preg_replace( "!$root/!i", '', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 1 );
1919 // Unless request looks like a full URL (ie request is a simple keyword) strip query string
1920 if( !preg_match( "@^[a-zA-Z]+://.+@", $request ) ) {
1921 $request = current( explode( '?', $request ) );
1924 return yourls_apply_filter( 'get_request', $request );
1928 * Change protocol to match current scheme used (http or https)
1931 function yourls_match_current_protocol( $url, $normal = 'http://', $ssl = 'https://' ) {
1932 if( yourls_is_ssl() )
1933 $url = str_replace( $normal, $ssl, $url );
1934 return yourls_apply_filter( 'match_current_protocol', $url );
1938 * Fix $_SERVER['REQUEST_URI'] variable for various setups. Stolen from WP.
1941 function yourls_fix_request_uri() {
1943 $default_server_values = array(
1944 'SERVER_SOFTWARE' => '',
1945 'REQUEST_URI' => '',
1947 $_SERVER = array_merge( $default_server_values, $_SERVER );
1949 // Fix for IIS when running with PHP ISAPI
1950 if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {
1953 if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
1954 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
1956 // IIS Isapi_Rewrite
1957 else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {
1958 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
1960 // Use ORIG_PATH_INFO if there is no PATH_INFO
1961 if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )
1962 $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
1964 // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
1965 if ( isset( $_SERVER['PATH_INFO'] ) ) {
1966 if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
1967 $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
1969 $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
1972 // Append the query string if it exists and isn't null
1973 if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
1974 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
1981 * Shutdown function, runs just before PHP shuts down execution. Stolen from WP
1984 function yourls_shutdown() {
1985 yourls_do_action( 'shutdown' );
1989 * Auto detect custom favicon in /user directory, fallback to YOURLS favicon, and echo/return its URL
1992 function yourls_favicon( $echo = true ) {
1993 static $favicon = null;
1994 if( $favicon !== null )
1998 // search for favicon.(gif|ico|png|jpg|svg)
1999 foreach( array( 'gif', 'ico', 'png', 'jpg', 'svg' ) as $ext ) {
2000 if( file_exists( YOURLS_USERDIR. '/favicon.' . $ext ) ) {
2001 $custom = 'favicon.' . $ext;
2007 $favicon = yourls_site_url( false, YOURLS_USERURL . '/' . $custom );
2009 $favicon = yourls_site_url( false ) . '/images/favicon.gif';
2017 * Check for maintenance mode. If yes, die. See yourls_maintenance_mode(). Stolen from WP.
2020 function yourls_check_maintenance_mode() {
2022 $file = YOURLS_ABSPATH . '/.maintenance' ;
2023 if ( !file_exists( $file ) || yourls_is_upgrading() || yourls_is_installing() )
2026 global $maintenance_start;
2028 include_once( $file );
2029 // If the $maintenance_start timestamp is older than 10 minutes, don't die.
2030 if ( ( time() - $maintenance_start ) >= 600 )
2033 // Use any /user/maintenance.php file
2034 if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {
2035 include_once( YOURLS_USERDIR.'/maintenance.php' );
2039 // https://www.youtube.com/watch?v=Xw-m4jEY-Ns
2040 $title = yourls__( 'Service temporarily unavailable' );
2041 $message = yourls__( 'Our service is currently undergoing scheduled maintenance.' ) . "</p>\n<p>" .
2042 yourls__( 'Things should not last very long, thank you for your patience and please excuse the inconvenience' );
2043 yourls_die( $message, $title , 503 );
2048 * Return current admin page, or null if not an admin page
2050 * @return mixed string if admin page, null if not an admin page
2053 function yourls_current_admin_page() {
2054 if( yourls_is_admin() ) {
2055 $current = substr( yourls_get_request(), 6 );
2056 if( $current === false )
2057 $current = 'index.php'; // if current page is http://sho.rt/admin/ instead of http://sho.rt/admin/index.php
2065 * Check if a URL protocol is allowed
2067 * Checks a URL against a list of whitelisted protocols. Protocols must be defined with
2068 * their complete scheme name, ie 'stuff:' or 'stuff://' (for instance, 'mailto:' is a valid
2069 * protocol, 'mailto://' isn't, and 'http:' with no double slashed isn't either
2073 * @param string $url URL to be check
2074 * @param array $protocols Optional. Array of protocols, defaults to global $yourls_allowedprotocols
2075 * @return boolean true if protocol allowed, false otherwise
2077 function yourls_is_allowed_protocol( $url, $protocols = array() ) {
2078 if( ! $protocols ) {
2079 global $yourls_allowedprotocols;
2080 $protocols = $yourls_allowedprotocols;
2083 $protocol = yourls_get_protocol( $url );
2084 return yourls_apply_filter( 'is_allowed_protocol', in_array( $protocol, $protocols ), $url, $protocols );
2088 * Get protocol from a URL (eg mailto:, http:// ...)
2092 * @param string $url URL to be check
2093 * @return string Protocol, with slash slash if applicable. Empty string if no protocol
2095 function yourls_get_protocol( $url ) {
2096 preg_match( '!^[a-zA-Z0-9\+\.-]+:(//)?!', $url, $matches );
2098 http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
2099 The scheme name consists of a sequence of characters beginning with a letter and followed by any
2100 combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). Although schemes are
2101 case-insensitive, the canonical form is lowercase and documents that specify schemes must do so
2102 with lowercase letters. It is followed by a colon (":").
2104 $protocol = ( isset( $matches[0] ) ? $matches[0] : '' );
2105 return yourls_apply_filter( 'get_protocol', $protocol, $url );
2109 * Get relative URL (eg 'abc' from 'http://sho.rt/abc')
2111 * Treat indifferently http & https. If a URL isn't relative to the YOURLS install, return it as is
2112 * or return empty string if $strict is true
2115 * @param string $url URL to relativize
2116 * @param bool $strict if true and if URL isn't relative to YOURLS install, return empty string
2117 * @return string URL
2119 function yourls_get_relative_url( $url, $strict = true ) {
2120 $url = yourls_sanitize_url( $url );
2122 // Remove protocols to make it easier
2123 $noproto_url = str_replace( 'https:', 'http:', $url );
2124 $noproto_site = str_replace( 'https:', 'http:', YOURLS_SITE );
2126 // Trim URL from YOURLS root URL : if no modification made, URL wasn't relative
2127 $_url = str_replace( $noproto_site . '/', '', $noproto_url );
2128 if( $_url == $noproto_url )
2129 $_url = ( $strict ? '' : $url );
2131 return yourls_apply_filter( 'get_relative_url', $_url, $url );
2135 * Marks a function as deprecated and informs when it has been used. Stolen from WP.
2137 * There is a hook deprecated_function that will be called that can be used
2138 * to get the backtrace up to what file and function called the deprecated
2141 * The current behavior is to trigger a user error if YOURLS_DEBUG is true.
2143 * This function is to be used in every function that is deprecated.
2146 * @uses yourls_do_action() Calls 'deprecated_function' and passes the function name, what to use instead,
2147 * and the version the function was deprecated in.
2148 * @uses yourls_apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2149 * trigger or false to not trigger error.
2151 * @param string $function The function that was called
2152 * @param string $version The version of WordPress that deprecated the function
2153 * @param string $replacement Optional. The function that should have been called
2155 function yourls_deprecated_function( $function, $version, $replacement = null ) {
2157 yourls_do_action( 'deprecated_function', $function, $replacement, $version );
2159 // Allow plugin to filter the output error trigger
2160 if ( YOURLS_DEBUG && yourls_apply_filters( 'deprecated_function_trigger_error', true ) ) {
2161 if ( ! is_null( $replacement ) )
2162 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2164 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2169 * Return the value if not an empty string
2171 * Used with array_filter(), to remove empty keys but not keys with value 0 or false
2174 * @param mixed $val Value to test against ''
2175 * @return bool True if not an empty string
2177 function yourls_return_if_not_empty_string( $val ) {
2178 return( $val !== '' );
2182 * Add a message to the debug log
2184 * When in debug mode ( YOURLS_DEBUG == true ) the debug log is echoed in yourls_html_footer()
2185 * Log messages are appended to $ydb->debug_log array, which is instanciated within class ezSQLcore_YOURLS
2188 * @param string $msg Message to add to the debug log
2189 * @return string The message itself
2191 function yourls_debug_log( $msg ) {
2193 $ydb->debug_log[] = $msg;
2198 * Explode a URL in an array of ( 'protocol' , 'slashes if any', 'rest of the URL' )
2200 * Some hosts trip up when a query string contains 'http://' - see http://git.io/j1FlJg
2201 * The idea is that instead of passing the whole URL to a bookmarklet, eg index.php?u=http://blah.com,
2202 * we pass it by pieces to fool the server, eg index.php?proto=http:&slashes=//&rest=blah.com
2204 * Known limitation: this won't work if the rest of the URL itself contains 'http://', for example
2205 * if rest = blah.com/file.php?url=http://foo.com
2209 * with 'mailto:jsmith@example.com?subject=hey' :
2210 * array( 'protocol' => 'mailto:', 'slashes' => '', 'rest' => 'jsmith@example.com?subject=hey' )
2212 * with 'http://example.com/blah.html' :
2213 * array( 'protocol' => 'http:', 'slashes' => '//', 'rest' => 'example.com/blah.html' )
2216 * @param string $url URL to be parsed
2217 * @param array $array Optional, array of key names to be used in returned array
2218 * @return mixed false if no protocol found, array of ('protocol' , 'slashes', 'rest') otherwise
2220 function yourls_get_protocol_slashes_and_rest( $url, $array = array( 'protocol', 'slashes', 'rest' ) ) {
2221 $proto = yourls_get_protocol( $url );
2223 if( !$proto or count( $array ) != 3 )
2226 list( $null, $rest ) = explode( $proto, $url, 2 );
2228 list( $proto, $slashes ) = explode( ':', $proto );
2230 return array( $array[0] => $proto . ':', $array[1] => $slashes, $array[2] => $rest );