Completed
Push — branch-7.5-sans-dna ( 35efd3...c0f9d3 )
by
unknown
09:27
created

class.jetpack-xmlrpc-server.php (2 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/**
4
 * Just a sack of functions.  Not actually an IXR_Server
5
 */
6
class Jetpack_XMLRPC_Server {
7
	/**
8
	 * The current error object
9
	 */
10
	public $error = null;
11
12
	/**
13
	 * The current user
14
	 */
15
	public $user = null;
16
17
	/**
18
	 * Whitelist of the XML-RPC methods available to the Jetpack Server. If the
19
	 * user is not authenticated (->login()) then the methods are never added,
20
	 * so they will get a "does not exist" error.
21
	 */
22
	function xmlrpc_methods( $core_methods ) {
23
		$jetpack_methods = array(
24
			'jetpack.jsonAPI'           => array( $this, 'json_api' ),
25
			'jetpack.verifyAction'      => array( $this, 'verify_action' ),
26
			'jetpack.getUser'           => array( $this, 'get_user' ),
27
			'jetpack.remoteRegister'    => array( $this, 'remote_register' ),
28
			'jetpack.remoteProvision'   => array( $this, 'remote_provision' ),
29
		);
30
31
		$this->user = $this->login();
32
33
		if ( $this->user ) {
34
			$jetpack_methods = array_merge( $jetpack_methods, array(
35
				'jetpack.testConnection'    => array( $this, 'test_connection' ),
36
				'jetpack.testAPIUserCode'   => array( $this, 'test_api_user_code' ),
37
				'jetpack.featuresAvailable' => array( $this, 'features_available' ),
38
				'jetpack.featuresEnabled'   => array( $this, 'features_enabled' ),
39
				'jetpack.disconnectBlog'    => array( $this, 'disconnect_blog' ),
40
				'jetpack.unlinkUser'        => array( $this, 'unlink_user' ),
41
				'jetpack.syncObject'        => array( $this, 'sync_object' ),
42
				'jetpack.idcUrlValidation'  => array( $this, 'validate_urls_for_idc_mitigation' ),
43
			) );
44
45
			if ( isset( $core_methods['metaWeblog.editPost'] ) ) {
46
				$jetpack_methods['metaWeblog.newMediaObject'] = $core_methods['metaWeblog.newMediaObject'];
47
				$jetpack_methods['jetpack.updateAttachmentParent'] = array( $this, 'update_attachment_parent' );
48
			}
49
50
			/**
51
			 * Filters the XML-RPC methods available to Jetpack for authenticated users.
52
			 *
53
			 * @since 1.1.0
54
			 *
55
			 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
56
			 * @param array $core_methods Available core XML-RPC methods.
57
			 * @param WP_User $user Information about a given WordPress user.
58
			 */
59
			$jetpack_methods = apply_filters( 'jetpack_xmlrpc_methods', $jetpack_methods, $core_methods, $this->user );
60
		}
61
62
		/**
63
		 * Filters the XML-RPC methods available to Jetpack for unauthenticated users.
64
		 *
65
		 * @since 3.0.0
66
		 *
67
		 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
68
		 * @param array $core_methods Available core XML-RPC methods.
69
		 */
70
		return apply_filters( 'jetpack_xmlrpc_unauthenticated_methods', $jetpack_methods, $core_methods );
71
	}
72
73
	/**
74
	 * Whitelist of the bootstrap XML-RPC methods
75
	 */
76
	function bootstrap_xmlrpc_methods() {
77
		return array(
78
			'jetpack.verifyRegistration' => array( $this, 'verify_registration' ),
79
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
80
			'jetpack.remoteRegister' => array( $this, 'remote_register' ),
81
		);
82
	}
83
84
	function authorize_xmlrpc_methods() {
85
		return array(
86
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
87
		);
88
	}
89
90
	function provision_xmlrpc_methods() {
91
		return array(
92
			'jetpack.remoteRegister'  => array( $this, 'remote_register' ),
93
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
94
			'jetpack.remoteConnect'   => array( $this, 'remote_connect' ),
95
			'jetpack.getUser'         => array( $this, 'get_user' ),
96
		);
97
	}
98
99
	/**
100
	 * Used to verify whether a local user exists and what role they have.
101
	 *
102
	 * @param int|string|array $request One of:
103
	 *                         int|string The local User's ID, username, or email address.
104
	 *                         array      A request array containing:
105
	 *                                    0: int|string The local User's ID, username, or email address.
106
	 *
107
	 * @return array|IXR_Error Information about the user, or error if no such user found:
108
	 *                         roles:     string[] The user's rols.
109
	 *                         login:     string   The user's username.
110
	 *                         email_hash string[] The MD5 hash of the user's normalized email address.
111
	 *                         caps       string[] The user's capabilities.
112
	 *                         allcaps    string[] The user's granular capabilities, merged from role capabilities.
113
	 *                         token_key  string   The Token Key of the user's Jetpack token. Empty string if none.
114
	 */
115
	function get_user( $request ) {
116
		$user_id = is_array( $request ) ? $request[0] : $request;
117
118
		if ( ! $user_id ) {
119
			return $this->error(
120
				new Jetpack_Error(
121
					'invalid_user',
122
					__( 'Invalid user identifier.', 'jetpack' ),
123
					400
124
				),
125
				'jpc_get_user_fail'
126
			);
127
		}
128
129
		$user = $this->get_user_by_anything( $user_id );
130
131
		if ( ! $user ) {
132
			return $this->error(
133
				new Jetpack_Error(
134
					'user_unknown',
135
					__( 'User not found.', 'jetpack' ),
136
					404
137
				),
138
				'jpc_get_user_fail'
139
			);
140
		}
141
142
		$connection = Jetpack::connection();
0 ignored issues
show
The method connection() does not exist on Jetpack. Did you maybe mean jetpack_connection_banner_callback()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
143
		$user_token = $connection->get_access_token( $user->ID );
144
145
		if ( $user_token ) {
146
			list( $user_token_key, $user_token_private ) = explode( '.', $user_token->secret );
0 ignored issues
show
The assignment to $user_token_private is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
147
			if ( $user_token_key === $user_token->secret ) {
148
				$user_token_key = '';
149
			}
150
		} else {
151
			$user_token_key = '';
152
		}
153
154
		return array(
155
			'id'         => $user->ID,
156
			'login'      => $user->user_login,
157
			'email_hash' => md5( strtolower( trim( $user->user_email ) ) ),
158
			'roles'      => $user->roles,
159
			'caps'       => $user->caps,
160
			'allcaps'    => $user->allcaps,
161
			'token_key'  => $user_token_key,
162
		);
163
	}
164
165
	function remote_authorize( $request ) {
166
		$user = get_user_by( 'id', $request['state'] );
167
		JetpackTracking::record_user_event( 'jpc_remote_authorize_begin', array(), $user );
168
169
		foreach( array( 'secret', 'state', 'redirect_uri', 'code' ) as $required ) {
170
			if ( ! isset( $request[ $required ] ) || empty( $request[ $required ] ) ) {
171
				return $this->error( new Jetpack_Error( 'missing_parameter', 'One or more parameters is missing from the request.', 400 ), 'jpc_remote_authorize_fail' );
172
			}
173
		}
174
175
		if ( ! $user ) {
176
			return $this->error( new Jetpack_Error( 'user_unknown', 'User not found.', 404 ), 'jpc_remote_authorize_fail' );
177
		}
178
179
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $request['state'] ) ) {
180
			return $this->error( new Jetpack_Error( 'already_connected', 'User already connected.', 400 ), 'jpc_remote_authorize_fail' );
181
		}
182
183
		$verified = $this->verify_action( array( 'authorize', $request['secret'], $request['state'] ) );
184
185
		if ( is_a( $verified, 'IXR_Error' ) ) {
186
			return $this->error( $verified, 'jpc_remote_authorize_fail' );
187
		}
188
189
		wp_set_current_user( $request['state'] );
190
191
		$client_server = new Jetpack_Client_Server;
192
		$result = $client_server->authorize( $request );
193
194
		if ( is_wp_error( $result ) ) {
195
			return $this->error( $result, 'jpc_remote_authorize_fail' );
196
		}
197
198
		JetpackTracking::record_user_event( 'jpc_remote_authorize_success' );
199
200
		return array(
201
			'result' => $result,
202
		);
203
	}
