Completed
Push — update/partner-provision-via-r... ( 9dc788...9e291f )
by
unknown
18:11 queued 05:03
created

class.jetpack-xmlrpc-server.php (1 issue)

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
		);
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['local_username'] ) ) {
131
			return $this->error( new Jetpack_Error( 'local_username_missing', sprintf( 'The required "%s" parameter is missing.', 'local_username' ), 400 ), 'jpc_remote_provision_fail' );
132
		}
133
134
		$access_token = $request['access_token'];
0 ignored issues
show
$access_token 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...
135
		$local_username = $request['local_username'];
136
137
		$user = get_user_by( 'login', $local_username );
138
139
		if ( ! $user ) {
140
			$user = get_user_by( 'email', $local_username );
141
		}
142
143
		if ( ! $user ) {
144
			return $this->error( new Jetpack_Error( 'user_unknown', 'User not found.', 404 ) );
145
		}
146
147
		require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';
148
149
		wp_set_current_user( $user->ID );
150
151
		// Filter allowed parameters.
152
		$allowed_provision_args = array( 'wpcom_user_id', 'wpcom_user_email', 'local_username', 'plan', 'force_register', 'force_connect', 'onboarding', 'partner_tracking_id' );
153
		$args = array_intersect_key(
154
			$request,
155
			array_flip( $allowed_provision_args )
156
		);
157
158
		$result = Jetpack_Provision::register_and_build_request_body( $args );
159
160
		if ( is_wp_error( $result ) ) {
161
			return $this->error( $result, 'jpc_remote_provision_fail' );
162
		}
163
164
		return $result;
165
	}
166
167
	private function tracks_record_error( $name, $error, $user = null ) {
168
		if ( is_wp_error( $error ) ) {
169
			JetpackTracking::record_user_event( $name, array(
170
				'error_code' => $error->get_error_code(),
171
				'error_message' => $error->get_error_message()
172
			), $user );
173
		} elseif( is_a( $error, 'IXR_Error' ) ) {
174
			JetpackTracking::record_user_event( $name, array(
175
				'error_code' => $error->code,
176
				'error_message' => $error->message
177
			), $user );
178
		}
179
180
		return $error;
181
	}
182
183
	/**
184
	* Verifies that Jetpack.WordPress.com received a registration request from this site
185
	*/
186
	function verify_registration( $data ) {
187
		// failure modes will be recorded in tracks in the verify_action method
188
		return $this->verify_action( array( 'register', $data[0], $data[1] ) );
189
	}
190
191
	/**
192
	 * @return WP_Error|string secret_2 on success, WP_Error( error_code => error_code, error_message => error description, error_data => status code ) on failure
193
	 *
194
	 * Possible error_codes:
195
	 *
196
	 * verify_secret_1_missing
197
	 * verify_secret_1_malformed
198
	 * verify_secrets_missing: verification secrets are not found in database
199
	 * verify_secrets_incomplete: verification secrets are only partially found in database
200
	 * verify_secrets_expired: verification secrets have expired
201
	 * verify_secrets_mismatch: stored secret_1 does not match secret_1 sent by Jetpack.WordPress.com
202
	 * state_missing: required parameter of state not found
203
	 * state_malformed: state is not a digit
204
	 * invalid_state: state in request does not match the stored state
205
	 *
206
	 * The 'authorize' and 'register' actions have additional error codes
207
	 *
208
	 * state_missing: a state ( user id ) was not supplied
209
	 * state_malformed: state is not the correct data type
210
	 * invalid_state: supplied state does not match the stored state
211
	 */
212
	function verify_action( $params ) {
213
		$action = $params[0];
214
		$verify_secret = $params[1];
215
		$state = isset( $params[2] ) ? $params[2] : '';
216
		$user = get_user_by( 'id', $state );
217
		JetpackTracking::record_user_event( 'jpc_verify_' . $action . '_begin', array(), $user );
218
		$tracks_failure_event_name = 'jpc_verify_' . $action . '_fail';
219
220
		if ( empty( $verify_secret ) ) {
221
			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 );
222
		} else if ( ! is_string( $verify_secret ) ) {
223
			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 );
