Completed
Push — add/masterbar--my-home ( 5c5e9c...8732fd )
by
unknown
10:54 queued 04:17
created

Jetpack_XMLRPC_Server::verify_action()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 16
nop 1
dl 0
loc 13
rs 9.5222
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\Utils as Connection_Utils;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Sync\Modules;
13
use Automattic\Jetpack\Sync\Functions;
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
	 * @param Automattic\Jetpack\Connection\Manager $manager the connection manager object.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $manager not be Manager|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...
45
	 */
46
	public function __construct( $manager = null ) {
47
		$this->connection = is_null( $manager ) ? new Connection_Manager() : $manager;
48
	}
49
50
	/**
51
	 * Whitelist of the XML-RPC methods available to the Jetpack Server. If the
52
	 * user is not authenticated (->login()) then the methods are never added,
53
	 * so they will get a "does not exist" error.
54
	 *
55
	 * @param array $core_methods Core XMLRPC methods.
56
	 */
57
	public function xmlrpc_methods( $core_methods ) {
58
		$jetpack_methods = array(
59
			'jetpack.jsonAPI'         => array( $this, 'json_api' ),
60
			'jetpack.verifyAction'    => array( $this, 'verify_action' ),
61
			'jetpack.getUser'         => array( $this, 'get_user' ),
62
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
63
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
64
		);
65
66
		$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...
67
68
		if ( $this->user ) {
69
			$jetpack_methods = array_merge(
70
				$jetpack_methods,
71
				array(
72
					'jetpack.testConnection'    => array( $this, 'test_connection' ),
73
					'jetpack.testAPIUserCode'   => array( $this, 'test_api_user_code' ),
74
					'jetpack.featuresAvailable' => array( $this, 'features_available' ),
75
					'jetpack.featuresEnabled'   => array( $this, 'features_enabled' ),
76
					'jetpack.disconnectBlog'    => array( $this, 'disconnect_blog' ),
77
					'jetpack.unlinkUser'        => array( $this, 'unlink_user' ),
78
					'jetpack.idcUrlValidation'  => array( $this, 'validate_urls_for_idc_mitigation' ),
79
				)
80
			);
81
82
			if ( isset( $core_methods['metaWeblog.editPost'] ) ) {
83
				$jetpack_methods['metaWeblog.newMediaObject']      = $core_methods['metaWeblog.newMediaObject'];
84
				$jetpack_methods['jetpack.updateAttachmentParent'] = array( $this, 'update_attachment_parent' );
85
			}
86
87
			/**
88
			 * Filters the XML-RPC methods available to Jetpack for authenticated users.
89
			 *
90
			 * @since 1.1.0
91
			 *
92
			 * @param array    $jetpack_methods XML-RPC methods available to the Jetpack Server.
93
			 * @param array    $core_methods    Available core XML-RPC methods.
94
			 * @param \WP_User $user            Information about a given WordPress user.
95
			 */
96
			$jetpack_methods = apply_filters( 'jetpack_xmlrpc_methods', $jetpack_methods, $core_methods, $this->user );
97
		}
98
99
		/**
100
		 * Filters the XML-RPC methods available to Jetpack for unauthenticated users.
101
		 *
102
		 * @since 3.0.0
103
		 *
104
		 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
105
		 * @param array $core_methods    Available core XML-RPC methods.
106
		 */
107
		return apply_filters( 'jetpack_xmlrpc_unauthenticated_methods', $jetpack_methods, $core_methods );
108
	}
109
110
	/**
111
	 * Whitelist of the bootstrap XML-RPC methods
112
	 */
113
	public function bootstrap_xmlrpc_methods() {
114
		return array(
115
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
116
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
117
		);
118
	}
119
120
	/**
121
	 * Additional method needed for authorization calls.
122
	 */
123
	public function authorize_xmlrpc_methods() {
124
		return array(
125
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
126
		);
127
	}
128
129
	/**
130
	 * Remote provisioning methods.
131
	 */
