Completed
Push — add/testing-info ( be1095...03b7e9 )
by
unknown
09:20
created

Jetpack_XMLRPC_Server::json_api()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Jetpack XMLRPC Server.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
use Automattic\Jetpack\Connection\Client;
9
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
10
use Automattic\Jetpack\Connection\Secrets;
11
use Automattic\Jetpack\Connection\Tokens;
12
use Automattic\Jetpack\Connection\Urls;
13
use Automattic\Jetpack\Roles;
14
use Automattic\Jetpack\Sync\Sender;
15
16
/**
17
 * Just a sack of functions.  Not actually an IXR_Server
18
 */
19
class Jetpack_XMLRPC_Server {
20
	/**
21
	 * The current error object
22
	 *
23
	 * @var \WP_Error
24
	 */
25
	public $error = null;
26
27
	/**
28
	 * The current user
29
	 *
30
	 * @var \WP_User
31
	 */
32
	public $user = null;
33
34
	/**
35
	 * The connection manager object.
36
	 *
37
	 * @var Automattic\Jetpack\Connection\Manager
38
	 */
39
	private $connection;
40
41
	/**
42
	 * Creates a new XMLRPC server object.
43
	 */
44
	public function __construct() {
45
		$this->connection = new Connection_Manager();
46
	}
47
48
	/**
49
	 * Whitelist of the XML-RPC methods available to the Jetpack Server. If the
50
	 * user is not authenticated (->login()) then the methods are never added,
51
	 * so they will get a "does not exist" error.
52
	 *
53
	 * @param array $core_methods Core XMLRPC methods.
54
	 */
55
	public function xmlrpc_methods( $core_methods ) {
56
		$jetpack_methods = array(
57
			'jetpack.verifyAction'     => array( $this, 'verify_action' ),
58
			'jetpack.idcUrlValidation' => array( $this, 'validate_urls_for_idc_mitigation' ),
59
			'jetpack.unlinkUser'       => array( $this, 'unlink_user' ),
60
			'jetpack.testConnection'   => array( $this, 'test_connection' ),
61
		);
62
63
		$jetpack_methods = array_merge( $jetpack_methods, $this->provision_xmlrpc_methods() );
64
65
		$this->user = $this->login();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->login() can also be of type boolean. However, the property $user is declared as type object<WP_User>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
66
67
		if ( $this->user ) {
68
			$jetpack_methods = array_merge(
69
				$jetpack_methods,
70
				array(
71
					'jetpack.testAPIUserCode' => array( $this, 'test_api_user_code' ),
72
				)
73
			);
74
75
			if ( isset( $core_methods['metaWeblog.editPost'] ) ) {
76
				$jetpack_methods['metaWeblog.newMediaObject']      = $core_methods['metaWeblog.newMediaObject'];
77
				$jetpack_methods['jetpack.updateAttachmentParent'] = array( $this, 'update_attachment_parent' );
78
			}
79
80
			/**
81
			 * Filters the XML-RPC methods available to Jetpack for authenticated users.
82
			 *
83
			 * @since 1.1.0
84
			 *
85
			 * @param array    $jetpack_methods XML-RPC methods available to the Jetpack Server.
86
			 * @param array    $core_methods    Available core XML-RPC methods.
87
			 * @param \WP_User $user            Information about the user authenticated in the request.
88
			 */
89
			$jetpack_methods = apply_filters( 'jetpack_xmlrpc_methods', $jetpack_methods, $core_methods, $this->user );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $core_methods.

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...
90
		}
91
92
		/**
93
		 * Filters the XML-RPC methods available to Jetpack for requests signed both with a blog token or a user token.
94
		 *
95
		 * @since 3.0.0
96
		 * @since 9.6.0 Introduced the $user parameter.
97
		 *
98
		 * @param array         $jetpack_methods XML-RPC methods available to the Jetpack Server.
99
		 * @param array         $core_methods    Available core XML-RPC methods.
100
		 * @param \WP_User|bool $user            Information about the user authenticated in the request. False if authenticated with blog token.
101
		 */
102
		return apply_filters( 'jetpack_xmlrpc_unauthenticated_methods', $jetpack_methods, $core_methods, $this->user );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $core_methods.

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...
103
	}
104
105
	/**
106
	 * Whitelist of the bootstrap XML-RPC methods
107
	 */
108
	public function bootstrap_xmlrpc_methods() {
109
		return array(
110
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
111
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
112
		);
113
	}
114
115
	/**
116
	 * Additional method needed for authorization calls.
117
	 */
118
	public function authorize_xmlrpc_methods() {
119
		return array(
120
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
121
		);
122
	}
123
124
	/**
125
	 * Remote provisioning methods.
126
	 */
127
	public function provision_xmlrpc_methods() {
128
		return array(
129
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
130
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
131
			'jetpack.remoteConnect'   => array( $this, 'remote_connect' ),
132
			'jetpack.getUser'         => array( $this, 'get_user' ),
133
		);
134
	}
135
136
	/**
137
	 * Used to verify whether a local user exists and what role they have.
138
	 *
139
	 * @param int|string|array $request One of:
140
	 *                         int|string The local User's ID, username, or email address.
141
	 *                         array      A request array containing:
142
	 *                                    0: int|string The local User's ID, username, or email address.
143
	 *
144
	 * @return array|\IXR_Error Information about the user, or error if no such user found:
145
	 *                          roles:     string[] The user's rols.
146
	 *                          login:     string   The user's username.
147
	 *                          email_hash string[] The MD5 hash of the user's normalized email address.
148
	 *                          caps       string[] The user's capabilities.
149
	 *                          allcaps    string[] The user's granular capabilities, merged from role capabilities.
150
	 *                          token_key  string   The Token Key of the user's Jetpack token. Empty string if none.
151
	 */
152
	public function get_user( $request ) {
153
		$user_id = is_array( $request ) ? $request[0] : $request;
154
155
		if ( ! $user_id ) {
156
			return $this->error(
157
				new \WP_Error(
158
					'invalid_user',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_user'.

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...
159
					__( 'Invalid user identifier.', 'jetpack' ),
160
					400
161
				),
162
				'get_user'
163
			);
164
		}
165
166
		$user = $this->get_user_by_anything( $user_id );
167
168
		if ( ! $user ) {
169
			return $this->error(
170
				new \WP_Error(
171
					'user_unknown',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_unknown'.

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...
172
					__( 'User not found.', 'jetpack' ),
173
					404
174
				),
175
				'get_user'
176
			);
177
		}
178
179
		$user_token = ( new Tokens() )->get_access_token( $user->ID );
180
181
		if ( $user_token ) {
182
			list( $user_token_key ) = explode( '.', $user_token->secret );
183
			if ( $user_token_key === $user_token->secret ) {
184
				$user_token_key = '';
185
			}
186
		} else {
187
			$user_token_key = '';
188
		}
189
190
		return array(
191
			'id'         => $user->ID,
192
			'login'      => $user->user_login,
193
			'email_hash' => md5( strtolower( trim( $user->user_email ) ) ),
194
			'roles'      => $user->roles,
195
			'caps'       => $user->caps,
196
			'allcaps'    => $user->allcaps,
197
			'token_key'  => $user_token_key,
198
		);
199
	}
200
201
	/**
202
	 * Remote authorization XMLRPC method handler.
203
	 *
204
	 * @param array $request the request.
205
	 */
206
	public function remote_authorize( $request ) {
207
		$user = get_user_by( 'id', $request['state'] );
208
209
		/**
210
		 * Happens on various request handling events in the Jetpack XMLRPC server.
211
		 * The action combines several types of events:
212
		 *    - remote_authorize
213
		 *    - remote_provision
214
		 *    - get_user.
215
		 *
216
		 * @since 8.0.0
217
		 *
218
		 * @param String  $action the action name, i.e., 'remote_authorize'.
219
		 * @param String  $stage  the execution stage, can be 'begin', 'success', 'error', etc.
220
		 * @param array   $parameters extra parameters from the event.
221
		 * @param WP_User $user the acting user.
222
		 */
223
		do_action( 'jetpack_xmlrpc_server_event', 'remote_authorize', 'begin', array(), $user );
224
225
		foreach ( array( 'secret', 'state', 'redirect_uri', 'code' ) as $required ) {
226
			if ( ! isset( $request[ $required ] ) || empty( $request[ $required ] ) ) {
227
				return $this->error(
228
					new \WP_Error( 'missing_parameter', 'One or more parameters is missing from the request.', 400 ),
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_parameter'.

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...
229
					'remote_authorize'
230
				);
231
			}
232
		}
233
234
		if ( ! $user ) {
235
			return $this->error( new \WP_Error( 'user_unknown', 'User not found.', 404 ), 'remote_authorize' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_unknown'.

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...
236
		}
237
238
		if ( $this->connection->has_connected_owner() && $this->connection->is_user_connected( $request['state'] ) ) {
239
			return $this->error( new \WP_Error( 'already_connected', 'User already connected.', 400 ), 'remote_authorize' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'already_connected'.

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...
240
		}
241
242
		$verified = $this->verify_action( array( 'authorize', $request['secret'], $request['state'] ) );
243
244
		if ( is_a( $verified, 'IXR_Error' ) ) {
245
			return $this->error( $verified, 'remote_authorize' );
246
		}
247
248
		wp_set_current_user( $request['state'] );
249
250
		$result = $this->connection->authorize( $request );
251
252
		if ( is_wp_error( $result ) ) {
253
			return $this->error( $result, 'remote_authorize' );
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->connection->authorize($request) on line 250 can also be of type string; however, Jetpack_XMLRPC_Server::error() does only seem to accept object<WP_Error>|object<IXR_Error>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
254
		}
255
256
		// This action is documented in class.jetpack-xmlrpc-server.php.
257
		do_action( 'jetpack_xmlrpc_server_event', 'remote_authorize', 'success' );
258
259
		return array(
260
			'result' => $result,
261
		);
262
	}
263
264
	/**
265
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
266
	 * register this site so that a plan can be provisioned.
267
	 *
268
	 * @param array $request An array containing at minimum nonce and local_user keys.
269
	 *
270
	 * @return \WP_Error|array
271
	 */
272
	public function remote_register( $request ) {
273
		// This action is documented in class.jetpack-xmlrpc-server.php.
274
		do_action( 'jetpack_xmlrpc_server_event', 'remote_register', 'begin', array() );
275
276
		$user = $this->fetch_and_verify_local_user( $request );
277
278
		if ( ! $user ) {
279
			return $this->error(
280
				new WP_Error( 'input_error', __( 'Valid user is required', 'jetpack' ), 400 ),
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'input_error'.

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...
281
				'remote_register'
282
			);
283
		}
284
285
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
286
			return $this->error( $user, 'remote_register' );
287
		}
288
289
		if ( empty( $request['nonce'] ) ) {
290
			return $this->error(
291
				new \WP_Error(
292
					'nonce_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'nonce_missing'.

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...
293
					__( 'The required "nonce" parameter is missing.', 'jetpack' ),
294
					400
295
				),
296
				'remote_register'
297
			);
298
		}
299
300
		$nonce = sanitize_text_field( $request['nonce'] );
301
		unset( $request['nonce'] );
302
303
		$api_url  = $this->connection->api_url( 'partner_provision_nonce_check' );
304
		$response = Client::_wp_remote_request(
305
			esc_url_raw( add_query_arg( 'nonce', $nonce, $api_url ) ),
306
			array( 'method' => 'GET' ),
307
			true
308
		);
309
310
		if (
311
			200 !== wp_remote_retrieve_response_code( $response ) ||
312
			'OK' !== trim( wp_remote_retrieve_body( $response ) )
313
		) {
314
			return $this->error(
315
				new \WP_Error(
316
					'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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...
317
					__( 'There was an issue validating this request.', 'jetpack' ),
318
					400
319
				),
320
				'remote_register'
321
			);
322
		}
323
324
		if ( ! Jetpack_Options::get_option( 'id' ) || ! ( new Tokens() )->get_access_token() || ! empty( $request['force'] ) ) {
325
			wp_set_current_user( $user->ID );
326
327
			// This code mostly copied from Jetpack::admin_page_load.
328
			if ( isset( $request['from'] ) ) {
329
				$this->connection->add_register_request_param( 'from', (string) $request['from'] );
330
			}
331
			$registered = $this->connection->try_registration();
332
			if ( is_wp_error( $registered ) ) {
333
				return $this->error( $registered, 'remote_register' );
0 ignored issues
show
Bug introduced by
It seems like $registered defined by $this->connection->try_registration() on line 331 can also be of type boolean; however, Jetpack_XMLRPC_Server::error() does only seem to accept object<WP_Error>|object<IXR_Error>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
334
			} elseif ( ! $registered ) {
335
				return $this->error(
336
					new \WP_Error(
337
						'registration_error',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'registration_error'.

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...
338
						__( 'There was an unspecified error registering the site', 'jetpack' ),
339
						400
340
					),
341
					'remote_register'
342
				);
343
			}
344
		}
345
346
		// This action is documented in class.jetpack-xmlrpc-server.php.
347
		do_action( 'jetpack_xmlrpc_server_event', 'remote_register', 'success' );
348
349
		return array(
350
			'client_id' => Jetpack_Options::get_option( 'id' ),
351
		);
352
	}
353
354
	/**
355
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
356
	 * register this site so that a plan can be provisioned.
357
	 *
358
	 * @param array $request An array containing at minimum a nonce key and a local_username key.
359
	 *
360
	 * @return \WP_Error|array
361
	 */
362
	public function remote_provision( $request ) {
363
		$user = $this->fetch_and_verify_local_user( $request );
364
365
		if ( ! $user ) {
366
			return $this->error(
367
				new WP_Error( 'input_error', __( 'Valid user is required', 'jetpack' ), 400 ),
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'input_error'.

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...
368
				'remote_provision'
369
			);
370
		}
371
372
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
373
			return $this->error( $user, 'remote_provision' );
374
		}
375
376
		$site_icon = get_site_icon_url();
377
378
		/**
379
		 * Filters the Redirect URI returned by the remote_register XMLRPC method
380
		 *
381
		 * @param string $redirect_uri The Redirect URI
382
		 *
383
		 * @since 9.8.0
384
		 */
385
		$redirect_uri = apply_filters( 'jetpack_xmlrpc_remote_register_redirect_uri', admin_url() );
386
387
		// Generate secrets.
388
		$roles   = new Roles();
389
		$role    = $roles->translate_user_to_role( $user );
390
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID );
391
392
		$response = array(
393
			'jp_version'   => JETPACK__VERSION,
394
			'redirect_uri' => $redirect_uri,
395
			'user_id'      => $user->ID,
396
			'user_email'   => $user->user_email,
397
			'user_login'   => $user->user_login,
398
			'scope'        => $this->connection->sign_role( $role, $user->ID ),
399
			'secret'       => $secrets['secret_1'],
400
			'is_active'    => $this->connection->has_connected_owner(),
401
		);
402
403
		if ( $site_icon ) {
404
			$response['site_icon'] = $site_icon;
405
		}
406
407
		/**
408
		 * Filters the response of the remote_provision XMLRPC method
409
		 *
410
		 * @param array    $response The response.
411
		 * @param array    $request An array containing at minimum a nonce key and a local_username key.
412
		 * @param \WP_User $user The local authenticated user.
413
		 *
414
		 * @since 9.8.0
415
		 */
416
		$response = apply_filters( 'jetpack_remote_xmlrpc_provision_response', $response, $request, $user );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $request.

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...
417
418
		return $response;
419
	}
