Completed
Push — branch-5.9-built ( 2c7d25...e32972 )
by
unknown
42:22 queued 33:02
created

Jetpack_XMLRPC_Server::remote_provision()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 46
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 24
nc 10
nop 1
dl 0
loc 46
rs 5.5555
c 0
b 0
f 0
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
		);
27
28
		$this->user = $this->login();
29
30
		if ( $this->user ) {
31
			$jetpack_methods = array_merge( $jetpack_methods, array(
32
				'jetpack.testConnection'    => array( $this, 'test_connection' ),
33
				'jetpack.testAPIUserCode'   => array( $this, 'test_api_user_code' ),
34
				'jetpack.featuresAvailable' => array( $this, 'features_available' ),
35
				'jetpack.featuresEnabled'   => array( $this, 'features_enabled' ),
36
				'jetpack.disconnectBlog'    => array( $this, 'disconnect_blog' ),
37
				'jetpack.unlinkUser'        => array( $this, 'unlink_user' ),
38
				'jetpack.syncObject'        => array( $this, 'sync_object' ),
39
				'jetpack.idcUrlValidation'  => array( $this, 'validate_urls_for_idc_mitigation' ),
40
			) );
41
42
			if ( isset( $core_methods['metaWeblog.editPost'] ) ) {
43
				$jetpack_methods['metaWeblog.newMediaObject'] = $core_methods['metaWeblog.newMediaObject'];
44
				$jetpack_methods['jetpack.updateAttachmentParent'] = array( $this, 'update_attachment_parent' );
45
			}
46
47
			/**
48
			 * Filters the XML-RPC methods available to Jetpack for authenticated users.
49
			 *
50
			 * @since 1.1.0
51
			 *
52
			 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
53
			 * @param array $core_methods Available core XML-RPC methods.
54
			 * @param WP_User $user Information about a given WordPress user.
55
			 */
56
			$jetpack_methods = apply_filters( 'jetpack_xmlrpc_methods', $jetpack_methods, $core_methods, $this->user );
57
		}
58
59
		/**
60
		 * Filters the XML-RPC methods available to Jetpack for unauthenticated users.
61
		 *
62
		 * @since 3.0.0
63
		 *
64
		 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
65
		 * @param array $core_methods Available core XML-RPC methods.
66
		 */
67
		return apply_filters( 'jetpack_xmlrpc_unauthenticated_methods', $jetpack_methods, $core_methods );
68
	}
69
70
	/**
71
	 * Whitelist of the bootstrap XML-RPC methods
72
	 */
73
	function bootstrap_xmlrpc_methods() {
74
		return array(
75
			'jetpack.verifyRegistration' => array( $this, 'verify_registration' ),
76
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
77
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
78
		);
79
	}
80
81
	function authorize_xmlrpc_methods() {
82
		return array(
83
			'jetpack.remoteAuthorize' => array( $this, 'remote_authorize' ),
84
			'jetpack.remoteProvision' => array( $this, 'remote_provision' ),
85
		);
86
	}
87
88
	function remote_authorize( $request ) {
89
		$user = get_user_by( 'id', $request['state'] );
90
		JetpackTracking::record_user_event( 'jpc_remote_authorize_begin', array(), $user );
91
92
		foreach( array( 'secret', 'state', 'redirect_uri', 'code' ) as $required ) {
93
			if ( ! isset( $request[ $required ] ) || empty( $request[ $required ] ) ) {
94
				return $this->error( new Jetpack_Error( 'missing_parameter', 'One or more parameters is missing from the request.', 400 ), 'jpc_remote_authorize_fail' );
95
			}
96
		}
97
98
		if ( ! $user ) {
99
			return $this->error( new Jetpack_Error( 'user_unknown', 'User not found.', 404 ), 'jpc_remote_authorize_fail' );
100
		}
101
102
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $request['state'] ) ) {
103
			return $this->error( new Jetpack_Error( 'already_connected', 'User already connected.', 400 ), 'jpc_remote_authorize_fail' );
104
		}
105
106
		$verified = $this->verify_action( array( 'authorize', $request['secret'], $request['state'] ) );
107
108
		if ( is_a( $verified, 'IXR_Error' ) ) {
109
			return $this->error( $verified, 'jpc_remote_authorize_fail' );
110
		}
111
112
		wp_set_current_user( $request['state'] );