132
	public function provision_xmlrpc_methods() {
133
		return array(
134
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
135
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
136
			'jetpack.remoteConnect'   => array( $this, 'remote_connect' ),
137
			'jetpack.getUser'         => array( $this, 'get_user' ),
138
		);
139
	}
140
141
	/**
142
	 * Used to verify whether a local user exists and what role they have.
143
	 *
144
	 * @param int|string|array $request One of:
145
	 *                         int|string The local User's ID, username, or email address.
146
	 *                         array      A request array containing:
147
	 *                                    0: int|string The local User's ID, username, or email address.
148
	 *
149
	 * @return array|\IXR_Error Information about the user, or error if no such user found:
150
	 *                          roles:     string[] The user's rols.
151
	 *                          login:     string   The user's username.
152
	 *                          email_hash string[] The MD5 hash of the user's normalized email address.
153
	 *                          caps       string[] The user's capabilities.
154
	 *                          allcaps    string[] The user's granular capabilities, merged from role capabilities.
155
	 *                          token_key  string   The Token Key of the user's Jetpack token. Empty string if none.
156
	 */
157
	public function get_user( $request ) {
158
		$user_id = is_array( $request ) ? $request[0] : $request;
159
160
		if ( ! $user_id ) {
161
			return $this->error(
162
				new Jetpack_Error(
163
					'invalid_user',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
164
					__( 'Invalid user identifier.', 'jetpack' ),
165
					400
166
				),
167
				'get_user'
168
			);
169
		}
170
171
		$user = $this->get_user_by_anything( $user_id );
172
173
		if ( ! $user ) {
174
			return $this->error(
175
				new Jetpack_Error(
176
					'user_unknown',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
177
					__( 'User not found.', 'jetpack' ),
178
					404
179
				),
180
				'get_user'
181
			);
182
		}
183
184
		$user_token = $this->connection->get_access_token( $user->ID );
185
186
		if ( $user_token ) {
187
			list( $user_token_key ) = explode( '.', $user_token->secret );
188
			if ( $user_token_key === $user_token->secret ) {
189
				$user_token_key = '';
190
			}
191
		} else {
192
			$user_token_key = '';
193
		}
194
195
		return array(
196
			'id'         => $user->ID,
197
			'login'      => $user->user_login,
198
			'email_hash' => md5( strtolower( trim( $user->user_email ) ) ),
199
			'roles'      => $user->roles,
200
			'caps'       => $user->caps,
201
			'allcaps'    => $user->allcaps,
202
			'token_key'  => $user_token_key,
203
		);
204
	}
205
206
	/**
207
	 * Remote authorization XMLRPC method handler.
208
	 *
209
	 * @param array $request the request.
210
	 */
211
	public function remote_authorize( $request ) {
212
		$user = get_user_by( 'id', $request['state'] );
213
214
		/**
215
		 * Happens on various request handling events in the Jetpack XMLRPC server.
216
		 * The action combines several types of events:
217
		 *    - remote_authorize
218
		 *    - remote_provision
219
		 *    - get_user.
220
		 *
221
		 * @since 8.0.0
222
		 *
223
		 * @param String  $action the action name, i.e., 'remote_authorize'.
224
		 * @param String  $stage  the execution stage, can be 'begin', 'success', 'error', etc.
225
		 * @param Array   $parameters extra parameters from the event.
226
		 * @param WP_User $user the acting user.
227
		 */
228
		do_action( 'jetpack_xmlrpc_server_event', 'remote_authorize', 'begin', array(), $user );
229
230
		foreach ( array( 'secret', 'state', 'redirect_uri', 'code' ) as $required ) {
231
			if ( ! isset( $request[ $required ] ) || empty( $request[ $required ] ) ) {
232
				return $this->error(
233
					new Jetpack_Error( 'missing_parameter', 'One or more parameters is missing from the request.', 400 ),
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
234
					'remote_authorize'
235
				);
236
			}
237
		}
238
239
		if ( ! $user ) {
240
			return $this->error( new Jetpack_Error( 'user_unknown', 'User not found.', 404 ), 'remote_authorize' );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
241
		}
242
243
		if ( $this->connection->is_active() && $this->connection->is_user_connected( $request['state'] ) ) {
244
			return $this->error( new Jetpack_Error( 'already_connected', 'User already connected.', 400 ), 'remote_authorize' );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
245
		}
246
247
		$verified = $this->verify_action( array( 'authorize', $request['secret'], $request['state'] ) );
248
249
		if ( is_a( $verified, 'IXR_Error' ) ) {
250
			return $this->error( $verified, 'remote_authorize' );
251
		}
252
253
		wp_set_current_user( $request['state'] );
254
255
		$result = $this->connection->authorize( $request );
256
257
		if ( is_wp_error( $result ) ) {
258
			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 255 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...
259
		}
260
261
		// This action is documented in class.jetpack-xmlrpc-server.php.
262
		do_action( 'jetpack_xmlrpc_server_event', 'remote_authorize', 'success' );
263
264
		return array(
265
			'result' => $result,
266
		);
267
	}
