Completed
Push — add/rest-api-sandbox-const ( f7b74b )
by
unknown
23:14
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
		);
21
22
		$args = wp_parse_args( $args, $defaults );
23
24
		$args['blog_id'] = (int) $args['blog_id'];
25
26
		if ( 'header' != $args['auth_location'] ) {
27
			$args['auth_location'] = 'query_string';
28
		}
29
30
		$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...
31
		if ( !$token ) {
32
			return new Jetpack_Error( 'missing_token' );
33
		}
34
35
		$method = strtoupper( $args['method'] );
36
37
		$timeout = intval( $args['timeout'] );
38
39
		$redirection = $args['redirection'];
40
41
		$request = compact( 'method', 'body', 'timeout', 'redirection' );
42
43
		@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...
44
		if ( empty( $token ) || empty( $secret ) ) {
45
			return new Jetpack_Error( 'malformed_token' );
46
		}
47
48
		$token_key = sprintf( '%s:%d:%d', $token_key, JETPACK__API_VERSION, $token->external_user_id );
49
50
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
51
52
		$time_diff = (int) Jetpack_Options::get_option( 'time_diff' );
53
		$jetpack_signature = new Jetpack_Signature( $token->secret, $time_diff );
54
55
		$timestamp = time() + $time_diff;
56
57
		if( function_exists( 'wp_generate_password' ) ) {
58
			$nonce = wp_generate_password( 10, false );
59
		} else {
60
			$nonce = substr( sha1( rand( 0, 1000000 ) ), 0, 10);
61
		}
62
63
		// Kind of annoying.  Maybe refactor Jetpack_Signature to handle body-hashing
64 View Code Duplication
		if ( is_null( $body ) ) {
65
			$body_hash = '';
66
		} else {
67
			if ( !is_string( $body ) ) {
68
				return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
69
			}
70
			$body_hash = jetpack_sha1_base64( $body );
71
		}
72
73
		$auth = array(
74
			'token' => $token_key,
75
			'timestamp' => $timestamp,
76
			'nonce' => $nonce,
77
			'body-hash' => $body_hash,
78
		);
79
80
		if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
81
			$url_args = array(
82
				'for'           => 'jetpack',
83
				'wpcom_blog_id' => Jetpack_Options::get_option( 'id' ),
84
			);
85
		} else {
86
			$url_args = array();
87
		}
88
89
		if ( 'header' != $args['auth_location'] ) {
90
			$url_args += $auth;
91
		}
92
93
		$url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
94
		$url = Jetpack::fix_url_for_bad_hosts( $url );
95
96
		$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
97
98
		if ( !$signature || is_wp_error( $signature ) ) {
99
			return $signature;
100
		}
101
102
		// Send an Authorization header so various caches/proxies do the right thing
103
		$auth['signature'] = $signature;
104
		$auth['version'] = JETPACK__VERSION;
105
		$header_pieces = array();
106
		foreach ( $auth as $key => $value ) {
107
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
108
		}
109
110
		$request['headers'] = array(
111
			'Authorization' => "X_JETPACK " . join( ' ', $header_pieces ),
112
 			'Host'          => 'public-api.wordpress.com'
113
		);
114
115
		if ( 'header' != $args['auth_location'] ) {
116
			$url = add_query_arg( 'signature', urlencode( $signature ), $url );
117
		}
118
119
		return Jetpack_Client::_wp_remote_request( $url, $request );
120
	}
121
122
	/**
123
	 * Wrapper for wp_remote_request().  Turns off SSL verification for certain SSL errors.
124
	 * This is lame, but many, many, many hosts have misconfigured SSL.
125
	 *
126
	 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
127
	 * 1. a certificate error is found AND
128
	 * 2. not verifying the certificate works around the problem.
129
	 *
130
	 * The option is checked on each request.
131
	 *
132
	 * @internal
133
	 * @see Jetpack::fix_url_for_bad_hosts()
134
	 *
135
	 * @return array|WP_Error WP HTTP response on success
136
	 */
