Completed
Push — suppress-initial-full-sync ( e87659 )
by
unknown
112:44 queued 96:37
created

Jetpack_Provision::get_api_host()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php //phpcs:ignore
2
3
class Jetpack_Provision { //phpcs:ignore
4
5
	/**
6
	 * Responsible for checking pre-conditions, registering site, and returning an array of details
7
	 * that can be used to provision a plan for the site.
8
	 *
9
	 * @param array $named_args The array of arguments.
10
	 *
11
	 * @return WP_Error|array
12
	 */
13
	public static function register_and_build_request_body( $named_args ) {
14
		$url_args = array(
15
			'home_url' => 'WP_HOME',
16
			'site_url' => 'WP_SITEURL',
17
		);
18
19
		foreach ( $url_args as $url_arg => $constant_name ) {
20
			// Anonymous functions were introduced in 5.3.0. So, if we're running on
21
			// >= 5.3.0, use an anonymous function to set the home/siteurl value%s.
22
			//
23
			// Otherwise, fallback to setting the home/siteurl value via the WP_HOME and
24
			// WP_SITEURL constants if the constant hasn't already been defined.
25
			if ( isset( $named_args[ $url_arg ] ) ) {
26
				if ( version_compare( phpversion(), '5.3.0', '>=' ) ) {
27
					add_filter( $url_arg, function() use ( $url_arg, $named_args ) { // phpcs:ignore PHPCompatibility.PHP.NewClosure.Found
28
						return $named_args[ $url_arg ];
29
					}, 11 );
30
				} elseif ( ! defined( $constant_name ) ) {
31
					define( $constant_name, $named_args[ $url_arg ] );
32
				}
33
			}
34
		}
35
36
		/*
37
		// If Jetpack is currently connected, and is not in Safe Mode already, kick off a sync of the current
38
		// functions/callables so that we can test if this site is in IDC.
39
		if ( Jetpack::is_active() && ! Jetpack::validate_sync_error_idc_option() && Jetpack_Sync_Actions::sync_allowed() ) {
40
			Jetpack_Sync_Actions::do_full_sync( array( 'functions' => true ) );
41
			Jetpack_Sync_Actions::$sender->do_full_sync();
42
		}
43
44
45
		if ( Jetpack::validate_sync_error_idc_option() ) {
46
			return new WP_Error(
47
				'site_in_safe_mode',
48
				__( 'Can not provision a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
49
			);
50
		}
51
		*/
52
53
		$blog_id    = Jetpack_Options::get_option( 'id' );
54
		$blog_token = Jetpack_Options::get_option( 'blog_token' );
55
56
		if ( ! $blog_id || ! $blog_token || ( isset( $named_args['force_register'] ) && intval( $named_args['force_register'] ) ) ) {
57
			// This code mostly copied from Jetpack::admin_page_load.
58
			Jetpack::maybe_set_version_option();
59
			$registered = Jetpack::try_registration();
60
			if ( is_wp_error( $registered ) ) {
61
				return $registered;
62
			} elseif ( ! $registered ) {
63
				return new WP_Error( 'registration_error', __( 'There was an unspecified error registering the site', 'jetpack' ) );
64
			}
65
66
			$blog_id    = Jetpack_Options::get_option( 'id' );
0 ignored issues
show
Unused Code introduced by
$blog_id 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...
67
			$blog_token = Jetpack_Options::get_option( 'blog_token' );
0 ignored issues
show
Unused Code introduced by
$blog_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...
68
		}
69
70
		// If the user isn't specified, but we have a current master user, then set that to current user.
71
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
72
		if ( ! get_current_user_id() && $master_user_id ) {
73
			wp_set_current_user( $master_user_id );
74
		}
75
76
		$site_icon = ( function_exists( 'has_site_icon' ) && has_site_icon() )
77
			? get_site_icon_url()
78
			: false;
79
80
		$auto_enable_sso = ( ! Jetpack::is_active() || Jetpack::is_module_active( 'sso' ) );
81
82
		/** This filter is documented in class.jetpack-cli.php */
83 View Code Duplication
		if ( apply_filters( 'jetpack_start_enable_sso', $auto_enable_sso ) ) {
84
			$redirect_uri = add_query_arg(
85
				array(
86
					'action'      => 'jetpack-sso',
87
					'redirect_to' => rawurlencode( admin_url() ),
88
				),
89
				wp_login_url() // TODO: come back to Jetpack dashboard?
90
			);
91
		} else {
92
			$redirect_uri = admin_url();
93
		}
94
95
		$request_body = array(
96
			'jp_version'   => JETPACK__VERSION,
97
			'redirect_uri' => $redirect_uri,
98
		);
99
100
		if ( $site_icon ) {
101
			$request_body['site_icon'] = $site_icon;
102
		}
103
104
		if ( get_current_user_id() ) {
105
			$user = wp_get_current_user();
106
107
			// Role.
108
			$role        = Jetpack::translate_current_user_to_role();
109
			$signed_role = Jetpack::sign_role( $role );
110
111
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
112
113
			// Jetpack auth stuff.
114
			$request_body['scope']  = $signed_role;
115
			$request_body['secret'] = $secrets['secret_1'];
116
117
			// User stuff.
118
			$request_body['user_id']    = $user->ID;
119
			$request_body['user_email'] = $user->user_email;
120
			$request_body['user_login'] = $user->user_login;
121
		}
122
123
		// Optional additional params.
124 View Code Duplication
		if ( isset( $named_args['wpcom_user_id'] ) && ! empty( $named_args['wpcom_user_id'] ) ) {
125
			$request_body['wpcom_user_id'] = $named_args['wpcom_user_id'];
126
		}
127
128
		// Override email of selected user.
129 View Code Duplication
		if ( isset( $named_args['wpcom_user_email'] ) && ! empty( $named_args['wpcom_user_email'] ) ) {
130
			$request_body['user_email'] = $named_args['wpcom_user_email'];
131
		}
132
133 View Code Duplication
		if ( isset( $named_args['plan'] ) && ! empty( $named_args['plan'] ) ) {
134
			$request_body['plan'] = $named_args['plan'];
135
		}
136
137 View Code Duplication
		if ( isset( $named_args['onboarding'] ) && ! empty( $named_args['onboarding'] ) ) {
138
			$request_body['onboarding'] = intval( $named_args['onboarding'] );
139
		}
140
141 View Code Duplication
		if ( isset( $named_args['force_connect'] ) && ! empty( $named_args['force_connect'] ) ) {
142
			$request_body['force_connect'] = intval( $named_args['force_connect'] );
143
		}
144
145
		if ( isset( $request_body['onboarding'] ) && (bool) $request_body['onboarding'] ) {
146
			Jetpack::create_onboarding_token();
147
		}
148
149
		return $request_body;
150
	}
151
152
	/**
153
	 * Given an access token and an array of arguments, will provision a plan for this site.
154
	 *
155
	 * @param string $access_token The access token from the partner.
156
	 * @param array  $named_args   The arguments used for registering the site and then provisioning a plan.
157
	 *
158
	 * @return WP_Error|array
159
	 */
160
	public static function partner_provision( $access_token, $named_args ) {
161
		// First, verify the token.
162
		$verify_response = self::verify_token( $access_token );
163
164
		if ( is_wp_error( $verify_response ) ) {
165
			return $verify_response;
166
		}
167
168
		$request_body = self::register_and_build_request_body( $named_args );
169
		if ( is_wp_error( $request_body ) ) {
170
			return $request_body;
171
		}
172
173
		$request = array(
174
			'headers' => array(
175
				'Authorization' => "Bearer $access_token",
176
				'Host'          => 'public-api.wordpress.com',
177
			),
178
			'timeout' => 60,
179
			'method'  => 'POST',
180
			'body'    => wp_json_encode( $request_body ),
181
		);
182
183
		$blog_id = Jetpack_Options::get_option( 'id' );
184
		$url     = esc_url_raw( sprintf(
185
			'https://%s/rest/v1.3/jpphp/%d/partner-provision',
186
			self::get_api_host(),
187
			$blog_id
188
		) );
189 View Code Duplication
		if ( ! empty( $named_args['partner_tracking_id'] ) ) {
190
			$url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
191
		}
192
193
		// Add calypso env if set.
194
		if ( getenv( 'CALYPSO_ENV' ) ) {
195
			$url = add_query_arg( array( 'calypso_env' => getenv( 'CALYPSO_ENV' ) ), $url );
196
		}
197
198
		$result = Jetpack_Client::_wp_remote_request( $url, $request );
199
200
		if ( is_wp_error( $result ) ) {
201
			return $result;
202
		}
203
204
		$response_code = wp_remote_retrieve_response_code( $result );
205
		$body_json     = json_decode( wp_remote_retrieve_body( $result ) );
206
207 View Code Duplication
		if ( 200 !== $response_code ) {
208
			if ( isset( $body_json->error ) ) {
209
				return new WP_Error( $body_json->error, $body_json->message );
210
			} else {
211
				return new WP_Error(
212
					'server_error',
213
					/* translators: %s is an HTTP status code retured from an API request. Ex. – 400 */
214
					sprintf( __( 'Request failed with code %s', 'jetpack' ), $response_code )
215
				);
216
			}
217
		}
218
219
		if ( isset( $body_json->access_token ) && is_user_logged_in() ) {
220
			// Check if this matches the existing token before replacing.
221
			$existing_token = Jetpack_Data::get_access_token( get_current_user_id() );
222
			if ( empty( $existing_token ) || $existing_token->secret !== $body_json->access_token ) {
223
				self::authorize_user( get_current_user_id(), $body_json->access_token );
224
			}
225
		}
226
227
		return $body_json;
228
	}
229
230
	private static function authorize_user( $user_id, $access_token ) {
231
		// authorize user and enable SSO
232
		Jetpack::update_user_token( $user_id, sprintf( '%s.%d', $access_token, $user_id ), true );
233
234
		/**
235
		 * Auto-enable SSO module for new Jetpack Start connections
236
		 *
237
		 * @since 5.0.0
238
		 *
239
		 * @param bool $enable_sso Whether to enable the SSO module. Default to true.
240
		 */
241
		$other_modules = apply_filters( 'jetpack_start_enable_sso', true )
242
			? array( 'sso' )
243
			: array();
244
245
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
246
			Jetpack::delete_active_modules();
247
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), false );
0 ignored issues
show
Documentation introduced by
999 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...
248
		} else {
249
			Jetpack::activate_default_modules( false, false, $other_modules, false );
250
		}