113
114
		$client_server = new Jetpack_Client_Server;
115
		$result = $client_server->authorize( $request );
116
117
		if ( is_wp_error( $result ) ) {
118
			return $this->error( $result, 'jpc_remote_authorize_fail' );
119
		}
120
121
		JetpackTracking::record_user_event( 'jpc_remote_authorize_success' );
122
123
		$response = array(
124
			'result' => $result,
125
		);
126
		return $response;
127
	}
128
129
	function remote_provision( $request ) {
130
		if ( ! isset( $request['access_token'] ) ) {
131
			return $this->error( new Jetpack_Error( 'access_token_missing', sprintf( 'The required "%s" parameter is missing.', 'access_token' ), 400 ), 'jpc_remote_provision_fail' );
132
		}
133
134
		if ( ! isset( $request['local_username'] ) ) {
135
			return $this->error( new Jetpack_Error( 'local_username_missing', sprintf( 'The required "%s" parameter is missing.', 'local_username' ), 400 ), 'jpc_remote_provision_fail' );
136
		}
137
138
		$access_token = $request['access_token'];
139
		$local_username = $request['local_username'];
140
141
		$user = get_user_by( 'login', $local_username );
142
143
		if ( ! $user ) {
144
			$user = get_user_by( 'email', $local_username );
145
		}
146
147
		if ( ! $user ) {
148
			return $this->error( new Jetpack_Error( 'user_unknown', 'User not found.', 404 ) );
149
		}
150
151
		require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';
152
153
		wp_set_current_user( $user->ID );
154
155
		// filter allowed parameters
156
		$allowed_provision_args = array( 'access_token', 'wpcom_user_id', 'wpcom_user_email', 'local_username', 'plan', 'force_register', 'force_connect', 'onboarding', 'partner_tracking_id' );
157
		$args = array_intersect_key(
158
			$request,
159
			array_flip( $allowed_provision_args )
160
		);
161
162
		$result = Jetpack_Provision::partner_provision( $access_token, $args );
163
164
		if ( is_wp_error( $result ) ) {
165
			return $this->error( $result, 'jpc_remote_provision_fail' );
166
		}
167
168
		// this is to prevent us from returning the access_token secret via a potentially unsecured channel.
169
		if ( isset( $result->access_token ) && ! empty( $result->access_token ) ) {
170
			unset( $result->access_token );
171
		}
172
173
		return $result;
174
	}
175
176
	private function tracks_record_error( $name, $error, $user = null ) {
177
		if ( is_wp_error( $error ) ) {
178
			JetpackTracking::record_user_event( $name, array(
179
				'error_code' => $error->get_error_code(),
180
				'error_message' => $error->get_error_message()
181
			), $user );
182
		} elseif( is_a( $error, 'IXR_Error' ) ) {
183
			JetpackTracking::record_user_event( $name, array(
184
				'error_code' => $error->code,
185
				'error_message' => $error->message
186
			), $user );
187
		}
188
189
		return $error;
190
	}
191
192
	/**
193
	* Verifies that Jetpack.WordPress.com received a registration request from this site
194
	*/
195
	function verify_registration( $data ) {
196
		// failure modes will be recorded in tracks in the verify_action method
197
		return $this->verify_action( array( 'register', $data[0], $data[1] ) );
198
	}
199
200
	/**
201
	 * @return WP_Error|string secret_2 on success, WP_Error( error_code => error_code, error_message => error description, error_data => status code ) on failure
202
	 *
203
	 * Possible error_codes:
204
	 *
205
	 * verify_secret_1_missing
206
	 * verify_secret_1_malformed
207
	 * verify_secrets_missing: verification secrets are not found in database
208
	 * verify_secrets_incomplete: verification secrets are only partially found in database
209
	 * verify_secrets_expired: verification secrets have expired
210
	 * verify_secrets_mismatch: stored secret_1 does not match secret_1 sent by Jetpack.WordPress.com
211
	 * state_missing: required parameter of state not found
212
	 * state_malformed: state is not a digit
213
	 * invalid_state: state in request does not match the stored state
214
	 *
215
	 * The 'authorize' and 'register' actions have additional error codes
216
	 *
217
	 * state_missing: a state ( user id ) was not supplied
218
	 * state_malformed: state is not the correct data type
219
	 * invalid_state: supplied state does not match the stored state
220
	 */