204
205
	/**
206
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
207
	 * register this site so that a plan can be provisioned.
208
	 *
209
	 * @param array $request An array containing at minimum nonce and local_user keys.
210
	 *
211
	 * @return WP_Error|array
212
	 */
213
	public function remote_register( $request ) {
214
		JetpackTracking::record_user_event( 'jpc_remote_register_begin', array() );
215
216
		$user = $this->fetch_and_verify_local_user( $request );
217
218
		if ( ! $user ) {
219
			return $this->error( new WP_Error( 'input_error', __( 'Valid user is required', 'jetpack' ), 400 ), 'jpc_remote_register_fail' );
220
		}
221
222
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
223
			return $this->error( $user, 'jpc_remote_register_fail' );
224
		}
225
226
		if ( empty( $request['nonce'] ) ) {
227
			return $this->error(
228
				new Jetpack_Error(
229
					'nonce_missing',
230
					__( 'The required "nonce" parameter is missing.', 'jetpack' ),
231
					400
232
				),
233
				'jpc_remote_register_fail'
234
			);
235
		}
236
237
		$nonce = sanitize_text_field( $request['nonce'] );
238
		unset( $request['nonce'] );
239
240
		$api_url  = Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'partner_provision_nonce_check' ) );
241
		$response = Jetpack_Client::_wp_remote_request(
242
			esc_url_raw( add_query_arg( 'nonce', $nonce, $api_url ) ),
243
			array( 'method' => 'GET' ),
244
			true
245
		);