420
421
	/**
422
	 * Given an array containing a local user identifier and a nonce, will attempt to fetch and set
423
	 * an access token for the given user.
424
	 *
425
	 * @param array       $request    An array containing local_user and nonce keys at minimum.
426
	 * @param \IXR_Client $ixr_client The client object, optional.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $ixr_client not be false|IXR_Client?

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...
427
	 * @return mixed
428
	 */
429
	public function remote_connect( $request, $ixr_client = false ) {
430
		if ( $this->connection->has_connected_owner() ) {
431
			return $this->error(
432
				new WP_Error(
433
					'already_connected',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'already_connected'.

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...
434
					__( 'Jetpack is already connected.', 'jetpack' ),
435
					400
436
				),
437
				'remote_connect'
438
			);
439
		}
440
441
		$user = $this->fetch_and_verify_local_user( $request );
442
443
		if ( ! $user || is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
444
			return $this->error(
445
				new WP_Error(
446
					'input_error',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'input_error'.

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...
447
					__( 'Valid user is required.', 'jetpack' ),
448
					400
449
				),
450
				'remote_connect'
451
			);
452
		}
453
454
		if ( empty( $request['nonce'] ) ) {
455
			return $this->error(
456
				new WP_Error(
457
					'input_error',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'input_error'.

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...
458
					__( 'A non-empty nonce must be supplied.', 'jetpack' ),
459
					400
460
				),
461
				'remote_connect'
462
			);
463
		}
464
465
		if ( ! $ixr_client ) {
466
			$ixr_client = new Jetpack_IXR_Client();
467
		}
468
		// TODO: move this query into the Tokens class?
469
		$ixr_client->query(
470
			'jetpack.getUserAccessToken',
471
			array(
472
				'nonce'            => sanitize_text_field( $request['nonce'] ),
473
				'external_user_id' => $user->ID,
474
			)
475
		);
476
477
		$token = $ixr_client->isError() ? false : $ixr_client->getResponse();
478
		if ( empty( $token ) ) {
479
			return $this->error(
480
				new WP_Error(
481
					'token_fetch_failed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_fetch_failed'.

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...
482
					__( 'Failed to fetch user token from WordPress.com.', 'jetpack' ),
483
					400
484
				),
485
				'remote_connect'
486
			);
487
		}
488
		$token = sanitize_text_field( $token );
489
490
		( new Tokens() )->update_user_token( $user->ID, sprintf( '%s.%d', $token, $user->ID ), true );
491
492
		/**
493
		 * Hook fired at the end of the jetpack.remoteConnect XML-RPC callback
494
		 *
495
		 * @since 9.8.0
496
		 */
497
		do_action( 'jetpack_remote_connect_end' );
498
499
		return $this->connection->has_connected_owner();
500
	}
