]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-http.php
Refactor proxy functions
[Github/YOURLS.git] / includes / functions-http.php
1 <?php
2 /**
3  * Functions that relate to HTTP requests
4  *
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
13  *
14  * @since 1.7
15  */
16
17 /**
18  * Perform a GET request, return response object or error string message
19  *
20  * Notable object properties: body, headers, status_code
21  *
22  * @since 1.7
23  * @see yourls_http_request
24  * @return mixed Response object, or error string
25  */
26 function yourls_http_get( $url, $headers = array(), $data = array(), $options = array() ) {
27         return yourls_http_request( 'GET', $url, $headers, $data, $options );
28 }
29
30 /**
31  * Perform a GET request, return body or null if there was an error
32  *
33  * @since 1.7
34  * @see yourls_http_request
35  * @return mixed String (page body) or null if error
36  */
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;
40 }
41
42 /**
43  * Perform a POST request, return response object
44  *
45  * Notable object properties: body, headers, status_code
46  *
47  * @since 1.7
48  * @see yourls_http_request
49  * @return mixed Response object, or error string
50  */
51 function yourls_http_post( $url, $headers = array(), $data = array(), $options = array() ) {
52         return yourls_http_request( 'POST', $url, $headers, $data, $options );
53 }
54
55 /**
56  * Perform a POST request, return body
57  *
58  * Wrapper for yourls_http_request()
59  *
60  * @since 1.7
61  * @see yourls_http_request
62  * @return mixed String (page body) or null if error
63  */
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;
67 }
68
69 /**
70  * Get proxy information
71  *
72  * @uses YOURLS_PROXY YOURLS_PROXY_USERNAME YOURLS_PROXY_PASSWORD
73  * @since 1.7.1
74  * @return mixed false if no proxy is defined, or string like '10.0.0.201:3128' or array like ('10.0.0.201:3128', 'username', 'password')
75  */
76 function yourls_http_get_proxy() {
77     $proxy = false;
78     
79     if( defined( 'YOURLS_PROXY' ) && !empty( 'YOURLS_PROXY' ) ) {
80         $proxy = YOURLS_PROXY;
81         // Username (?) and password can be defined as an empty string : no check for empty()
82         if( defined( 'YOURLS_PROXY_USERNAME' ) && defined( 'YOURLS_PROXY_PASSWORD' ) ) {
83             $proxy = array( YOURLS_PROXY, YOURLS_PROXY_USERNAME, YOURLS_PROXY_PASSWORD );
84         }
85     }
86     
87     return yourls_apply_filter( 'http_get_proxy', $proxy );
88 }
89
90 /**
91  * Get list of hosts that should bypass the proxy
92  *
93  * @uses YOURLS_PROXY_BYPASS_HOSTS
94  * @since 1.7.1
95  * @return mixed false if no host defined, or string like "example.com, *.mycorp.com"
96  */
97 function yourls_http_get_proxy_bypass_host() {
98     $hosts = defined( 'YOURLS_PROXY_BYPASS_HOSTS' ) ? YOURLS_PROXY_BYPASS_HOSTS : false;
99
100     return yourls_apply_filter( 'http_get_proxy_bypass_host', $hosts );
101 }
102
103 /**
104  * Default HTTP requests options for YOURLS
105  *
106  * For a list of all available options, see function request() in /includes/Requests/Requests.php
107  *
108  * @since 1.7
109  * @return array Options
110  */
111 function yourls_http_default_options() {
112         $options = array(
113                 'timeout'          => yourls_apply_filter( 'http_default_options_timeout', 3 ),
114                 'useragent'        => yourls_http_user_agent(),
115                 'follow_redirects' => true,
116                 'redirects'        => 3,
117         );
118
119         if( yourls_http_get_proxy() ) {
120         $options['proxy'] = yourls_http_get_proxy();
121         }
122
123         return yourls_apply_filter( 'http_default_options', $options ); 
124 }
125
126 /**
127  * Whether URL should be sent through the proxy server.
128  *
129  * Concept stolen from WordPress. The idea is to allow some URLs, including localhost and the YOURLS install itself,
130  * to be requested directly and bypassing any defined proxy.
131  *
132  * @uses YOURLS_PROXY
133  * @uses YOURLS_PROXY_BYPASS_HOSTS
134  * @since 1.7
135  * @param string $url URL to check
136  * @return bool true to request through proxy, false to request directly
137  */
138 function yourls_send_through_proxy( $url ) {
139
140         // Allow plugins to short-circuit the whole function
141         $pre = yourls_apply_filter( 'shunt_send_through_proxy', null, $url );
142         if ( null !== $pre )
143                 return $pre;
144
145         $check = @parse_url( $url );
146     
147     if( !isset( $check['host'] ) ) {
148         return false;
149     }
150         
151         // Malformed URL, can not process, but this could mean ssl, so let through anyway.
152         if ( $check === false )
153                 return true;
154         
155         // Self and loopback URLs are considered local (':' is parse_url() host on '::1')
156         $home = parse_url( YOURLS_SITE );
157         $local = array( 'localhost', '127.0.0.1', '127.1', '[::1]', ':', $home['host'] );
158         
159         if( in_array( $check['host'], $local ) )
160                 return false;
161                 
162     $bypass = yourls_http_get_proxy_bypass_host();
163     
164     if( $bypass === false OR $bypass === '' ) {
165         return true;
166     }
167         
168         // Build array of hosts to bypass
169         static $bypass_hosts;
170         static $wildcard_regex = false;
171         if ( null == $bypass_hosts ) {
172         $bypass_hosts = preg_split( '|\s*,\s*|', $bypass );
173
174         if ( false !== strpos( $bypass, '*' ) ) {
175             $wildcard_regex = array();
176             foreach ( $bypass_hosts as $host ) {
177                 $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
178                 if ( false !== strpos( $host, '*' ) ) {
179                     $wildcard_regex[] = str_replace( '\*\.', '', preg_quote( $host, '/' ) );
180                 }
181             }
182             $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
183         }
184         }
185
186         if ( !empty( $wildcard_regex ) )
187                 return !preg_match( $wildcard_regex, $check['host'] );
188         else
189                 return !in_array( $check['host'], $bypass_hosts );
190 }
191
192 /**
193  * Perform a HTTP request, return response object
194  *
195  * @since 1.7
196  * @param string $type HTTP request type (GET, POST)
197  * @param string $url URL to request
198  * @param array $headers Extra headers to send with the request
199  * @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
200  * @param array $options Options for the request (see /includes/Requests/Requests.php:request())
201  * @return object Requests_Response object
202  */
203 function yourls_http_request( $type, $url, $headers, $data, $options ) {
204         yourls_http_load_library();
205         
206         $options = array_merge( yourls_http_default_options(), $options );
207         
208         if( yourls_http_get_proxy() && !yourls_send_through_proxy( $url ) )
209                 unset( $options['proxy'] );
210         
211         try {
212                 $result = Requests::request( $url, $headers, $data, $type, $options );
213         } catch( Requests_Exception $e ) {
214                 $result = yourls_debug_log( $e->getMessage() . ' (' . $type . ' on ' . $url . ')' );
215         };
216         
217         return $result;
218 }
219
220 /**
221  * Check if Requests class is defined, include Requests library if need be
222  *
223  * All HTTP functions should perform that check prior to any operation. This is to avoid
224  * include()-ing all the Requests files on every YOURLS instance disregarding whether needed or not.
225  *
226  * @since 1.7
227  */
228 function yourls_http_load_library() {
229         if ( !class_exists( 'Requests', false ) ) {
230                 require_once dirname( __FILE__ ) . '/Requests/Requests.php';
231                 Requests::register_autoloader();
232         }
233 }
234
235 /**
236  * Return funky user agent string
237  *
238  * @since 1.5
239  * @return string UA string
240  */
241 function yourls_http_user_agent() {
242         return yourls_apply_filter( 'http_user_agent', 'YOURLS v'.YOURLS_VERSION.' +http://yourls.org/ (running on '.YOURLS_SITE.')' );
243 }
244
245 /**
246  * Check api.yourls.org if there's a newer version of YOURLS
247  *
248  * This function collects various stats to help us improve YOURLS. See the blog post about it:
249  * http://blog.yourls.org/2014/01/on-yourls-1-7-and-api-yourls-org/
250  * Results of requests sent to api.yourls.org are stored in option 'core_version_checks' and is an object
251  * with the following properties:
252  *    - failed_attempts : number of consecutive failed attempts
253  *    - last_attempt    : time() of last attempt
254  *    - last_result     : content retrieved from api.yourls.org during previous check
255  *    - version_checked : installed YOURLS version that was last checked
256  *
257  * @since 1.7
258  * @return mixed JSON data if api.yourls.org successfully requested, false otherwise
259  */
260 function yourls_check_core_version() {
261
262         global $ydb, $yourls_user_passwords;
263         
264         $checks = yourls_get_option( 'core_version_checks' );
265         
266         // Invalidate check data when YOURLS version changes
267         if ( is_object( $checks ) && YOURLS_VERSION != $checks->version_checked ) {
268                 $checks = false;
269         }
270         
271         if( !is_object( $checks ) ) {
272                 $checks = new stdClass;
273                 $checks->failed_attempts = 0;
274                 $checks->last_attempt    = 0;
275                 $checks->last_result     = '';
276                 $checks->version_checked = YOURLS_VERSION;
277         }
278
279         // Config file location ('u' for '/user' or 'i' for '/includes')
280         $conf_loc = str_replace( YOURLS_ABSPATH, '', YOURLS_CONFIGFILE );
281         $conf_loc = str_replace( '/config.php', '', $conf_loc );
282         $conf_loc = ( $conf_loc == '/user' ? 'u' : 'i' );
283                 
284         // The collection of stuff to report
285         $stuff = array(
286                 // Globally uniquish site identifier
287                 'md5'                => md5( YOURLS_SITE . YOURLS_ABSPATH ),
288
289                 // Install information
290                 'failed_attempts'    => $checks->failed_attempts,
291                 'yourls_site'        => defined( 'YOURLS_SITE' ) ? YOURLS_SITE : 'unknown',
292                 'yourls_version'     => defined( 'YOURLS_VERSION' ) ? YOURLS_VERSION : 'unknown',
293                 'php_version'        => phpversion(),
294                 'mysql_version'      => $ydb->mysql_version(),
295                 'locale'             => yourls_get_locale(),
296
297                 // custom DB driver if any, and useful common PHP extensions
298                 'db_driver'          => defined( 'YOURLS_DB_DRIVER' ) ? YOURLS_DB_DRIVER : 'unset',
299                 'db_ext_pdo'         => extension_loaded( 'pdo_mysql' ) ? 1 : 0,
300                 'db_ext_mysql'       => extension_loaded( 'mysql' )     ? 1 : 0,
301                 'db_ext_mysqli'      => extension_loaded( 'mysqli' )    ? 1 : 0,
302                 'ext_curl'           => extension_loaded( 'curl' )      ? 1 : 0,
303
304                 // Config information
305                 'num_users'          => count( $yourls_user_passwords ),
306                 'config_location'    => $conf_loc,
307                 'yourls_private'     => defined( 'YOURLS_PRIVATE' ) && YOURLS_PRIVATE ? 1 : 0,
308                 'yourls_unique'      => defined( 'YOURLS_UNIQUE_URLS' ) && YOURLS_UNIQUE_URLS ? 1 : 0,
309                 'yourls_url_convert' => defined( 'YOURLS_URL_CONVERT' ) ? YOURLS_URL_CONVERT : 'unknown',
310                 'num_active_plugins' => yourls_has_active_plugins(),
311                 'num_pages'          => defined( 'YOURLS_PAGEDIR' ) ? count( (array) glob( YOURLS_PAGEDIR .'/*.php') ) : 0,
312         );
313         
314         $stuff = yourls_apply_filter( 'version_check_stuff', $stuff );
315         
316         // Send it in
317         $url = 'http://api.yourls.org/core/version/1.0/';
318     if( yourls_can_http_over_ssl() )
319         $url = yourls_set_url_scheme( $url, 'https' );
320         $req = yourls_http_post( $url, array(), $stuff );
321         
322         $checks->last_attempt = time();
323         $checks->version_checked = YOURLS_VERSION;
324
325         // Unexpected results ?
326         if( is_string( $req ) or !$req->success ) {
327                 $checks->failed_attempts = $checks->failed_attempts + 1;
328                 yourls_update_option( 'core_version_checks', $checks );
329                 return false;
330         }
331         
332         // Parse response
333         $json = json_decode( trim( $req->body ) );
334         
335         if( isset( $json->latest ) && isset( $json->zipurl ) ) {
336                 // All went OK - mark this down
337                 $checks->failed_attempts = 0;
338                 $checks->last_result     = $json;
339                 yourls_update_option( 'core_version_checks', $checks );
340                 
341                 return $json;
342         }
343         
344         // Request returned actual result, but not what we expected
345         return false;   
346 }
347
348 /**
349  * Determine if we want to check for a newer YOURLS version (and check if applicable)
350  *
351  * Currently checks are performed every 24h and only when someone is visiting an admin page.
352  * In the future (1.8?) maybe check with cronjob emulation instead.
353  *
354  * @since 1.7
355  * @return bool true if a check was needed and successfully performed, false otherwise
356  */
357 function yourls_maybe_check_core_version() {
358
359         // Allow plugins to short-circuit the whole function
360         $pre = yourls_apply_filter( 'shunt_maybe_check_core_version', null );
361         if ( null !== $pre )
362                 return $pre;
363
364         if( defined( 'YOURLS_NO_VERSION_CHECK' ) && YOURLS_NO_VERSION_CHECK )
365                 return false;
366
367         if( !yourls_is_admin() )
368                 return false;
369
370         $checks = yourls_get_option( 'core_version_checks' );
371         
372         /* We don't want to check if :
373          - last_result is set (a previous check was performed)
374          - and it was less than 24h ago (or less than 2h ago if it wasn't successful)
375          - and version checked matched version running
376          Otherwise, we want to check.
377         */
378         if( !empty( $checks->last_result )
379                 AND
380                 ( 
381                         ( $checks->failed_attempts == 0 && ( ( time() - $checks->last_attempt ) < 24 * 3600 ) )
382                         OR
383                         ( $checks->failed_attempts > 0  && ( ( time() - $checks->last_attempt ) <  2 * 3600 ) )
384                 )
385                 AND ( $checks->version_checked == YOURLS_VERSION )
386         )
387                 return false;
388
389         // We want to check if there's a new version
390         $new_check = yourls_check_core_version();
391         
392         // Could not check for a new version, and we don't have ancient data
393         if( false == $new_check && !isset( $checks->last_result->latest ) )
394                 return false;
395         
396         return true;
397 }
398
399 /**
400  * Check if server can perform HTTPS requests, return bool
401  *
402  * @since 1.7.1
403  * @return bool whether the server can perform HTTP requests over SSL
404  */
405 function yourls_can_http_over_ssl() {
406     $ssl_curl = $ssl_socket = false;
407     
408     if( function_exists( 'curl_exec' ) ) {
409         $curl_version  = curl_version();
410         $ssl_curl = ( $curl_version['features'] & CURL_VERSION_SSL );
411     }
412     
413     if( function_exists( 'stream_socket_client' ) ) {
414         $ssl_socket = extension_loaded( 'openssl' ) && function_exists( 'openssl_x509_parse' );    
415     }
416     
417     return ( $ssl_curl OR $ssl_socket );
418 }
419