246
247
		if (
248
			200 !== wp_remote_retrieve_response_code( $response ) ||
249
			'OK' !== trim( wp_remote_retrieve_body( $response ) )
250
		) {
251
			return $this->error(
252
				new Jetpack_Error(
253
					'invalid_nonce',
254
					__( 'There was an issue validating this request.', 'jetpack' ),
255
					400
256
				),
257
				'jpc_remote_register_fail'
258
			);
259
		}
260
261
		if ( ! Jetpack_Options::get_option( 'id' ) || ! Jetpack_Data::get_access_token() || ! empty( $request['force'] ) ) {
262
			wp_set_current_user( $user->ID );
263
264
			// This code mostly copied from Jetpack::admin_page_load.
265
			Jetpack::maybe_set_version_option();
266
			$registered = Jetpack::try_registration();
267
			if ( is_wp_error( $registered ) ) {
268
				return $this->error( $registered, 'jpc_remote_register_fail' );
269
			} elseif ( ! $registered ) {
270
				return $this->error(
271
					new Jetpack_Error(
272
						'registration_error',
273
						__( 'There was an unspecified error registering the site', 'jetpack' ),
274
						400
275
					),
276
					'jpc_remote_register_fail'
277
				);
278
			}
279
		}
280
281
		JetpackTracking::record_user_event( 'jpc_remote_register_success' );
282
283
		return array(
284
			'client_id' => Jetpack_Options::get_option( 'id' )
285
		);
286
	}
287
288
	/**
289
	 * This XML-RPC method is called from the /jpphp/provision endpoint on WPCOM in order to
290
	 * register this site so that a plan can be provisioned.
291
	 *
292
	 * @param array $request An array containing at minimum a nonce key and a local_username key.
293
	 *
294
	 * @return WP_Error|array
295
	 */
296
	public function remote_provision( $request ) {
297
		$user = $this->fetch_and_verify_local_user( $request );
298
299
		if ( ! $user ) {
300
			return $this->error( new WP_Error( 'input_error', __( 'Valid user is required', 'jetpack' ), 400 ), 'jpc_remote_provision_fail' );
301
		}
302
303
		if ( is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
304
			return $this->error( $user, 'jpc_remote_provision_fail' );
305
		}
306
307
		$site_icon = get_site_icon_url();
308
309
		$auto_enable_sso = ( ! Jetpack::is_active() || Jetpack::is_module_active( 'sso' ) );
310
311
		/** This filter is documented in class.jetpack-cli.php */
312 View Code Duplication
		if ( apply_filters( 'jetpack_start_enable_sso', $auto_enable_sso ) ) {
313
			$redirect_uri = add_query_arg(
314
				array(
315
					'action'      => 'jetpack-sso',
316
					'redirect_to' => rawurlencode( admin_url() ),
317
				),
318
				wp_login_url() // TODO: come back to Jetpack dashboard?
319
			);
320
		} else {
321
			$redirect_uri = admin_url();
322
		}
323
324
		// Generate secrets.
325
		$role    = Jetpack::translate_user_to_role( $user );
326
		$secrets = Jetpack::init()->generate_secrets( 'authorize', $user->ID );
327
328
		$response = array(
329
			'jp_version'   => JETPACK__VERSION,
330
			'redirect_uri' => $redirect_uri,
331
			'user_id'      => $user->ID,
332
			'user_email'   => $user->user_email,
333
			'user_login'   => $user->user_login,
334
			'scope'        => Jetpack::sign_role( $role, $user->ID ),
335
			'secret'       => $secrets['secret_1'],
336
			'is_active'    => Jetpack::is_active(),
337
		);
338
339
		if ( $site_icon ) {
340
			$response['site_icon'] = $site_icon;
341
		}
342
343
		if ( ! empty( $request['onboarding'] ) ) {
344
			Jetpack::create_onboarding_token();
345
			$response['onboarding_token'] = Jetpack_Options::get_option( 'onboarding' );
346
		}
347
348
		return $response;
349
	}
