Completed
Push — fix/fallback-if-rest-api-disab... ( 3c6c28...2d3652 )
by
unknown
350:00 queued 342:52
created

class.jetpack-client.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
class Jetpack_Client {
4
	const WPCOM_JSON_API_VERSION = '1.1';
5
6
	/**
7
	 * Makes an authorized remote request using Jetpack_Signature
8
	 *
9
	 * @return array|WP_Error WP HTTP response on success
10
	 */
11
	public static function remote_request( $args, $body = null ) {
12
		$defaults = array(
13
			'url' => '',
14
			'user_id' => 0,
15
			'blog_id' => 0,
16
			'auth_location' => JETPACK_CLIENT__AUTH_LOCATION,
17
			'method' => 'POST',
18
			'timeout' => 10,
19
			'redirection' => 0,
20
			'headers' => array(),
21
			'stream' => false,
22
			'filename' => null,
23
		);
24
25
		$args = wp_parse_args( $args, $defaults );
26
27
		$args['blog_id'] = (int) $args['blog_id'];
28
29
		if ( 'header' != $args['auth_location'] ) {
30
			$args['auth_location'] = 'query_string';
31
		}
32
33
		$token = Jetpack_Data::get_access_token( $args['user_id'] );
0 ignored issues
show
$args['user_id'] is of type integer|string, but the function expects a boolean.

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...
34
		if ( !$token ) {
35
			return new Jetpack_Error( 'missing_token' );
36
		}
37
38
		$method = strtoupper( $args['method'] );
39
40
		$timeout = intval( $args['timeout'] );
41
42
		$redirection = $args['redirection'];
43
		$stream = $args['stream'];
44
		$filename = $args['filename'];
45
46
		$request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename' );
47
48
		@list( $token_key, $secret ) = explode( '.', $token->secret );
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...
49
		if ( empty( $token ) || empty( $secret ) ) {
50
			return new Jetpack_Error( 'malformed_token' );
51
		}
52
53
		$token_key = sprintf( '%s:%d:%d', $token_key, JETPACK__API_VERSION, $token->external_user_id );
54
55
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
56
57
		$time_diff = (int) Jetpack_Options::get_option( 'time_diff' );
58
		$jetpack_signature = new Jetpack_Signature( $token->secret, $time_diff );
59
60
		$timestamp = time() + $time_diff;
61
62
		if( function_exists( 'wp_generate_password' ) ) {
63
			$nonce = wp_generate_password( 10, false );
64
		} else {
65
			$nonce = substr( sha1( rand( 0, 1000000 ) ), 0, 10);
66
		}
67
68
		// Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing
69
		if ( is_null( $body ) ) {
70
			$body_hash = '';
71
72
		} else {
73
			// Allow arrays to be used in passing data.
74
			$body_to_hash = $body;
75
76
			if ( is_array( $body ) ) {
77
				// We cast this to a new variable, because the array form of $body needs to be
78
				// maintained so it can be passed into the request later on in the code.
79
				if ( count( $body ) > 0 ) {
80
					$body_to_hash = json_encode( self::_stringify_data( $body ) );
81
				} else {
82
					$body_to_hash = '';
83
				}
84
			}
85
86
			if ( ! is_string( $body_to_hash ) ) {
87
				return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
88
			}
89
90
			$body_hash = jetpack_sha1_base64( $body_to_hash );
91
		}
92
93
		$auth = array(
94
			'token' => $token_key,
95
			'timestamp' => $timestamp,
96
			'nonce' => $nonce,
97
			'body-hash' => $body_hash,
98
		);
99
100
		if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
101
			$url_args = array(
102
				'for'           => 'jetpack',
103
				'wpcom_blog_id' => Jetpack_Options::get_option( 'id' ),
104
			);
105
		} else {
106
			$url_args = array();
107
		}
108
109
		if ( 'header' != $args['auth_location'] ) {
110
			$url_args += $auth;
111
		}
112
113
		$url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
114
		$url = Jetpack::fix_url_for_bad_hosts( $url );
115
116
		$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
117
118
		if ( !$signature || is_wp_error( $signature ) ) {
119
			return $signature;
120
		}
121
122
		// Send an Authorization header so various caches/proxies do the right thing
123
		$auth['signature'] = $signature;
124
		$auth['version'] = JETPACK__VERSION;
125
		$header_pieces = array();
126
		foreach ( $auth as $key => $value ) {
127
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
128
		}
129
		$request['headers'] = array_merge( $args['headers'], array(
130
			'Authorization' => "X_JETPACK " . join( ' ', $header_pieces ),
131
		) );
132
133
		// Make sure we keep the host when we do JETPACK__WPCOM_JSON_API_HOST requests.
134
		$host = parse_url( $url, PHP_URL_HOST );
135
		if ( $host === JETPACK__WPCOM_JSON_API_HOST ) {
136
			$request['headers']['Host'] = 'public-api.wordpress.com';
137
		}
138
139
		if ( 'header' != $args['auth_location'] ) {
140
			$url = add_query_arg( 'signature', urlencode( $signature ), $url );
141
		}
142
143
		return Jetpack_Client::_wp_remote_request( $url, $request );
144
	}
145
146
	/**
147
	 * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
148
	 * This is lame, but many, many, many hosts have misconfigured SSL.
149
	 *
150
	 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
151
	 * 1. a certificate error is found AND
152
	 * 2. not verifying the certificate works around the problem.
153
	 *
154
	 * The option is checked on each request.
155
	 *
156
	 * @internal
157
	 * @see Jetpack::fix_url_for_bad_hosts()
158
	 *
159
	 * @return array|WP_Error WP HTTP response on success
160
	 */