224
		} else if ( empty( $state ) ) {
225
			return $this->error( new Jetpack_Error( 'state_missing', sprintf( 'The required "%s" parameter is missing.', 'state' ), 400 ), $tracks_failure_event_name, $user );
226
		} else if ( ! ctype_digit( $state ) ) {
227
			return $this->error( new Jetpack_Error( 'state_malformed', sprintf( 'The required "%s" parameter is malformed.', 'state' ), 400 ), $tracks_failure_event_name, $user );
228
		}
229
230
		$secrets = Jetpack::get_secrets( $action, $state );
231
232
		if ( ! $secrets ) {
233
			Jetpack::delete_secrets( $action, $state );
234
			return $this->error( new Jetpack_Error( 'verify_secrets_missing', 'Verification secrets not found', 400 ), $tracks_failure_event_name, $user );
235
		}
236
237
		if ( is_wp_error( $secrets ) ) {
238
			Jetpack::delete_secrets( $action, $state );
239
			return $this->error( new Jetpack_Error( $secrets->get_error_code(), $secrets->get_error_message(), 400 ), $tracks_failure_event_name, $user );
240
		}
241
242
		if ( empty( $secrets['secret_1'] ) || empty( $secrets['secret_2'] ) || empty( $secrets['exp'] ) ) {
243
			Jetpack::delete_secrets( $action, $state );
244
			return $this->error( new Jetpack_Error( 'verify_secrets_incomplete', 'Verification secrets are incomplete', 400 ), $tracks_failure_event_name, $user );
245
		}
246
247
		if ( ! hash_equals( $verify_secret, $secrets['secret_1'] ) ) {
248
			Jetpack::delete_secrets( $action, $state );
249
			return $this->error( new Jetpack_Error( 'verify_secrets_mismatch', 'Secret mismatch', 400 ), $tracks_failure_event_name, $user );
250
		}
251
252
		Jetpack::delete_secrets( $action, $state );
253
254
		JetpackTracking::record_user_event( 'jpc_verify_' . $action . '_success', array(), $user );
255
256
		return $secrets['secret_2'];
257
	}
258
259
	/**
260
	 * Wrapper for wp_authenticate( $username, $password );
261
	 *
262
	 * @return WP_User|bool
263
	 */
264
	function login() {
265
		Jetpack::init()->require_jetpack_authentication();
266
		$user = wp_authenticate( 'username', 'password' );
267
		if ( is_wp_error( $user ) ) {
268
			if ( 'authentication_failed' == $user->get_error_code() ) { // Generic error could mean most anything.
269
				$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
270
			} else {
271
				$this->error = $user;
272
			}
273
			return false;
274
		} else if ( !$user ) { // Shouldn't happen.
275
			$this->error = new Jetpack_Error( 'invalid_request', 'Invalid Request', 403 );
276
			return false;
277
		}
278
279
		return $user;
280
	}
281
282
	/**
283
	 * Returns the current error as an IXR_Error
284
	 *
285
	 * @return bool|IXR_Error
286
	 */
287
	function error( $error = null, $tracks_event_name = null, $user = null ) {
288
		// record using Tracks
289
		if ( null !== $tracks_event_name ) {
290
			$this->tracks_record_error( $tracks_event_name, $error, $user );
291
		}
292
293
		if ( !is_null( $error ) ) {
294
			$this->error = $error;
295
		}
296
297
		if ( is_wp_error( $this->error ) ) {
298
			$code = $this->error->get_error_data();
299
			if ( !$code ) {
300
				$code = -10520;
301
			}
302
			$message = sprintf( 'Jetpack: [%s] %s', $this->error->get_error_code(), $this->error->get_error_message() );
303
			return new IXR_Error( $code, $message );
304
		} else if ( is_a( $this->error, 'IXR_Error' ) ) {
305
			return $this->error;
306
		}
307
308
		return false;
309
	}
310
311
/* API Methods */
312
313
	/**
314
	 * Just authenticates with the given Jetpack credentials.
315
	 *
316
	 * @return string The current Jetpack version number
317
	 */
318
	function test_connection() {
319
		return JETPACK__VERSION;
320
	}