350
351
	/**
352
	 * Given an array containing a local user identifier and a nonce, will attempt to fetch and set
353
	 * an access token for the given user.
354
	 *
355
	 * @param array $request An array containing local_user and nonce keys at minimum.
356
	 * @return mixed
357
	 */
358
	public function remote_connect( $request, $ixr_client = false ) {
359
		if ( Jetpack::is_active() ) {
360
			return $this->error(
361
				new WP_Error(
362
					'already_connected',
363
					__( 'Jetpack is already connected.', 'jetpack' ),
364
					400
365
				),
366
				'jpc_remote_connect_fail'
367
			);
368
		}
369
370
		$user = $this->fetch_and_verify_local_user( $request );
371
372
		if ( ! $user || is_wp_error( $user ) || is_a( $user, 'IXR_Error' ) ) {
373
			return $this->error(
374
				new WP_Error(
375
					'input_error',
376
					__( 'Valid user is required.', 'jetpack' ),
377
					400
378
				),
379
				'jpc_remote_connect_fail'
380
			);
381
		}
382
383
		if ( empty( $request['nonce'] ) ) {
384
			return $this->error(
385
				new WP_Error(
386
					'input_error',
387
					__( 'A non-empty nonce must be supplied.', 'jetpack' ),
388
					400
389
				),
390
				'jpc_remote_connect_fail'
391
			);
392
		}
393
394
		if ( ! $ixr_client ) {
395
			Jetpack::load_xml_rpc_client();
396
			$ixr_client = new Jetpack_IXR_Client();
397
		}
398
		$ixr_client->query( 'jetpack.getUserAccessToken', array(
399
			'nonce'            => sanitize_text_field( $request['nonce'] ),
400
			'external_user_id' => $user->ID,
401
		) );
402
403
		$token = $ixr_client->isError() ? false : $ixr_client->getResponse();
404
		if ( empty( $token ) ) {
405
			return $this->error(
406
				new WP_Error(
407
					'token_fetch_failed',
408
					__( 'Failed to fetch user token from WordPress.com.', 'jetpack' ),
409
					400
410
				),
411
				'jpc_remote_connect_fail'
412
			);
413
		}
414
		$token = sanitize_text_field( $token );
415
416
		Jetpack::update_user_token( $user->ID, sprintf( '%s.%d', $token, $user->ID ), true );
417
418
		$this->do_post_authorization();
419
420
		return Jetpack::is_active();
421
	}
422
423
	private function fetch_and_verify_local_user( $request ) {
424
		if ( empty( $request['local_user'] ) ) {
425
			return $this->error(
426
				new Jetpack_Error(
427
					'local_user_missing',
428
					__( 'The required "local_user" parameter is missing.', 'jetpack' ),
429
					400
430
				),
431
				'jpc_remote_provision_fail'
432
			);
433
		}
434
435
		// local user is used to look up by login, email or ID
436
		$local_user_info = $request['local_user'];
437
438
		return $this->get_user_by_anything( $local_user_info );
439
	}
440
441
	private function get_user_by_anything( $user_id ) {
442
		$user = get_user_by( 'login', $user_id );
443
444
		if ( ! $user ) {
445
			$user = get_user_by( 'email', $user_id );
446
		}
447
448
		if ( ! $user ) {
449
			$user = get_user_by( 'ID', $user_id );
450
		}
451
452
		return $user;
453
	}