268
269
	/**
270
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
271
	 * register this site so that a plan can be provisioned.
272
	 *
273
	 * @param array $request An array containing at minimum nonce and local_user keys.
274
	 *
275
	 * @return \WP_Error|array
276
	 */
277
	public function remote_register( $request ) {
278
		// This action is documented in class.jetpack-xmlrpc-server.php.
279
		do_action( 'jetpack_xmlrpc_server_event', 'remote_register', 'begin', array() );
280
281
		$user = $this->fetch_and_verify_local_user( $request );
282
283
		if ( ! $user ) {
284
			return $this->error(
285
				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...
286
				'remote_register'
287
			);
288
		}
289
290
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
291
			return $this->error( $user, 'remote_register' );
292
		}
293
294
		if ( empty( $request['nonce'] ) ) {
295
			return $this->error(
296
				new Jetpack_Error(
297
					'nonce_missing',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
298
					__( 'The required "nonce" parameter is missing.', 'jetpack' ),
299
					400
300
				),
301
				'remote_register'
302
			);
303
		}
304
305
		$nonce = sanitize_text_field( $request['nonce'] );
306
		unset( $request['nonce'] );
307
308
		$api_url  = Connection_Utils::fix_url_for_bad_hosts(
309
			$this->connection->api_url( 'partner_provision_nonce_check' )
310
		);
311
		$response = Client::_wp_remote_request(
312
			esc_url_raw( add_query_arg( 'nonce', $nonce, $api_url ) ),
313
			array( 'method' => 'GET' ),
314
			true
315
		);
316
317
		if (
318
			200 !== wp_remote_retrieve_response_code( $response ) ||
319
			'OK' !== trim( wp_remote_retrieve_body( $response ) )
320
		) {
321
			return $this->error(
322
				new Jetpack_Error(
323
					'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
324
					__( 'There was an issue validating this request.', 'jetpack' ),
325
					400
326
				),
327
				'remote_register'
328
			);
329
		}
330
331
		if ( ! Jetpack_Options::get_option( 'id' ) || ! $this->connection->get_access_token() || ! empty( $request['force'] ) ) {
332
			wp_set_current_user( $user->ID );
333
334
			// This code mostly copied from Jetpack::admin_page_load.
335
			Jetpack::maybe_set_version_option();
336
			$registered = Jetpack::try_registration();
337
			if ( is_wp_error( $registered ) ) {
338
				return $this->error( $registered, 'remote_register' );
339
			} elseif ( ! $registered ) {
340
				return $this->error(
341
					new Jetpack_Error(
342
						'registration_error',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
343
						__( 'There was an unspecified error registering the site', 'jetpack' ),
344
						400
345
					),
346
					'remote_register'
347
				);
348
			}
349
		}
350
351
		// This action is documented in class.jetpack-xmlrpc-server.php.
352
		do_action( 'jetpack_xmlrpc_server_event', 'remote_register', 'success' );
353
354
		return array(
355
			'client_id' => Jetpack_Options::get_option( 'id' ),
356
		);