221
	function verify_action( $params ) {
222
		$action = $params[0];
223
		$verify_secret = $params[1];
224
		$state = isset( $params[2] ) ? $params[2] : '';
225
		$user = get_user_by( 'id', $state );
226
		JetpackTracking::record_user_event( 'jpc_verify_' . $action . '_begin', array(), $user );
227
		$tracks_failure_event_name = 'jpc_verify_' . $action . '_fail';
228
229
		if ( empty( $verify_secret ) ) {
230
			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 );
231
		} else if ( ! is_string( $verify_secret ) ) {
232
			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 );
233
		} else if ( empty( $state ) ) {
234
			return $this->error( new Jetpack_Error( 'state_missing', sprintf( 'The required "%s" parameter is missing.', 'state' ), 400 ), $tracks_failure_event_name, $user );
235
		} else if ( ! ctype_digit( $state ) ) {
236
			return $this->error( new Jetpack_Error( 'state_malformed', sprintf( 'The required "%s" parameter is malformed.', 'state' ), 400 ), $tracks_failure_event_name, $user );
237
		}
238
239
		$secrets = Jetpack::get_secrets( $action, $state );
240
241
		if ( ! $secrets ) {
242
			Jetpack::delete_secrets( $action, $state );
243
			return $this->error( new Jetpack_Error( 'verify_secrets_missing', 'Verification secrets not found', 400 ), $tracks_failure_event_name, $user );
244
		}
245
246
		if ( is_wp_error( $secrets ) ) {
247
			Jetpack::delete_secrets( $action, $state );
248
			return $this->error( new Jetpack_Error( $secrets->get_error_code(), $secrets->get_error_message(), 400 ), $tracks_failure_event_name, $user );
249
		}
250
251
		if ( empty( $secrets['secret_1'] ) || empty( $secrets['secret_2'] ) || empty( $secrets['exp'] ) ) {
252
			Jetpack::delete_secrets( $action, $state );
253
			return $this->error( new Jetpack_Error( 'verify_secrets_incomplete', 'Verification secrets are incomplete', 400 ), $tracks_failure_event_name, $user );
254
		}
255
256
		if ( ! hash_equals( $verify_secret, $secrets['secret_1'] ) ) {
257
			Jetpack::delete_secrets( $action, $state );
258
			return $this->error( new Jetpack_Error( 'verify_secrets_mismatch', 'Secret mismatch', 400 ), $tracks_failure_event_name, $user );
259
		}
260
261
		Jetpack::delete_secrets( $action, $state );
262
263
		JetpackTracking::record_user_event( 'jpc_verify_' . $action . '_success', array(), $user );
264
265
		return $secrets['secret_2'];
266
	}
267
268
	/**
269
	 * Wrapper for wp_authenticate( $username, $password );
270
	 *
271
	 * @return WP_User|bool
272
	 */
273
	function login() {
274
		Jetpack::init()->require_jetpack_authentication();
275
		$user = wp_authenticate( 'username', 'password' );
276
		if ( is_wp_error( $user ) ) {
277
			if ( 'authentication_failed' == $user->get_error_code() ) { // Generic error could mean most anything.
278
				$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
279
			} else {
280
				$this->error = $user;
281
			}
282
			return false;
283
		} else if ( !$user ) { // Shouldn't happen.
284
			$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
285
			return false;
286
		}
287
288
		return $user;
289
	}
290
291
	/**
292
	 * Returns the current error as an IXR_Error
293
	 *
294
	 * @return bool|IXR_Error
295
	 */
296
	function error( $error = null, $tracks_event_name = null, $user = null ) {
297
		// record using Tracks
298
		if ( null !== $tracks_event_name ) {
299
			$this->tracks_record_error( $tracks_event_name, $error, $user );
300
		}
301
302
		if ( !is_null( $error ) ) {
303
			$this->error = $error;
304
		}
305
306
		if ( is_wp_error( $this->error ) ) {
307
			$code = $this->error->get_error_data();
308
			if ( !$code ) {
309
				$code = -10520;
310
			}
311
			$message = sprintf( 'Jetpack: [%s] %s', $this->error->get_error_code(), $this->error->get_error_message() );
312
			return new IXR_Error( $code, $message );
313
		} else if ( is_a( $this->error, 'IXR_Error' ) ) {
314
			return $this->error;
315
		}
316
317
		return false;
318
	}
