Completed
Push — update/extract-client-helpers ( a86430...df803c )
by Bernhard
31:46 queued 23:51
created

Client::set_time_diff()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 6
nop 2
dl 0
loc 29
rs 7.6666
c 0
b 0
f 0

How to fix   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
		add_filter(
27
			'jetpack_constant_default_value',
28
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
29
			10,
30
			2
31
		);
32
33
		$defaults = array(
34
			'url'           => '',
35
			'user_id'       => 0,
36
			'blog_id'       => 0,
37
			'auth_location' => Constants::get_constant( 'JETPACK_CLIENT__AUTH_LOCATION' ),
38
			'method'        => 'POST',
39
			'timeout'       => 10,
40
			'redirection'   => 0,
41
			'headers'       => array(),
42
			'stream'        => false,
43
			'filename'      => null,
44
			'sslverify'     => true,
45
		);
46
47
		$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...
48
49
		$args['blog_id'] = (int) $args['blog_id'];
50
51
		if ( 'header' !== $args['auth_location'] ) {
52
			$args['auth_location'] = 'query_string';
53
		}
54
55
		$connection = new Manager();
56
		$token      = $connection->get_access_token( $args['user_id'] );
57
		if ( ! $token ) {
58
			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...
59
		}
60
61
		$method = strtoupper( $args['method'] );
62
63
		$timeout = intval( $args['timeout'] );
64
65
		$redirection = $args['redirection'];
66
		$stream      = $args['stream'];
67
		$filename    = $args['filename'];
68
		$sslverify   = $args['sslverify'];
69
70
		$request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
71
72
		@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...
73
		if ( empty( $token ) || empty( $secret ) ) {
74
			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...
75
		}
76
77
		$token_key = sprintf(
78
			'%s:%d:%d',
79
			$token_key,
80
			Constants::get_constant( 'JETPACK__API_VERSION' ),
81
			$token->external_user_id
82
		);
83
84
		$time_diff         = (int) \Jetpack_Options::get_option( 'time_diff' );
85
		$jetpack_signature = new \Jetpack_Signature( $token->secret, $time_diff );
86
87
		$timestamp = time() + $time_diff;
88
89 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
90
			$nonce = wp_generate_password( 10, false );
91
		} else {
92
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
93
		}
94
95
		// Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing.
96
		if ( is_null( $body ) ) {
97
			$body_hash = '';
98
99
		} else {
100
			// Allow arrays to be used in passing data.
101
			$body_to_hash = $body;
102
103
			if ( is_array( $body ) ) {
104
				// We cast this to a new variable, because the array form of $body needs to be
105
				// maintained so it can be passed into the request later on in the code.
106
				if ( count( $body ) > 0 ) {
107
					$body_to_hash = wp_json_encode( self::_stringify_data( $body ) );
108
				} else {
109
					$body_to_hash = '';
110
				}
111
			}
112
113
			if ( ! is_string( $body_to_hash ) ) {
114
				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...
115
			}
116
117
			$body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
118
		}
119
120
		$auth = array(
121
			'token'     => $token_key,
122
			'timestamp' => $timestamp,
123
			'nonce'     => $nonce,
124
			'body-hash' => $body_hash,
125
		);
126
127
		if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
128
			$url_args = array(
129
				'for'           => 'jetpack',
130
				'wpcom_blog_id' => \Jetpack_Options::get_option( 'id' ),
131
			);
132
		} else {
133
			$url_args = array();
134
		}
135
136
		if ( 'header' !== $args['auth_location'] ) {
137
			$url_args += $auth;
138
		}
139
140
		$url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
141
142
		$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
143
144
		if ( ! $signature || is_wp_error( $signature ) ) {
145
			return $signature;
146
		}
147
148
		// Send an Authorization header so various caches/proxies do the right thing.
149
		$auth['signature'] = $signature;
150
		$auth['version']   = Constants::get_constant( 'JETPACK__VERSION' );
151
		$header_pieces     = array();
152
		foreach ( $auth as $key => $value ) {
153
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
154
		}
155
		$request['headers'] = array_merge(
156
			$args['headers'],
157
			array(
158
				'Authorization' => 'X_JETPACK ' . join( ' ', $header_pieces ),
159
			)
160
		);
161
162
		if ( 'header' !== $args['auth_location'] ) {
163
			$url = add_query_arg( 'signature', rawurlencode( $signature ), $url );
164
		}