357
	}
358
359
	/**
360
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
361
	 * register this site so that a plan can be provisioned.
362
	 *
363
	 * @param array $request An array containing at minimum a nonce key and a local_username key.
364
	 *
365
	 * @return \WP_Error|array
366
	 */
367
	public function remote_provision( $request ) {
368
		$user = $this->fetch_and_verify_local_user( $request );
369
370
		if ( ! $user ) {
371
			return $this->error(
372
				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...
373
				'remote_provision'
374
			);
375
		}
376
377
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
378
			return $this->error( $user, 'remote_provision' );
379
		}
380
381
		$site_icon = get_site_icon_url();
382
383
		$auto_enable_sso = ( ! $this->connection->is_active() || Jetpack::is_module_active( 'sso' ) );
384
385
		/** This filter is documented in class.jetpack-cli.php */
386 View Code Duplication
		if ( apply_filters( 'jetpack_start_enable_sso', $auto_enable_sso ) ) {
387
			$redirect_uri = add_query_arg(
388
				array(
389
					'action'      => 'jetpack-sso',
390
					'redirect_to' => rawurlencode( admin_url() ),
391
				),
392
				wp_login_url() // TODO: come back to Jetpack dashboard?
393
			);
394
		} else {
395
			$redirect_uri = admin_url();
396
		}
397
398
		// Generate secrets.
399
		$roles   = new Roles();
400
		$role    = $roles->translate_user_to_role( $user );
401
		$secrets = $this->connection->generate_secrets( 'authorize', $user->ID );
402
403
		$response = array(
404
			'jp_version'   => JETPACK__VERSION,
405
			'redirect_uri' => $redirect_uri,
406
			'user_id'      => $user->ID,
407
			'user_email'   => $user->user_email,
408
			'user_login'   => $user->user_login,
409
			'scope'        => $this->connection->sign_role( $role, $user->ID ),
410
			'secret'       => $secrets['secret_1'],
411
			'is_active'    => $this->connection->is_active(),
412
		);
413
414
		if ( $site_icon ) {
415
			$response['site_icon'] = $site_icon;
416
		}
417
418
		if ( ! empty( $request['onboarding'] ) ) {
419
			Jetpack::create_onboarding_token();
420
			$response['onboarding_token'] = Jetpack_Options::get_option( 'onboarding' );
421
		}
422
423
		return $response;
424
	}
425
426
	/**
427
	 * Given an array containing a local user identifier and a nonce, will attempt to fetch and set
428
	 * an access token for the given user.
429
	 *
430
	 * @param array       $request    An array containing local_user and nonce keys at minimum.
431
	 * @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...
432
	 * @return mixed
433
	 */
434
	public function remote_connect( $request, $ixr_client = false ) {
435
		if ( $this->connection->is_active() ) {
436
			return $this->error(
437
				new WP_Error(
438
					'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...
439
					__( 'Jetpack is already connected.', 'jetpack' ),
440
					400
441
				),
442
				'remote_connect'
443
			);
444
		}
445
446
		$user = $this->fetch_and_verify_local_user( $request );
447
448
		if ( ! $user || is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
449
			return $this->error(
450
				new WP_Error(
451
					'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...
452
					__( 'Valid user is required.', 'jetpack' ),
453
					400
454
				),
455
				'remote_connect'
456
			);
457
		}
458
459
		if ( empty( $request['nonce'] ) ) {
460
			return $this->error(
461
				new WP_Error(
462
					'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...
463
					__( 'A non-empty nonce must be supplied.', 'jetpack' ),
464
					400
465
				),
466
				'remote_connect'
467
			);
468
		}
469
470
		if ( ! $ixr_client ) {
471
			$ixr_client = new Jetpack_IXR_Client();
472
		}
473
		$ixr_client->query(
474
			'jetpack.getUserAccessToken',
475
			array(
476
				'nonce'            => sanitize_text_field( $request['nonce'] ),
477
				'external_user_id' => $user->ID,
478
			)
479
		);
480
481
		$token = $ixr_client->isError() ? false : $ixr_client->getResponse();
482
		if ( empty( $token ) ) {
483
			return $this->error(
484
				new WP_Error(
485
					'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...
486
					__( 'Failed to fetch user token from WordPress.com.', 'jetpack' ),
487
					400
488
				),
489
				'remote_connect'
490
			);
491
		}
492
		$token = sanitize_text_field( $token );
493
494
		Connection_Utils::update_user_token( $user->ID, sprintf( '%s.%d', $token, $user->ID ), true );
495
496
		$this->do_post_authorization();
497
498
		return $this->connection->is_active();
499
	}