321
322
	function test_api_user_code( $args ) {
323
		$client_id = (int) $args[0];
324
		$user_id   = (int) $args[1];
325
		$nonce     = (string) $args[2];
326
		$verify    = (string) $args[3];
327
328
		if ( !$client_id || !$user_id || !strlen( $nonce ) || 32 !== strlen( $verify ) ) {
329
			return false;
330
		}
331
332
		$user = get_user_by( 'id', $user_id );
333
		if ( !$user || is_wp_error( $user ) ) {
334
			return false;
335
		}
336
337
		/* debugging
338
		error_log( "CLIENT: $client_id" );
339
		error_log( "USER:   $user_id" );
340
		error_log( "NONCE:  $nonce" );
341
		error_log( "VERIFY: $verify" );
342
		*/
343
344
		$jetpack_token = Jetpack_Data::get_access_token( $user_id );
345
346
		$api_user_code = get_user_meta( $user_id, "jetpack_json_api_$client_id", true );
347
		if ( !$api_user_code ) {
348
			return false;
349
		}
350
351
		$hmac = hash_hmac( 'md5', json_encode( (object) array(
352
			'client_id' => (int) $client_id,
353
			'user_id'   => (int) $user_id,
354
			'nonce'     => (string) $nonce,
355
			'code'      => (string) $api_user_code,
356
		) ), $jetpack_token->secret );
357
358
		if ( ! hash_equals( $hmac, $verify ) ) {
359
			return false;
360
		}
361
362
		return $user_id;
363
	}
364
365
	/**
366
	* Disconnect this blog from the connected wordpress.com account
367
	* @return boolean
368
	*/
369
	function disconnect_blog() {
370
371
		// For tracking
372
		if ( ! empty( $this->user->ID ) ) {
373
			wp_set_current_user( $this->user->ID );
374
		}
375
376
		Jetpack::log( 'disconnect' );
377
		Jetpack::disconnect();
378
379
		return true;
380
	}
381
382
	/**
383
	 * Unlink a user from WordPress.com
384
	 *
385
	 * This will fail if called by the Master User.
386
	 */
387
	function unlink_user() {
388
		Jetpack::log( 'unlink' );
389
		return Jetpack::unlink_user();
390
	}
391
392
	/**
393
	 * Returns any object that is able to be synced
394
	 */
395
	function sync_object( $args ) {
396
		// e.g. posts, post, 5
397
		list( $module_name, $object_type, $id ) = $args;
398
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-modules.php';
399
		require_once dirname( __FILE__ ) . '/sync/class.jetpack-sync-sender.php';
400
401
		$sync_module = Jetpack_Sync_Modules::get_module( $module_name );
402
		$codec = Jetpack_Sync_Sender::get_instance()->get_codec();
403
404
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
405
	}
406
407
	/**
408
	 * Returns the home URL and site URL for the current site which can be used on the WPCOM side for
409
	 * IDC mitigation to decide whether sync should be allowed if the home and siteurl values differ between WPCOM
410
	 * and the remote Jetpack site.
411
	 *
412
	 * @return array
413
	 */
414
	function validate_urls_for_idc_mitigation() {
415
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
416
		return array(
417
			'home'    => Jetpack_Sync_Functions::home_url(),
418
			'siteurl' => Jetpack_Sync_Functions::site_url(),
419
		);
420
	}
421
422
	/**
423
	 * Returns what features are available. Uses the slug of the module files.
424
	 *
425
	 * @return array
426
	 */
427 View Code Duplication
	function features_available() {
428
		$raw_modules = Jetpack::get_available_modules();
429
		$modules = array();
430
		foreach ( $raw_modules as $module ) {
431
			$modules[] = Jetpack::get_module_slug( $module );
432
		}
433
434
		return $modules;
435
	}
436
437
	/**
438
	 * Returns what features are enabled. Uses the slug of the modules files.
439
	 *
440
	 * @return array
441
	 */
442 View Code Duplication
	function features_enabled() {
443
		$raw_modules = Jetpack::get_active_modules();
444
		$modules = array();
445
		foreach ( $raw_modules as $module ) {
446
			$modules[] = Jetpack::get_module_slug( $module );
447
		}
448
449
		return $modules;
450
	}