165
166
		return self::_wp_remote_request( $url, $request );
167
	}
168
169
	/**
170
	 * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
171
	 * This is lame, but many, many, many hosts have misconfigured SSL.
172
	 *
173
	 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
174
	 * 1. a certificate error is found AND
175
	 * 2. not verifying the certificate works around the problem.
176
	 *
177
	 * The option is checked on each request.
178
	 *
179
	 * @internal
180
	 *
181
	 * @param String  $url the request URL.
182
	 * @param array   $args request arguments.
183
	 * @param Boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
184
	 * @return array|WP_Error WP HTTP response on success
185
	 */
186
	public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
187
		/**
188
		 * SSL verification (`sslverify`) for the JetpackClient remote request
189
		 * defaults to off, use this filter to force it on.
190
		 *
191
		 * Return `true` to ENABLE SSL verification, return `false`
192
		 * to DISABLE SSL verification.
193
		 *
194
		 * @since 3.6.0
195
		 *
196
		 * @param bool Whether to force `sslverify` or not.
197
		 */
198
		if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
199
			return wp_remote_request( $url, $args );
200
		}
201
202
		$fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
203
		if ( false === $fallback ) {
204
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
205
		}
206
207
		if ( (int) $fallback ) {
208
			// We're flagged to fallback.
209
			$args['sslverify'] = false;
210
		}
211
212
		$response = wp_remote_request( $url, $args );
213
214
		if (
215
			! $set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens.
216
			||
217
			isset( $args['sslverify'] ) && ! $args['sslverify'] // No verification - no point in doing it again.
218
			||
219
			! is_wp_error( $response )                          // Let it ride.
220
		) {
221
			self::set_time_diff( $response, $set_fallback );
222
			return $response;
223
		}
224
225
		// At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
226
227
		$message = $response->get_error_message();
228
229
		// Is it an SSL Certificate verification error?
230
		if (
231
			false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error.
232
			&&
233
			false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error.
234
			&&
235
			false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found.
236
			&&
237
			false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
238
			// Different versions of curl have different error messages
239
			// this string should catch them all.
240
			&&
241
			false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights.
242
		) {
243
			// No, it is not.
244
			return $response;
245
		}
246
247
		// Redo the request without SSL certificate verification.
248
		$args['sslverify'] = false;
249
		$response          = wp_remote_request( $url, $args );
250
251
		if ( ! is_wp_error( $response ) ) {
252
			// The request went through this time, flag for future fallbacks.
253
			\Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
254
			self::set_time_diff( $response, $set_fallback );
255
		}
256
257
		return $response;
258
	}
259
260
	/**
261
	 * Sets the time difference for correct signature computation.
262
	 *
263
	 * @param HTTP_Response $response the response object.
264
	 * @param Boolean       $force_set whether to force setting the time difference.
265
	 */
266
	public static function set_time_diff( &$response, $force_set = false ) {
267
		$code = wp_remote_retrieve_response_code( $response );
268
269
		// Only trust the Date header on some responses.
270
		if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) { // phpcs:ignore  WordPress.PHP.StrictComparisons.LooseComparison
271
			return;
272
		}
273
274
		$date = wp_remote_retrieve_header( $response, 'date' );
275
		if ( ! $date ) {
276
			return;
277
		}
278
279
		$time = (int) strtotime( $date );
280
		if ( 0 >= $time ) {
281
			return;
282
		}
283
284
		$time_diff = $time - time();
285
286
		if ( $force_set ) { // During register.
287
			\Jetpack_Options::update_option( 'time_diff', $time_diff );
288
		} else { // Otherwise.
289
			$old_diff = \Jetpack_Options::get_option( 'time_diff' );
290
			if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
291
				\Jetpack_Options::update_option( 'time_diff', $time_diff );
292
			}
293
		}
294
	}
295
296
	/**
297
	 * Validate and build arguments for a WordPress.com REST API request.
298
	 *
299
	 * @param String $path The API endpoint relative path.
300
	 * @param String $version The API version.
301
	 * @param array  $args Request arguments.
302
	 * @param String $base_api_path (optional) the API base path override, defaults to 'rest'.
303
	 * @return array|WP_Error $response Data.
304
	 */