500
501
	/**
502
	 * Getter for the local user to act as.
503
	 *
504
	 * @param array $request the current request data.
505
	 */
506
	private function fetch_and_verify_local_user( $request ) {
507
		if ( empty( $request['local_user'] ) ) {
508
			return $this->error(
509
				new Jetpack_Error(
510
					'local_user_missing',
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
511
					__( 'The required "local_user" parameter is missing.', 'jetpack' ),
512
					400
513
				),
514
				'remote_provision'
515
			);
516
		}
517
518
		// Local user is used to look up by login, email or ID.
519
		$local_user_info = $request['local_user'];
520
521
		return $this->get_user_by_anything( $local_user_info );
522
	}
523
524
	/**
525
	 * Gets the user object by its data.
526
	 *
527
	 * @param string $user_id can be any identifying user data.
528
	 */
529
	private function get_user_by_anything( $user_id ) {
530
		$user = get_user_by( 'login', $user_id );
531
532
		if ( ! $user ) {
533
			$user = get_user_by( 'email', $user_id );
534
		}
535
536
		if ( ! $user ) {
537
			$user = get_user_by( 'ID', $user_id );
538
		}
539
540
		return $user;
541
	}
542
543
	/**
544
	 * Possible error_codes:
545
	 *
546
	 * - verify_secret_1_missing
547
	 * - verify_secret_1_malformed
548
	 * - verify_secrets_missing: verification secrets are not found in database
549
	 * - verify_secrets_incomplete: verification secrets are only partially found in database
550
	 * - verify_secrets_expired: verification secrets have expired
551
	 * - verify_secrets_mismatch: stored secret_1 does not match secret_1 sent by Jetpack.WordPress.com
552
	 * - state_missing: required parameter of state not found
553
	 * - state_malformed: state is not a digit
554
	 * - invalid_state: state in request does not match the stored state
555
	 *
556
	 * The 'authorize' and 'register' actions have additional error codes
557
	 *
558
	 * state_missing: a state ( user id ) was not supplied
559
	 * state_malformed: state is not the correct data type
560
	 * invalid_state: supplied state does not match the stored state
561
	 *
562
	 * @param array $params action An array of 3 parameters:
563
	 *     [0]: string action. Possible values are `authorize`, `publicize` and `register`.
564
	 *     [1]: string secret_1.
565
	 *     [2]: int state.
566
	 * @return \IXR_Error|string IXR_Error on failure, secret_2 on success.
567
	 */
568
	public function verify_action( $params ) {
569
		$action        = isset( $params[0] ) ? $params[0] : '';
570
		$verify_secret = isset( $params[1] ) ? $params[1] : '';
571
		$state         = isset( $params[2] ) ? $params[2] : '';
572
573
		$result = $this->connection->verify_secrets( $action, $verify_secret, $state );
574
575
		if ( is_wp_error( $result ) ) {
576
			return $this->error( $result );
0 ignored issues
show
Bug introduced by
It seems like $result defined by $this->connection->verif...$verify_secret, $state) on line 573 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...
577
		}
578
579
		return $result;
580
	}
581
582
	/**
583
	 * Wrapper for wp_authenticate( $username, $password );
584
	 *
585
	 * @return \WP_User|bool
586
	 */