454
455
	private function tracks_record_error( $name, $error, $user = null ) {
456
		if ( is_wp_error( $error ) ) {
457
			JetpackTracking::record_user_event( $name, array(
458
				'error_code' => $error->get_error_code(),
459
				'error_message' => $error->get_error_message()
460
			), $user );
461
		} elseif( is_a( $error, 'IXR_Error' ) ) {
462
			JetpackTracking::record_user_event( $name, array(
463
				'error_code' => $error->code,
464
				'error_message' => $error->message
465
			), $user );
466
		}
467
468
		return $error;
469
	}
470
471
	/**
472
	* Verifies that Jetpack.WordPress.com received a registration request from this site
473
	*/
474
	function verify_registration( $data ) {
475
		// failure modes will be recorded in tracks in the verify_action method
476
		return $this->verify_action( array( 'register', $data[0], $data[1] ) );
477
	}
478
479
	/**
480
	 * @return WP_Error|string secret_2 on success, WP_Error( error_code => error_code, error_message => error description, error_data => status code ) on failure
481
	 *
482
	 * Possible error_codes:
483
	 *
484
	 * verify_secret_1_missing
485
	 * verify_secret_1_malformed
486
	 * verify_secrets_missing: verification secrets are not found in database
487
	 * verify_secrets_incomplete: verification secrets are only partially found in database
488
	 * verify_secrets_expired: verification secrets have expired
489
	 * verify_secrets_mismatch: stored secret_1 does not match secret_1 sent by Jetpack.WordPress.com
490
	 * state_missing: required parameter of state not found
491
	 * state_malformed: state is not a digit
492
	 * invalid_state: state in request does not match the stored state
493
	 *
494
	 * The 'authorize' and 'register' actions have additional error codes
495
	 *
496
	 * Possible values for action are `authorize`, `publicize` and `register`.
497
	 *
498
	 * state_missing: a state ( user id ) was not supplied
499
	 * state_malformed: state is not the correct data type
500
	 * invalid_state: supplied state does not match the stored state
501
	 */
502
	function verify_action( $params ) {
503
		$action = $params[0];
504
		$verify_secret = $params[1];
505
		$state = isset( $params[2] ) ? $params[2] : '';
506
		$user = get_user_by( 'id', $state );
507
		$tracks_failure_event_name = '';
508
509
		if ( 'authorize' === $action ) {
510
			$tracks_failure_event_name = 'jpc_verify_authorize_fail';
511
			JetpackTracking::record_user_event( 'jpc_verify_authorize_begin', array(), $user );
512
		}
513
		if ( 'publicize' === $action ) {
514
			// This action is used on a response from a direct XML-RPC done from WordPress.com
515
			$tracks_failure_event_name = 'jpc_verify_publicize_fail';
516
			JetpackTracking::record_user_event( 'jpc_verify_publicize_begin', array(), $user );
517
		}
518
		if ( 'register' === $action ) {
519
			$tracks_failure_event_name = 'jpc_verify_register_fail';
520
			JetpackTracking::record_user_event( 'jpc_verify_register_begin', array(), $user );
521
		}
522
523
		if ( empty( $verify_secret ) ) {
524
			return $this->error( new Jetpack_Error( 'verify_secret_1_missing', sprintf( 'The required "%s" parameter is missing.', 'secret_1' ), 400 ), $tracks_failure_event_name, $user );
525
		} else if ( ! is_string( $verify_secret ) ) {
526
			return $this->error( new Jetpack_Error( 'verify_secret_1_malformed', sprintf( 'The required "%s" parameter is malformed.', 'secret_1' ), 400 ), $tracks_failure_event_name, $user );
527
		} else if ( empty( $state ) ) {
528
			return $this->error( new Jetpack_Error( 'state_missing', sprintf( 'The required "%s" parameter is missing.', 'state' ), 400 ), $tracks_failure_event_name, $user );
529
		} else if ( ! ctype_digit( $state ) ) {
530
			return $this->error( new Jetpack_Error( 'state_malformed', sprintf( 'The required "%s" parameter is malformed.', 'state' ), 400 ), $tracks_failure_event_name, $user );
531
		}
532
533
		$secrets = Jetpack::get_secrets( $action, $state );
534
535
		if ( ! $secrets ) {
536
			Jetpack::delete_secrets( $action, $state );
537
			return $this->error( new Jetpack_Error( 'verify_secrets_missing', 'Verification secrets not found', 400 ), $tracks_failure_event_name, $user );
538
		}
539
540
		if ( is_wp_error( $secrets ) ) {
541
			Jetpack::delete_secrets( $action, $state );
542
			return $this->error( new Jetpack_Error( $secrets->get_error_code(), $secrets->get_error_message(), 400 ), $tracks_failure_event_name, $user );
543
		}
544
545
		if ( empty( $secrets['secret_1'] ) || empty( $secrets['secret_2'] ) || empty( $secrets['exp'] ) ) {
546
			Jetpack::delete_secrets( $action, $state );
547
			return $this->error( new Jetpack_Error( 'verify_secrets_incomplete', 'Verification secrets are incomplete', 400 ), $tracks_failure_event_name, $user );
548
		}
549
550
		if ( ! hash_equals( $verify_secret, $secrets['secret_1'] ) ) {
551
			Jetpack::delete_secrets( $action, $state );
552
			return $this->error( new Jetpack_Error( 'verify_secrets_mismatch', 'Secret mismatch', 400 ), $tracks_failure_event_name, $user );
553
		}
554
555
		Jetpack::delete_secrets( $action, $state );
556
557
		if ( 'authorize' === $action ) {
558
			JetpackTracking::record_user_event( 'jpc_verify_authorize_success', array(), $user );
559
		}
560
		if ( 'publicize' === $action ) {
561
			JetpackTracking::record_user_event( 'jpc_verify_publicize_success', array(), $user );
562
		}
563
		if ( 'register' === $action ) {
564
			JetpackTracking::record_user_event( 'jpc_verify_register_success', array(), $user );
565
		}
566
567
		return $secrets['secret_2'];
568
	}
