Completed
Pull Request — master (#2066)
by
unknown
03:04
created

functions-http.php ➔ yourls_check_core_version()   F

Complexity

Conditions 23
Paths > 20000

Size

Total Lines 87
Code Lines 52

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 23
eloc 52
nc 393216
nop 0
dl 0
loc 87
rs 2.0338

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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