587
	public function login() {
588
		$this->connection->require_jetpack_authentication();
589
		$user = wp_authenticate( 'username', 'password' );
590
		if ( is_wp_error( $user ) ) {
591
			if ( 'authentication_failed' === $user->get_error_code() ) { // Generic error could mean most anything.
592
				$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
593
			} else {
594
				$this->error = $user;
595
			}
596
			return false;
597
		} elseif ( ! $user ) { // Shouldn't happen.
598
			$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
599
			return false;
600
		}
601
602
		return $user;
603
	}
604
605
	/**
606
	 * Returns the current error as an \IXR_Error
607
	 *
608
	 * @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...
609
	 * @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...
610
	 * @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...
611
	 * @return bool|\IXR_Error
612
	 */
613
	public function error( $error = null, $event_name = null, $user = null ) {
614
		if ( null !== $event_name ) {
615
			// This action is documented in class.jetpack-xmlrpc-server.php.
616
			do_action( 'jetpack_xmlrpc_server_event', $event_name, 'fail', $error, $user );
617
		}
618
619
		if ( ! is_null( $error ) ) {
620
			$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...
621
		}
622
623
		if ( is_wp_error( $this->error ) ) {
624
			$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...
625
			if ( ! $code ) {
626
				$code = -10520;
627
			}
628
			$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...
629
			return new \IXR_Error( $code, $message );
630
		} elseif ( is_a( $this->error, 'IXR_Error' ) ) {
631
			return $this->error;
632
		}
633
634
		return false;
635
	}
636
637
	/* API Methods */
638
639
	/**
640
	 * Just authenticates with the given Jetpack credentials.
641
	 *
642
	 * @return string The current Jetpack version number
643
	 */
644
	public function test_connection() {
645
		return JETPACK__VERSION;
646
	}
647
648
	/**
649
	 * Test the API user code.
650
	 *
651
	 * @param array $args arguments identifying the test site.
652
	 */
653
	public function test_api_user_code( $args ) {
654
		$client_id = (int) $args[0];
655
		$user_id   = (int) $args[1];
656
		$nonce     = (string) $args[2];
657
		$verify    = (string) $args[3];
658
659
		if ( ! $client_id || ! $user_id || ! strlen( $nonce ) || 32 !== strlen( $verify ) ) {
660
			return false;
661
		}
662
663
		$user = get_user_by( 'id', $user_id );
664
		if ( ! $user || is_wp_error( $user ) ) {
665
			return false;
666
		}
667
668
		/* phpcs:ignore
669
		 debugging
670
		error_log( "CLIENT: $client_id" );
671
		error_log( "USER:   $user_id" );
672
		error_log( "NONCE:  $nonce" );
673
		error_log( "VERIFY: $verify" );
674
		*/
675
676
		$jetpack_token = $this->connection->get_access_token( $user_id );
677
678
		$api_user_code = get_user_meta( $user_id, "jetpack_json_api_$client_id", true );
679
		if ( ! $api_user_code ) {
680
			return false;
681
		}
682
683
		$hmac = hash_hmac(
684
			'md5',
685
			json_encode( // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
686
				(object) array(
687
					'client_id' => (int) $client_id,
688
					'user_id'   => (int) $user_id,
689
					'nonce'     => (string) $nonce,
690
					'code'      => (string) $api_user_code,
691
				)
692
			),
693
			$jetpack_token->secret
694
		);
695
696
		if ( ! hash_equals( $hmac, $verify ) ) {
697
			return false;
698
		}
699
700
		return $user_id;
701
	}
702
703
	/**
704
	 * Disconnect this blog from the connected wordpress.com account
705
	 *
706
	 * @return boolean
707
	 */
708
	public function disconnect_blog() {
709
710
		// For tracking.
711
		if ( ! empty( $this->user->ID ) ) {
712
			wp_set_current_user( $this->user->ID );
713
		}
714
715
		/**
716
		 * Fired when we want to log an event to the Jetpack event log.
717
		 *
718
		 * @since 7.7.0
719
		 *
720
		 * @param string $code Unique name for the event.
721
		 * @param string $data Optional data about the event.
722
		 */
723
		do_action( 'jetpack_event_log', 'disconnect' );
724
		Jetpack::disconnect();
725
726
		return true;
727
	}
