Completed
Push — merge/site-search ( 4f1546...22a4b2 )
by
unknown
13:12
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 Method

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