451
452
	function update_attachment_parent( $args ) {
453
		$attachment_id = (int) $args[0];
454
		$parent_id     = (int) $args[1];
455
456
		return wp_update_post( array(
457
			'ID'          => $attachment_id,
458
			'post_parent' => $parent_id,
459
		) );
460
	}
461
462
	function json_api( $args = array() ) {
463
		$json_api_args = $args[0];
464
		$verify_api_user_args = $args[1];
465
466
		$method       = (string) $json_api_args[0];
467
		$url          = (string) $json_api_args[1];
468
		$post_body    = is_null( $json_api_args[2] ) ? null : (string) $json_api_args[2];
469
		$user_details = (array) $json_api_args[4];
470
		$locale       = (string) $json_api_args[5];
471
472
		if ( !$verify_api_user_args ) {
473
			$user_id = 0;
474
		} elseif ( 'internal' === $verify_api_user_args[0] ) {
475
			$user_id = (int) $verify_api_user_args[1];
476
			if ( $user_id ) {
477
				$user = get_user_by( 'id', $user_id );
478
				if ( !$user || is_wp_error( $user ) ) {
479
					return false;
480
				}
481
			}
482
		} else {
483
			$user_id = call_user_func( array( $this, 'test_api_user_code' ), $verify_api_user_args );
484
			if ( !$user_id ) {
485
				return false;
486
			}
487
		}
488
489
		/* debugging
490
		error_log( "-- begin json api via jetpack debugging -- " );
491
		error_log( "METHOD: $method" );
492
		error_log( "URL: $url" );
493
		error_log( "POST BODY: $post_body" );
494
		error_log( "VERIFY_ARGS: " . print_r( $verify_api_user_args, 1 ) );
495
		error_log( "VERIFIED USER_ID: " . (int) $user_id );
496
		error_log( "-- end json api via jetpack debugging -- " );
497
		*/
498
499
		if ( 'en' !== $locale ) {
500
			// .org mo files are named slightly different from .com, and all we have is this the locale -- try to guess them.
501
			$new_locale = $locale;
502
			if ( strpos( $locale, '-' ) !== false ) {
503
				$locale_pieces = explode( '-', $locale );
504
				$new_locale = $locale_pieces[0];
505
				$new_locale .= ( ! empty( $locale_pieces[1] ) ) ? '_' . strtoupper( $locale_pieces[1] ) : '';
506
			} else {
507
				// .com might pass 'fr' because thats what our language files are named as, where core seems
508
				// to do fr_FR - so try that if we don't think we can load the file.
509
				if ( ! file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {
510
					$new_locale =  $locale . '_' . strtoupper( $locale );
511
				}
512
			}
513
514
			if ( file_exists( WP_LANG_DIR . '/' . $new_locale . '.mo' ) ) {
515
				unload_textdomain( 'default' );
516
				load_textdomain( 'default', WP_LANG_DIR . '/' . $new_locale . '.mo' );
517
			}
518
		}
519
520
		$old_user = wp_get_current_user();
521
		wp_set_current_user( $user_id );
522
523
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
524
		if ( !$token || is_wp_error( $token ) ) {
525
			return false;
526
		}
527
528
		define( 'REST_API_REQUEST', true );
529
		define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
530
531
		// needed?
532
		require_once ABSPATH . 'wp-admin/includes/admin.php';
533
534
		require_once JETPACK__PLUGIN_DIR . 'class.json-api.php';
535
		$api = WPCOM_JSON_API::init( $method, $url, $post_body );
536
		$api->token_details['user'] = $user_details;
537
		require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
538
539
		$display_errors = ini_set( 'display_errors', 0 );
540
		ob_start();
541
		$content_type = $api->serve( false );
542
		$output = ob_get_clean();
543
		ini_set( 'display_errors', $display_errors );
544
545
		$nonce = wp_generate_password( 10, false );
546
		$hmac  = hash_hmac( 'md5', $nonce . $output, $token->secret );
547
548
		wp_set_current_user( isset( $old_user->ID ) ? $old_user->ID : 0 );
549
550
		return array(
551
			(string) $output,
552
			(string) $nonce,
553
			(string) $hmac,
554
		);
555
	}
556
}
557