728
729
	/**
730
	 * Unlink a user from WordPress.com
731
	 *
732
	 * This will fail if called by the Master User.
733
	 */
734
	public function unlink_user() {
735
		/**
736
		 * Fired when we want to log an event to the Jetpack event log.
737
		 *
738
		 * @since 7.7.0
739
		 *
740
		 * @param string $code Unique name for the event.
741
		 * @param string $data Optional data about the event.
742
		 */
743
		do_action( 'jetpack_event_log', 'unlink' );
744
		return Connection_Manager::disconnect_user();
745
	}
746
747
	/**
748
	 * Returns any object that is able to be synced.
749
	 *
750
	 * @deprecated since 7.8.0
751
	 * @see Automattic\Jetpack\Sync\Sender::sync_object()
752
	 *
753
	 * @param array $args the synchronized object parameters.
754
	 * @return string Encoded sync object.
755
	 */
756
	public function sync_object( $args ) {
757
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Sync\\Sender::sync_object' );
758
		return Sender::get_instance()->sync_object( $args );
759
	}
760
761
	/**
762
	 * Returns the home URL and site URL for the current site which can be used on the WPCOM side for
763
	 * IDC mitigation to decide whether sync should be allowed if the home and siteurl values differ between WPCOM
764
	 * and the remote Jetpack site.
765
	 *
766
	 * @return array
767
	 */
768
	public function validate_urls_for_idc_mitigation() {
769
		return array(
770
			'home'    => Functions::home_url(),
771
			'siteurl' => Functions::site_url(),
772
		);
773
	}
774
775
	/**
776
	 * Returns what features are available. Uses the slug of the module files.
777
	 *
778
	 * @return array
779
	 */
780 View Code Duplication
	public function features_available() {
781
		$raw_modules = Jetpack::get_available_modules();
782
		$modules     = array();
783
		foreach ( $raw_modules as $module ) {
784
			$modules[] = Jetpack::get_module_slug( $module );
785
		}
786
787
		return $modules;
788
	}
789
790
	/**
791
	 * Returns what features are enabled. Uses the slug of the modules files.
792
	 *
793
	 * @return array
794
	 */
795 View Code Duplication
	public function features_enabled() {
796
		$raw_modules = Jetpack::get_active_modules();
797
		$modules     = array();
798
		foreach ( $raw_modules as $module ) {
799
			$modules[] = Jetpack::get_module_slug( $module );
800
		}
801
802
		return $modules;
803
	}
804
805
	/**
806
	 * Updates the attachment parent object.
807
	 *
808
	 * @param array $args attachment and parent identifiers.
809
	 */
810
	public function update_attachment_parent( $args ) {
811
		$attachment_id = (int) $args[0];
812
		$parent_id     = (int) $args[1];
813
814
		return wp_update_post(
815
			array(
816
				'ID'          => $attachment_id,
817
				'post_parent' => $parent_id,
818
			)
819
		);
820
	}
821
822
	/**
823
	 * Serve a JSON API request.
824
	 *
825
	 * @param array $args request arguments.
826
	 */