569
570
	/**
571
	 * Wrapper for wp_authenticate( $username, $password );
572
	 *
573
	 * @return WP_User|bool
574
	 */
575
	function login() {
576
		Jetpack::init()->require_jetpack_authentication();
577
		$user = wp_authenticate( 'username', 'password' );
578
		if ( is_wp_error( $user ) ) {
579
			if ( 'authentication_failed' == $user->get_error_code() ) { // Generic error could mean most anything.
580
				$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
581
			} else {
582
				$this->error = $user;
583
			}
584
			return false;
585
		} else if ( !$user ) { // Shouldn't happen.
586
			$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
587
			return false;
588
		}
589
590
		return $user;
591
	}
592
593
	/**
594
	 * Returns the current error as an IXR_Error
595
	 *
596
	 * @return bool|IXR_Error
597
	 */
598
	function error( $error = null, $tracks_event_name = null, $user = null ) {
599
		// record using Tracks
600
		if ( null !== $tracks_event_name ) {
601
			$this->tracks_record_error( $tracks_event_name, $error, $user );
602
		}
603
604
		if ( !is_null( $error ) ) {
605
			$this->error = $error;
606
		}
607
608
		if ( is_wp_error( $this->error ) ) {
609
			$code = $this->error->get_error_data();
610
			if ( !$code ) {
611
				$code = -10520;
612
			}
613
			$message = sprintf( 'Jetpack: [%s] %s', $this->error->get_error_code(), $this->error->get_error_message() );
614
			return new IXR_Error( $code, $message );
615
		} else if ( is_a( $this->error, 'IXR_Error' ) ) {
616
			return $this->error;
617
		}
618
619
		return false;
620
	}
621
622
/* API Methods */
623
624
	/**
625
	 * Just authenticates with the given Jetpack credentials.
626
	 *
627
	 * @return string The current Jetpack version number
628
	 */
629
	function test_connection() {
630
		return JETPACK__VERSION;
631
	}
