Completed
Push — replace-intval ( 844d28 )
by Jeremy
36:38 queued 27:41
created

Client::_wp_remote_request()   C

Complexity

Conditions 14
Paths 17

Size

Total Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
nc 17
nop 3
dl 0
loc 73
rs 5.6024
c 0
b 0
f 0

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
 * The Connection Client class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
12
/**
13
 * The Client class that is used to connect to WordPress.com Jetpack API.
14
 */
15
class Client {
16
	const WPCOM_JSON_API_VERSION = '1.1';
17
18
	/**
19
	 * Makes an authorized remote request using Jetpack_Signature
20
	 *
21
	 * @param array        $args the arguments for the remote request.
22
	 * @param array|String $body the request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be array|string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
23
	 * @return array|WP_Error WP HTTP response on success
24
	 */
25
	public static function remote_request( $args, $body = null ) {
26
		$result = self::build_signed_request( $args, $body );
27
		if ( ! $result || is_wp_error( $result ) ) {
28
			return $result;
29
		}
30
		return self::_wp_remote_request( $result['url'], $result['request'] );
31
	}
32
33
	/**
34
	 * Adds authorization signature to a remote request using Jetpack_Signature
35
	 *
36
	 * @param array        $args the arguments for the remote request.
37
	 * @param array|String $body the request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be array|string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
38
	 * @return WP_Error|array {
39
	 *     An array containing URL and request items.
40
	 *
41
	 *     @type String $url     The request URL.
42
	 *     @type array  $request Request arguments.
43
	 * }
44
	 */
45
	public static function build_signed_request( $args, $body = null ) {
46
		add_filter(
47
			'jetpack_constant_default_value',
48
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
49
			10,
50
			2
51
		);
52
53
		$defaults = array(
54
			'url'           => '',
55
			'user_id'       => 0,
56
			'blog_id'       => 0,
57
			'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
58
			'method'        => 'POST',
59
			'timeout'       => 10,
60
			'redirection'   => 0,
61
			'headers'       => array(),
62
			'stream'        => false,
63
			'filename'      => null,
64
			'sslverify'     => true,
65
		);
66
67
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,*,{"url":"s..."sslverify":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
68
69
		$args['blog_id'] = (int) $args['blog_id'];
70
71
		if ( 'header' !== $args['auth_location'] ) {
72
			$args['auth_location'] = 'query_string';
73
		}
74
75
		$connection = new Manager();
76
		$token      = $connection->get_access_token( $args['user_id'] );
77
		if ( ! $token ) {
78
			return new \WP_Error( 'missing_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
79
		}
80
81
		$method = strtoupper( $args['method'] );
82
83
		$timeout = (int) $args['timeout'];
84
85
		$redirection = $args['redirection'];
86
		$stream      = $args['stream'];
87
		$filename    = $args['filename'];
88
		$sslverify   = $args['sslverify'];
89
90
		$request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
91
92
		@list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
93
		if ( empty( $token ) || empty( $secret ) ) {
94
			return new \WP_Error( 'malformed_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
95
		}
96
97
		$token_key = sprintf(
98
			'%s:%d:%d',
99
			$token_key,
100
			Constants::get_constant( 'JETPACK__API_VERSION' ),
101
			$token->external_user_id
102
		);
103
104
		$time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
105
		$jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
106
107
		$timestamp = time() + $time_diff;
108
109 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
110
			$nonce = wp_generate_password( 10, false );
111
		} else {
112
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
113
		}
114
115
		// Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
116
		if ( is_null( $body ) ) {
117
			$body_hash = '';
118
119
		} else {
120
			// Allow arrays to be used in passing data.
121
			$body_to_hash = $body;
122
123
			if ( is_array( $body ) ) {
124
				// We cast this to a new variable, because the array form of $body needs to be
125
				// maintained so it can be passed into the request later on in the code.
126
				if ( count( $body ) > 0 ) {
127
					$body_to_hash = wp_json_encode( self::_stringify_data( $body ) );
128
				} else {
129
					$body_to_hash = '';
130
				}
131
			}
132
133
			if ( ! is_string( $body_to_hash ) ) {
134
				return new \WP_Error( 'invalid_body', 'Body is malformed.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_body'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
135
			}
136
137
			$body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
138
		}
139
140
		$auth = array(
141
			'token'     => $token_key,
142
			'timestamp' => $timestamp,
143
			'nonce'     => $nonce,
144
			'body-hash' => $body_hash,
145
		);
146
147
		if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
148
			$url_args = array(
149
				'for'           => 'jetpack',
150
				'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
151
			);
152
		} else {
153
			$url_args = array();
154
		}
155
156
		if ( 'header' !== $args['auth_location'] ) {
157
			$url_args += $auth;
158
		}
159
160
		$url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
161
162
		$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
163
164
		if ( ! $signature || is_wp_error( $signature ) ) {
165
			return $signature;
166
		}
167
168
		// Send an Authorization header so various caches/proxies do the right thing.
169
		$auth['signature'] = $signature;
170
		$auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
171
		$header_pieces     = array();
172
		foreach ( $auth as $key => $value ) {
173
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
174
		}
175
		$request['headers'] = array_merge(
176
			$args['headers'],
177
			array(
178
				'Authorization' => 'X_JETPACK ' . join( ' ', $header_pieces ),
179
			)
180
		);
181
182
		if ( 'header' !== $args['auth_location'] ) {
183
			$url = add_query_arg( 'signature', rawurlencode( $signature ), $url );
184
		}
185
186
		return compact( 'url', 'request' );
187
	}
188
189
	/**
190
	 * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
191
	 * This is lame, but many, many, many hosts have misconfigured SSL.
192
	 *
193
	 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
194
	 * 1. a certificate error is found AND
195
	 * 2. not verifying the certificate works around the problem.
196
	 *
197
	 * The option is checked on each request.
198
	 *
199
	 * @internal
200
	 *
201
	 * @param String  $url the request URL.
202
	 * @param array   $args request arguments.
203
	 * @param Boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
204
	 * @return array|WP_Error WP HTTP response on success
205
	 */
206
	public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
207
		/**
208
		 * SSL verification (`sslverify`) for the JetpackClient remote request
209
		 * defaults to off, use this filter to force it on.
210
		 *
211
		 * Return `true` to ENABLE SSL verification, return `false`
212
		 * to DISABLE SSL verification.
213
		 *
214
		 * @since 3.6.0
215
		 *
216
		 * @param bool Whether to force `sslverify` or not.
217
		 */
218
		if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
219
			return wp_remote_request( $url, $args );
220
		}
221
222
		$fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
223
		if ( false === $fallback ) {
224
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
225
		}
226
227
		if ( (int) $fallback ) {
228
			// We're flagged to fallback.
229
			$args['sslverify'] = false;
230
		}
231
232
		$response = wp_remote_request( $url, $args );
233
234
		if (
235
			! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
236
			||
237
			isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
238
			||
239
			! is_wp_error( $response )                          // Let it ride.
240
		) {
241
			self::set_time_diff( $response, $set_fallback );
242
			return $response;
243
		}
244
245
		// At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
246
247
		$message = $response->get_error_message();
248
249
		// Is it an SSL Certificate verification error?
250
		if (
251
			false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
252
			&&
253
			false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
254
			&&
255
			false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
256
			&&
257
			false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
258
			// Different versions of curl have different error messages
259
			// this string should catch them all.
260
			&&
261
			false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
262
		) {
263
			// No, it is not.
264
			return $response;
265
		}
266
267
		// Redo the request without SSL certificate verification.
268
		$args['sslverify'] = false;
269
		$response          = wp_remote_request( $url, $args );
270
271
		if ( ! is_wp_error( $response ) ) {
272
			// The request went through this time, flag for future fallbacks.
273
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
274
			self::set_time_diff( $response, $set_fallback );
275
		}
276
277
		return $response;
278
	}
279
280
	/**
281
	 * Sets the time difference for correct signature computation.
282
	 *
283
	 * @param HTTP_Response $response the response object.
284
	 * @param Boolean       $force_set whether to force setting the time difference.
285
	 */
286
	public static function set_time_diff( &$response, $force_set = false ) {
287
		$code = wp_remote_retrieve_response_code( $response );
288
289
		// Only trust the Date header on some responses.
290
		if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  WordPress.PHP.StrictComparisons.LooseComparison
291
			return;
292
		}
293
294
		$date = wp_remote_retrieve_header( $response, 'date' );
295
		if ( ! $date ) {
296
			return;
297
		}
298
299
		$time = (int) strtotime( $date );
300
		if ( 0 >= $time ) {
301
			return;
302
		}
303
304
		$time_diff = $time - time();
305
306
		if ( $force_set ) { // During register.
307
			\Jetpack_Options::update_option( 'time_diff', $time_diff );
308
		} else { // Otherwise.
309
			$old_diff = \Jetpack_Options::get_option( 'time_diff' );
310
			if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
311
				\Jetpack_Options::update_option( 'time_diff', $time_diff );
312
			}
313
		}