501
502
	/**
503
	 * Getter for the local user to act as.
504
	 *
505
	 * @param array $request the current request data.
506
	 */
507
	private function fetch_and_verify_local_user( $request ) {
508
		if ( empty( $request['local_user'] ) ) {
509
			return $this->error(
510
				new \WP_Error(
511
					'local_user_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'local_user_missing'.

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...
512
					__( 'The required "local_user" parameter is missing.', 'jetpack' ),
513
					400
514
				),
515
				'remote_provision'
516
			);
517
		}
518
519
		// Local user is used to look up by login, email or ID.
520
		$local_user_info = $request['local_user'];
521
522
		return $this->get_user_by_anything( $local_user_info );
523
	}
524
525
	/**
526
	 * Gets the user object by its data.
527
	 *
528
	 * @param string $user_id can be any identifying user data.
529
	 */
530
	private function get_user_by_anything( $user_id ) {
531
		$user = get_user_by( 'login', $user_id );
532
533
		if ( ! $user ) {
534
			$user = get_user_by( 'email', $user_id );
535
		}
536
537
		if ( ! $user ) {
538
			$user = get_user_by( 'ID', $user_id );
539
		}
540
541
		return $user;
542
	}
543
544
	/**
545
	 * Possible error_codes:
546
	 *
547
	 * - verify_secret_1_missing
548
	 * - verify_secret_1_malformed
549
	 * - verify_secrets_missing: verification secrets are not found in database
550
	 * - verify_secrets_incomplete: verification secrets are only partially found in database
551
	 * - verify_secrets_expired: verification secrets have expired
552
	 * - verify_secrets_mismatch: stored secret_1 does not match secret_1 sent by Jetpack.WordPress.com
553
	 * - state_missing: required parameter of state not found
554
	 * - state_malformed: state is not a digit
555
	 * - invalid_state: state in request does not match the stored state
556
	 *
557
	 * The 'authorize' and 'register' actions have additional error codes
558
	 *
559
	 * state_missing: a state ( user id ) was not supplied
560
	 * state_malformed: state is not the correct data type
561
	 * invalid_state: supplied state does not match the stored state
562
	 *
563
	 * @param array $params action An array of 3 parameters:
564
	 *     [0]: string action. Possible values are `authorize`, `publicize` and `register`.
565
	 *     [1]: string secret_1.
566
	 *     [2]: int state.
567
	 * @return \IXR_Error|string IXR_Error on failure, secret_2 on success.
568
	 */