632
633
	function test_api_user_code( $args ) {
634
		$client_id = (int) $args[0];
635
		$user_id   = (int) $args[1];
636
		$nonce     = (string) $args[2];
637
		$verify    = (string) $args[3];
638
639
		if ( !$client_id || !$user_id || !strlen( $nonce ) || 32 !== strlen( $verify ) ) {
640
			return false;
641
		}
642
643
		$user = get_user_by( 'id', $user_id );
644
		if ( !$user || is_wp_error( $user ) ) {
645
			return false;
646
		}
647
648
		/* debugging
649
		error_log( "CLIENT: $client_id" );
650
		error_log( "USER:   $user_id" );
651
		error_log( "NONCE:  $nonce" );
652
		error_log( "VERIFY: $verify" );
653
		*/
654
655
		$jetpack_token = Jetpack_Data::get_access_token( $user_id );
656
657
		$api_user_code = get_user_meta( $user_id, "jetpack_json_api_$client_id", true );
658
		if ( !$api_user_code ) {
659
			return false;
660
		}
661
662
		$hmac = hash_hmac( 'md5', json_encode( (object) array(
663
			'client_id' => (int) $client_id,
664
			'user_id'   => (int) $user_id,
665
			'nonce'     => (string) $nonce,
666
			'code'      => (string) $api_user_code,
667
		) ), $jetpack_token->secret );
668
669
		if ( ! hash_equals( $hmac, $verify ) ) {
670
			return false;
671
		}
672
673
		return $user_id;
674
	}
675
676
	/**
677
	* Disconnect this blog from the connected wordpress.com account
678
	* @return boolean
679
	*/
680
	function disconnect_blog() {
681
682
		// For tracking
683
		if ( ! empty( $this->user->ID ) ) {
684
			wp_set_current_user( $this->user->ID );
685
		}
686
687
		Jetpack::log( 'disconnect' );
688
		Jetpack::disconnect();
689
690
		return true;
691
	}
692
693
	/**
694
	 * Unlink a user from WordPress.com
695
	 *
696
	 * This will fail if called by the Master User.
697
	 */
698
	function unlink_user() {
699
		Jetpack::log( 'unlink' );
700
		return Jetpack::unlink_user();
701
	}
702
703
	/**
704
	 * Returns any object that is able to be synced
705
	 */
706
	function sync_object( $args ) {
707
		// e.g. posts, post, 5
708
		list( $module_name, $object_type, $id ) = $args;
709
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-modules.php';
710
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-sender.php';
711
712
		$sync_module = Jetpack_Sync_Modules::get_module( $module_name );
713
		$codec = Jetpack_Sync_Sender::get_instance()->get_codec();
714
715
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
716
	}
717
718
	/**
719
	 * Returns the home URL and site URL for the current site which can be used on the WPCOM side for
720
	 * IDC mitigation to decide whether sync should be allowed if the home and siteurl values differ between WPCOM
721
	 * and the remote Jetpack site.
722
	 *
723
	 * @return array
724
	 */
725
	function validate_urls_for_idc_mitigation() {
726
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
727
		return array(
728
			'home'    => Jetpack_Sync_Functions::home_url(),
729
			'siteurl' => Jetpack_Sync_Functions::site_url(),
730
		);
731
	}
732
733
	/**
734
	 * Returns what features are available. Uses the slug of the module files.
735
	 *
736
	 * @return array
737
	 */
738 View Code Duplication
	function features_available() {
739
		$raw_modules = Jetpack::get_available_modules();
740
		$modules = array();
741
		foreach ( $raw_modules as $module ) {
742
			$modules[] = Jetpack::get_module_slug( $module );
743
		}
744
745
		return $modules;
746
	}
747
748
	/**
749
	 * Returns what features are enabled. Uses the slug of the modules files.
750
	 *
751
	 * @return array
752
	 */
753 View Code Duplication
	function features_enabled() {
754
		$raw_modules = Jetpack::get_active_modules();
755
		$modules = array();
756
		foreach ( $raw_modules as $module ) {
757
			$modules[] = Jetpack::get_module_slug( $module );
758
		}
759
760
		return $modules;
761
	}
762
763
	function update_attachment_parent( $args ) {
764
		$attachment_id = (int) $args[0];
765
		$parent_id     = (int) $args[1];
766
767
		return wp_update_post( array(
768
			'ID'          => $attachment_id,
769
			'post_parent' => $parent_id,
770
		) );
771
	}
