3 * Functions that relate to HTTP requests
5 * On functions using the 3rd party library Requests:
6 * Thir goal here is to provide convenient wrapper functions to the Requests library. There are
7 * 2 types of functions for each METHOD, where METHOD is 'get' or 'post' (implement more as needed)
8 * - yourls_http_METHOD() :
9 * Return a complete Response object (with ->body, ->headers, ->status_code, etc...) or
10 * a simple string (error message)
11 * - yourls_http_METHOD_body() :
12 * Return a string (response body) or null if there was an error
18 * Perform a GET request, return response object or error string message
20 * Notable object properties: body, headers, status_code
23 * @see yourls_http_request
24 * @return mixed Response object, or error string
26 function yourls_http_get( $url, $headers = array(), $data = array(), $options = array() ) {
27 return yourls_http_request( 'GET', $url, $headers, $data, $options );
31 * Perform a GET request, return body or null if there was an error
34 * @see yourls_http_request
35 * @return mixed String (page body) or null if error
37 function yourls_http_get_body( $url, $headers = array(), $data = array(), $options = array() ) {
38 $return = yourls_http_get( $url, $headers, $data, $options );
39 return isset( $return->body ) ? $return->body : null;
43 * Perform a POST request, return response object
45 * Notable object properties: body, headers, status_code
48 * @see yourls_http_request
49 * @return mixed Response object, or error string
51 function yourls_http_post( $url, $headers = array(), $data = array(), $options = array() ) {
52 return yourls_http_request( 'POST', $url, $headers, $data, $options );
56 * Perform a POST request, return body
58 * Wrapper for yourls_http_request()
61 * @see yourls_http_request
62 * @return mixed String (page body) or null if error
64 function yourls_http_post_body( $url, $headers = array(), $data = array(), $options = array() ) {
65 $return = yourls_http_post( $url, $headers, $data, $options );
66 return isset( $return->body ) ? $return->body : null;
70 * Check if a proxy is defined for HTTP requests
74 * @return bool true if a proxy is defined, false otherwise
76 function yourls_http_proxy_is_defined() {
77 return yourls_apply_filter( 'http_proxy_is_defined', defined( 'YOURLS_PROXY' ) );
81 * Default HTTP requests options for YOURLS
83 * For a list of all available options, see function request() in /includes/Requests/Requests.php
86 * @uses YOURLS_PROXY_USERNAME
87 * @uses YOURLS_PROXY_PASSWORD
89 * @return array Options
91 function yourls_http_default_options() {
93 'timeout' => yourls_apply_filter( 'http_default_options_timeout', 3 ),
94 'useragent' => yourls_http_user_agent(),
95 'follow_redirects' => true,
99 if( yourls_http_proxy_is_defined() ) {
100 if( defined( 'YOURLS_PROXY_USERNAME' ) && defined( 'YOURLS_PROXY_PASSWORD' ) ) {
101 $options['proxy'] = array( YOURLS_PROXY, YOURLS_PROXY_USERNAME, YOURLS_PROXY_PASSWORD );
103 $options['proxy'] = YOURLS_PROXY;
107 return yourls_apply_filter( 'http_default_options', $options );
111 * Whether URL should be sent through the proxy server.
113 * Concept stolen from WordPress. The idea is to allow some URLs, including localhost and the YOURLS install itself,
114 * to be requested directly and bypassing any defined proxy.
117 * @uses YOURLS_PROXY_BYPASS_HOSTS
119 * @param string $url URL to check
120 * @return bool true to request through proxy, false to request directly
122 function yourls_send_through_proxy( $url ) {
124 // Allow plugins to short-circuit the whole function
125 $pre = yourls_apply_filter( 'shunt_send_through_proxy', null, $url );
129 $check = @parse_url( $url );
131 // Malformed URL, can not process, but this could mean ssl, so let through anyway.
132 if ( $check === false )
135 // Self and loopback URLs are considered local (':' is parse_url() host on '::1')
136 $home = parse_url( YOURLS_SITE );
137 $local = array( 'localhost', '127.0.0.1', '127.1', '[::1]', ':', $home['host'] );
139 if( in_array( $check['host'], $local ) )
142 if ( !defined( 'YOURLS_PROXY_BYPASS_HOSTS' ) )
145 // Check YOURLS_PROXY_BYPASS_HOSTS
146 static $bypass_hosts;
147 static $wildcard_regex = false;
148 if ( null == $bypass_hosts ) {
149 $bypass_hosts = preg_split( '|,\s*|', YOURLS_PROXY_BYPASS_HOSTS );
151 if ( false !== strpos( YOURLS_PROXY_BYPASS_HOSTS, '*' ) ) {
152 $wildcard_regex = array();
153 foreach ( $bypass_hosts as $host )
154 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
155 $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
159 if ( !empty( $wildcard_regex ) )
160 return !preg_match( $wildcard_regex, $check['host'] );
162 return !in_array( $check['host'], $bypass_hosts );
166 * Perform a HTTP request, return response object
169 * @param string $type HTTP request type (GET, POST)
170 * @param string $url URL to request
171 * @param array $headers Extra headers to send with the request
172 * @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
173 * @param array $options Options for the request (see /includes/Requests/Requests.php:request())
174 * @return object Requests_Response object
176 function yourls_http_request( $type, $url, $headers, $data, $options ) {
177 yourls_http_load_library();
179 $options = array_merge( yourls_http_default_options(), $options );
181 if( yourls_http_proxy_is_defined() && !yourls_send_through_proxy( $url ) )
182 unset( $options['proxy'] );
185 $result = Requests::request( $url, $headers, $data, $type, $options );
186 } catch( Requests_Exception $e ) {
187 $result = yourls_debug_log( $e->getMessage() . ' (' . $type . ' on ' . $url . ')' );
194 * Check if Requests class is defined, include Requests library if need be
196 * All HTTP functions should perform that check prior to any operation. This is to avoid
197 * include()-ing all the Requests files on every YOURLS instance disregarding whether needed or not.
201 function yourls_http_load_library() {
202 if ( !class_exists( 'Requests', false ) ) {
203 require_once dirname( __FILE__ ) . '/Requests/Requests.php';
204 Requests::register_autoloader();
209 * Return funky user agent string
212 * @return string UA string
214 function yourls_http_user_agent() {
215 return yourls_apply_filter( 'http_user_agent', 'YOURLS v'.YOURLS_VERSION.' +http://yourls.org/ (running on '.YOURLS_SITE.')' );
219 * Check api.yourls.org if there's a newer version of YOURLS
221 * This function collects various stats to help us improve YOURLS. See the blog post about it:
222 * http://blog.yourls.org/2014/01/on-yourls-1-7-and-api-yourls-org/
223 * Results of requests sent to api.yourls.org are stored in option 'core_version_checks' and is an object
224 * with the following properties:
225 * - failed_attempts : number of consecutive failed attempts
226 * - last_attempt : time() of last attempt
227 * - last_result : content retrieved from api.yourls.org during previous check
228 * - version_checked : installed YOURLS version that was last checked
231 * @return mixed JSON data if api.yourls.org successfully requested, false otherwise
233 function yourls_check_core_version() {
235 global $ydb, $yourls_user_passwords;
237 $checks = yourls_get_option( 'core_version_checks' );
239 // Invalidate check data when YOURLS version changes
240 if ( is_object( $checks ) && YOURLS_VERSION != $checks->version_checked ) {
244 if( !is_object( $checks ) ) {
245 $checks = new stdClass;
246 $checks->failed_attempts = 0;
247 $checks->last_attempt = 0;
248 $checks->last_result = '';
249 $checks->version_checked = YOURLS_VERSION;
252 // Config file location ('u' for '/user' or 'i' for '/includes')
253 $conf_loc = str_replace( YOURLS_ABSPATH, '', YOURLS_CONFIGFILE );
254 $conf_loc = str_replace( '/config.php', '', $conf_loc );
255 $conf_loc = ( $conf_loc == '/user' ? 'u' : 'i' );
257 // The collection of stuff to report
259 // Globally uniquish site identifier
260 'md5' => md5( YOURLS_SITE . YOURLS_ABSPATH ),
262 // Install information
263 'failed_attempts' => $checks->failed_attempts,
264 'yourls_site' => defined( 'YOURLS_SITE' ) ? YOURLS_SITE : 'unknown',
265 'yourls_version' => defined( 'YOURLS_VERSION' ) ? YOURLS_VERSION : 'unknown',
266 'php_version' => phpversion(),
267 'mysql_version' => $ydb->mysql_version(),
268 'locale' => yourls_get_locale(),
270 // custom DB driver if any, and useful common PHP extensions
271 'db_driver' => defined( 'YOURLS_DB_DRIVER' ) ? YOURLS_DB_DRIVER : 'unset',
272 'db_ext_pdo' => extension_loaded( 'pdo_mysql' ) ? 1 : 0,
273 'db_ext_mysql' => extension_loaded( 'mysql' ) ? 1 : 0,
274 'db_ext_mysqli' => extension_loaded( 'mysqli' ) ? 1 : 0,
275 'ext_curl' => extension_loaded( 'curl' ) ? 1 : 0,
277 // Config information
278 'num_users' => count( $yourls_user_passwords ),
279 'config_location' => $conf_loc,
280 'yourls_private' => defined( 'YOURLS_PRIVATE' ) && YOURLS_PRIVATE ? 1 : 0,
281 'yourls_unique' => defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS ? 1 : 0,
282 'yourls_url_convert' => defined( 'YOURLS_URL_CONVERT' ) ? YOURLS_URL_CONVERT : 'unknown',
283 'num_active_plugins' => yourls_has_active_plugins(),
284 'num_pages' => defined( 'YOURLS_PAGEDIR' ) ? count( (array) glob( YOURLS_PAGEDIR .'/*.php') ) : 0,
287 $stuff = yourls_apply_filter( 'version_check_stuff', $stuff );
290 $url = 'http://api.yourls.org/core/version/1.0/';
291 if( yourls_can_http_over_ssl() )
292 $url = yourls_set_url_scheme( $url, 'https' );
293 $req = yourls_http_post( $url, array(), $stuff );
295 $checks->last_attempt = time();
296 $checks->version_checked = YOURLS_VERSION;
298 // Unexpected results ?
299 if( is_string( $req ) or !$req->success ) {
300 $checks->failed_attempts = $checks->failed_attempts + 1;
301 yourls_update_option( 'core_version_checks', $checks );
306 $json = json_decode( trim( $req->body ) );
308 if( isset( $json->latest ) && isset( $json->zipurl ) ) {
309 // All went OK - mark this down
310 $checks->failed_attempts = 0;
311 $checks->last_result = $json;
312 yourls_update_option( 'core_version_checks', $checks );
317 // Request returned actual result, but not what we expected
322 * Determine if we want to check for a newer YOURLS version (and check if applicable)
324 * Currently checks are performed every 24h and only when someone is visiting an admin page.
325 * In the future (1.8?) maybe check with cronjob emulation instead.
328 * @return bool true if a check was needed and successfully performed, false otherwise
330 function yourls_maybe_check_core_version() {
332 // Allow plugins to short-circuit the whole function
333 $pre = yourls_apply_filter( 'shunt_maybe_check_core_version', null );
337 if( defined( 'YOURLS_NO_VERSION_CHECK' ) && YOURLS_NO_VERSION_CHECK )
340 if( !yourls_is_admin() )
343 $checks = yourls_get_option( 'core_version_checks' );
345 /* We don't want to check if :
346 - last_result is set (a previous check was performed)
347 - and it was less than 24h ago (or less than 2h ago if it wasn't successful)
348 - and version checked matched version running
349 Otherwise, we want to check.
351 if( !empty( $checks->last_result )
354 ( $checks->failed_attempts == 0 && ( ( time() - $checks->last_attempt ) < 24 * 3600 ) )
356 ( $checks->failed_attempts > 0 && ( ( time() - $checks->last_attempt ) < 2 * 3600 ) )
358 AND ( $checks->version_checked == YOURLS_VERSION )
362 // We want to check if there's a new version
363 $new_check = yourls_check_core_version();
365 // Could not check for a new version, and we don't have ancient data
366 if( false == $new_check && !isset( $checks->last_result->latest ) )
373 * Check if server can perform HTTPS requests, return bool
376 * @return bool whether the server can perform HTTP requests over SSL
378 function yourls_can_http_over_ssl() {
379 $ssl_curl = $ssl_socket = false;
381 if( function_exists( 'curl_exec' ) ) {
382 $curl_version = curl_version();
383 $ssl_curl = ( $curl_version['features'] & CURL_VERSION_SSL );
386 if( function_exists( 'stream_socket_client' ) ) {
387 $ssl_socket = extension_loaded( 'openssl' ) && function_exists( 'openssl_x509_parse' );
390 return ( $ssl_curl OR $ssl_socket );