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