314
	}
315
316
	/**
317
	 * Validate and build arguments for a WordPress.com REST API request.
318
	 *
319
	 * @param  string $path             REST API path.
320
	 * @param  string $version          REST API version. Default is `2`.
321
	 * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
322
	 * @param  string $base_api_path    REST API root. Default is `wpcom`.
323
	 *
324
	 * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
325
	 */
326
	public static function validate_args_for_wpcom_json_api_request(
327
		$path,
328
		$version = '2',
329
		$args = array(),
330
		$base_api_path = 'wpcom'
331
	) {
332
		$base_api_path = trim( $base_api_path, '/' );
333
		$version       = ltrim( $version, 'v' );
334
		$path          = ltrim( $path, '/' );
335
336
		$filtered_args = array_intersect_key(
337
			$args,
338
			array(
339
				'headers'     => 'array',
340
				'method'      => 'string',
341
				'timeout'     => 'int',
342
				'redirection' => 'int',
343
				'stream'      => 'boolean',
344
				'filename'    => 'string',
345
				'sslverify'   => 'boolean',
346
			)
347
		);
348
349
		// Use GET by default whereas `remote_request` uses POST.
350
		$request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
351
352
		$url = sprintf(
353
			'%s/%s/v%s/%s',
354
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
355
			$base_api_path,
356
			$version,
357
			$path
358
		);
359
360
		$validated_args = array_merge(
361
			$filtered_args,
362
			array(
363
				'url'    => $url,
364
				'method' => $request_method,
365
			)
366
		);
367
368
		return $validated_args;
369
	}