827
	public function json_api( $args = array() ) {
828
		$json_api_args        = $args[0];
829
		$verify_api_user_args = $args[1];
830
831
		$method       = (string) $json_api_args[0];
832
		$url          = (string) $json_api_args[1];
833
		$post_body    = is_null( $json_api_args[2] ) ? null : (string) $json_api_args[2];
834
		$user_details = (array) $json_api_args[4];
835
		$locale       = (string) $json_api_args[5];
836
837
		if ( ! $verify_api_user_args ) {
838
			$user_id = 0;
839
		} elseif ( 'internal' === $verify_api_user_args[0] ) {
840
			$user_id = (int) $verify_api_user_args[1];
841
			if ( $user_id ) {
842
				$user = get_user_by( 'id', $user_id );
843
				if ( ! $user || is_wp_error( $user ) ) {
844
					return false;
845
				}
846
			}
847
		} else {
848
			$user_id = call_user_func( array( $this, 'test_api_user_code' ), $verify_api_user_args );
849
			if ( ! $user_id ) {
850
				return false;
851
			}
852
		}
853
854
		/* phpcs:ignore
855
		 debugging
856
		error_log( "-- begin json api via jetpack debugging -- " );
857
		error_log( "METHOD: $method" );
858
		error_log( "URL: $url" );
859
		error_log( "POST BODY: $post_body" );
860
		error_log( "VERIFY_ARGS: " . print_r( $verify_api_user_args, 1 ) );
861
		error_log( "VERIFIED USER_ID: " . (int) $user_id );
862
		error_log( "-- end json api via jetpack debugging -- " );
863
		*/
864
865
		if ( 'en' !== $locale ) {
866
			// .org mo files are named slightly different from .com, and all we have is this the locale -- try to guess them.
867
			$new_locale = $locale;
868
			if ( strpos( $locale, '-' ) !== false ) {
869
				$locale_pieces = explode( '-', $locale );
870
				$new_locale    = $locale_pieces[0];
871
				$new_locale   .= ( ! empty( $locale_pieces[1] ) ) ? '_' . strtoupper( $locale_pieces[1] ) : '';
872
			} else {
873
				// .com might pass 'fr' because thats what our language files are named as, where core seems
874
				// to do fr_FR - so try that if we don't think we can load the file.
875
				if ( ! file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {
876
					$new_locale = $locale . '_' . strtoupper( $locale );
877
				}
878
			}
879
880
			if ( file_exists( WP_LANG_DIR . '/' . $new_locale . '.mo' ) ) {
881
				unload_textdomain( 'default' );
882
				load_textdomain( 'default', WP_LANG_DIR . '/' . $new_locale . '.mo' );
883
			}
884
		}
885
886
		$old_user = wp_get_current_user();
887
		wp_set_current_user( $user_id );
888
889
		if ( $user_id ) {
890
			$token_key = false;
891
		} else {
892
			$verified  = $this->connection->verify_xml_rpc_signature();
893
			$token_key = $verified['token_key'];
894
		}
895
896
		$token = $this->connection->get_access_token( $user_id, $token_key );
897
		if ( ! $token || is_wp_error( $token ) ) {
898
			return false;
899
		}
900
901
		define( 'REST_API_REQUEST', true );
902
		define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
903
904
		// needed?
905
		require_once ABSPATH . 'wp-admin/includes/admin.php';
906
907
		require_once JETPACK__PLUGIN_DIR . 'class.json-api.php';
908
		$api                        = WPCOM_JSON_API::init( $method, $url, $post_body );
909
		$api->token_details['user'] = $user_details;
910
		require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
911
912
		$display_errors = ini_set( 'display_errors', 0 ); // phpcs:ignore WordPress.PHP.IniSet
913
		ob_start();
914
		$api->serve( false );
915
		$output = ob_get_clean();
916
		ini_set( 'display_errors', $display_errors ); // phpcs:ignore WordPress.PHP.IniSet
917
918
		$nonce = wp_generate_password( 10, false );
919
		$hmac  = hash_hmac( 'md5', $nonce . $output, $token->secret );
920
921
		wp_set_current_user( isset( $old_user->ID ) ? $old_user->ID : 0 );
922
923
		return array(
924
			(string) $output,
925
			(string) $nonce,
926
			(string) $hmac,
927
		);
928
	}
929
930
	/**
931
	 * Handles authorization actions after connecting a site, such as enabling modules.
932
	 *
933
	 * This do_post_authorization() is used in this class, as opposed to calling
934
	 * Jetpack::handle_post_authorization_actions() directly so that we can mock this method as necessary.
935
	 *
936
	 * @return void
937
	 */
938
	public function do_post_authorization() {
939
		/** This filter is documented in class.jetpack-cli.php */
940
		$enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
941
		Jetpack::handle_post_authorization_actions( $enable_sso, false, false );
942
	}
943
}
944