Completed
Push — feature/sync-json-endpoints ( bf1919...f7fa9b )
by
unknown
33:49 queued 21:50
created

Jetpack_XMLRPC_Server::remote_authorize()   D

Complexity

Conditions 9
Paths 11

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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