319
320
/* API Methods */
321
322
	/**
323
	 * Just authenticates with the given Jetpack credentials.
324
	 *
325
	 * @return string The current Jetpack version number
326
	 */
327
	function test_connection() {
328
		return JETPACK__VERSION;
329
	}
330
331
	function test_api_user_code( $args ) {
332
		$client_id = (int) $args[0];
333
		$user_id   = (int) $args[1];
334
		$nonce     = (string) $args[2];
335
		$verify    = (string) $args[3];
336
337
		if ( !$client_id || !$user_id || !strlen( $nonce ) || 32 !== strlen( $verify ) ) {
338
			return false;
339
		}
340
341
		$user = get_user_by( 'id', $user_id );
342
		if ( !$user || is_wp_error( $user ) ) {
343
			return false;
344
		}
345
346
		/* debugging
347
		error_log( "CLIENT: $client_id" );
348
		error_log( "USER:   $user_id" );
349
		error_log( "NONCE:  $nonce" );
350
		error_log( "VERIFY: $verify" );
351
		*/
352
353
		$jetpack_token = Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
354
355
		$api_user_code = get_user_meta( $user_id, "jetpack_json_api_$client_id", true );
356
		if ( !$api_user_code ) {
357
			return false;
358
		}
359
360
		$hmac = hash_hmac( 'md5', json_encode( (object) array(
361
			'client_id' => (int) $client_id,
362
			'user_id'   => (int) $user_id,
363
			'nonce'     => (string) $nonce,
364
			'code'      => (string) $api_user_code,
365
		) ), $jetpack_token->secret );
366
367
		if ( ! hash_equals( $hmac, $verify ) ) {
368
			return false;
369
		}
370
371
		return $user_id;
372
	}
373
374
	/**
375
	* Disconnect this blog from the connected wordpress.com account
376
	* @return boolean
377
	*/
378
	function disconnect_blog() {
379
380
		// For tracking
381
		if ( ! empty( $this->user->ID ) ) {
382
			wp_set_current_user( $this->user->ID );
383
		}
384
385
		Jetpack::log( 'disconnect' );
386
		Jetpack::disconnect();
387
388
		return true;
389
	}
390
391
	/**
392
	 * Unlink a user from WordPress.com
393
	 *
394
	 * This will fail if called by the Master User.
395
	 */
396
	function unlink_user() {
397
		Jetpack::log( 'unlink' );
398
		return Jetpack::unlink_user();
399
	}
400
401
	/**
402
	 * Returns any object that is able to be synced
403
	 */
404
	function sync_object( $args ) {
405
		// e.g. posts, post, 5
406
		list( $module_name, $object_type, $id ) = $args;
407
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-modules.php';
408
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-sender.php';
409
410
		$sync_module = Jetpack_Sync_Modules::get_module( $module_name );
411
		$codec = Jetpack_Sync_Sender::get_instance()->get_codec();
412
413
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
414
	}
415
416
	/**
417
	 * Returns the home URL and site URL for the current site which can be used on the WPCOM side for
418
	 * IDC mitigation to decide whether sync should be allowed if the home and siteurl values differ between WPCOM
419
	 * and the remote Jetpack site.
420
	 *
421
	 * @return array
422
	 */
423
	function validate_urls_for_idc_mitigation() {
424
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
425
		return array(
426
			'home'    => Jetpack_Sync_Functions::home_url(),
427
			'siteurl' => Jetpack_Sync_Functions::site_url(),
428
		);
429
	}
430
431
	/**
432
	 * Returns what features are available. Uses the slug of the module files.
433
	 *
434
	 * @return array
435
	 */
436 View Code Duplication
	function features_available() {
437
		$raw_modules = Jetpack::get_available_modules();
438
		$modules = array();
439
		foreach ( $raw_modules as $module ) {
440
			$modules[] = Jetpack::get_module_slug( $module );
441
		}
442
443
		return $modules;
444
	}
445
446
	/**
447
	 * Returns what features are enabled. Uses the slug of the modules files.
448
	 *
449
	 * @return array
450
	 */
451 View Code Duplication
	function features_enabled() {
452
		$raw_modules = Jetpack::get_active_modules();
453
		$modules = array();
454
		foreach ( $raw_modules as $module ) {
455
			$modules[] = Jetpack::get_module_slug( $module );
456
		}
457
458
		return $modules;
459
	}