161
	public static function _wp_remote_request( $url, $args, $set_fallback = false ) {
162
		/**
163
		 * SSL verification (`sslverify`) for the JetpackClient remote request
164
		 * defaults to off, use this filter to force it on.
165
		 *
166
		 * Return `true` to ENABLE SSL verification, return `false`
167
		 * to DISABLE SSL verification.
168
		 *
169
		 * @since 3.6.0
170
		 *
171
		 * @param bool Whether to force `sslverify` or not.
172
		 */
173
		if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
174
			return wp_remote_request( $url, $args );
175
		}
176
177
		$fallback = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
178
		if ( false === $fallback ) {
179
			Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
180
		}
181
182
		if ( (int) $fallback ) {
183
			// We're flagged to fallback
184
			$args['sslverify'] = false;
185
		}
186
187
		$response = wp_remote_request( $url, $args );
188
189
		if (
190
			!$set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens
191
		||
192
			isset( $args['sslverify'] ) && !$args['sslverify'] // No verification - no point in doing it again
193
		||
194
			!is_wp_error( $response )                          // Let it ride
195
		) {
196
			Jetpack_Client::set_time_diff( $response, $set_fallback );
197
			return $response;
198
		}
199
200
		// At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
201
202
		$message = $response->get_error_message();
203
204
		// Is it an SSL Certificate verification error?
205
		if (
206
			false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error
207
		&&
208
			false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error
209
		&&
210
			false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found
211
		&&
212
			false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
213
			                                                                              // different versions of curl have different error messages
214
			                                                                              // this string should catch them all
215
		&&
216
			false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights
217
		) {
218
			// No, it is not.
219
			return $response;
220
		}
221
222
		// Redo the request without SSL certificate verification.
223
		$args['sslverify'] = false;
224
		$response = wp_remote_request( $url, $args );
225
226
		if ( !is_wp_error( $response ) ) {
227
			// The request went through this time, flag for future fallbacks
228
			Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
229
			Jetpack_Client::set_time_diff( $response, $set_fallback );
230
		}
231
232
		return $response;
233
	}
234
235
	public static function set_time_diff( &$response, $force_set = false ) {
236
		$code = wp_remote_retrieve_response_code( $response );
237
238
		// Only trust the Date header on some responses
239
		if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) {
240
			return;
241
		}
242
243
		if ( !$date = wp_remote_retrieve_header( $response, 'date' ) ) {
244
			return;
245
		}
246
247
		if ( 0 >= $time = (int) strtotime( $date ) ) {
248
			return;
249
		}
250
251
		$time_diff = $time - time();
252
253
		if ( $force_set ) { // during register
254
			Jetpack_Options::update_option( 'time_diff', $time_diff );
255
		} else { // otherwise
256
			$old_diff = Jetpack_Options::get_option( 'time_diff' );
257
			if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
258
				Jetpack_Options::update_option( 'time_diff', $time_diff );
259
			}
260
		}
261
	}
262
263
	/**
264
	 * Query the WordPress.com REST API using the blog token
265
	 *
266
	 * @param string  $path
267
	 * @param string  $version
268
	 * @param array   $args
269
	 * @param string  $body
0 ignored issues
show
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...
270
	 * @return array|WP_Error $response Data.
271
	 */
272
	static function wpcom_json_api_request_as_blog( $path, $version = self::WPCOM_JSON_API_VERSION, $args = array(), $body = null ) {
273
		$filtered_args = array_intersect_key( $args, array(
274
			'method'      => 'string',
275
			'timeout'     => 'int',
276
			'redirection' => 'int',
277
			'stream'      => 'boolean',
278
			'filename'    => 'string',
279
		) );
280
281
		/**
282
		 * Determines whether Jetpack can send outbound https requests to the WPCOM api.
283
		 *
284
		 * @since 3.6.0
285
		 *
286
		 * @param bool $proto Defaults to true.
287
		 */
288
		$proto = apply_filters( 'jetpack_can_make_outbound_https', true ) ? 'https' : 'http';
289
290
		// unprecedingslashit
291
		$_path = preg_replace( '/^\//', '', $path );
292
293
		// Use GET by default whereas `remote_request` uses POST
294
		if ( isset( $filtered_args['method'] ) && strtoupper( $filtered_args['method'] === 'POST' ) ) {
295
			$request_method = 'POST';
296
		} else {
297
			$request_method = 'GET';
298
		}
299
300
		$validated_args = array_merge( $filtered_args, array(
301
			'url'     => sprintf( '%s://%s/rest/v%s/%s', $proto, JETPACK__WPCOM_JSON_API_HOST, $version, $_path ),
302
			'blog_id' => (int) Jetpack_Options::get_option( 'id' ),
303
			'method'  => $request_method,
304
		) );
305
306
		return Jetpack_Client::remote_request( $validated_args, $body );
307
	}
308
309
	/**
310
	 * Takes an array or similar structure and recursively turns all values into strings. This is used to
311
	 * make sure that body hashes are made ith the string version, which is what will be seen after a
312
	 * server pulls up the data in the $_POST array.
313
	 *
314
	 * @param array|mixed $data
315
	 *
316
	 * @return array|string
317
	 */
318
	public static function _stringify_data( $data ) {
319
320
		// Booleans are special, lets just makes them and explicit 1/0 instead of the 0 being an empty string.
321
		if ( is_bool( $data ) ) {
322
			return $data ? "1" : "0";
323
		}
324
325
		// Cast objects into arrays.
326
		if ( is_object( $data ) ) {
327
			$data = (array) $data;
328
		}
329
330
		// Non arrays at this point should be just converted to strings.
331
		if ( ! is_array( $data ) ) {
332
			return (string)$data;
333
		}
334
335
		foreach ( $data as $key => &$value ) {
336
			$value = self::_stringify_data( $value );
337
		}
338
339
		return $data;
340
	}
341
}
342