772
773
	function json_api( $args = array() ) {
774
		$json_api_args = $args[0];
775
		$verify_api_user_args = $args[1];
776
777
		$method       = (string) $json_api_args[0];
778
		$url          = (string) $json_api_args[1];
779
		$post_body    = is_null( $json_api_args[2] ) ? null : (string) $json_api_args[2];
780
		$user_details = (array) $json_api_args[4];
781
		$locale       = (string) $json_api_args[5];
782
783
		if ( !$verify_api_user_args ) {
784
			$user_id = 0;
785
		} elseif ( 'internal' === $verify_api_user_args[0] ) {
786
			$user_id = (int) $verify_api_user_args[1];
787
			if ( $user_id ) {
788
				$user = get_user_by( 'id', $user_id );
789
				if ( !$user || is_wp_error( $user ) ) {
790
					return false;
791
				}
792
			}
793
		} else {
794
			$user_id = call_user_func( array( $this, 'test_api_user_code' ), $verify_api_user_args );
795
			if ( !$user_id ) {
796
				return false;
797
			}
798
		}
799
800
		/* debugging
801
		error_log( "-- begin json api via jetpack debugging -- " );
802
		error_log( "METHOD: $method" );
803
		error_log( "URL: $url" );
804
		error_log( "POST BODY: $post_body" );
805
		error_log( "VERIFY_ARGS: " . print_r( $verify_api_user_args, 1 ) );
806
		error_log( "VERIFIED USER_ID: " . (int) $user_id );
807
		error_log( "-- end json api via jetpack debugging -- " );
808
		*/
809
810
		if ( 'en' !== $locale ) {
811
			// .org mo files are named slightly different from .com, and all we have is this the locale -- try to guess them.
812
			$new_locale = $locale;
813
			if ( strpos( $locale, '-' ) !== false ) {
814
				$locale_pieces = explode( '-', $locale );
815
				$new_locale = $locale_pieces[0];
816
				$new_locale .= ( ! empty( $locale_pieces[1] ) ) ? '_' . strtoupper( $locale_pieces[1] ) : '';
817
			} else {
818
				// .com might pass 'fr' because thats what our language files are named as, where core seems
819
				// to do fr_FR - so try that if we don't think we can load the file.
820
				if ( ! file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {
821
					$new_locale =  $locale . '_' . strtoupper( $locale );
822
				}
823
			}
824
825
			if ( file_exists( WP_LANG_DIR . '/' . $new_locale . '.mo' ) ) {
826
				unload_textdomain( 'default' );
827
				load_textdomain( 'default', WP_LANG_DIR . '/' . $new_locale . '.mo' );
828
			}
829
		}
830
831
		$old_user = wp_get_current_user();
832
		wp_set_current_user( $user_id );
833
834
		if ( $user_id ) {
835
			$token_key = false;
836
		} else {
837
			$jetpack   = Jetpack::init();
838
			$verified  = $jetpack->verify_xml_rpc_signature();
839
			$token_key = $verified['token_key'];
840
		}
841
842
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
843
		if ( !$token || is_wp_error( $token ) ) {
844
			return false;
845
		}
846
847
		define( 'REST_API_REQUEST', true );
848
		define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
849
850
		// needed?
851
		require_once ABSPATH . 'wp-admin/includes/admin.php';
852
853
		require_once JETPACK__PLUGIN_DIR . 'class.json-api.php';
854
		$api = WPCOM_JSON_API::init( $method, $url, $post_body );
855
		$api->token_details['user'] = $user_details;
856
		require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
857
858
		$display_errors = ini_set( 'display_errors', 0 );
859
		ob_start();
860
		$content_type = $api->serve( false );
861
		$output = ob_get_clean();
862
		ini_set( 'display_errors', $display_errors );
863
864
		$nonce = wp_generate_password( 10, false );
865
		$hmac  = hash_hmac( 'md5', $nonce . $output, $token->secret );
866
867
		wp_set_current_user( isset( $old_user->ID ) ? $old_user->ID : 0 );
868
869
		return array(
870
			(string) $output,
871
			(string) $nonce,
872
			(string) $hmac,
873
		);
874
	}
875
876
	/**
877
	 * Handles authorization actions after connecting a site, such as enabling modules.
878
	 *
879
	 * This do_post_authorization() is used in this class, as opposed to calling
880
	 * Jetpack::handle_post_authorization_actions() directly so that we can mock this method as necessary.
881
	 *
882
	 * @return void
883
	 */
884
	public function do_post_authorization() {
885
		/** This filter is documented in class.jetpack-cli.php */
886
		$enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
887
		Jetpack::handle_post_authorization_actions( $enable_sso, false, false );
888
	}
889
}
890