569
	public function verify_action( $params ) {
570
		$action        = isset( $params[0] ) ? $params[0] : '';
571
		$verify_secret = isset( $params[1] ) ? $params[1] : '';
572
		$state         = isset( $params[2] ) ? $params[2] : '';
573
574
		$result = ( new Secrets() )->verify( $action, $verify_secret, $state );
575
576
		if ( is_wp_error( $result ) ) {
577
			return $this->error( $result );
0 ignored issues
show
Bug introduced by
It seems like $result defined by (new \Automattic\Jetpack...$verify_secret, $state) on line 574 can also be of type string; however, Jetpack_XMLRPC_Server::error() does only seem to accept object<WP_Error>|object<IXR_Error>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
578
		}
579
580
		return $result;
581
	}
582
583
	/**
584
	 * Wrapper for wp_authenticate( $username, $password );
585
	 *
586
	 * @return \WP_User|bool
587
	 */
588
	public function login() {
589
		$this->connection->require_jetpack_authentication();
590
		$user = wp_authenticate( 'username', 'password' );
591
		if ( is_wp_error( $user ) ) {
592
			if ( 'authentication_failed' === $user->get_error_code() ) { // Generic error could mean most anything.
593
				$this->error = new \WP_Error( 'invalid_request', 'Invalid Request', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_request'.

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...
594
			} else {
595
				$this->error = $user;
596
			}
597
			return false;
598
		} elseif ( ! $user ) { // Shouldn't happen.
599
			$this->error = new \WP_Error( 'invalid_request', 'Invalid Request', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_request'.

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...
600
			return false;
601
		}
602
603
		wp_set_current_user( $user->ID );
604
605
		return $user;
606
	}
607
608
	/**
609
	 * Returns the current error as an \IXR_Error
610
	 *
611
	 * @param \WP_Error|\IXR_Error $error             The error object, optional.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $error not be WP_Error|IXR_Error|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...
612
	 * @param string               $event_name The event name.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $event_name 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...
613
	 * @param \WP_User             $user              The user object.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be WP_User|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...
614
	 * @return bool|\IXR_Error
615
	 */
616
	public function error( $error = null, $event_name = null, $user = null ) {
617
		if ( null !== $event_name ) {
618
			// This action is documented in class.jetpack-xmlrpc-server.php.
619
			do_action( 'jetpack_xmlrpc_server_event', $event_name, 'fail', $error, $user );
620
		}
621
622
		if ( ! is_null( $error ) ) {
623
			$this->error = $error;
0 ignored issues
show
Documentation Bug introduced by
It seems like $error can also be of type object<IXR_Error>. However, the property $error is declared as type object<WP_Error>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
624
		}
625
626
		if ( is_wp_error( $this->error ) ) {
627
			$code = $this->error->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
628
			if ( ! $code ) {
629
				$code = -10520;
630
			}
631
			$message = sprintf( 'Jetpack: [%s] %s', $this->error->get_error_code(), $this->error->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
632
			return new \IXR_Error( $code, $message );
633
		} elseif ( is_a( $this->error, 'IXR_Error' ) ) {
634
			return $this->error;
635
		}
636
637
		return false;
638
	}
639
640
	/* API Methods */
641
642
	/**
643
	 * Just authenticates with the given Jetpack credentials.
644
	 *
645
	 * @return string A success string. The Jetpack plugin filters it and make it return the Jetpack plugin version.
646
	 */
647
	public function test_connection() {
648
		/**
649
		 * Filters the successful response of the XMLRPC test_connection method
650
		 *
651
		 * @param string $response The response string.
652
		 */
653
		return apply_filters( 'jetpack_xmlrpc_test_connection_response', 'success' );
654
	}
655
656
	/**
657
	 * Test the API user code.
658
	 *
659
	 * @param array $args arguments identifying the test site.
660
	 */
661
	public function test_api_user_code( $args ) {
662
		$client_id = (int) $args[0];
663
		$user_id   = (int) $args[1];
664
		$nonce     = (string) $args[2];
665
		$verify    = (string) $args[3];
666
667
		if ( ! $client_id || ! $user_id || ! strlen( $nonce ) || 32 !== strlen( $verify ) ) {
668
			return false;
669
		}
670
671
		$user = get_user_by( 'id', $user_id );
672
		if ( ! $user || is_wp_error( $user ) ) {
673
			return false;
674
		}
675
676
		/* phpcs:ignore
677
		 debugging
678
		error_log( "CLIENT: $client_id" );
679
		error_log( "USER:   $user_id" );
680
		error_log( "NONCE:  $nonce" );
681
		error_log( "VERIFY: $verify" );
682
		*/
683
684
		$jetpack_token = ( new Tokens() )->get_access_token( $user_id );
685
686
		$api_user_code = get_user_meta( $user_id, "jetpack_json_api_$client_id", true );
687
		if ( ! $api_user_code ) {
688
			return false;
689
		}
690
691
		$hmac = hash_hmac(
692
			'md5',
693
			json_encode( // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
694
				(object) array(
695
					'client_id' => (int) $client_id,
696
					'user_id'   => (int) $user_id,
697
					'nonce'     => (string) $nonce,
698
					'code'      => (string) $api_user_code,
699
				)
700
			),
701
			$jetpack_token->secret
702
		);
703
704
		if ( ! hash_equals( $hmac, $verify ) ) {
705
			return false;
706
		}
707
708
		return $user_id;
709
	}
710
711
	/**
712
	 * Unlink a user from WordPress.com
713
	 *
714
	 * When the request is done without any parameter, this XMLRPC callback gets an empty array as input.
715
	 *
716
	 * If $user_id is not provided, it will try to disconnect the current logged in user. This will fail if called by the Master User.
717
	 *
718
	 * If $user_id is is provided, it will try to disconnect the informed user, even if it's the Master User.
719
	 *
720
	 * @param mixed $user_id The user ID to disconnect from this site.
721
	 */
722
	public function unlink_user( $user_id = array() ) {
723
		$user_id = (int) $user_id;
724
		if ( $user_id < 1 ) {
725
			$user_id = null;
726
		}
727
		/**
728
		 * Fired when we want to log an event to the Jetpack event log.
729
		 *
730
		 * @since 7.7.0
731
		 *
732
		 * @param string $code Unique name for the event.
733
		 * @param string $data Optional data about the event.
734
		 */
735
		do_action( 'jetpack_event_log', 'unlink' );
736
		return $this->connection->disconnect_user(
737
			$user_id,
738
			(bool) $user_id
739
		);
740
	}
741
742
	/**
743
	 * Returns any object that is able to be synced.
744
	 *
745
	 * @deprecated since 7.8.0
746
	 * @see Automattic\Jetpack\Sync\Sender::sync_object()
747
	 *
748
	 * @param array $args the synchronized object parameters.
749
	 * @return string Encoded sync object.
750
	 */
751
	public function sync_object( $args ) {
752
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Sync\\Sender::sync_object' );
753
		return Sender::get_instance()->sync_object( $args );
754
	}
755
756
	/**
757
	 * Returns the home URL and site URL for the current site which can be used on the WPCOM side for
758
	 * IDC mitigation to decide whether sync should be allowed if the home and siteurl values differ between WPCOM
759
	 * and the remote Jetpack site.
760
	 *
761
	 * @return array
762
	 */
763
	public function validate_urls_for_idc_mitigation() {
764
		return array(
765
			'home'    => Urls::home_url(),
766
			'siteurl' => Urls::site_url(),
767
		);
768
	}
769
770
	/**
771
	 * Updates the attachment parent object.
772
	 *
773
	 * @param array $args attachment and parent identifiers.
774
	 */
775
	public function update_attachment_parent( $args ) {
776
		$attachment_id = (int) $args[0];
777
		$parent_id     = (int) $args[1];
778
779
		return wp_update_post(
780
			array(
781
				'ID'          => $attachment_id,
782
				'post_parent' => $parent_id,
783
			)
784
		);
785
	}
786
787
	/**
788
	 * Deprecated: This method is no longer part of the Connection package and now lives on the Jetpack plugin.
789
	 *
790
	 * Disconnect this blog from the connected wordpress.com account
791
	 *
792
	 * @deprecated since 9.6.0
793
	 * @see Jetpack_XMLRPC_Methods::disconnect_blog() in the Jetpack plugin
794
	 *
795
	 * @return boolean
796
	 */
797
	public function disconnect_blog() {
798
		_deprecated_function( __METHOD__, 'jetpack-9.6', 'Jetpack_XMLRPC_Methods::disconnect_blog()' );
799
		if ( class_exists( 'Jetpack_XMLRPC_Methods' ) ) {
800
			return Jetpack_XMLRPC_Methods::disconnect_blog();
801
		}
802
		return false;
803
	}
804
805
	/**
806
	 * Deprecated: This method is no longer part of the Connection package and now lives on the Jetpack plugin.
807
	 *
808
	 * Returns what features are available. Uses the slug of the module files.
809
	 *
810
	 * @deprecated since 9.6.0
811
	 * @see Jetpack_XMLRPC_Methods::features_available() in the Jetpack plugin
812
	 *
813
	 * @return array
814
	 */
815
	public function features_available() {
816
		_deprecated_function( __METHOD__, 'jetpack-9.6', 'Jetpack_XMLRPC_Methods::features_available()' );
817
		if ( class_exists( 'Jetpack_XMLRPC_Methods' ) ) {
818
			return Jetpack_XMLRPC_Methods::features_available();
819
		}
820
		return array();
821
	}
822
823
	/**
824
	 * Deprecated: This method is no longer part of the Connection package and now lives on the Jetpack plugin.
825
	 *
826
	 * Returns what features are enabled. Uses the slug of the modules files.
827
	 *
828
	 * @deprecated since 9.6.0
829
	 * @see Jetpack_XMLRPC_Methods::features_enabled() in the Jetpack plugin
830
	 *
831
	 * @return array
832
	 */
833
	public function features_enabled() {
834
		_deprecated_function( __METHOD__, 'jetpack-9.6', 'Jetpack_XMLRPC_Methods::features_enabled()' );
835
		if ( class_exists( 'Jetpack_XMLRPC_Methods' ) ) {
836
			return Jetpack_XMLRPC_Methods::features_enabled();
837
		}
838
		return array();
839
	}
840
841
	/**
842
	 * Deprecated: This method is no longer part of the Connection package and now lives on the Jetpack plugin.
843
	 *
844
	 * Serve a JSON API request.
845
	 *
846
	 * @deprecated since 9.6.0
847
	 * @see Jetpack_XMLRPC_Methods::json_api() in the Jetpack plugin
848
	 *
849
	 * @param array $args request arguments.
850
	 */
851
	public function json_api( $args = array() ) {
852
		_deprecated_function( __METHOD__, 'jetpack-9.6', 'Jetpack_XMLRPC_Methods::json_api()' );
853
		if ( class_exists( 'Jetpack_XMLRPC_Methods' ) ) {
854
			return Jetpack_XMLRPC_Methods::json_api( $args );
855
		}
856
		return array();
857
	}
858
859
}
860