summaryrefslogtreecommitdiff
blob: 1a53ed7412be69c1f0748713d64fa93ea840ae22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<?php //phpcs:ignore

class Jetpack_Provision { //phpcs:ignore

	/**
	 * Responsible for checking pre-conditions, registering site, and returning an array of details
	 * that can be used to provision a plan for the site.
	 *
	 * @param array $named_args The array of arguments.
	 *
	 * @return WP_Error|array
	 */
	public static function register_and_build_request_body( $named_args ) {
		$url_args = array(
			'home_url' => 'WP_HOME',
			'site_url' => 'WP_SITEURL',
		);

		foreach ( $url_args as $url_arg => $constant_name ) {
			// Anonymous functions were introduced in 5.3.0. So, if we're running on
			// >= 5.3.0, use an anonymous function to set the home/siteurl value%s.
			//
			// Otherwise, fallback to setting the home/siteurl value via the WP_HOME and
			// WP_SITEURL constants if the constant hasn't already been defined.
			if ( isset( $named_args[ $url_arg ] ) ) {
				if ( version_compare( phpversion(), '5.3.0', '>=' ) ) {
					add_filter( $url_arg, function() use ( $url_arg, $named_args ) { // phpcs:ignore PHPCompatibility.PHP.NewClosure.Found
						return $named_args[ $url_arg ];
					}, 11 );
				} elseif ( ! defined( $constant_name ) ) {
					define( $constant_name, $named_args[ $url_arg ] );
				}
			}
		}

		// If Jetpack is currently connected, and is not in Safe Mode already, kick off a sync of the current
		// functions/callables so that we can test if this site is in IDC.
		if ( Jetpack::is_active() && ! Jetpack::validate_sync_error_idc_option() && Jetpack_Sync_Actions::sync_allowed() ) {
			Jetpack_Sync_Actions::do_full_sync( array( 'functions' => true ) );
			Jetpack_Sync_Actions::$sender->do_full_sync();
		}

		if ( Jetpack::validate_sync_error_idc_option() ) {
			return new WP_Error(
				'site_in_safe_mode',
				__( 'Can not provision a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
			);
		}

		$blog_id    = Jetpack_Options::get_option( 'id' );
		$blog_token = Jetpack_Options::get_option( 'blog_token' );

		if ( ! $blog_id || ! $blog_token || ( isset( $named_args['force_register'] ) && intval( $named_args['force_register'] ) ) ) {
			// This code mostly copied from Jetpack::admin_page_load.
			Jetpack::maybe_set_version_option();
			$registered = Jetpack::try_registration();
			if ( is_wp_error( $registered ) ) {
				return $registered;
			} elseif ( ! $registered ) {
				return new WP_Error( 'registration_error', __( 'There was an unspecified error registering the site', 'jetpack' ) );
			}

			$blog_id    = Jetpack_Options::get_option( 'id' );
			$blog_token = Jetpack_Options::get_option( 'blog_token' );
		}

		// If the user isn't specified, but we have a current master user, then set that to current user.
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
		if ( ! get_current_user_id() && $master_user_id ) {
			wp_set_current_user( $master_user_id );
		}

		$site_icon = ( function_exists( 'has_site_icon' ) && has_site_icon() )
			? get_site_icon_url()
			: false;

		$auto_enable_sso = ( ! Jetpack::is_active() || Jetpack::is_module_active( 'sso' ) );

		/** This filter is documented in class.jetpack-cli.php */
		if ( apply_filters( 'jetpack_start_enable_sso', $auto_enable_sso ) ) {
			$redirect_uri = add_query_arg(
				array(
					'action'      => 'jetpack-sso',
					'redirect_to' => rawurlencode( admin_url() ),
				),
				wp_login_url() // TODO: come back to Jetpack dashboard?
			);
		} else {
			$redirect_uri = admin_url();
		}

		$request_body = array(
			'jp_version'   => JETPACK__VERSION,
			'redirect_uri' => $redirect_uri,
		);

		if ( $site_icon ) {
			$request_body['site_icon'] = $site_icon;
		}

		if ( get_current_user_id() ) {
			$user = wp_get_current_user();

			// Role.
			$role        = Jetpack::translate_current_user_to_role();
			$signed_role = Jetpack::sign_role( $role );

			$secrets = Jetpack::init()->generate_secrets( 'authorize' );

			// Jetpack auth stuff.
			$request_body['scope']  = $signed_role;
			$request_body['secret'] = $secrets['secret_1'];

			// User stuff.
			$request_body['user_id']    = $user->ID;
			$request_body['user_email'] = $user->user_email;
			$request_body['user_login'] = $user->user_login;
		}

		// Optional additional params.
		if ( isset( $named_args['wpcom_user_id'] ) && ! empty( $named_args['wpcom_user_id'] ) ) {
			$request_body['wpcom_user_id'] = $named_args['wpcom_user_id'];
		}

		// Override email of selected user.
		if ( isset( $named_args['wpcom_user_email'] ) && ! empty( $named_args['wpcom_user_email'] ) ) {
			$request_body['user_email'] = $named_args['wpcom_user_email'];
		}

		if ( isset( $named_args['plan'] ) && ! empty( $named_args['plan'] ) ) {
			$request_body['plan'] = $named_args['plan'];
		}

		if ( isset( $named_args['onboarding'] ) && ! empty( $named_args['onboarding'] ) ) {
			$request_body['onboarding'] = intval( $named_args['onboarding'] );
		}

		if ( isset( $named_args['force_connect'] ) && ! empty( $named_args['force_connect'] ) ) {
			$request_body['force_connect'] = intval( $named_args['force_connect'] );
		}

		if ( isset( $request_body['onboarding'] ) && (bool) $request_body['onboarding'] ) {
			Jetpack::create_onboarding_token();
		}

		return $request_body;
	}

	/**
	 * Given an access token and an array of arguments, will provision a plan for this site.
	 *
	 * @param string $access_token The access token from the partner.
	 * @param array  $named_args   The arguments used for registering the site and then provisioning a plan.
	 *
	 * @return WP_Error|array
	 */
	public static function partner_provision( $access_token, $named_args ) {
		// First, verify the token.
		$verify_response = self::verify_token( $access_token );

		if ( is_wp_error( $verify_response ) ) {
			return $verify_response;
		}

		$request_body = self::register_and_build_request_body( $named_args );
		if ( is_wp_error( $request_body ) ) {
			return $request_body;
		}

		$request = array(
			'headers' => array(
				'Authorization' => "Bearer $access_token",
				'Host'          => 'public-api.wordpress.com',
			),
			'timeout' => 60,
			'method'  => 'POST',
			'body'    => wp_json_encode( $request_body ),
		);

		$blog_id = Jetpack_Options::get_option( 'id' );
		$url     = esc_url_raw( sprintf(
			'https://%s/rest/v1.3/jpphp/%d/partner-provision',
			self::get_api_host(),
			$blog_id
		) );
		if ( ! empty( $named_args['partner_tracking_id'] ) ) {
			$url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
		}

		// Add calypso env if set.
		if ( getenv( 'CALYPSO_ENV' ) ) {
			$url = add_query_arg( array( 'calypso_env' => getenv( 'CALYPSO_ENV' ) ), $url );
		}

		$result = Jetpack_Client::_wp_remote_request( $url, $request );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$response_code = wp_remote_retrieve_response_code( $result );
		$body_json     = json_decode( wp_remote_retrieve_body( $result ) );

		if ( 200 !== $response_code ) {
			if ( isset( $body_json->error ) ) {
				return new WP_Error( $body_json->error, $body_json->message );
			} else {
				return new WP_Error(
					'server_error',
					/* translators: %s is an HTTP status code retured from an API request. Ex. – 400 */
					sprintf( __( 'Request failed with code %s', 'jetpack' ), $response_code )
				);
			}
		}

		if ( isset( $body_json->access_token ) && is_user_logged_in() ) {
			// Check if this matches the existing token before replacing.
			$existing_token = Jetpack_Data::get_access_token( get_current_user_id() );
			if ( empty( $existing_token ) || $existing_token->secret !== $body_json->access_token ) {
				self::authorize_user( get_current_user_id(), $body_json->access_token );
			}
		}

		return $body_json;
	}

	private static function authorize_user( $user_id, $access_token ) {
		// authorize user and enable SSO
		Jetpack::update_user_token( $user_id, sprintf( '%s.%d', $access_token, $user_id ), true );

		/**
		 * Auto-enable SSO module for new Jetpack Start connections
		 *
		 * @since 5.0.0
		 *
		 * @param bool $enable_sso Whether to enable the SSO module. Default to true.
		 */
		$other_modules = apply_filters( 'jetpack_start_enable_sso', true )
			? array( 'sso' )
			: array();

		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
			Jetpack::delete_active_modules();
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), false );
		} else {
			Jetpack::activate_default_modules( false, false, $other_modules, false );
		}
	}

	private static function verify_token( $access_token ) {
		$request = array(
			'headers' => array(
				'Authorization' => "Bearer " . $access_token,
				'Host'          => 'public-api.wordpress.com',
			),
			'timeout' => 10,
			'method'  => 'POST',
			'body'    => ''
		);

		$url = sprintf( 'https://%s/rest/v1.3/jpphp/partner-keys/verify', self::get_api_host() );
		$result = Jetpack_Client::_wp_remote_request( $url, $request );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$response_code = wp_remote_retrieve_response_code( $result );
		$body_json     = json_decode( wp_remote_retrieve_body( $result ) );

		if( 200 !== $response_code ) {
			if ( isset( $body_json->error ) ) {
				return new WP_Error( $body_json->error, $body_json->message );
			} else {
				return new WP_Error( 'server_error', sprintf( __( 'Request failed with code %s', 'jetpack' ), $response_code ) );
			}
		}

		return true;
	}

	private static function get_api_host() {
		$env_api_host = getenv( 'JETPACK_START_API_HOST', true );
		return $env_api_host ? $env_api_host : JETPACK__WPCOM_JSON_API_HOST;
	}
}