305
	public static function validate_args_for_wpcom_json_api_request(
306
		$path,
307
		$version,
308
		$args = array(),
309
		$base_api_path = 'rest'
310
	) {
311
		$base_api_path = trim( $base_api_path, '/' );
312
		$version       = ltrim( $version, 'v' );
313
		$path          = ltrim( $path, '/' );
314
315
		$filtered_args = array_intersect_key(
316
			$args,
317
			array(
318
				'headers'     => 'array',
319
				'method'      => 'string',
320
				'timeout'     => 'int',
321
				'redirection' => 'int',
322
				'stream'      => 'boolean',
323
				'filename'    => 'string',
324
				'sslverify'   => 'boolean',
325
			)
326
		);
327
328
		// Use GET by default whereas `remote_request` uses POST.
329
		$request_method = isset( $filtered_args['method'] ) ? strtoupper( $filtered_args['method'] ) : 'GET';
330
331
		$url = sprintf(
332
			'%s/%s/v%s/%s',
333
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
334
			$base_api_path,
335
			$version,
336
			$path
337
		);
338
339
		$validated_args = array_merge(
340
			$filtered_args,
341
			array(
342
				'url'    => $url,
343
				'method' => $request_method,
344
			)
345
		);
346
347
		return $validated_args;
348
	}
349
350
	/**
351
	 * Queries the WordPress.com REST API with a user token.
352
	 *
353
	 * @param  string $path             REST API path.
354
	 * @param  string $version          REST API version. Default is `2`.
355
	 * @param  array  $args             Arguments to {@see WP_Http}. Default is `array()`.
356
	 * @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...
357
	 * @param  string $base_api_path    REST API root. Default is `wpcom`.
358
	 *
359
	 * @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
360
	 */
361
	public static function wpcom_json_api_request_as_user(
362
		$path,
363
		$version = '2',
364
		$args = array(),
365
		$body = null,
366
		$base_api_path = 'wpcom'
367
	) {
368
		$args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
369
		$args['user_id'] = get_current_user_id();
370
371
		if ( isset( $body ) && ! isset( $args['headers'] ) && in_array( $args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
372
			$args['headers'] = array( 'Content-Type' => 'application/json' );
373
		}
374
375
		if ( isset( $body ) && ! is_string( $body ) ) {
376
			$body = wp_json_encode( $body );
377
		}
378
379
		return self::remote_request( $args, $body );
380
	}
381
382
	/**
383
	 * Query the WordPress.com REST API using the blog token
384
	 *
385
	 * @param String $path The API endpoint relative path.
386
	 * @param String $version The API version.
387
	 * @param array  $args Request arguments.
388
	 * @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...
389
	 * @param String $base_api_path (optional) the API base path override, defaults to 'rest'.
390
	 * @return array|WP_Error $response Data.
391
	 */
392
	public static function wpcom_json_api_request_as_blog(
393
		$path,
394
		$version = self::WPCOM_JSON_API_VERSION,
395
		$args = array(),
396
		$body = null,
397
		$base_api_path = 'rest'
398
	) {
399
		$validated_args            = self::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
400
		$validated_args['blog_id'] = (int) \Jetpack_Options::get_option( 'id' );
401
		return self::remote_request( $validated_args, $body );
402
	}
403
404
	/**
405
	 * Takes an array or similar structure and recursively turns all values into strings. This is used to
406
	 * make sure that body hashes are made ith the string version, which is what will be seen after a
407
	 * server pulls up the data in the $_POST array.
408
	 *
409
	 * @param array|Mixed $data the data that needs to be stringified.
410
	 *
411
	 * @return array|string
412
	 */
413
	public static function _stringify_data( $data ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
414
415
		// Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
416
		if ( is_bool( $data ) ) {
417
			return $data ? '1' : '0';
418
		}
419
420
		// Cast objects into arrays.
421
		if ( is_object( $data ) ) {
422
			$data = (array) $data;
423
		}
424
425
		// Non arrays at this point should be just converted to strings.
426
		if ( ! is_array( $data ) ) {
427
			return (string) $data;
428
		}
429
430
		foreach ( $data as &$value ) {
431
			$value = self::_stringify_data( $value );
432
		}
433
434
		return $data;
435
	}
436
437
	/**
438
	 * Gets protocol string.
439
	 *
440
	 * @return string Always 'https'.
441
	 *
442
	 * @deprecated 9.1.0 WP.com API no longer supports requests using `http://`.
443
	 */
444
	public static function protocol() {
445
		_deprecated_function( __METHOD__, 'jetpack-9.1.0' );
446
447
		return 'https';
448
	}
449
}
450