370
371
	/**
372
	 * Queries the WordPress.com REST API with a user token.
373
	 *
374
	 * @param  string $path             REST API path.
375
	 * @param  string $version          REST API version. Default is `2`.
376
	 * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
377
	 * @param  string $body             Body passed to {@see WP_Http}. Default is `null`.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
378
	 * @param  string $base_api_path    REST API root. Default is `wpcom`.
379
	 *
380
	 * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
381
	 */
382
	public static function wpcom_json_api_request_as_user(
383
		$path,
384
		$version = '2',
385
		$args = array(),
386
		$body = null,
387
		$base_api_path = 'wpcom'
388
	) {
389
		$args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
390
		$args['user_id'] = get_current_user_id();
391
392
		if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
393
			$args['headers'] = array( 'Content-Type' => 'application/json' );
394
		}
395
396
		if ( isset( $body ) && ! is_string( $body ) ) {
397
			$body = wp_json_encode( $body );
398
		}
399
400
		return self::remote_request( $args, $body );
401
	}
402
403
	/**
404
	 * Query the WordPress.com REST API using the blog token
405
	 *
406
	 * @param String $path The API endpoint relative path.
407
	 * @param String $version The API version.
408
	 * @param array  $args Request arguments.
409
	 * @param String $body Request body.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $body not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
410
	 * @param String $base_api_path (optional) the API base path override, defaults to 'rest'.
411
	 * @return array|WP_Error $response Data.
412
	 */
413
	public static function wpcom_json_api_request_as_blog(
414
		$path,
415
		$version = self::WPCOM_JSON_API_VERSION,
416
		$args = array(),
417
		$body = null,
418
		$base_api_path = 'rest'
419
	) {
420
		$validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
421
		$validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
422
423
		// For Simple sites get the response directly without any HTTP requests.
424
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
425
			add_filter( 'is_jetpack_authorized_for_site', '__return_true' );
426
			require_lib( 'wpcom-api-direct' );
427
			return \WPCOM_API_Direct::do_request( $validated_args );
428
		}
429
430
		return self::remote_request( $validated_args, $body );
431
	}
432
433
	/**
434
	 * Takes an array or similar structure and recursively turns all values into strings. This is used to
435
	 * make sure that body hashes are made ith the string version, which is what will be seen after a
436
	 * server pulls up the data in the $_POST array.
437
	 *
438
	 * @param array|Mixed $data the data that needs to be stringified.
439
	 *
440
	 * @return array|string
441
	 */
442
	public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
443
444
		// Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
445
		if ( is_bool( $data ) ) {
446
			return $data ? '1' : '0';
447
		}
448
449
		// Cast objects into arrays.
450
		if ( is_object( $data ) ) {
451
			$data = (array) $data;
452
		}
453
454
		// Non arrays at this point should be just converted to strings.
455
		if ( ! is_array( $data ) ) {
456
			return (string) $data;
457
		}
458
459
		foreach ( $data as &$value ) {
460
			$value = self::_stringify_data( $value );
461
		}
462
463
		return $data;
464
	}
465
466
	/**
467
	 * Gets protocol string.
468
	 *
469
	 * @return string Always 'https'.
470
	 *
471
	 * @deprecated 9.1.0 WP.com API no longer supports requests using `http://`.
472
	 */
473
	public static function protocol() {
474
		_deprecated_function( __METHOD__, 'jetpack-9.1.0' );
475
476
		return 'https';
477
	}
478
}
479