8 * Determine the allowed character set in short URLs
\r
11 function yourls_get_shorturl_charset() {
\r
12 static $charset = null;
\r
13 if( $charset !== null )
\r
16 if( !defined('YOURLS_URL_CONVERT') ) {
\r
17 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
\r
19 switch( YOURLS_URL_CONVERT ) {
\r
21 $charset = '0123456789abcdefghijklmnopqrstuvwxyz';
\r
24 case 64: // just because some people get this wrong in their config.php
\r
25 $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
\r
30 $charset = yourls_apply_filter( 'get_shorturl_charset', $charset );
\r
35 * Make an optimized regexp pattern from a string of characters
38 function yourls_make_regexp_pattern( $string ) {
\r
39 $pattern = preg_quote( $string, '-' ); // add - as an escaped characters -- this is fixed in PHP 5.3
\r
40 // TODO: replace char sequences by smart sequences such as 0-9, a-z, A-Z ... ?
\r
45 * Is a URL a short URL?
48 function yourls_is_shorturl( $shorturl ) {
\r
49 // TODO: make sure this function evolves with the feature set.
\r
52 $keyword = yourls_get_relative_url( $shorturl ); // accept either 'http://ozh.in/abc' or 'abc'
\r
53 if( $keyword && $keyword == yourls_sanitize_string( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {
\r
57 return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );
\r
61 * Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool
64 function yourls_keyword_is_reserved( $keyword ) {
\r
65 global $yourls_reserved_URL;
\r
66 $keyword = yourls_sanitize_keyword( $keyword );
\r
69 if ( in_array( $keyword, $yourls_reserved_URL)
\r
70 or file_exists( YOURLS_ABSPATH ."/pages/$keyword.php" )
\r
71 or is_dir( YOURLS_ABSPATH ."/$keyword" )
\r
75 return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );
\r
79 * Function: Get client IP Address. Returns a DB safe string.
82 function yourls_get_IP() {
\r
83 // Precedence: if set, X-Forwarded-For > HTTP_X_FORWARDED_FOR > HTTP_CLIENT_IP > HTTP_VIA > REMOTE_ADDR
\r
84 $headers = array( 'X-Forwarded-For', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_VIA', 'REMOTE_ADDR' );
\r
85 foreach( $headers as $header ) {
\r
86 if ( !empty( $_SERVER[ $header ] ) ) {
\r
87 $ip = $_SERVER[ $header ];
\r
92 // headers can contain multiple IPs (X-Forwarded-For = client, proxy1, proxy2). Take first one.
\r
93 if ( strpos( $ip, ',' ) !== false )
\r
94 $ip = substr( $ip, 0, strpos( $ip, ',' ) );
\r
96 return yourls_apply_filter( 'get_IP', yourls_sanitize_ip( $ip ) );
\r
100 * Get next id a new link will have if no custom keyword provided
103 function yourls_get_next_decimal() {
\r
104 return yourls_apply_filter( 'get_next_decimal', (int)yourls_get_option( 'next_id' ) );
\r
108 * Update id for next link with no custom keyword
111 function yourls_update_next_decimal( $int = '' ) {
\r
112 $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
\r
113 $update = yourls_update_option( 'next_id', $int );
\r
114 yourls_do_action( 'update_next_decimal', $int, $update );
\r
119 * Delete a link in the DB
122 function yourls_delete_link_by_keyword( $keyword ) {
\r
125 $table = YOURLS_DB_TABLE_URL;
\r
126 $keyword = yourls_sanitize_string( $keyword );
\r
127 $delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
\r
128 yourls_do_action( 'delete_link', $keyword, $delete );
\r
133 * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting
136 function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {
\r
139 $url = yourls_escape( yourls_sanitize_url( $url ) );
\r
140 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
\r
141 $title = yourls_escape( yourls_sanitize_title( $title ) );
\r
143 $table = YOURLS_DB_TABLE_URL;
\r
144 $timestamp = date('Y-m-d H:i:s');
\r
145 $ip = yourls_get_IP();
\r
146 $insert = $ydb->query("INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");
\r
148 yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );
\r
150 return (bool)$insert;
\r
154 * Check if a URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.
157 function yourls_url_exists( $url ) {
\r
158 // Allow plugins to short-circuit the whole function
\r
159 $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );
\r
160 if ( false !== $pre )
\r
164 $table = YOURLS_DB_TABLE_URL;
\r
165 $strip_url = stripslashes($url);
\r
166 $url_exists = $ydb->get_row("SELECT * FROM `$table` WHERE `url` = '".$strip_url."';");
\r
168 return yourls_apply_filter( 'url_exists', $url_exists, $url );
\r
172 * Add a new link in the DB, either with custom keyword, or find one
175 function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
\r
178 // Allow plugins to short-circuit the whole function
\r
179 $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
\r
180 if ( false !== $pre )
\r
183 $url = yourls_encodeURI( $url );
\r
184 $url = yourls_escape( yourls_sanitize_url( $url ) );
\r
185 if ( !$url || $url == 'http://' || $url == 'https://' ) {
\r
186 $return['status'] = 'fail';
\r
187 $return['code'] = 'error:nourl';
\r
188 $return['message'] = yourls__( 'Missing or malformed URL' );
\r
189 $return['errorCode'] = '400';
\r
190 return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
\r
193 // Prevent DB flood
\r
194 $ip = yourls_get_IP();
\r
195 yourls_check_IP_flood( $ip );
\r
197 // Prevent internal redirection loops: cannot shorten a shortened URL
\r
198 if( yourls_get_relative_url( $url ) ) {
\r
199 if( yourls_is_shorturl( $url ) ) {
\r
200 $return['status'] = 'fail';
\r
201 $return['code'] = 'error:noloop';
\r
202 $return['message'] = yourls__( 'URL is a short URL' );
\r
203 $return['errorCode'] = '400';
\r
204 return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );
\r
208 yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );
\r
210 $strip_url = stripslashes( $url );
\r
213 // duplicates allowed or new URL => store it
\r
214 if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_url_exists( $url ) ) ) {
\r
216 if( isset( $title ) && !empty( $title ) ) {
\r
217 $title = yourls_sanitize_title( $title );
\r
219 $title = yourls_get_remote_title( $url );
\r
221 $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );
\r
223 // Custom keyword provided
\r
226 yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );
\r
228 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
\r
229 $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );
\r
230 if ( !yourls_keyword_is_free( $keyword ) ) {
\r
231 // This shorturl either reserved or taken already
\r
232 $return['status'] = 'fail';
\r
233 $return['code'] = 'error:keyword';
\r
234 $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );
\r
236 // all clear, store !
\r
237 yourls_insert_link_in_db( $url, $keyword, $title );
\r
238 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
\r
239 $return['status'] = 'success';
\r
240 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
\r
241 $return['title'] = $title;
\r
242 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
\r
243 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
246 // Create random keyword
\r
249 yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );
\r
251 $timestamp = date( 'Y-m-d H:i:s' );
\r
252 $id = yourls_get_next_decimal();
\r
255 $keyword = yourls_int2string( $id );
\r
256 $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );
\r
257 $free = yourls_keyword_is_free($keyword);
\r
258 $add_url = @yourls_insert_link_in_db( $url, $keyword, $title );
\r
259 $ok = ($free && $add_url);
\r
260 if ( $ok === false && $add_url === 1 ) {
\r
261 // we stored something, but shouldn't have (ie reserved id)
\r
262 $delete = yourls_delete_link_by_keyword( $keyword );
\r
263 $return['extra_info'] .= '(deleted '.$keyword.')';
\r
265 // everything ok, populate needed vars
\r
266 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );
\r
267 $return['status'] = 'success';
\r
268 $return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
\r
269 $return['title'] = $title;
\r
270 $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
\r
271 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;
\r
275 @yourls_update_next_decimal( $id );
\r
278 // URL was already stored
\r
281 yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );
\r
283 $return['status'] = 'fail';
\r
284 $return['code'] = 'error:url';
\r
285 $return['url'] = array( 'keyword' => $url_exists->keyword, 'url' => $strip_url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );
\r
286 $return['message'] = /* //translators: eg "http://someurl/ already exists" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $strip_url ) );
\r
287 $return['title'] = $url_exists->title;
\r
288 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
\r
291 yourls_do_action( 'post_add_new_link', $url, $keyword, $title );
\r
293 $return['statusCode'] = 200; // regardless of result, this is still a valid request
\r
294 return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );
\r
302 function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {
\r
305 $table = YOURLS_DB_TABLE_URL;
\r
306 $url = yourls_escape (yourls_sanitize_url( $url ) );
\r
307 $keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
\r
308 $title = yourls_escape( yourls_sanitize_title( $title ) );
\r
309 $newkeyword = yourls_escape( yourls_sanitize_string( $newkeyword ) );
\r
310 $strip_url = stripslashes( $url );
\r
311 $strip_title = stripslashes( $title );
\r
312 $old_url = $ydb->get_var( "SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';" );
\r
314 // Check if new URL is not here already
\r
315 if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {
\r
316 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));
\r
318 $new_url_already_there = false;
\r
321 // Check if the new keyword is not here already
\r
322 if ( $newkeyword != $keyword ) {
\r
323 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );
\r
325 $keyword_is_ok = true;
\r
328 yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );
\r
330 // All clear, update
\r
331 if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
\r
332 $update_url = $ydb->query( "UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';" );
\r
333 if( $update_url ) {
\r
334 $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'title' => $strip_title, 'display_title' => yourls_trim_long_string( $strip_title ) );
\r
335 $return['status'] = 'success';
\r
336 $return['message'] = yourls__( 'Link updated in database' );
\r
338 $return['status'] = 'fail';
\r
339 $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 ) ;
\r
344 $return['status'] = 'fail';
\r
345 $return['message'] = yourls__( 'URL or keyword already exists in database' );
\r
348 return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );
\r
352 * Update a title link (no checks for duplicates etc..)
355 function yourls_edit_link_title( $keyword, $title ) {
\r
358 $keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
\r
359 $title = yourls_escape( yourls_sanitize_title( $title ) );
\r
361 $table = YOURLS_DB_TABLE_URL;
\r
362 $update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");
\r
369 * Check if keyword id is free (ie not already taken, and not reserved). Return bool.
372 function yourls_keyword_is_free( $keyword ) {
\r
374 if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
\r
377 return yourls_apply_filter( 'keyword_is_free', $free, $keyword );
\r
381 * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.
384 function yourls_keyword_is_taken( $keyword ) {
\r
386 $keyword = yourls_sanitize_keyword( $keyword );
\r
388 $table = YOURLS_DB_TABLE_URL;
\r
389 $already_exists = $ydb->get_var( "SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';" );
\r
390 if ( $already_exists )
\r
393 return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );
\r
401 function yourls_db_connect() {
\r
404 if ( !defined( 'YOURLS_DB_USER' )
\r
405 or !defined( 'YOURLS_DB_PASS' )
\r
406 or !defined( 'YOURLS_DB_NAME' )
\r
407 or !defined( 'YOURLS_DB_HOST' )
\r
408 or !class_exists( 'ezSQL_mysql' )
\r
409 ) yourls_die ( yourls__( 'DB config missing, or could not find DB class' ), yourls__( 'Fatal error' ), 503 );
\r
411 // Are we standalone or in the WordPress environment?
\r
412 if ( class_exists( 'wpdb' ) ) {
\r
413 $ydb = new wpdb( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
\r
415 $ydb = new ezSQL_mysql( YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST );
\r
417 if ( $ydb->last_error )
\r
418 yourls_die( $ydb->last_error, yourls__( 'Fatal error' ), 503 );
\r
420 if ( defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG === true )
\r
421 $ydb->show_errors = true;
\r
430 function yourls_xml_encode( $array ) {
\r
431 require_once( YOURLS_INC.'/functions-xml.php' );
\r
432 $converter= new yourls_array2xml;
\r
433 return $converter->array2xml( $array );
\r
437 * Return array of all informations associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB
440 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
\r
442 $keyword = yourls_sanitize_string( $keyword );
\r
444 yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );
\r
446 if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
\r
447 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
\r
450 yourls_do_action( 'get_keyword_not_cached', $keyword );
\r
452 $table = YOURLS_DB_TABLE_URL;
\r
453 $infos = $ydb->get_row( "SELECT * FROM `$table` WHERE `keyword` = '$keyword'" );
\r
456 $infos = (array)$infos;
\r
457 $ydb->infos[ $keyword ] = $infos;
\r
459 $ydb->infos[ $keyword ] = false;
\r
462 return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
\r
466 * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
469 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
\r
471 // Allow plugins to short-circuit the whole function
\r
472 $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );
\r
473 if ( false !== $pre )
\r
476 $keyword = yourls_sanitize_string( $keyword );
\r
477 $infos = yourls_get_keyword_infos( $keyword );
\r
479 $return = $notfound;
\r
480 if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )
\r
481 $return = $infos[ $field ];
\r
483 return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );
\r
487 * Return title associated with keyword. Optional $notfound = string default message if nothing found
490 function yourls_get_keyword_title( $keyword, $notfound = false ) {
\r
491 return yourls_get_keyword_info( $keyword, 'title', $notfound );
\r
495 * Return long URL associated with keyword. Optional $notfound = string default message if nothing found
498 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
\r
499 return yourls_get_keyword_info( $keyword, 'url', $notfound );
\r
503 * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
506 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
\r
507 return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
\r
511 * Return IP that added a keyword. Optional $notfound = string default message if nothing found
514 function yourls_get_keyword_IP( $keyword, $notfound = false ) {
\r
515 return yourls_get_keyword_info( $keyword, 'ip', $notfound );
\r
519 * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
522 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
\r
523 return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
\r
527 * Update click count on a short URL. Return 0/1 for error/success.
530 function yourls_update_clicks( $keyword, $clicks = false ) {
\r
531 // Allow plugins to short-circuit the whole function
\r
532 $pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword, $clicks );
\r
533 if ( false !== $pre )
\r
537 $keyword = yourls_sanitize_string( $keyword );
\r
538 $table = YOURLS_DB_TABLE_URL;
\r
539 if ( $clicks !== false && is_int( $clicks ) && $clicks >= 0 )
\r
540 $update = $ydb->query( "UPDATE `$table` SET `clicks` = $clicks WHERE `keyword` = '$keyword'" );
\r
542 $update = $ydb->query( "UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'" );
\r
544 yourls_do_action( 'update_clicks', $keyword, $update, $clicks );
\r
549 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
552 function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {
\r
555 switch( $filter ) {
\r
557 $sort_by = 'clicks';
\r
558 $sort_order = 'asc';
\r
561 $sort_by = 'timestamp';
\r
562 $sort_order = 'desc';
\r
566 $sort_by = 'RAND()';
\r
571 $sort_by = 'clicks';
\r
572 $sort_order = 'desc';
\r
577 $limit = intval( $limit );
\r
578 $start = intval( $start );
\r
579 if ( $limit > 0 ) {
\r
581 $table_url = YOURLS_DB_TABLE_URL;
\r
582 $results = $ydb->get_results( "SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;" );
\r
587 foreach ( (array)$results as $res ) {
\r
588 $return['links']['link_'.$i++] = array(
\r
589 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
\r
590 'url' => $res->url,
\r
591 'title' => $res->title,
\r
592 'timestamp'=> $res->timestamp,
\r
594 'clicks' => $res->clicks,
\r
599 $return['stats'] = yourls_get_db_stats();
\r
601 $return['statusCode'] = 200;
\r
603 return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );
\r
607 * Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
610 function yourls_get_link_stats( $shorturl ) {
\r
613 $table_url = YOURLS_DB_TABLE_URL;
\r
614 $res = $ydb->get_row( "SELECT * FROM `$table_url` WHERE keyword = '$shorturl';" );
\r
618 // non existent link
\r
620 'statusCode' => 404,
\r
621 'message' => 'Error: short URL not found',
\r
625 'statusCode' => 200,
\r
626 'message' => 'success',
\r
628 'shorturl' => YOURLS_SITE .'/'. $res->keyword,
\r
629 'url' => $res->url,
\r
630 'title' => $res->title,
\r
631 'timestamp'=> $res->timestamp,
\r
633 'clicks' => $res->clicks,
\r
638 return yourls_apply_filter( 'get_link_stats', $return, $shorturl );
\r
642 * Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
645 function yourls_get_db_stats( $where = '' ) {
\r
647 $table_url = YOURLS_DB_TABLE_URL;
\r
649 $totals = $ydb->get_row( "SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where" );
\r
650 $return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
\r
652 return yourls_apply_filter( 'get_db_stats', $return, $where );
\r
656 * Get number of SQL queries performed
659 function yourls_get_num_queries() {
\r
662 return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );
\r
666 * Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
669 function yourls_get_user_agent() {
\r
670 if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
\r
673 $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
\r
674 $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
\r
676 return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );
\r
680 * Redirect to another page
683 function yourls_redirect( $location, $code = 301 ) {
\r
684 yourls_do_action( 'pre_redirect', $location, $code );
\r
685 $location = yourls_apply_filter( 'redirect', $location, $code );
\r
686 // Redirect, either properly if possible, or via Javascript otherwise
\r
687 if( !headers_sent() ) {
\r
688 yourls_status_header( $code );
\r
689 header( "Location: $location" );
\r
691 yourls_redirect_javascript( $location );
\r
697 * Set HTTP status header
700 function yourls_status_header( $code = 200 ) {
\r
701 if( headers_sent() )
\r
704 $protocol = $_SERVER["SERVER_PROTOCOL"];
\r
705 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
\r
706 $protocol = 'HTTP/1.0';
\r
708 $code = intval( $code );
\r
709 $desc = yourls_get_HTTP_status( $code );
\r
711 @header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
\r
712 yourls_do_action( 'status_header', $code );
\r
716 * 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)
719 function yourls_redirect_javascript( $location, $dontwait = true ) {
\r
720 yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );
\r
721 $location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );
\r
723 $message = yourls_s( 'if you are not redirected after 10 seconds, please <a href="%s">click here</a>', $location );
\r
725 <script type="text/javascript">
\r
726 window.location="$location";
\r
728 <small>($message)</small>
\r
731 echo '<p>' . yourls_s( 'Please <a href="%s">click here</a>', $location ) . '</p>';
\r
733 yourls_do_action( 'post_redirect_javascript', $location );
\r
737 * Return a HTTP status code
740 function yourls_get_HTTP_status( $code ) {
\r
741 $code = intval( $code );
\r
742 $headers_desc = array(
\r
744 101 => 'Switching Protocols',
\r
745 102 => 'Processing',
\r
750 203 => 'Non-Authoritative Information',
\r
751 204 => 'No Content',
\r
752 205 => 'Reset Content',
\r
753 206 => 'Partial Content',
\r
754 207 => 'Multi-Status',
\r
757 300 => 'Multiple Choices',
\r
758 301 => 'Moved Permanently',
\r
760 303 => 'See Other',
\r
761 304 => 'Not Modified',
\r
762 305 => 'Use Proxy',
\r
764 307 => 'Temporary Redirect',
\r
766 400 => 'Bad Request',
\r
767 401 => 'Unauthorized',
\r
768 402 => 'Payment Required',
\r
769 403 => 'Forbidden',
\r
770 404 => 'Not Found',
\r
771 405 => 'Method Not Allowed',
\r
772 406 => 'Not Acceptable',
\r
773 407 => 'Proxy Authentication Required',
\r
774 408 => 'Request Timeout',
\r
777 411 => 'Length Required',
\r
778 412 => 'Precondition Failed',
\r
779 413 => 'Request Entity Too Large',
\r
780 414 => 'Request-URI Too Long',
\r
781 415 => 'Unsupported Media Type',
\r
782 416 => 'Requested Range Not Satisfiable',
\r
783 417 => 'Expectation Failed',
\r
784 422 => 'Unprocessable Entity',
\r
786 424 => 'Failed Dependency',
\r
787 426 => 'Upgrade Required',
\r
789 500 => 'Internal Server Error',
\r
790 501 => 'Not Implemented',
\r
791 502 => 'Bad Gateway',
\r
792 503 => 'Service Unavailable',
\r
793 504 => 'Gateway Timeout',
\r
794 505 => 'HTTP Version Not Supported',
\r
795 506 => 'Variant Also Negotiates',
\r
796 507 => 'Insufficient Storage',
\r
797 510 => 'Not Extended'
\r
800 if ( isset( $headers_desc[$code] ) )
\r
801 return $headers_desc[$code];
\r
808 * Log a redirect (for stats)
811 function yourls_log_redirect( $keyword ) {
\r
812 // Allow plugins to short-circuit the whole function
\r
813 $pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );
\r
814 if ( false !== $pre )
\r
817 if ( !yourls_do_log_redirect() )
\r
821 $table = YOURLS_DB_TABLE_LOG;
\r
823 $keyword = yourls_sanitize_string( $keyword );
\r
824 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );
\r
825 $ua = yourls_get_user_agent();
\r
826 $ip = yourls_get_IP();
\r
827 $location = yourls_geo_ip_to_countrycode( $ip );
\r
829 return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
\r
833 * Check if we want to not log redirects (for stats)
836 function yourls_do_log_redirect() {
\r
837 return ( !defined( 'YOURLS_NOSTATS' ) || YOURLS_NOSTATS != true );
\r
841 * Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
844 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
\r
845 // Allow plugins to short-circuit the Geo IP API
\r
846 $location = yourls_apply_filter( 'shunt_geo_ip_to_countrycode', false, $ip, $default ); // at this point $ip can be '', check if your plugin hooks in here
\r
847 if ( false !== $location )
\r
850 if ( !file_exists( YOURLS_INC.'/geo/GeoIP.dat') || !file_exists( YOURLS_INC.'/geo/geoip.inc') )
\r
854 $ip = yourls_get_IP();
\r
856 require_once( YOURLS_INC.'/geo/geoip.inc') ;
\r
857 $gi = geoip_open( YOURLS_INC.'/geo/GeoIP.dat', GEOIP_STANDARD);
\r
858 $location = geoip_country_code_by_addr($gi, $ip);
\r
861 return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );
\r
865 * Converts a 2 letter country code to long name (ie AU -> Australia)
868 function yourls_geo_countrycode_to_countryname( $code ) {
\r
869 // Allow plugins to short-circuit the Geo IP API
\r
870 $country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );
\r
871 if ( false !== $country )
\r
874 // Load the Geo class if not already done
\r
875 if( !class_exists( 'GeoIP' ) ) {
\r
876 $temp = yourls_geo_ip_to_countrycode( '127.0.0.1' );
\r
879 if( class_exists( 'GeoIP' ) ) {
\r
881 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[ $code ];
\r
882 $long = $geo->GEOIP_COUNTRY_NAMES[ $id ];
\r
890 * Return flag URL from 2 letter country code
893 function yourls_geo_get_flag( $code ) {
\r
894 if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {
\r
895 $img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.( strtolower( $code ) ).'.gif' );
\r
899 return yourls_apply_filter( 'geo_get_flag', $img, $code );
\r
904 * Check if an upgrade is needed
907 function yourls_upgrade_is_needed() {
\r
908 // check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
\r
909 list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
\r
910 if( $currentsql < YOURLS_DB_VERSION )
\r
917 * Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
920 function yourls_get_current_version_from_sql() {
\r
921 $currentver = yourls_get_option( 'version' );
\r
922 $currentsql = yourls_get_option( 'db_version' );
\r
924 // Values if version is 1.3
\r
926 $currentver = '1.3';
\r
928 $currentsql = '100';
\r
930 return array( $currentver, $currentsql);
\r
934 * Read an option from DB (or from cache if available). Return value or $default if not found
937 function yourls_get_option( $option_name, $default = false ) {
\r
940 // Allow plugins to short-circuit options
\r
941 $pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );
\r
942 if ( false !== $pre )
\r
945 // If option not cached already, get its value from the DB
\r
946 if ( !isset( $ydb->option[$option_name] ) ) {
\r
947 $table = YOURLS_DB_TABLE_OPTIONS;
\r
948 $option_name = yourls_escape( $option_name );
\r
949 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
\r
950 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
\r
951 $value = $row->option_value;
\r
952 } else { // option does not exist, so we must cache its non-existence
\r
955 $ydb->option[ $option_name ] = yourls_maybe_unserialize( $value );
\r
958 return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );
\r
962 * Read all options from DB at once
965 function yourls_get_all_options() {
\r
968 // Allow plugins to short-circuit all options. (Note: regular plugins are loaded after all options)
\r
969 $pre = yourls_apply_filter( 'shunt_all_options', false );
\r
970 if ( false !== $pre )
\r
973 $table = YOURLS_DB_TABLE_OPTIONS;
\r
975 $allopt = $ydb->get_results( "SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1" );
\r
977 foreach( (array)$allopt as $option ) {
\r
978 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );
\r
981 $ydb->option = yourls_apply_filter( 'get_all_options', $ydb->option );
\r
985 * Update (add if doesn't exist) an option to DB
988 function yourls_update_option( $option_name, $newvalue ) {
\r
990 $table = YOURLS_DB_TABLE_OPTIONS;
\r
992 $safe_option_name = yourls_escape( $option_name );
\r
994 $oldvalue = yourls_get_option( $safe_option_name );
\r
996 // If the new and old values are the same, no need to update.
\r
997 if ( $newvalue === $oldvalue )
\r
1000 if ( false === $oldvalue ) {
\r
1001 yourls_add_option( $option_name, $newvalue );
\r
1005 $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );
\r
1007 yourls_do_action( 'update_option', $option_name, $oldvalue, $newvalue );
\r
1009 $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'" );
\r
1011 if ( $ydb->rows_affected == 1 ) {
\r
1012 $ydb->option[ $option_name ] = $newvalue;
\r
1019 * Add an option to the DB
1022 function yourls_add_option( $name, $value = '' ) {
\r
1024 $table = YOURLS_DB_TABLE_OPTIONS;
\r
1025 $safe_name = yourls_escape( $name );
\r
1027 // Make sure the option doesn't already exist
\r
1028 if ( false !== yourls_get_option( $safe_name ) )
\r
1031 $_value = yourls_escape( yourls_maybe_serialize( $value ) );
\r
1033 yourls_do_action( 'add_option', $safe_name, $_value );
\r
1035 $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );
\r
1036 $ydb->option[ $name ] = $value;
\r
1042 * Delete an option from the DB
1045 function yourls_delete_option( $name ) {
\r
1047 $table = YOURLS_DB_TABLE_OPTIONS;
\r
1048 $name = yourls_escape( $name );
\r
1050 // Get the ID, if no ID then return
\r
1051 $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );
\r
1052 if ( is_null( $option ) || !$option->option_id )
\r
1055 yourls_do_action( 'delete_option', $option_name );
\r
1057 $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );
\r
1064 * Serialize data if needed. Stolen from WordPress
1067 function yourls_maybe_serialize( $data ) {
\r
1068 if ( is_array( $data ) || is_object( $data ) )
\r
1069 return serialize( $data );
\r
1071 if ( yourls_is_serialized( $data ) )
\r
1072 return serialize( $data );
\r
1078 * Check value to find if it was serialized. Stolen from WordPress
1081 function yourls_is_serialized( $data ) {
\r
1082 // if it isn't a string, it isn't serialized
\r
1083 if ( !is_string( $data ) )
\r
1085 $data = trim( $data );
\r
1086 if ( 'N;' == $data )
\r
1088 if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
\r
1090 switch ( $badions[1] ) {
\r
1094 if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
\r
1100 if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
\r
1108 * Unserialize value only if it was serialized. Stolen from WP
1111 function yourls_maybe_unserialize( $original ) {
\r
1112 if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
\r
1113 return @unserialize( $original );
\r
1118 * Determine if the current page is private
1121 function yourls_is_private() {
\r
1124 if ( defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true ) {
\r
1126 // Allow overruling for particular pages:
\r
1129 if( yourls_is_API() ) {
\r
1130 if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )
\r
1134 } elseif( yourls_is_infos() ) {
\r
1135 if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )
\r
1145 return yourls_apply_filter( 'is_private', $private );
\r
1149 * Show login form if required
1152 function yourls_maybe_require_auth() {
\r
1153 if( yourls_is_private() )
\r
1154 require_once( YOURLS_INC.'/auth.php' );
\r
1158 * Allow several short URLs for the same long URL ?
1161 function yourls_allow_duplicate_longurls() {
\r
1162 // special treatment if API to check for WordPress plugin requests
\r
1163 if( yourls_is_API() ) {
\r
1164 if ( isset($_REQUEST['source']) && $_REQUEST['source'] == 'plugin' )
\r
1167 return ( defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS == false );
\r
1171 * Return list of all shorturls associated to the same long URL. Returns NULL or array of keywords.
1174 function yourls_get_duplicate_keywords( $longurl ) {
\r
1175 if( !yourls_allow_duplicate_longurls() )
\r
1179 $longurl = yourls_escape( yourls_sanitize_url($longurl) );
\r
1180 $table = YOURLS_DB_TABLE_URL;
\r
1182 $return = $ydb->get_col( "SELECT `keyword` FROM `$table` WHERE `url` = '$longurl'" );
\r
1183 return yourls_apply_filter( 'get_duplicate_keywords', $return, $longurl );
\r
1187 * Check if an IP shortens URL too fast to prevent DB flood. Return true, or die.
1190 function yourls_check_IP_flood( $ip = '' ) {
\r
1192 // Allow plugins to short-circuit the whole function
\r
1193 $pre = yourls_apply_filter( 'shunt_check_IP_flood', false, $ip );
\r
1194 if ( false !== $pre )
\r
1197 yourls_do_action( 'pre_check_ip_flood', $ip ); // at this point $ip can be '', check it if your plugin hooks in here
\r
1200 ( defined('YOURLS_FLOOD_DELAY_SECONDS') && YOURLS_FLOOD_DELAY_SECONDS === 0 ) ||
\r
1201 !defined('YOURLS_FLOOD_DELAY_SECONDS')
\r
1205 $ip = ( $ip ? yourls_sanitize_ip( $ip ) : yourls_get_IP() );
\r
1207 // Don't throttle whitelist IPs
\r
1208 if( defined( 'YOURLS_FLOOD_IP_WHITELIST' ) && YOURLS_FLOOD_IP_WHITELIST ) {
\r
1209 $whitelist_ips = explode( ',', YOURLS_FLOOD_IP_WHITELIST );
\r
1210 foreach( (array)$whitelist_ips as $whitelist_ip ) {
\r
1211 $whitelist_ip = trim( $whitelist_ip );
\r
1212 if ( $whitelist_ip == $ip )
\r
1217 // Don't throttle logged in users
\r
1218 if( yourls_is_private() ) {
\r
1219 if( yourls_is_valid_user() === true )
\r
1223 yourls_do_action( 'check_ip_flood', $ip );
\r
1226 $table = YOURLS_DB_TABLE_URL;
\r
1228 $lasttime = $ydb->get_var( "SELECT `timestamp` FROM $table WHERE `ip` = '$ip' ORDER BY `timestamp` DESC LIMIT 1" );
\r
1230 $now = date( 'U' );
\r
1231 $then = date( 'U', strtotime( $lasttime ) );
\r
1232 if( ( $now - $then ) <= YOURLS_FLOOD_DELAY_SECONDS ) {
\r
1234 yourls_do_action( 'ip_flood', $ip, $now - $then );
\r
1235 yourls_die( yourls__( 'Too many URLs added too fast. Slow down please.' ), yourls__( 'Forbidden' ), 403 );
\r
1243 * Check if YOURLS is installing
\r
1248 function yourls_is_installing() {
\r
1249 $installing = defined( 'YOURLS_INSTALLING' ) && YOURLS_INSTALLING == true;
\r
1250 return yourls_apply_filter( 'is_installing', $installing );
\r
1254 * Check if YOURLS is upgrading
\r
1259 function yourls_is_upgrading() {
\r
1260 $upgrading = defined( 'YOURLS_UPGRADING' ) && YOURLS_UPGRADING == true;
\r
1261 return yourls_apply_filter( 'is_upgrading', $upgrading );
\r
1266 * Check if YOURLS is installed
1269 function yourls_is_installed() {
\r
1270 static $is_installed = false;
\r
1271 if ( $is_installed === false ) {
\r
1272 $check_14 = $check_13 = false;
\r
1274 if( defined('YOURLS_DB_TABLE_NEXTDEC') )
\r
1275 $check_13 = $ydb->get_var('SELECT `next_id` FROM '.YOURLS_DB_TABLE_NEXTDEC);
\r
1276 $check_14 = yourls_get_option( 'version' );
\r
1277 $is_installed = $check_13 || $check_14;
\r
1279 return yourls_apply_filter( 'is_installed', $is_installed );
\r
1283 * Generate random string of (int)$length length and type $type (see function for details)
1286 function yourls_rnd_string ( $length = 5, $type = 0, $charlist = '' ) {
\r
1288 $length = intval( $length );
\r
1290 // define possible characters
\r
1291 switch ( $type ) {
\r
1293 // custom char list, or comply to charset as defined in config
\r
1295 $possible = $charlist ? $charlist : yourls_get_shorturl_charset() ;
\r
1298 // no vowels to make no offending word, no 0/1/o/l to avoid confusion between letters & digits. Perfect for passwords.
\r
1300 $possible = "23456789bcdfghjkmnpqrstvwxyz";
\r
1303 // Same, with lower + upper
\r
1305 $possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
\r
1308 // all letters, lowercase
\r
1310 $possible = "abcdefghijklmnopqrstuvwxyz";
\r
1313 // all letters, lowercase + uppercase
\r
1315 $possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1318 // all digits & letters lowercase
\r
1320 $possible = "0123456789abcdefghijklmnopqrstuvwxyz";
\r
1323 // all digits & letters lowercase + uppercase
\r
1325 $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
\r
1331 while ($i < $length) {
\r
1332 $str .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
\r
1336 return yourls_apply_filter( 'rnd_string', $str, $length, $type, $charlist );
\r
1340 * Return salted string
1343 function yourls_salt( $string ) {
\r
1344 $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
\r
1345 return yourls_apply_filter( 'yourls_salt', md5 ($string . $salt), $string );
\r
1349 * Add a query var to a URL and return URL. Completely stolen from WP.
\r
1351 * Works with one of these parameter patterns:
\r
1352 * array( 'var' => 'value' )
\r
1353 * array( 'var' => 'value' ), $url
\r
1355 * 'var', 'value', $url
\r
1356 * If $url ommited, uses $_SERVER['REQUEST_URI']
1359 function yourls_add_query_arg() {
\r
1361 if ( is_array( func_get_arg(0) ) ) {
\r
1362 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
\r
1363 $uri = $_SERVER['REQUEST_URI'];
\r
1365 $uri = @func_get_arg( 1 );
\r
1367 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
\r
1368 $uri = $_SERVER['REQUEST_URI'];
\r
1370 $uri = @func_get_arg( 2 );
\r
1373 $uri = str_replace( '&', '&', $uri );
\r
1376 if ( $frag = strstr( $uri, '#' ) )
\r
1377 $uri = substr( $uri, 0, -strlen( $frag ) );
\r
1381 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
\r
1382 $protocol = $matches[0];
\r
1383 $uri = substr( $uri, strlen( $protocol ) );
\r
1388 if ( strpos( $uri, '?' ) !== false ) {
\r
1389 $parts = explode( '?', $uri, 2 );
\r
1390 if ( 1 == count( $parts ) ) {
\r
1392 $query = $parts[0];
\r
1394 $base = $parts[0] . '?';
\r
1395 $query = $parts[1];
\r
1397 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
\r
1398 $base = $uri . '?';
\r
1405 parse_str( $query, $qs );
\r
1406 $qs = yourls_urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
\r
1407 if ( is_array( func_get_arg( 0 ) ) ) {
\r
1408 $kayvees = func_get_arg( 0 );
\r
1409 $qs = array_merge( $qs, $kayvees );
\r
1411 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
\r
1414 foreach ( (array) $qs as $k => $v ) {
\r
1415 if ( $v === false )
\r
1419 $ret = http_build_query( $qs );
\r
1420 $ret = trim( $ret, '?' );
\r
1421 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
\r
1422 $ret = $protocol . $base . $ret . $frag;
\r
1423 $ret = rtrim( $ret, '?' );
\r
1428 * Navigates through an array and encodes the values to be used in a URL. Stolen from WP, used in yourls_add_query_arg()
1431 function yourls_urlencode_deep( $value ) {
\r
1432 $value = is_array( $value ) ? array_map( 'yourls_urlencode_deep', $value ) : urlencode( $value );
\r
1437 * Remove arg from query. Opposite of yourls_add_query_arg. Stolen from WP.
1440 function yourls_remove_query_arg( $key, $query = false ) {
\r
1441 if ( is_array( $key ) ) { // removing multiple keys
\r
1442 foreach ( $key as $k )
\r
1443 $query = yourls_add_query_arg( $k, false, $query );
\r
1446 return yourls_add_query_arg( $key, false, $query );
\r
1450 * Return a time-dependent string for nonce creation
1453 function yourls_tick() {
\r
1454 return ceil( time() / YOURLS_NONCE_LIFE );
\r
1458 * Create a time limited, action limited and user limited token
1461 function yourls_create_nonce( $action, $user = false ) {
\r
1462 if( false == $user )
\r
1463 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
\r
1464 $tick = yourls_tick();
\r
1465 return substr( yourls_salt($tick . $action . $user), 0, 10 );
\r
1469 * Create a nonce field for inclusion into a form
1472 function yourls_nonce_field( $action, $name = 'nonce', $user = false, $echo = true ) {
\r
1473 $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';
\r
1480 * Add a nonce to a URL. If URL omitted, adds nonce to current URL
1483 function yourls_nonce_url( $action, $url = false, $name = 'nonce', $user = false ) {
\r
1484 $nonce = yourls_create_nonce( $action, $user );
\r
1485 return yourls_add_query_arg( $name, $nonce, $url );
\r
1489 * Check validity of a nonce (ie time span, user and action match).
\r
1491 * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined)
\r
1492 * if $nonce is false or unspecified, it will use $_REQUEST['nonce']
1495 function yourls_verify_nonce( $action, $nonce = false, $user = false, $return = '' ) {
\r
1497 if( false == $user )
\r
1498 $user = defined( 'YOURLS_USER' ) ? YOURLS_USER : '-1';
\r
1500 // get current nonce value
\r
1501 if( false == $nonce && isset( $_REQUEST['nonce'] ) )
\r
1502 $nonce = $_REQUEST['nonce'];
\r
1504 // what nonce should be
\r
1505 $valid = yourls_create_nonce( $action, $user );
\r
1507 if( $nonce == $valid ) {
\r
1512 yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );
\r
1517 * Converts keyword into short link (prepend with YOURLS base URL)
1520 function yourls_link( $keyword = '' ) {
\r
1521 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword );
\r
1522 return yourls_apply_filter( 'yourls_link', $link, $keyword );
\r
1526 * Converts keyword into stat link (prepend with YOURLS base URL, append +)
1529 function yourls_statlink( $keyword = '' ) {
\r
1530 $link = YOURLS_SITE . '/' . yourls_sanitize_keyword( $keyword ) . '+';
\r
1531 if( yourls_is_ssl() )
\r
1532 $link = str_replace( 'http://', 'https://', $link );
\r
1533 return yourls_apply_filter( 'yourls_statlink', $link, $keyword );
\r
1537 * Check if we're in API mode. Returns bool
1540 function yourls_is_API() {
\r
1541 if ( defined( 'YOURLS_API' ) && YOURLS_API == true )
\r
1547 * Check if we're in Ajax mode. Returns bool
1550 function yourls_is_Ajax() {
\r
1551 if ( defined( 'YOURLS_AJAX' ) && YOURLS_AJAX == true )
\r
1557 * Check if we're in GO mode (yourls-go.php). Returns bool
1560 function yourls_is_GO() {
\r
1561 if ( defined( 'YOURLS_GO' ) && YOURLS_GO == true )
\r
1567 * Check if we're displaying stats infos (yourls-infos.php). Returns bool
1570 function yourls_is_infos() {
\r
1571 if ( defined( 'YOURLS_INFOS' ) && YOURLS_INFOS == true )
\r
1577 * Check if we'll need interface display function (ie not API or redirection)
1580 function yourls_has_interface() {
\r
1581 if( yourls_is_API() or yourls_is_GO() )
\r
1587 * Check if we're in the admin area. Returns bool
1590 function yourls_is_admin() {
\r
1591 if ( defined( 'YOURLS_ADMIN' ) && YOURLS_ADMIN == true )
\r
1597 * Check if the server seems to be running on Windows. Not exactly sure how reliable this is.
1600 function yourls_is_windows() {
\r
1601 return defined( 'DIRECTORY_SEPARATOR' ) && DIRECTORY_SEPARATOR == '\\';
\r
1605 * Check if SSL is required. Returns bool.
1608 function yourls_needs_ssl() {
\r
1609 if ( defined('YOURLS_ADMIN_SSL') && YOURLS_ADMIN_SSL == true )
\r
1615 * Return admin link, with SSL preference if applicable.
1618 function yourls_admin_url( $page = '' ) {
\r
1619 $admin = YOURLS_SITE . '/admin/' . $page;
\r
1620 if( yourls_is_ssl() or yourls_needs_ssl() )
\r
1621 $admin = str_replace('http://', 'https://', $admin);
\r
1622 return yourls_apply_filter( 'admin_url', $admin, $page );
\r
1626 * Return YOURLS_SITE or URL under YOURLS setup, with SSL preference
1629 function yourls_site_url( $echo = true, $url = '' ) {
\r
1630 $url = yourls_get_relative_url( $url );
\r
1631 $url = trim( YOURLS_SITE . '/' . $url, '/' );
\r
1633 // Do not enforce (checking yourls_need_ssl() ) but check current usage so it won't force SSL on non-admin pages
\r
1634 if( yourls_is_ssl() )
\r
1635 $url = str_replace( 'http://', 'https://', $url );
\r
1636 $url = yourls_apply_filter( 'site_url', $url );
\r
1643 * Check if SSL is used, returns bool. Stolen from WP.
1646 function yourls_is_ssl() {
\r
1648 if ( isset( $_SERVER['HTTPS'] ) ) {
\r
1649 if ( 'on' == strtolower( $_SERVER['HTTPS'] ) )
\r
1651 if ( '1' == $_SERVER['HTTPS'] )
\r
1653 } elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
\r
1656 return yourls_apply_filter( 'is_ssl', $is_ssl );
\r
1661 * Get a remote page <title>, return a string (either title or url)
1664 function yourls_get_remote_title( $url ) {
\r
1665 // Allow plugins to short-circuit the whole function
\r
1666 $pre = yourls_apply_filter( 'shunt_get_remote_title', false, $url );
\r
1667 if ( false !== $pre )
\r
1670 require_once( YOURLS_INC.'/functions-http.php' );
\r
1672 $url = yourls_sanitize_url( $url );
\r
1674 $title = $charset = false;
\r
1676 $content = yourls_get_remote_content( $url );
\r
1678 // If false, return url as title.
\r
1679 // Todo: improve this with temporary title when shorturl_meta available?
\r
1680 if( false === $content )
\r
1683 if( $content !== false ) {
\r
1684 // look for <title>
\r
1685 if ( preg_match('/<title>(.*?)<\/title>/is', $content, $found ) ) {
\r
1686 $title = $found[1];
\r
1690 // look for charset
\r
1691 // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
\r
1692 if ( preg_match('/<meta[^>]*?charset=([^>]*?)\/?>/is', $content, $found ) ) {
\r
1693 $charset = trim($found[1], '"\' ');
\r
1698 // if title not found, guess if returned content was actually an error message
\r
1699 if( $title == false && strpos( $content, 'Error' ) === 0 ) {
\r
1700 $title = $content;
\r
1703 if( $title == false )
\r
1707 if( !yourls_seems_utf8( $title ) )
\r
1708 $title = utf8_encode( $title );
\r
1711 // Charset conversion. We use @ to remove warnings (mb_ functions are easily bitching about illegal chars)
\r
1712 if( function_exists( 'mb_convert_encoding' ) ) {
\r
1714 $title = @mb_convert_encoding( $title, 'UTF-8', $charset );
\r
1716 $title = @mb_convert_encoding( $title, 'UTF-8' );
\r
1720 // Remove HTML entities
\r
1721 $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' );
\r
1723 // Strip out evil things
\r
1724 $title = yourls_sanitize_title( $title );
\r
1726 return yourls_apply_filter( 'get_remote_title', $title, $url );
\r
1730 * Quick UA check for mobile devices. Return boolean.
1733 function yourls_is_mobile_device() {
\r
1734 // Strings searched
\r
1736 'android', 'blackberry', 'blazer',
\r
1737 'compal', 'elaine', 'fennec', 'hiptop',
\r
1738 'iemobile', 'iphone', 'ipod', 'ipad',
\r
1739 'iris', 'kindle', 'opera mobi', 'opera mini',
\r
1740 'palm', 'phone', 'pocket', 'psp', 'symbian',
\r
1741 'treo', 'wap', 'windows ce', 'windows phone'
\r
1744 // Current user-agent
\r
1745 $current = strtolower( $_SERVER['HTTP_USER_AGENT'] );
\r
1747 // Check and return
\r
1748 $is_mobile = ( str_replace( $mobiles, '', $current ) != $current );
\r
1749 return yourls_apply_filter( 'is_mobile_device', $is_mobile );
\r
1753 * Get request in YOURLS base (eg in 'http://site.com/yourls/abcd' get 'abdc')
1756 function yourls_get_request() {
\r
1757 // Allow plugins to short-circuit the whole function
\r
1758 $pre = yourls_apply_filter( 'shunt_get_request', false );
\r
1759 if ( false !== $pre )
\r
1762 static $request = null;
\r
1764 yourls_do_action( 'pre_get_request', $request );
\r
1766 if( $request !== null )
\r
1769 // Ignore protocol & www. prefix
\r
1770 $root = str_replace( array( 'https://', 'http://', 'https://www.', 'http://www.' ), '', YOURLS_SITE );
\r
1771 // Case insensitive comparison of the YOURLS root to match both http://Sho.rt/blah and http://sho.rt/blah
\r
1772 $request = preg_replace( "!$root/!i", '', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 1 );
\r
1774 // Unless request looks like a full URL (ie request is a simple keyword) strip query string
\r
1775 if( !preg_match( "@^[a-zA-Z]+://.+@", $request ) ) {
\r
1776 $request = current( explode( '?', $request ) );
\r
1779 return yourls_apply_filter( 'get_request', $request );
\r
1783 * Change protocol to match current scheme used (http or https)
1786 function yourls_match_current_protocol( $url, $normal = 'http', $ssl = 'https' ) {
\r
1787 if( yourls_is_ssl() )
\r
1788 $url = str_replace( $normal, $ssl, $url );
\r
1789 return yourls_apply_filter( 'match_current_protocol', $url );
\r
1793 * Fix $_SERVER['REQUEST_URI'] variable for various setups. Stolen from WP.
1796 function yourls_fix_request_uri() {
\r
1798 $default_server_values = array(
\r
1799 'SERVER_SOFTWARE' => '',
\r
1800 'REQUEST_URI' => '',
\r
1802 $_SERVER = array_merge( $default_server_values, $_SERVER );
\r
1804 // Fix for IIS when running with PHP ISAPI
\r
1805 if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {
\r
1807 // IIS Mod-Rewrite
\r
1808 if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
\r
1809 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
\r
1811 // IIS Isapi_Rewrite
\r
1812 else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {
\r
1813 $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
\r
1815 // Use ORIG_PATH_INFO if there is no PATH_INFO
\r
1816 if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )
\r
1817 $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
\r
1819 // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
\r
1820 if ( isset( $_SERVER['PATH_INFO'] ) ) {
\r
1821 if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
\r
1822 $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
\r
1824 $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
\r
1827 // Append the query string if it exists and isn't null
\r
1828 if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
\r
1829 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
\r
1836 * Shutdown function, runs just before PHP shuts down execution. Stolen from WP
1839 function yourls_shutdown() {
\r
1840 yourls_do_action( 'shutdown' );
\r
1844 * Auto detect custom favicon in /user directory, fallback to YOURLS favicon, and echo/return its URL
1847 function yourls_favicon( $echo = true ) {
\r
1848 static $favicon = null;
\r
1849 if( $favicon !== null )
\r
1853 // search for favicon.(gif|ico|png|jpg|svg)
\r
1854 foreach( array( 'gif', 'ico', 'png', 'jpg', 'svg' ) as $ext ) {
\r
1855 if( file_exists( YOURLS_USERDIR. '/favicon.' . $ext ) ) {
\r
1856 $custom = 'favicon.' . $ext;
\r
1862 $favicon = yourls_site_url( false, YOURLS_USERURL . '/' . $custom );
\r
1864 $favicon = yourls_site_url( false ) . '/images/favicon.gif';
\r
1872 * Check for maintenance mode. If yes, die. See yourls_maintenance_mode(). Stolen from WP.
1875 function yourls_check_maintenance_mode() {
\r
1877 $file = YOURLS_ABSPATH . '/.maintenance' ;
\r
1878 if ( !file_exists( $file ) || yourls_is_upgrading() || yourls_is_installing() )
\r
1881 global $maintenance_start;
\r
1884 // If the $maintenance_start timestamp is older than 10 minutes, don't die.
\r
1885 if ( ( time() - $maintenance_start ) >= 600 )
\r
1888 // Use any /user/maintenance.php file
\r
1889 if( file_exists( YOURLS_USERDIR.'/maintenance.php' ) ) {
\r
1890 include( YOURLS_USERDIR.'/maintenance.php' );
\r
1894 // https://www.youtube.com/watch?v=Xw-m4jEY-Ns
\r
1895 $title = yourls__( 'Service temporarily unavailable' );
\r
1896 $message = yourls__( 'Our service is currently undergoing scheduled maintenance.' ) . "</p>\n<p>" .
\r
1897 yourls__( 'Things should not last very long, thank you for your patience and please excuse the inconvenience' );
\r
1898 yourls_die( $message, $title , 503 );
\r
1903 * Return current admin page, or null if not an admin page
\r
1905 * @return mixed string if admin page, null if not an admin page
\r
1908 function yourls_current_admin_page() {
\r
1909 if( yourls_is_admin() ) {
\r
1910 $current = substr( yourls_get_request(), 6 );
\r
1911 if( $current === false )
\r
1912 $current = 'index.php'; // if current page is http://sho.rt/admin/ instead of http://sho.rt/admin/index.php
\r
1920 * Check if a URL protocol is allowed
\r
1922 * Checks a URL against a list of whitelisted protocols. Protocols must be defined with
\r
1923 * their complete scheme name, ie 'stuff:' or 'stuff://' (for instance, 'mailto:' is a valid
\r
1924 * protocol, 'mailto://' isn't, and 'http:' with no double slashed isn't either
\r
1928 * @param string $url URL to be check
\r
1929 * @param array $protocols Optional. Array of protocols, defaults to global $yourls_allowedprotocols
\r
1930 * @return boolean true if protocol allowed, false otherwise
\r
1932 function yourls_is_allowed_protocol( $url, $protocols = array() ) {
\r
1933 if( ! $protocols ) {
\r
1934 global $yourls_allowedprotocols;
\r
1935 $protocols = $yourls_allowedprotocols;
\r
1938 $protocol = yourls_get_protocol( $url );
\r
1939 return yourls_apply_filter( 'is_allowed_protocol', in_array( $protocol, $protocols ), $url, $protocols );
\r
1943 * Get protocol from a URL (eg mailto:, http:// ...)
\r
1947 * @param string $url URL to be check
\r
1948 * @return string Protocol, with slash slash if applicable. Empty string if no protocol
\r
1950 function yourls_get_protocol( $url ) {
\r
1951 preg_match( '!^[a-zA-Z0-9\+\.-]+:(//)?!', $url, $matches );
\r
1953 http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
\r
1954 The scheme name consists of a sequence of characters beginning with a letter and followed by any
\r
1955 combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). Although schemes are
\r
1956 case-insensitive, the canonical form is lowercase and documents that specify schemes must do so
\r
1957 with lowercase letters. It is followed by a colon (":").
\r
1959 $protocol = ( isset( $matches[0] ) ? $matches[0] : '' );
\r
1960 return yourls_apply_filter( 'get_protocol', $protocol, $url );
\r
1964 * Get relative URL (eg 'abc' from 'http://sho.rt/abc')
\r
1966 * Treat indifferently http & https. If a URL isn't relative to the YOURLS install, return it as is
\r
1967 * or return empty string if $strict is true
\r
1970 * @param string $url URL to relativize
\r
1971 * @param bool $strict if true and if URL isn't relative to YOURLS install, return empty string
\r
1972 * @return string URL
\r
1974 function yourls_get_relative_url( $url, $strict = true ) {
\r
1975 $url = yourls_sanitize_url( $url );
\r
1977 // Remove protocols to make it easier
\r
1978 $noproto_url = str_replace( 'https:', 'http:', $url );
\r
1979 $noproto_site = str_replace( 'https:', 'http:', YOURLS_SITE );
\r
1981 // Trim URL from YOURLS root URL : if no modification made, URL wasn't relative
\r
1982 $_url = str_replace( $noproto_site . '/', '', $noproto_url );
\r
1983 if( $_url == $noproto_url )
\r
1984 $_url = ( $strict ? '' : $url );
\r
1986 return yourls_apply_filter( 'get_relative_url', $_url, $url );
\r
1990 * Marks a function as deprecated and informs when it has been used. Stolen from WP.
\r
1992 * There is a hook deprecated_function that will be called that can be used
\r
1993 * to get the backtrace up to what file and function called the deprecated
\r
1996 * The current behavior is to trigger a user error if YOURLS_DEBUG is true.
\r
1998 * This function is to be used in every function that is deprecated.
\r
2001 * @uses yourls_do_action() Calls 'deprecated_function' and passes the function name, what to use instead,
\r
2002 * and the version the function was deprecated in.
\r
2003 * @uses yourls_apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
\r
2004 * trigger or false to not trigger error.
\r
2006 * @param string $function The function that was called
\r
2007 * @param string $version The version of WordPress that deprecated the function
\r
2008 * @param string $replacement Optional. The function that should have been called
\r
2010 function yourls_deprecated_function( $function, $version, $replacement = null ) {
\r
2012 yourls_do_action( 'deprecated_function', $function, $replacement, $version );
\r
2014 // Allow plugin to filter the output error trigger
\r
2015 if ( YOURLS_DEBUG && yourls_apply_filters( 'deprecated_function_trigger_error', true ) ) {
\r
2016 if ( ! is_null( $replacement ) )
\r
2017 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
\r
2019 trigger_error( sprintf( yourls__('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
\r
2024 * Return the value if not an empty string
\r
2026 * Used with array_filter(), to remove empty keys but not keys with value 0 or false
\r
2029 * @param mixed $val Value to test against ''
\r
2030 * @return bool True if not an empty string
\r
2032 function yourls_return_if_not_empty_string( $val ) {
\r
2033 return( $val !== '' );
\r