137
	public static function _wp_remote_request( $url, $args, $set_fallback = false ) {
138
		/**
139
		 * SSL verification (`sslverify`) for the JetpackClient remote request
140
		 * defaults to off, use this filter to force it on.
141
		 *
142
		 * Return `true` to ENABLE SSL verification, return `false`
143
		 * to DISABLE SSL verification.
144
		 *
145
		 * @since 3.6.0
146
		 *
147
		 * @param bool Whether to force `sslverify` or not.
148
		 */
149
		if ( apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
150
			return wp_remote_request( $url, $args );
151
		}
152
153
		$fallback = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
154
		if ( false === $fallback ) {
155
			Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', 0 );
156
		}
157
158
		if ( (int) $fallback ) {
159
			// We're flagged to fallback
160
			$args['sslverify'] = false;
161
		}
162
163
		$response = wp_remote_request( $url, $args );
164
165
		if (
166
			!$set_fallback                                     // We're not allowed to set the flag on this request, so whatever happens happens
167
		||
168
			isset( $args['sslverify'] ) && !$args['sslverify'] // No verification - no point in doing it again
169
		||
170
			!is_wp_error( $response )                          // Let it ride
171
		) {
172
			Jetpack_Client::set_time_diff( $response, $set_fallback );
173
			return $response;
174
		}
175
176
		// At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
177
178
		$message = $response->get_error_message();
179
180
		// Is it an SSL Certificate verification error?
181
		if (
182
			false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error
183
		&&
184
			false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error
185
		&&
186
			false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found
187
		&&
188
			false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
189
			                                                                              // different versions of curl have different error messages
190
			                                                                              // this string should catch them all
191
		&&
192
			false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights
193
		) {
194
			// No, it is not.
195
			return $response;
196
		}
197
198
		// Redo the request without SSL certificate verification.
199
		$args['sslverify'] = false;
200
		$response = wp_remote_request( $url, $args );
201
202
		if ( !is_wp_error( $response ) ) {
203
			// The request went through this time, flag for future fallbacks
204
			Jetpack_Options::update_option( 'fallback_no_verify_ssl_certs', time() );
205
			Jetpack_Client::set_time_diff( $response, $set_fallback );
206
		}
207
208
		return $response;
209
	}
210
211
	public static function set_time_diff( &$response, $force_set = false ) {
212
		$code = wp_remote_retrieve_response_code( $response );
213
214
		// Only trust the Date header on some responses
215
		if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) {
216
			return;
217
		}
218
219
		if ( !$date = wp_remote_retrieve_header( $response, 'date' ) ) {
220
			return;
221
		}
222
223
		if ( 0 >= $time = (int) strtotime( $date ) ) {
224
			return;
225
		}
226
227
		$time_diff = $time - time();
228
229
		if ( $force_set ) { // during register
230
			Jetpack_Options::update_option( 'time_diff', $time_diff );
231
		} else { // otherwise
232
			$old_diff = Jetpack_Options::get_option( 'time_diff' );
233
			if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
234
				Jetpack_Options::update_option( 'time_diff', $time_diff );
235
			}
236
		}
237
	}
238
239
	/**
240
	 * Query the WordPress.com REST API using the blog token
241
	 *
242
	 * @param string  $path
243
	 * @param string  $version
244
	 * @param array   $args
245
	 * @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...
246
	 * @return array|WP_Error $response Data.
247
	 */
248
	static function wpcom_json_api_request_as_blog( $path, $version = self::WPCOM_JSON_API_VERSION, $args = array(), $body = null ) {
249
		$filtered_args = array_intersect_key( $args, array(
250
			'method'      => 'string',
251
			'timeout'     => 'int',
252
			'redirection' => 'int',
253
		) );
254
255
		/**
256
		 * Determines whether Jetpack can send outbound https requests to the WPCOM api.
257
		 *
258
		 * @since 3.6.0
259
		 *
260
		 * @param bool $proto Defaults to true.
261
		 */
262
		$proto = apply_filters( 'jetpack_can_make_outbound_https', true ) ? 'https' : 'http';
263
264
		// unprecedingslashit
265
		$_path = preg_replace( '/^\//', '', $path );
266
267
		// Use GET by default whereas `remote_request` uses POST
268
		if ( isset( $filtered_args['method'] ) && strtoupper( $filtered_args['method'] === 'POST' ) ) {
269
			$request_method = 'POST';
270
		} else {
271
			$request_method = 'GET';
272
		}
273
274
		$validated_args = array_merge( $filtered_args, array(
275
			'url'     => sprintf( '%s://%s/rest/v%s/%s', $proto, JETPACK__WPCOM_JSON_API_HOST, $version, $_path ),
276
			'blog_id' => (int) Jetpack_Options::get_option( 'id' ),
277
			'method'  => $request_method,
278
		) );
279
280
		return Jetpack_Client::remote_request( $validated_args, $body );
281
	}
282
283
}
284