251
	}
252
253
	private static function verify_token( $access_token ) {
254
		$request = array(
255
			'headers' => array(
256
				'Authorization' => "Bearer " . $access_token,
257
				'Host'          => 'public-api.wordpress.com',
258
			),
259
			'timeout' => 10,
260
			'method'  => 'POST',
261
			'body'    => ''
262
		);
263
264
		$url = sprintf( 'https://%s/rest/v1.3/jpphp/partner-keys/verify', self::get_api_host() );
265
		$result = Jetpack_Client::_wp_remote_request( $url, $request );
266
267
		if ( is_wp_error( $result ) ) {
268
			return $result;
269
		}
270
271
		$response_code = wp_remote_retrieve_response_code( $result );
272
		$body_json     = json_decode( wp_remote_retrieve_body( $result ) );
273
274 View Code Duplication
		if( 200 !== $response_code ) {
275
			if ( isset( $body_json->error ) ) {
276
				return new WP_Error( $body_json->error, $body_json->message );
277
			} else {
278
				return new WP_Error( 'server_error', sprintf( __( 'Request failed with code %s', 'jetpack' ), $response_code ) );
279
			}
280
		}
281
282
		return true;
283
	}
284
285
	private static function get_api_host() {
286
		$env_api_host = getenv( 'JETPACK_START_API_HOST', true );
287
		return $env_api_host ? $env_api_host : JETPACK__WPCOM_JSON_API_HOST;
288
	}
289
}
290