460
461
	function update_attachment_parent( $args ) {
462
		$attachment_id = (int) $args[0];
463
		$parent_id     = (int) $args[1];
464
465
		return wp_update_post( array(
466
			'ID'          => $attachment_id,
467
			'post_parent' => $parent_id,
468
		) );
469
	}
470
471
	function json_api( $args = array() ) {
472
		$json_api_args = $args[0];
473
		$verify_api_user_args = $args[1];
474
475
		$method       = (string) $json_api_args[0];
476
		$url          = (string) $json_api_args[1];
477
		$post_body    = is_null( $json_api_args[2] ) ? null : (string) $json_api_args[2];
478
		$user_details = (array) $json_api_args[4];
479
		$locale       = (string) $json_api_args[5];
480
481
		if ( !$verify_api_user_args ) {
482
			$user_id = 0;
483
		} elseif ( 'internal' === $verify_api_user_args[0] ) {
484
			$user_id = (int) $verify_api_user_args[1];
485
			if ( $user_id ) {
486
				$user = get_user_by( 'id', $user_id );
487
				if ( !$user || is_wp_error( $user ) ) {
488
					return false;
489
				}
490
			}
491
		} else {
492
			$user_id = call_user_func( array( $this, 'test_api_user_code' ), $verify_api_user_args );
493
			if ( !$user_id ) {
494
				return false;
495
			}
496
		}
497
498
		/* debugging
499
		error_log( "-- begin json api via jetpack debugging -- " );
500
		error_log( "METHOD: $method" );
501
		error_log( "URL: $url" );
502
		error_log( "POST BODY: $post_body" );
503
		error_log( "VERIFY_ARGS: " . print_r( $verify_api_user_args, 1 ) );
504
		error_log( "VERIFIED USER_ID: " . (int) $user_id );
505
		error_log( "-- end json api via jetpack debugging -- " );
506
		*/
507
508
		if ( 'en' !== $locale ) {
509
			// .org mo files are named slightly different from .com, and all we have is this the locale -- try to guess them.
510
			$new_locale = $locale;
511
			if ( strpos( $locale, '-' ) !== false ) {
512
				$locale_pieces = explode( '-', $locale );
513
				$new_locale = $locale_pieces[0];
514
				$new_locale .= ( ! empty( $locale_pieces[1] ) ) ? '_' . strtoupper( $locale_pieces[1] ) : '';
515
			} else {
516
				// .com might pass 'fr' because thats what our language files are named as, where core seems
517
				// to do fr_FR - so try that if we don't think we can load the file.
518
				if ( ! file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {
519
					$new_locale =  $locale . '_' . strtoupper( $locale );
520
				}
521
			}
522
523
			if ( file_exists( WP_LANG_DIR . '/' . $new_locale . '.mo' ) ) {
524
				unload_textdomain( 'default' );
525
				load_textdomain( 'default', WP_LANG_DIR . '/' . $new_locale . '.mo' );
526
			}
527
		}
528
529
		$old_user = wp_get_current_user();
530
		wp_set_current_user( $user_id );
531
532
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
533
		if ( !$token || is_wp_error( $token ) ) {
534
			return false;
535
		}
536
537
		define( 'REST_API_REQUEST', true );
538
		define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
539
540
		// needed?
541
		require_once ABSPATH . 'wp-admin/includes/admin.php';
542
543
		require_once JETPACK__PLUGIN_DIR . 'class.json-api.php';
544
		$api = WPCOM_JSON_API::init( $method, $url, $post_body );
545
		$api->token_details['user'] = $user_details;
546
		require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
547
548
		$display_errors = ini_set( 'display_errors', 0 );
549
		ob_start();
550
		$content_type = $api->serve( false );
0 ignored issues
show
Unused Code introduced by
$content_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
551
		$output = ob_get_clean();
552
		ini_set( 'display_errors', $display_errors );
553
554
		$nonce = wp_generate_password( 10, false );
555
		$hmac  = hash_hmac( 'md5', $nonce . $output, $token->secret );
556
557
		wp_set_current_user( isset( $old_user->ID ) ? $old_user->ID : 0 );
558
559
		return array(
560
			(string) $output,
561
			(string) $nonce,
562
			(string) $hmac,
563
		);
564
	}
565
}
566