PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 9.5.2
Jetpack – WP Security, Backup, Speed, & Growth v9.5.2
15.9-a.7 15.9-a.5 15.9-a.3 15.9-a.1 15.8 15.8-beta 15.8-a.7 15.8-a.5 5.2.5 5.3.4 5.4.4 5.5.5 5.6.5 5.7.5 5.8.4 5.9.4 6.0.4 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.5 6.2 6.2.1 6.2.2 6.2.3 6.2.4 6.2.5 6.3 6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.5 6.5.1 6.5.2 6.5.3 6.5.4 6.6 6.6.1 6.6.2 6.6.3 6.6.4 6.6.5 6.7 6.7.1 6.7.2 6.7.3 6.7.4 6.8 6.8.1 6.8.2 6.8.3 6.8.4 6.8.5 6.9 6.9.1 6.9.2 6.9.3 6.9.4 7.0 7.0.1 7.0.2 7.0.3 7.0.4 7.0.5 7.1 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2 7.2.1 7.2.1.1 7.2.2 7.2.3 7.2.4 7.2.5 7.3 7.3.0.1 7.3.1 7.3.1.1 7.3.2 7.3.3 7.3.4 7.3.5 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.5.0.1 7.5.1 7.5.2 7.5.3 7.5.4 7.5.5 7.5.6 7.5.7 7.6 7.6.1 7.6.2 7.6.3 7.6.4 7.7 7.7.1 7.7.2 7.7.3 7.7.4 7.7.5 7.7.6 7.8 7.8.1 7.8.2 7.8.3 7.8.4 7.9 7.9.1 7.9.2 7.9.3 7.9.4 8.0 8.0.1 8.0.2 8.0.3 8.1 8.1.1 8.1.2 8.1.3 8.1.4 8.2 8.2.0.1 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.3 8.3.1 8.3.2 8.3.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.5 8.5.1 8.5.2 8.5.3 8.6 8.6.1 8.6.2 8.6.3 8.6.4 8.7 8.7.0.1 8.7.1 8.7.2 8.7.3 8.7.4 8.8 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.9 8.9.1 8.9.2 8.9.3 8.9.4 9.0 9.0.1 9.0.2 9.0.3 9.0.4 9.0.5 9.1 9.1.1 9.1.2 9.1.3 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.5 9.5.1 9.5.2 9.5.3 9.5.4 9.5.5 9.6 9.6.1 9.6.2 9.6.3 9.6.4 9.7 9.7.1 9.7.2 15.7-beta.2 9.7.3 15.7.1 9.8 15.8-a.1 9.8.1 15.8-a.3 9.8.2 2.0.9 9.8.3 2.1.7 9.9 2.2.10 9.9.1 2.3.10 9.9.2 2.4.7 9.9.3 2.5.5 2.6.6 2.7.5 2.8.5 2.9.6 3.0.6 3.1.5 3.2.5 3.3.6 3.4.6 3.5.6 3.6.4 3.7.5 3.8.5 3.9.10 4.0.7 4.1.4 4.2.5 4.3.5 4.4.5 4.5.3 4.6.3 4.7.4 4.8.5 4.9.3 5.0.3 5.1.4 trunk 10.0 10.0.1 10.0.2 10.1 10.1.1 10.1.2 10.2 10.2.1 10.2.2 10.2.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.2 10.5 10.5.1 10.5.2 10.5.3 10.6 10.6.1 10.6.2 10.7 10.7.1 10.7.2 10.8 10.8.1 10.8.2 10.9 10.9.1 10.9.2 10.9.3 11.0 11.0.1 11.0.2 11.1 11.1.1 11.1.2 11.1.3 11.1.4 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.3.3 11.3.4 11.4 11.4.1 11.4.2 11.5 11.5.1 11.5.2 11.5.3 11.6 11.6.1 11.6.2 11.7 11.7.1 11.7.2 11.7.3 11.8 11.8.3 11.8.4 11.8.5 11.8.6 11.9 11.9.1 11.9.2 11.9.3 12.0 12.0.1 12.0.2 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.3 12.3.1 12.4 12.4.1 12.5 12.5.1 12.6 12.6.1 12.6.2 12.6.3 12.7 12.7.1 12.7.2 12.8 12.8.1 12.8.2 12.9 12.9.1 12.9.2 12.9.3 12.9.4 13.0 13.0.1 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 13.2.2 13.2.3 13.3 13.3.1 13.3.2 13.4 13.4.1 13.4.2 13.4.3 13.4.4 13.5 13.5.1 13.6 13.6.1 13.7 13.7.1 13.8 13.8.1 13.8.2 13.9 13.9.1 14.0 14.1 14.2 14.2.1 14.3 14.4 14.4.1 14.5 14.6 14.7 14.8 14.9 14.9.1 15.0 15.0.1 15.0.2 15.1 15.1.1 15.2 15.3 15.3.1 15.4 15.5 15.6 15.7 15.7-a.1 15.7-a.3 15.7-a.5 15.7-a.7 15.7-beta
jetpack / class.jetpack-cli.php
jetpack Last commit date
3rd-party 5 years ago _inc 5 years ago css 5 years ago extensions 5 years ago images 5 years ago json-endpoints 5 years ago modules 5 years ago sal 5 years ago src 5 years ago vendor 5 years ago views 5 years ago SECURITY.md 5 years ago changelog.txt 5 years ago class-jetpack-recommendations-banner.php 5 years ago class-jetpack-wizard-banner.php 5 years ago class.frame-nonce-preview.php 6 years ago class.jetpack-admin.php 5 years ago class.jetpack-affiliate.php 6 years ago class.jetpack-autoupdate.php 5 years ago class.jetpack-bbpress-json-api.compat.php 5 years ago class.jetpack-cli.php 5 years ago class.jetpack-client-server.php 5 years ago class.jetpack-connection-banner.php 5 years ago class.jetpack-data.php 5 years ago class.jetpack-gutenberg.php 5 years ago class.jetpack-heartbeat.php 5 years ago class.jetpack-idc.php 6 years ago class.jetpack-ixr-client.php 5 years ago class.jetpack-modules-list-table.php 5 years ago class.jetpack-network-sites-list-table.php 6 years ago class.jetpack-network.php 5 years ago class.jetpack-plan.php 5 years ago class.jetpack-post-images.php 5 years ago class.jetpack-twitter-cards.php 5 years ago class.jetpack-user-agent.php 5 years ago class.jetpack.php 5 years ago class.json-api-endpoints.php 5 years ago class.json-api.php 5 years ago class.photon.php 5 years ago composer.json 5 years ago functions.compat.php 5 years ago functions.cookies.php 5 years ago functions.gallery.php 6 years ago functions.global.php 5 years ago functions.opengraph.php 5 years ago functions.photon.php 5 years ago jest.config.js 5 years ago jetpack.php 5 years ago json-api-config.php 5 years ago json-endpoints.php 7 years ago load-jetpack.php 5 years ago locales.php 7 years ago readme.txt 5 years ago require-lib.php 5 years ago uninstall.php 5 years ago wpml-config.xml 10 years ago
class.jetpack-cli.php
2078 lines
1 <?php
2
3 use Automattic\Jetpack\Connection\Client;
4 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5 use Automattic\Jetpack\Connection\Tokens;
6 use Automattic\Jetpack\Status;
7 use Automattic\Jetpack\Sync\Actions;
8 use Automattic\Jetpack\Sync\Listener;
9 use Automattic\Jetpack\Sync\Modules;
10 use Automattic\Jetpack\Sync\Queue;
11 use Automattic\Jetpack\Sync\Settings;
12
13 WP_CLI::add_command( 'jetpack', 'Jetpack_CLI' );
14
15 /**
16 * Control your local Jetpack installation.
17 */
18 class Jetpack_CLI extends WP_CLI_Command {
19 // Aesthetics.
20 public $green_open = "\033[32m";
21 public $red_open = "\033[31m";
22 public $yellow_open = "\033[33m";
23 public $color_close = "\033[0m";
24
25 /**
26 * Get Jetpack Details
27 *
28 * ## OPTIONS
29 *
30 * empty: Leave it empty for basic stats
31 *
32 * full: View full stats. It's the data from the heartbeat
33 *
34 * ## EXAMPLES
35 *
36 * wp jetpack status
37 * wp jetpack status full
38 */
39 public function status( $args, $assoc_args ) {
40 jetpack_require_lib( 'debugger' );
41
42 /* translators: %s is the site URL */
43 WP_CLI::line( sprintf( __( 'Checking status for %s', 'jetpack' ), esc_url( get_home_url() ) ) );
44
45 if ( isset( $args[0] ) && 'full' !== $args[0] ) {
46 /* translators: %s is a command like "prompt" */
47 WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $args[0] ) );
48 }
49
50 $master_user_email = Jetpack::get_master_user_email();
51
52 $cxntests = new Jetpack_Cxn_Tests();
53
54 if ( $cxntests->pass() ) {
55 $cxntests->output_results_for_cli();
56
57 WP_CLI::success( __( 'Jetpack is currently connected to WordPress.com', 'jetpack' ) );
58 } else {
59 $error = array();
60 foreach ( $cxntests->list_fails() as $fail ) {
61 $error[] = $fail['name'] . ': ' . $fail['message'];
62 }
63 WP_CLI::error_multi_line( $error );
64
65 $cxntests->output_results_for_cli();
66
67 WP_CLI::error( __( 'One or more tests did not pass. Please investigate!', 'jetpack' ) ); // Exit CLI.
68 }
69
70 /* translators: %s is current version of Jetpack, for example 7.3 */
71 WP_CLI::line( sprintf( __( 'The Jetpack Version is %s', 'jetpack' ), JETPACK__VERSION ) );
72 /* translators: %d is WP.com ID of this blog */
73 WP_CLI::line( sprintf( __( 'The WordPress.com blog_id is %d', 'jetpack' ), Jetpack_Options::get_option( 'id' ) ) );
74 /* translators: %s is the email address of the connection owner */
75 WP_CLI::line( sprintf( __( 'The WordPress.com account for the primary connection is %s', 'jetpack' ), $master_user_email ) );
76
77 /*
78 * Are they asking for all data?
79 *
80 * Loop through heartbeat data and organize by priority.
81 */
82 $all_data = ( isset( $args[0] ) && 'full' == $args[0] ) ? 'full' : false;
83 if ( $all_data ) {
84 // Heartbeat data
85 WP_CLI::line( "\n" . __( 'Additional data: ', 'jetpack' ) );
86
87 // Get the filtered heartbeat data.
88 // Filtered so we can color/list by severity
89 $stats = Jetpack::jetpack_check_heartbeat_data();
90
91 // Display red flags first
92 foreach ( $stats['bad'] as $stat => $value ) {
93 printf( "$this->red_open%-'.16s %s $this->color_close\n", $stat, $value );
94 }
95
96 // Display caution warnings next
97 foreach ( $stats['caution'] as $stat => $value ) {
98 printf( "$this->yellow_open%-'.16s %s $this->color_close\n", $stat, $value );
99 }
100
101 // The rest of the results are good!
102 foreach ( $stats['good'] as $stat => $value ) {
103
104 // Modules should get special spacing for aestetics
105 if ( strpos( $stat, 'odule-' ) ) {
106 printf( "%-'.30s %s\n", $stat, $value );
107 usleep( 4000 ); // For dramatic effect lolz
108 continue;
109 }
110 printf( "%-'.16s %s\n", $stat, $value );
111 usleep( 4000 ); // For dramatic effect lolz
112 }
113 } else {
114 // Just the basics
115 WP_CLI::line( "\n" . _x( "View full status with 'wp jetpack status full'", '"wp jetpack status full" is a command - do not translate', 'jetpack' ) );
116 }
117 }
118
119 /**
120 * Tests the active connection
121 *
122 * Does a two-way test to verify that the local site can communicate with remote Jetpack/WP.com servers and that Jetpack/WP.com servers can talk to the local site.
123 *
124 * ## EXAMPLES
125 *
126 * wp jetpack test-connection
127 *
128 * @subcommand test-connection
129 */
130 public function test_connection( $args, $assoc_args ) {
131
132 /* translators: %s is the site URL */
133 WP_CLI::line( sprintf( __( 'Testing connection for %s', 'jetpack' ), esc_url( get_site_url() ) ) );
134
135 if ( ! Jetpack::is_active() ) {
136 WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
137 }
138
139 $response = Client::wpcom_json_api_request_as_blog(
140 sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
141 Client::WPCOM_JSON_API_VERSION
142 );
143
144 if ( is_wp_error( $response ) ) {
145 /* translators: %1$s is the error code, %2$s is the error message */
146 WP_CLI::error( sprintf( __( 'Failed to test connection (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() ) );
147 }
148
149 $body = wp_remote_retrieve_body( $response );
150 if ( ! $body ) {
151 WP_CLI::error( __( 'Failed to test connection (empty response body)', 'jetpack' ) );
152 }
153
154 $result = json_decode( $body );
155 $is_connected = (bool) $result->connected;
156 $message = $result->message;
157
158 if ( $is_connected ) {
159 WP_CLI::success( $message );
160 } else {
161 WP_CLI::error( $message );
162 }
163 }
164
165 /**
166 * Disconnect Jetpack Blogs or Users
167 *
168 * ## OPTIONS
169 *
170 * blog: Disconnect the entire blog.
171 *
172 * user <user_identifier>: Disconnect a specific user from WordPress.com.
173 *
174 * Please note, the primary account that the blog is connected
175 * to WordPress.com with cannot be disconnected without
176 * disconnecting the entire blog.
177 *
178 * ## EXAMPLES
179 *
180 * wp jetpack disconnect blog
181 * wp jetpack disconnect user 13
182 * wp jetpack disconnect user username
183 * wp jetpack disconnect user email@domain.com
184 *
185 * @synopsis <blog|user> [<user_identifier>]
186 */
187 public function disconnect( $args, $assoc_args ) {
188 if ( ! Jetpack::is_active() ) {
189 WP_CLI::success( __( 'The site is not currently connected, so nothing to do!', 'jetpack' ) );
190 return;
191 }
192
193 $action = isset( $args[0] ) ? $args[0] : 'prompt';
194 if ( ! in_array( $action, array( 'blog', 'user', 'prompt' ) ) ) {
195 /* translators: %s is a command like "prompt" */
196 WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
197 }
198
199 if ( in_array( $action, array( 'user' ) ) ) {
200 if ( isset( $args[1] ) ) {
201 $user_id = $args[1];
202 if ( ctype_digit( $user_id ) ) {
203 $field = 'id';
204 $user_id = (int) $user_id;
205 } elseif ( is_email( $user_id ) ) {
206 $field = 'email';
207 $user_id = sanitize_user( $user_id, true );
208 } else {
209 $field = 'login';
210 $user_id = sanitize_user( $user_id, true );
211 }
212 if ( ! $user = get_user_by( $field, $user_id ) ) {
213 WP_CLI::error( __( 'Please specify a valid user.', 'jetpack' ) );
214 }
215 } else {
216 WP_CLI::error( __( 'Please specify a user by either ID, username, or email.', 'jetpack' ) );
217 }
218 }
219
220 switch ( $action ) {
221 case 'blog':
222 Jetpack::log( 'disconnect' );
223 Jetpack::disconnect();
224 WP_CLI::success(
225 sprintf(
226 /* translators: %s is the site URL */
227 __( 'Jetpack has been successfully disconnected for %s.', 'jetpack' ),
228 esc_url( get_site_url() )
229 )
230 );
231 break;
232 case 'user':
233 if ( ( new Connection_Manager( 'jetpack' ) )->disconnect_user( $user->ID ) ) {
234 Jetpack::log( 'unlink', $user->ID );
235 WP_CLI::success( __( 'User has been successfully disconnected.', 'jetpack' ) );
236 } else {
237 /* translators: %s is a username */
238 WP_CLI::error( sprintf( __( "User %s could not be disconnected. Are you sure they're connected currently?", 'jetpack' ), "{$user->login} <{$user->email}>" ) );
239 }
240 break;
241 case 'prompt':
242 WP_CLI::error( __( 'Please specify if you would like to disconnect a blog or user.', 'jetpack' ) );
243 break;
244 }
245 }
246
247 /**
248 * Reset Jetpack options and settings to default
249 *
250 * ## OPTIONS
251 *
252 * modules: Resets modules to default state ( get_default_modules() )
253 *
254 * options: Resets all Jetpack options except:
255 * - All private options (Blog token, user token, etc...)
256 * - id (The Client ID/WP.com Blog ID of this site)
257 * - master_user
258 * - version
259 * - activated
260 *
261 * ## EXAMPLES
262 *
263 * wp jetpack reset options
264 * wp jetpack reset modules
265 * wp jetpack reset sync-checksum --dry-run --offset=0
266 *
267 * @synopsis <modules|options|sync-checksum> [--dry-run] [--offset=<offset>]
268 */
269 public function reset( $args, $assoc_args ) {
270 $action = isset( $args[0] ) ? $args[0] : 'prompt';
271 if ( ! in_array( $action, array( 'options', 'modules', 'sync-checksum' ), true ) ) {
272 /* translators: %s is a command like "prompt" */
273 WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
274 }
275
276 $is_dry_run = ! empty( $assoc_args['dry-run'] );
277
278 if ( $is_dry_run ) {
279 WP_CLI::warning(
280 __( "\nThis is a dry run.\n", 'jetpack' ) .
281 __( "No actions will be taken.\n", 'jetpack' ) .
282 __( "The following messages will give you preview of what will happen when you run this command.\n\n", 'jetpack' )
283 );
284 } else {
285 // We only need to confirm "Are you sure?" when we are not doing a dry run.
286 jetpack_cli_are_you_sure();
287 }
288
289 switch ( $action ) {
290 case 'options':
291 $options_to_reset = Jetpack_Options::get_options_for_reset();
292 // Reset the Jetpack options
293 WP_CLI::line(
294 sprintf(
295 /* translators: %s is the site URL */
296 __( "Resetting Jetpack Options for %s...\n", 'jetpack' ),
297 esc_url( get_site_url() )
298 )
299 );
300 sleep( 1 ); // Take a breath
301 foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
302 if ( ! $is_dry_run ) {
303 Jetpack_Options::delete_option( $option_to_reset );
304 usleep( 100000 );
305 }
306
307 /* translators: This is the result of an action. The option named %s was reset */
308 WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
309 }
310
311 // Reset the WP options
312 WP_CLI::line( __( "Resetting the jetpack options stored in wp_options...\n", 'jetpack' ) );
313 usleep( 500000 ); // Take a breath
314 foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
315 if ( ! $is_dry_run ) {
316 delete_option( $option_to_reset );
317 usleep( 100000 );
318 }
319 /* translators: This is the result of an action. The option named %s was reset */
320 WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
321 }
322
323 // Reset to default modules
324 WP_CLI::line( __( "Resetting default modules...\n", 'jetpack' ) );
325 usleep( 500000 ); // Take a breath
326 $default_modules = Jetpack::get_default_modules();
327 if ( ! $is_dry_run ) {
328 Jetpack::update_active_modules( $default_modules );
329 }
330 WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
331 break;
332 case 'modules':
333 if ( ! $is_dry_run ) {
334 $default_modules = Jetpack::get_default_modules();
335 Jetpack::update_active_modules( $default_modules );
336 }
337
338 WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
339 break;
340 case 'prompt':
341 WP_CLI::error( __( 'Please specify if you would like to reset your options, modules or sync-checksum', 'jetpack' ) );
342 break;
343 case 'sync-checksum':
344 $option = 'jetpack_callables_sync_checksum';
345
346 if ( is_multisite() ) {
347 $offset = isset( $assoc_args['offset'] ) ? (int) $assoc_args['offset'] : 0;
348
349 /*
350 * 1000 is a good limit since we don't expect the number of sites to be more than 1000
351 * Offset can be used to paginate and try to clean up more sites.
352 */
353 $sites = get_sites(
354 array(
355 'number' => 1000,
356 'offset' => $offset,
357 )
358 );
359 $count_fixes = 0;
360 foreach ( $sites as $site ) {
361 switch_to_blog( $site->blog_id );
362 $count = self::count_option( $option );
363 if ( $count > 1 ) {
364 if ( ! $is_dry_run ) {
365 delete_option( $option );
366 }
367 WP_CLI::line(
368 sprintf(
369 /* translators: %1$d is a number, %2$s is the name of an option, %2$s is the site URL. */
370 __( 'Deleted %1$d %2$s options from %3$s', 'jetpack' ),
371 $count,
372 $option,
373 "{$site->domain}{$site->path}"
374 )
375 );
376 $count_fixes++;
377 if ( ! $is_dry_run ) {
378 /*
379 * We could be deleting a lot of options rows at the same time.
380 * Allow some time for replication to catch up.
381 */
382 sleep( 3 );
383 }
384 }
385
386 restore_current_blog();
387 }
388 if ( $count_fixes ) {
389 WP_CLI::success(
390 sprintf(
391 /* translators: %1$s is the name of an option, %2$d is a number of sites. */
392 __( 'Successfully reset %1$s on %2$d sites.', 'jetpack' ),
393 $option,
394 $count_fixes
395 )
396 );
397 } else {
398 WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
399 }
400 return;
401 }
402
403 $count = self::count_option( $option );
404 if ( $count > 1 ) {
405 if ( ! $is_dry_run ) {
406 delete_option( $option );
407 }
408 WP_CLI::success(
409 sprintf(
410 /* translators: %1$d is a number, %2$s is the name of an option. */
411 __( 'Deleted %1$d %2$s options', 'jetpack' ),
412 $count,
413 $option
414 )
415 );
416 return;
417 }
418
419 WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
420 break;
421
422 }
423 }
424
425 /**
426 * Return the number of times an option appears
427 * Normally an option would only appear 1 since the option key is supposed to be unique
428 * but if a site hasn't updated the DB schema then that would not be the case.
429 *
430 * @param string $option Option name.
431 *
432 * @return int
433 */
434 private static function count_option( $option ) {
435 global $wpdb;
436 return (int) $wpdb->get_var(
437 $wpdb->prepare(
438 "SELECT COUNT(*) FROM $wpdb->options WHERE option_name = %s",
439 $option
440 )
441 );
442
443 }
444
445 /**
446 * Manage Jetpack Modules
447 *
448 * ## OPTIONS
449 *
450 * <list|activate|deactivate|toggle>
451 * : The action to take.
452 * ---
453 * default: list
454 * options:
455 * - list
456 * - activate
457 * - deactivate
458 * - toggle
459 * ---
460 *
461 * [<module_slug>]
462 * : The slug of the module to perform an action on.
463 *
464 * [--format=<format>]
465 * : Allows overriding the output of the command when listing modules.
466 * ---
467 * default: table
468 * options:
469 * - table
470 * - json
471 * - csv
472 * - yaml
473 * - ids
474 * - count
475 * ---
476 *
477 * ## EXAMPLES
478 *
479 * wp jetpack module list
480 * wp jetpack module list --format=json
481 * wp jetpack module activate stats
482 * wp jetpack module deactivate stats
483 * wp jetpack module toggle stats
484 * wp jetpack module activate all
485 * wp jetpack module deactivate all
486 */
487 public function module( $args, $assoc_args ) {
488 $action = isset( $args[0] ) ? $args[0] : 'list';
489
490 if ( isset( $args[1] ) ) {
491 $module_slug = $args[1];
492 if ( 'all' !== $module_slug && ! Jetpack::is_module( $module_slug ) ) {
493 /* translators: %s is a module slug like "stats" */
494 WP_CLI::error( sprintf( __( '%s is not a valid module.', 'jetpack' ), $module_slug ) );
495 }
496 if ( 'toggle' === $action ) {
497 $action = Jetpack::is_module_active( $module_slug )
498 ? 'deactivate'
499 : 'activate';
500 }
501 if ( 'all' === $args[1] ) {
502 $action = ( 'deactivate' === $action )
503 ? 'deactivate_all'
504 : 'activate_all';
505 }
506 } elseif ( 'list' !== $action ) {
507 WP_CLI::line( __( 'Please specify a valid module.', 'jetpack' ) );
508 $action = 'list';
509 }
510
511 switch ( $action ) {
512 case 'list':
513 $modules_list = array();
514 $modules = Jetpack::get_available_modules();
515 sort( $modules );
516 foreach ( (array) $modules as $module_slug ) {
517 if ( 'vaultpress' === $module_slug ) {
518 continue;
519 }
520 $modules_list[] = array(
521 'slug' => $module_slug,
522 'status' => Jetpack::is_module_active( $module_slug )
523 ? __( 'Active', 'jetpack' )
524 : __( 'Inactive', 'jetpack' ),
525 );
526 }
527 WP_CLI\Utils\format_items( $assoc_args['format'], $modules_list, array( 'slug', 'status' ) );
528 break;
529 case 'activate':
530 $module = Jetpack::get_module( $module_slug );
531 Jetpack::log( 'activate', $module_slug );
532 if ( Jetpack::activate_module( $module_slug, false, false ) ) {
533 /* translators: %s is the name of a Jetpack module */
534 WP_CLI::success( sprintf( __( '%s has been activated.', 'jetpack' ), $module['name'] ) );
535 } else {
536 /* translators: %s is the name of a Jetpack module */
537 WP_CLI::error( sprintf( __( '%s could not be activated.', 'jetpack' ), $module['name'] ) );
538 }
539 break;
540 case 'activate_all':
541 $modules = Jetpack::get_available_modules();
542 Jetpack::update_active_modules( $modules );
543 WP_CLI::success( __( 'All modules activated!', 'jetpack' ) );
544 break;
545 case 'deactivate':
546 $module = Jetpack::get_module( $module_slug );
547 Jetpack::log( 'deactivate', $module_slug );
548 Jetpack::deactivate_module( $module_slug );
549 /* translators: %s is the name of a Jetpack module */
550 WP_CLI::success( sprintf( __( '%s has been deactivated.', 'jetpack' ), $module['name'] ) );
551 break;
552 case 'deactivate_all':
553 Jetpack::delete_active_modules();
554 WP_CLI::success( __( 'All modules deactivated!', 'jetpack' ) );
555 break;
556 case 'toggle':
557 // Will never happen, should have been handled above and changed to activate or deactivate.
558 break;
559 }
560 }
561
562 /**
563 * Manage Protect Settings
564 *
565 * ## OPTIONS
566 *
567 * allow: Add an IP address to an always allow list. You can also read or clear the allow list.
568 *
569 *
570 * ## EXAMPLES
571 *
572 * wp jetpack protect allow <ip address>
573 * wp jetpack protect allow list
574 * wp jetpack protect allow clear
575 *
576 * @synopsis <allow> [<ip|ip_low-ip_high|list|clear>]
577 */
578 public function protect( $args, $assoc_args ) {
579 $action = isset( $args[0] ) ? $args[0] : 'prompt';
580 if ( ! in_array( $action, array( 'whitelist', 'allow' ), true ) ) { // Still allow "whitelist" for legacy support.
581 /* translators: %s is a command like "prompt" */
582 WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
583 }
584 // Check if module is active
585 if ( ! Jetpack::is_module_active( __FUNCTION__ ) ) {
586 /* translators: %s is a module name */
587 WP_CLI::error( sprintf( _x( '%1$s is not active. You can activate it with "wp jetpack module activate %2$s"', '"wp jetpack module activate" is a command - do not translate', 'jetpack' ), __FUNCTION__, __FUNCTION__ ) );
588 }
589 if ( in_array( $action, array( 'allow', 'whitelist' ), true ) ) {
590 if ( isset( $args[1] ) ) {
591 $action = 'allow';
592 } else {
593 $action = 'prompt';
594 }
595 }
596 switch ( $action ) {
597 case 'allow':
598 $allow = array();
599 $new_ip = $args[1];
600 $current_allow = get_site_option( 'jetpack_protect_whitelist', array() ); // @todo Update the option name.
601
602 // Build array of IPs that are already on the allowed list.
603 // Re-build manually instead of using jetpack_protect_format_whitelist() so we can easily get
604 // low & high range params for jetpack_protect_ip_address_is_in_range();
605 foreach ( $current_allow as $allowed ) {
606
607 // IP ranges
608 if ( $allowed->range ) {
609
610 // Is it already on the allowed list?
611 if ( jetpack_protect_ip_address_is_in_range( $new_ip, $allowed->range_low, $allowed->range_high ) ) {
612 /* translators: %s is an IP address */
613 WP_CLI::error( sprintf( __( '%s is already on the always allow list.', 'jetpack' ), $new_ip ) );
614 break;
615 }
616 $allow[] = $allowed->range_low . ' - ' . $allowed->range_high;
617
618 } else { // Individual IPs
619
620 // Check if the IP is already on the allow list (single IP only).
621 if ( $new_ip === $allowed->ip_address ) {
622 /* translators: %s is an IP address */
623 WP_CLI::error( sprintf( __( '%s is already on the always allow list.', 'jetpack' ), $new_ip ) );
624 break;
625 }
626 $allow[] = $allowed->ip_address;
627
628 }
629 }
630
631 /*
632 * List the allowed IPs.
633 * Done here because it's easier to read the $allow array after it's been rebuilt.
634 */
635 if ( isset( $args[1] ) && 'list' == $args[1] ) {
636 if ( ! empty( $allow ) ) {
637 WP_CLI::success( __( 'Here are your always allowed IPs:', 'jetpack' ) );
638 foreach ( $allow as $ip ) {
639 WP_CLI::line( "\t" . str_pad( $ip, 24 ) );
640 }
641 } else {
642 WP_CLI::line( __( 'Always allow list is empty.', 'jetpack' ) );
643 }
644 break;
645 }
646
647 /*
648 * Clear the always allow list.
649 */
650 if ( isset( $args[1] ) && 'clear' == $args[1] ) {
651 if ( ! empty( $allow ) ) {
652 $allow = array();
653 jetpack_protect_save_whitelist( $allow ); // @todo Need to update function name in the Protect module.
654 WP_CLI::success( __( 'Cleared all IPs from the always allow list.', 'jetpack' ) );
655 } else {
656 WP_CLI::line( __( 'Always allow list is empty.', 'jetpack' ) );
657 }
658 break;
659 }
660
661 // Append new IP to allow array.
662 array_push( $allow, $new_ip );
663
664 // Save allow list if there are no errors.
665 $result = jetpack_protect_save_whitelist( $allow ); // @todo Need to update function name in the Protect module.
666 if ( is_wp_error( $result ) ) {
667 WP_CLI::error( $result );
668 }
669
670 /* translators: %s is an IP address */
671 WP_CLI::success( sprintf( __( '%s has been added to the always allowed list.', 'jetpack' ), $new_ip ) );
672 break;
673 case 'prompt':
674 WP_CLI::error(
675 __( 'No command found.', 'jetpack' ) . "\n" .
676 __( 'Please enter the IP address you want to always allow.', 'jetpack' ) . "\n" .
677 _x( 'You can save a range of IPs {low_range}-{high_range}. No spaces allowed. (example: 1.1.1.1-2.2.2.2)', 'Instructions on how to add IP ranges - low_range/high_range should be translated.', 'jetpack' ) . "\n" .
678 _x( "You can also 'list' or 'clear' the always allowed list.", "'list' and 'clear' are commands and should not be translated", 'jetpack' ) . "\n"
679 );
680 break;
681 }
682 }
683
684 /**
685 * Manage Jetpack Options
686 *
687 * ## OPTIONS
688 *
689 * list : List all jetpack options and their values
690 * delete : Delete an option
691 * - can only delete options that are white listed.
692 * update : update an option
693 * - can only update option strings
694 * get : get the value of an option
695 *
696 * ## EXAMPLES
697 *
698 * wp jetpack options list
699 * wp jetpack options get <option_name>
700 * wp jetpack options delete <option_name>
701 * wp jetpack options update <option_name> [<option_value>]
702 *
703 * @synopsis <list|get|delete|update> [<option_name>] [<option_value>]
704 */
705 public function options( $args, $assoc_args ) {
706 $action = isset( $args[0] ) ? $args[0] : 'list';
707 $safe_to_modify = Jetpack_Options::get_options_for_reset();
708
709 // Is the option flagged as unsafe?
710 $flagged = ! in_array( $args[1], $safe_to_modify );
711
712 if ( ! in_array( $action, array( 'list', 'get', 'delete', 'update' ) ) ) {
713 /* translators: %s is a command like "prompt" */
714 WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
715 }
716
717 if ( isset( $args[0] ) ) {
718 if ( 'get' == $args[0] && isset( $args[1] ) ) {
719 $action = 'get';
720 } elseif ( 'delete' == $args[0] && isset( $args[1] ) ) {
721 $action = 'delete';
722 } elseif ( 'update' == $args[0] && isset( $args[1] ) ) {
723 $action = 'update';
724 } else {
725 $action = 'list';
726 }
727 }
728
729 // Bail if the option isn't found
730 $option = isset( $args[1] ) ? Jetpack_Options::get_option( $args[1] ) : false;
731 if ( isset( $args[1] ) && ! $option && 'update' !== $args[0] ) {
732 WP_CLI::error( __( 'Option not found or is empty. Use "list" to list option names', 'jetpack' ) );
733 }
734
735 // Let's print_r the option if it's an array
736 // Used in the 'get' and 'list' actions
737 $option = is_array( $option ) ? print_r( $option ) : $option;
738
739 switch ( $action ) {
740 case 'get':
741 WP_CLI::success( "\t" . $option );
742 break;
743 case 'delete':
744 jetpack_cli_are_you_sure( $flagged );
745
746 Jetpack_Options::delete_option( $args[1] );
747 /* translators: %s is the option name */
748 WP_CLI::success( sprintf( __( 'Deleted option: %s', 'jetpack' ), $args[1] ) );
749 break;
750 case 'update':
751 jetpack_cli_are_you_sure( $flagged );
752
753 // Updating arrays would get pretty tricky...
754 $value = Jetpack_Options::get_option( $args[1] );
755 if ( $value && is_array( $value ) ) {
756 WP_CLI::error( __( 'Sorry, no updating arrays at this time', 'jetpack' ) );
757 }
758
759 Jetpack_Options::update_option( $args[1], $args[2] );
760 /* translators: %1$s is the previous value, %2$s is the new value */
761 WP_CLI::success( sprintf( _x( 'Updated option: %1$s to "%2$s"', 'Updating an option from "this" to "that".', 'jetpack' ), $args[1], $args[2] ) );
762 break;
763 case 'list':
764 $options_compact = Jetpack_Options::get_option_names();
765 $options_non_compact = Jetpack_Options::get_option_names( 'non_compact' );
766 $options_private = Jetpack_Options::get_option_names( 'private' );
767 $options = array_merge( $options_compact, $options_non_compact, $options_private );
768
769 // Table headers
770 WP_CLI::line( "\t" . str_pad( __( 'Option', 'jetpack' ), 30 ) . __( 'Value', 'jetpack' ) );
771
772 // List out the options and their values
773 // Tell them if the value is empty or not
774 // Tell them if it's an array
775 foreach ( $options as $option ) {
776 $value = Jetpack_Options::get_option( $option );
777 if ( ! $value ) {
778 WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Empty' );
779 continue;
780 }
781
782 if ( ! is_array( $value ) ) {
783 WP_CLI::line( "\t" . str_pad( $option, 30 ) . $value );
784 } elseif ( is_array( $value ) ) {
785 WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Array - Use "get <option>" to read option array.' );
786 }
787 }
788 $option_text = '{' . _x( 'option', 'a variable command that a user can write, provided in the printed instructions', 'jetpack' ) . '}';
789 $value_text = '{' . _x( 'value', 'the value that they want to update the option to', 'jetpack' ) . '}';
790
791 WP_CLI::success(
792 _x( "Above are your options. You may 'get', 'delete', and 'update' them.", "'get', 'delete', and 'update' are commands - do not translate.", 'jetpack' ) . "\n" .
793 str_pad( 'wp jetpack options get', 26 ) . $option_text . "\n" .
794 str_pad( 'wp jetpack options delete', 26 ) . $option_text . "\n" .
795 str_pad( 'wp jetpack options update', 26 ) . "$option_text $value_text" . "\n" .
796 _x( "Type 'wp jetpack options' for more info.", "'wp jetpack options' is a command - do not translate.", 'jetpack' ) . "\n"
797 );
798 break;
799 }
800 }
801
802 /**
803 * Get the status of or start a new Jetpack sync.
804 *
805 * ## OPTIONS
806 *
807 * status : Print the current sync status
808 * settings : Prints the current sync settings
809 * start : Start a full sync from this site to WordPress.com
810 * enable : Enables sync on the site
811 * disable : Disable sync on a site
812 * reset : Disables sync and Resets the sync queues on a site
813 *
814 * ## EXAMPLES
815 *
816 * wp jetpack sync status
817 * wp jetpack sync settings
818 * wp jetpack sync start --modules=functions --sync_wait_time=5
819 * wp jetpack sync enable
820 * wp jetpack sync disable
821 * wp jetpack sync reset
822 * wp jetpack sync reset --queue=full or regular
823 *
824 * @synopsis <status|start> [--<field>=<value>]
825 */
826 public function sync( $args, $assoc_args ) {
827
828 $action = isset( $args[0] ) ? $args[0] : 'status';
829
830 switch ( $action ) {
831 case 'status':
832 $status = Actions::get_sync_status();
833 $collection = array();
834 foreach ( $status as $key => $item ) {
835 $collection[] = array(
836 'option' => $key,
837 'value' => is_scalar( $item ) ? $item : json_encode( $item ),
838 );
839 }
840 WP_CLI::log( __( 'Sync Status:', 'jetpack' ) );
841 WP_CLI\Utils\format_items( 'table', $collection, array( 'option', 'value' ) );
842 break;
843 case 'settings':
844 WP_CLI::log( __( 'Sync Settings:', 'jetpack' ) );
845 foreach ( Settings::get_settings() as $setting => $item ) {
846 $settings[] = array(
847 'setting' => $setting,
848 'value' => is_scalar( $item ) ? $item : json_encode( $item ),
849 );
850 }
851 WP_CLI\Utils\format_items( 'table', $settings, array( 'setting', 'value' ) );
852
853 case 'disable':
854 // Don't set it via the Settings since that also resets the queues.
855 update_option( 'jetpack_sync_settings_disable', 1 );
856 /* translators: %s is the site URL */
857 WP_CLI::log( sprintf( __( 'Sync Disabled on %s', 'jetpack' ), get_site_url() ) );
858 break;
859 case 'enable':
860 Settings::update_settings( array( 'disable' => 0 ) );
861 /* translators: %s is the site URL */
862 WP_CLI::log( sprintf( __( 'Sync Enabled on %s', 'jetpack' ), get_site_url() ) );
863 break;
864 case 'reset':
865 // Don't set it via the Settings since that also resets the queues.
866 update_option( 'jetpack_sync_settings_disable', 1 );
867
868 /* translators: %s is the site URL */
869 WP_CLI::log( sprintf( __( 'Sync Disabled on %s. Use `wp jetpack sync enable` to enable syncing again.', 'jetpack' ), get_site_url() ) );
870 $listener = Listener::get_instance();
871 if ( empty( $assoc_args['queue'] ) ) {
872 $listener->get_sync_queue()->reset();
873 $listener->get_full_sync_queue()->reset();
874 /* translators: %s is the site URL */
875 WP_CLI::log( sprintf( __( 'Reset Full Sync and Regular Queues Queue on %s', 'jetpack' ), get_site_url() ) );
876 break;
877 }
878
879 if ( ! empty( $assoc_args['queue'] ) ) {
880 switch ( $assoc_args['queue'] ) {
881 case 'regular':
882 $listener->get_sync_queue()->reset();
883 /* translators: %s is the site URL */
884 WP_CLI::log( sprintf( __( 'Reset Regular Sync Queue on %s', 'jetpack' ), get_site_url() ) );
885 break;
886 case 'full':
887 $listener->get_full_sync_queue()->reset();
888 /* translators: %s is the site URL */
889 WP_CLI::log( sprintf( __( 'Reset Full Sync Queue on %s', 'jetpack' ), get_site_url() ) );
890 break;
891 default:
892 WP_CLI::error( __( 'Please specify what type of queue do you want to reset: `full` or `regular`.', 'jetpack' ) );
893 break;
894 }
895 }
896
897 break;
898 case 'start':
899 if ( ! Actions::sync_allowed() ) {
900 if ( Settings::get_setting( 'disable' ) ) {
901 WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. It is currently disabled. Run `wp jetpack sync enable` to enable it.', 'jetpack' ) );
902 return;
903 }
904 $connection = new Connection_Manager();
905 if ( ! $connection->is_connected() ) {
906 if ( ! doing_action( 'jetpack_site_registered' ) ) {
907 WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. Jetpack is not connected.', 'jetpack' ) );
908 return;
909 }
910 }
911
912 $status = new Status();
913
914 if ( $status->is_offline_mode() ) {
915 WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in offline mode.', 'jetpack' ) );
916 return;
917 }
918 if ( $status->is_staging_site() ) {
919 WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in staging mode.', 'jetpack' ) );
920 return;
921 }
922 }
923 // Get the original settings so that we can restore them later
924 $original_settings = Settings::get_settings();
925
926 // Initialize sync settigns so we can sync as quickly as possible
927 $sync_settings = wp_parse_args(
928 array_intersect_key( $assoc_args, Settings::$valid_settings ),
929 array(
930 'sync_wait_time' => 0,
931 'enqueue_wait_time' => 0,
932 'queue_max_writes_sec' => 10000,
933 'max_queue_size_full_sync' => 100000,
934 'full_sync_send_duration' => HOUR_IN_SECONDS,
935 )
936 );
937 Settings::update_settings( $sync_settings );
938
939 // Convert comma-delimited string of modules to an array
940 if ( ! empty( $assoc_args['modules'] ) ) {
941 $modules = array_map( 'trim', explode( ',', $assoc_args['modules'] ) );
942
943 // Convert the array so that the keys are the module name and the value is true to indicate
944 // that we want to sync the module
945 $modules = array_map( '__return_true', array_flip( $modules ) );
946 }
947
948 foreach ( array( 'posts', 'comments', 'users' ) as $module_name ) {
949 if (
950 'users' === $module_name &&
951 isset( $assoc_args[ $module_name ] ) &&
952 'initial' === $assoc_args[ $module_name ]
953 ) {
954 $modules['users'] = 'initial';
955 } elseif ( isset( $assoc_args[ $module_name ] ) ) {
956 $ids = explode( ',', $assoc_args[ $module_name ] );
957 if ( count( $ids ) > 0 ) {
958 $modules[ $module_name ] = $ids;
959 }
960 }
961 }
962
963 if ( empty( $modules ) ) {
964 $modules = null;
965 }
966
967 // Kick off a full sync
968 if ( Actions::do_full_sync( $modules ) ) {
969 if ( $modules ) {
970 /* translators: %s is a comma separated list of Jetpack modules */
971 WP_CLI::log( sprintf( __( 'Initialized a new full sync with modules: %s', 'jetpack' ), join( ', ', array_keys( $modules ) ) ) );
972 } else {
973 WP_CLI::log( __( 'Initialized a new full sync', 'jetpack' ) );
974 }
975 } else {
976
977 // Reset sync settings to original.
978 Settings::update_settings( $original_settings );
979
980 if ( $modules ) {
981 /* translators: %s is a comma separated list of Jetpack modules */
982 WP_CLI::error( sprintf( __( 'Could not start a new full sync with modules: %s', 'jetpack' ), join( ', ', $modules ) ) );
983 } else {
984 WP_CLI::error( __( 'Could not start a new full sync', 'jetpack' ) );
985 }
986 }
987
988 // Keep sending to WPCOM until there's nothing to send
989 $i = 1;
990 do {
991 $result = Actions::$sender->do_full_sync();
992 if ( is_wp_error( $result ) ) {
993 $queue_empty_error = ( 'empty_queue_full_sync' == $result->get_error_code() );
994 if ( ! $queue_empty_error || ( $queue_empty_error && ( 1 == $i ) ) ) {
995 /* translators: %s is an error code */
996 WP_CLI::error( sprintf( __( 'Sync errored with code: %s', 'jetpack' ), $result->get_error_code() ) );
997 }
998 } else {
999 if ( 1 == $i ) {
1000 WP_CLI::log( __( 'Sent data to WordPress.com', 'jetpack' ) );
1001 } else {
1002 WP_CLI::log( __( 'Sent more data to WordPress.com', 'jetpack' ) );
1003 }
1004
1005 // Immediate Full Sync does not wait for WP.com to process data so we need to enforce a wait.
1006 if ( false !== strpos( get_class( Modules::get_module( 'full-sync' ) ), 'Full_Sync_Immediately' ) ) {
1007 sleep( 15 );
1008 }
1009 }
1010 $i++;
1011 } while ( $result && ! is_wp_error( $result ) );
1012
1013 // Reset sync settings to original.
1014 Settings::update_settings( $original_settings );
1015
1016 WP_CLI::success( __( 'Finished syncing to WordPress.com', 'jetpack' ) );
1017 break;
1018 }
1019 }
1020
1021 /**
1022 * List the contents of a specific Jetpack sync queue.
1023 *
1024 * ## OPTIONS
1025 *
1026 * peek : List the 100 front-most items on the queue.
1027 *
1028 * ## EXAMPLES
1029 *
1030 * wp jetpack sync_queue full_sync peek
1031 *
1032 * @synopsis <incremental|full_sync> <peek>
1033 */
1034 public function sync_queue( $args, $assoc_args ) {
1035 if ( ! Actions::sync_allowed() ) {
1036 WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site.', 'jetpack' ) );
1037 }
1038
1039 $queue_name = isset( $args[0] ) ? $args[0] : 'sync';
1040 $action = isset( $args[1] ) ? $args[1] : 'peek';
1041
1042 // We map the queue name that way we can support more friendly queue names in the commands, but still use
1043 // the queue name that the code expects.
1044 $queue_name_map = $allowed_queues = array(
1045 'incremental' => 'sync',
1046 'full' => 'full_sync',
1047 );
1048 $mapped_queue_name = isset( $queue_name_map[ $queue_name ] ) ? $queue_name_map[ $queue_name ] : $queue_name;
1049
1050 switch ( $action ) {
1051 case 'peek':
1052 $queue = new Queue( $mapped_queue_name );
1053 $items = $queue->peek( 100 );
1054
1055 if ( empty( $items ) ) {
1056 /* translators: %s is the name of the queue, either 'incremental' or 'full' */
1057 WP_CLI::log( sprintf( __( 'Nothing is in the queue: %s', 'jetpack' ), $queue_name ) );
1058 } else {
1059 $collection = array();
1060 foreach ( $items as $item ) {
1061 $collection[] = array(
1062 'action' => $item[0],
1063 'args' => json_encode( $item[1] ),
1064 'current_user_id' => $item[2],
1065 'microtime' => $item[3],
1066 'importing' => (string) $item[4],
1067 );
1068 }
1069 WP_CLI\Utils\format_items(
1070 'table',
1071 $collection,
1072 array(
1073 'action',
1074 'args',
1075 'current_user_id',
1076 'microtime',
1077 'importing',
1078 )
1079 );
1080 }
1081 break;
1082 }
1083 }
1084
1085 /**
1086 * Cancel's the current Jetpack plan granted by this partner, if applicable
1087 *
1088 * Returns success or error JSON
1089 *
1090 * <token_json>
1091 * : JSON blob of WPCOM API token
1092 * [--partner_tracking_id=<partner_tracking_id>]
1093 * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
1094 *
1095 * * @synopsis <token_json> [--partner_tracking_id=<partner_tracking_id>]
1096 */
1097 public function partner_cancel( $args, $named_args ) {
1098 list( $token_json ) = $args;
1099
1100 if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
1101 /* translators: %s is the invalid JSON string */
1102 $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
1103 }
1104
1105 if ( isset( $token->error ) ) {
1106 $this->partner_provision_error( new WP_Error( $token->error, $token->message ) );
1107 }
1108
1109 if ( ! isset( $token->access_token ) ) {
1110 $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
1111 }
1112
1113 if ( Jetpack::validate_sync_error_idc_option() ) {
1114 $this->partner_provision_error(
1115 new WP_Error(
1116 'site_in_safe_mode',
1117 esc_html__( 'Can not cancel a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
1118 )
1119 );
1120 }
1121
1122 $site_identifier = Jetpack_Options::get_option( 'id' );
1123
1124 if ( ! $site_identifier ) {
1125 $status = new Status();
1126 $site_identifier = $status->get_site_suffix();
1127 }
1128
1129 $request = array(
1130 'headers' => array(
1131 'Authorization' => 'Bearer ' . $token->access_token,
1132 'Host' => 'public-api.wordpress.com',
1133 ),
1134 'timeout' => 60,
1135 'method' => 'POST',
1136 );
1137
1138 $url = sprintf( '%s/rest/v1.3/jpphp/%s/partner-cancel', $this->get_api_host(), $site_identifier );
1139 if ( ! empty( $named_args ) && ! empty( $named_args['partner_tracking_id'] ) ) {
1140 $url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
1141 }
1142
1143 $result = Client::_wp_remote_request( $url, $request );
1144
1145 Jetpack_Options::delete_option( 'onboarding' );
1146
1147 if ( is_wp_error( $result ) ) {
1148 $this->partner_provision_error( $result );
1149 }
1150
1151 WP_CLI::log( wp_remote_retrieve_body( $result ) );
1152 }
1153
1154 /**
1155 * Provision a site using a Jetpack Partner license
1156 *
1157 * Returns JSON blob
1158 *
1159 * ## OPTIONS
1160 *
1161 * <token_json>
1162 * : JSON blob of WPCOM API token
1163 * [--plan=<plan_name>]
1164 * : Slug of the requested plan, e.g. premium
1165 * [--wpcom_user_id=<user_id>]
1166 * : WordPress.com ID of user to connect as (must be whitelisted against partner key)
1167 * [--wpcom_user_email=<wpcom_user_email>]
1168 * : Override the email we send to WordPress.com for registration
1169 * [--onboarding=<onboarding>]
1170 * : Guide the user through an onboarding wizard
1171 * [--force_register=<register>]
1172 * : Whether to force a site to register
1173 * [--force_connect=<force_connect>]
1174 * : Force JPS to not reuse existing credentials
1175 * [--home_url=<home_url>]
1176 * : Overrides the home option via the home_url filter, or the WP_HOME constant
1177 * [--site_url=<site_url>]
1178 * : Overrides the siteurl option via the site_url filter, or the WP_SITEURL constant
1179 * [--partner_tracking_id=<partner_tracking_id>]
1180 * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
1181 *
1182 * ## EXAMPLES
1183 *
1184 * $ wp jetpack partner_provision '{ some: "json" }' premium 1
1185 * { success: true }
1186 *
1187 * @synopsis <token_json> [--wpcom_user_id=<user_id>] [--plan=<plan_name>] [--onboarding=<onboarding>] [--force_register=<register>] [--force_connect=<force_connect>] [--home_url=<home_url>] [--site_url=<site_url>] [--wpcom_user_email=<wpcom_user_email>] [--partner_tracking_id=<partner_tracking_id>]
1188 */
1189 public function partner_provision( $args, $named_args ) {
1190 list( $token_json ) = $args;
1191
1192 if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
1193 /* translators: %s is the invalid JSON string */
1194 $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
1195 }
1196
1197 if ( isset( $token->error ) ) {
1198 $message = isset( $token->message )
1199 ? $token->message
1200 : '';
1201 $this->partner_provision_error( new WP_Error( $token->error, $message ) );
1202 }
1203
1204 if ( ! isset( $token->access_token ) ) {
1205 $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
1206 }
1207
1208 require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';
1209
1210 $body_json = Jetpack_Provision::partner_provision( $token->access_token, $named_args );
1211
1212 if ( is_wp_error( $body_json ) ) {
1213 error_log(
1214 json_encode(
1215 array(
1216 'success' => false,
1217 'error_code' => $body_json->get_error_code(),
1218 'error_message' => $body_json->get_error_message(),
1219 )
1220 )
1221 );
1222 exit( 1 );
1223 }
1224
1225 WP_CLI::log( json_encode( $body_json ) );
1226 }
1227
1228 /**
1229 * Manages your Jetpack sitemap
1230 *
1231 * ## OPTIONS
1232 *
1233 * rebuild : Rebuild all sitemaps
1234 * --purge : if set, will remove all existing sitemap data before rebuilding
1235 *
1236 * ## EXAMPLES
1237 *
1238 * wp jetpack sitemap rebuild
1239 *
1240 * @subcommand sitemap
1241 * @synopsis <rebuild> [--purge]
1242 */
1243 public function sitemap( $args, $assoc_args ) {
1244 if ( ! Jetpack::is_active() ) {
1245 WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
1246 }
1247 if ( ! Jetpack::is_module_active( 'sitemaps' ) ) {
1248 WP_CLI::error( __( 'Jetpack Sitemaps module is not currently active. Activate it first if you want to work with sitemaps.', 'jetpack' ) );
1249 }
1250 if ( ! class_exists( 'Jetpack_Sitemap_Builder' ) ) {
1251 WP_CLI::error( __( 'Jetpack Sitemaps module is active, but unavailable. This can happen if your site is set to discourage search engine indexing. Please enable search engine indexing to allow sitemap generation.', 'jetpack' ) );
1252 }
1253
1254 if ( isset( $assoc_args['purge'] ) && $assoc_args['purge'] ) {
1255 $librarian = new Jetpack_Sitemap_Librarian();
1256 $librarian->delete_all_stored_sitemap_data();
1257 }
1258
1259 $sitemap_builder = new Jetpack_Sitemap_Builder();
1260 $sitemap_builder->update_sitemap();
1261 }
1262
1263 /**
1264 * Allows authorizing a user via the command line and will activate
1265 *
1266 * ## EXAMPLES
1267 *
1268 * wp jetpack authorize_user --token=123456789abcdef
1269 *
1270 * @synopsis --token=<value>
1271 */
1272 public function authorize_user( $args, $named_args ) {
1273 if ( ! is_user_logged_in() ) {
1274 WP_CLI::error( __( 'Please select a user to authorize via the --user global argument.', 'jetpack' ) );
1275 }
1276
1277 if ( empty( $named_args['token'] ) ) {
1278 WP_CLI::error( __( 'A non-empty token argument must be passed.', 'jetpack' ) );
1279 }
1280
1281 $is_master_user = ! Jetpack::is_active();
1282 $current_user_id = get_current_user_id();
1283
1284 ( new Tokens() )->update_user_token( $current_user_id, sprintf( '%s.%d', $named_args['token'], $current_user_id ), $is_master_user );
1285
1286 WP_CLI::log( wp_json_encode( $named_args ) );
1287
1288 if ( $is_master_user ) {
1289 /**
1290 * Auto-enable SSO module for new Jetpack Start connections
1291 *
1292 * @since 5.0.0
1293 *
1294 * @param bool $enable_sso Whether to enable the SSO module. Default to true.
1295 */
1296 $enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
1297 Jetpack::handle_post_authorization_actions( $enable_sso, false );
1298
1299 /* translators: %d is a user ID */
1300 WP_CLI::success( sprintf( __( 'Authorized %d and activated default modules.', 'jetpack' ), $current_user_id ) );
1301 } else {
1302 /* translators: %d is a user ID */
1303 WP_CLI::success( sprintf( __( 'Authorized %d.', 'jetpack' ), $current_user_id ) );
1304 }
1305 }
1306
1307 /**
1308 * Allows calling a WordPress.com API endpoint using the current blog's token.
1309 *
1310 * ## OPTIONS
1311 * --resource=<resource>
1312 * : The resource to call with the current blog's token, where `%d` represents the current blog's ID.
1313 *
1314 * [--api_version=<api_version>]
1315 * : The API version to query against.
1316 *
1317 * [--base_api_path=<base_api_path>]
1318 * : The base API path to query.
1319 * ---
1320 * default: rest
1321 * ---
1322 *
1323 * [--body=<body>]
1324 * : A JSON encoded string representing arguments to send in the body.
1325 *
1326 * [--field=<value>]
1327 * : Any number of arguments that should be passed to the resource.
1328 *
1329 * [--pretty]
1330 * : Will pretty print the results of a successful API call.
1331 *
1332 * [--strip-success]
1333 * : Will remove the green success label from successful API calls.
1334 *
1335 * ## EXAMPLES
1336 *
1337 * wp jetpack call_api --resource='/sites/%d'
1338 */
1339 public function call_api( $args, $named_args ) {
1340 if ( ! Jetpack::is_active() ) {
1341 WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
1342 }
1343
1344 $consumed_args = array(
1345 'resource',
1346 'api_version',
1347 'base_api_path',
1348 'body',
1349 'pretty',
1350 );
1351
1352 // Get args that should be passed to resource.
1353 $other_args = array_diff_key( $named_args, array_flip( $consumed_args ) );
1354
1355 $decoded_body = ! empty( $named_args['body'] )
1356 ? json_decode( $named_args['body'], true )
1357 : false;
1358
1359 $resource_url = ( false === strpos( $named_args['resource'], '%d' ) )
1360 ? $named_args['resource']
1361 : sprintf( $named_args['resource'], Jetpack_Options::get_option( 'id' ) );
1362
1363 $response = Client::wpcom_json_api_request_as_blog(
1364 $resource_url,
1365 empty( $named_args['api_version'] ) ? Client::WPCOM_JSON_API_VERSION : $named_args['api_version'],
1366 $other_args,
1367 empty( $decoded_body ) ? null : $decoded_body,
1368 empty( $named_args['base_api_path'] ) ? 'rest' : $named_args['base_api_path']
1369 );
1370
1371 if ( is_wp_error( $response ) ) {
1372 WP_CLI::error(
1373 sprintf(
1374 /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an error code, %3$s is an error message. */
1375 __( 'Request to %1$s returned an error: (%2$d) %3$s.', 'jetpack' ),
1376 $resource_url,
1377 $response->get_error_code(),
1378 $response->get_error_message()
1379 )
1380 );
1381 }
1382
1383 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1384 WP_CLI::error(
1385 sprintf(
1386 /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an HTTP status code. */
1387 __( 'Request to %1$s returned a non-200 response code: %2$d.', 'jetpack' ),
1388 $resource_url,
1389 wp_remote_retrieve_response_code( $response )
1390 )
1391 );
1392 }
1393
1394 $output = wp_remote_retrieve_body( $response );
1395 if ( isset( $named_args['pretty'] ) ) {
1396 $decoded_output = json_decode( $output );
1397 if ( $decoded_output ) {
1398 $output = wp_json_encode( $decoded_output, JSON_PRETTY_PRINT );
1399 }
1400 }
1401
1402 if ( isset( $named_args['strip-success'] ) ) {
1403 WP_CLI::log( $output );
1404 WP_CLI::halt( 0 );
1405 }
1406
1407 WP_CLI::success( $output );
1408 }
1409
1410 /**
1411 * Allows uploading SSH Credentials to the current site for backups, restores, and security scanning.
1412 *
1413 * ## OPTIONS
1414 *
1415 * [--host=<host>]
1416 * : The SSH server's address.
1417 *
1418 * [--ssh-user=<user>]
1419 * : The username to use to log in to the SSH server.
1420 *
1421 * [--pass=<pass>]
1422 * : The password used to log in, if using a password. (optional)
1423 *
1424 * [--kpri=<kpri>]
1425 * : The private key used to log in, if using a private key. (optional)
1426 *
1427 * [--pretty]
1428 * : Will pretty print the results of a successful API call. (optional)
1429 *
1430 * [--strip-success]
1431 * : Will remove the green success label from successful API calls. (optional)
1432 *
1433 * ## EXAMPLES
1434 *
1435 * wp jetpack upload_ssh_creds --host=example.com --ssh-user=example --pass=password
1436 * wp jetpack updload_ssh_creds --host=example.com --ssh-user=example --kpri=key
1437 */
1438 public function upload_ssh_creds( $args, $named_args ) {
1439 if ( ! Jetpack::is_active() ) {
1440 WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
1441 }
1442
1443 $required_args = array(
1444 'host',
1445 'ssh-user',
1446 );
1447
1448 foreach ( $required_args as $arg ) {
1449 if ( empty( $named_args[ $arg ] ) ) {
1450 WP_CLI::error(
1451 sprintf(
1452 /* translators: %s is a slug, such as 'host'. */
1453 __( '`%s` cannot be empty.', 'jetpack' ),
1454 $arg
1455 )
1456 );
1457 }
1458 }
1459
1460 if ( empty( $named_args['pass'] ) && empty( $named_args['kpri'] ) ) {
1461 WP_CLI::error( __( 'Both `pass` and `kpri` fields cannot be blank.', 'jetpack' ) );
1462 }
1463
1464 $values = array(
1465 'credentials' => array(
1466 'site_url' => get_site_url(),
1467 'abspath' => ABSPATH,
1468 'protocol' => 'ssh',
1469 'port' => 22,
1470 'role' => 'main',
1471 'host' => $named_args['host'],
1472 'user' => $named_args['ssh-user'],
1473 'pass' => empty( $named_args['pass'] ) ? '' : $named_args['pass'],
1474 'kpri' => empty( $named_args['kpri'] ) ? '' : $named_args['kpri'],
1475 ),
1476 );
1477
1478 $named_args = wp_parse_args(
1479 array(
1480 'resource' => '/activity-log/%d/update-credentials',
1481 'method' => 'POST',
1482 'api_version' => '1.1',
1483 'body' => wp_json_encode( $values ),
1484 'timeout' => 30,
1485 ),
1486 $named_args
1487 );
1488
1489 self::call_api( $args, $named_args );
1490 }
1491
1492 /**
1493 * API wrapper for getting stats from the WordPress.com API for the current site.
1494 *
1495 * ## OPTIONS
1496 *
1497 * [--quantity=<quantity>]
1498 * : The number of units to include.
1499 * ---
1500 * default: 30
1501 * ---
1502 *
1503 * [--period=<period>]
1504 * : The unit of time to query stats for.
1505 * ---
1506 * default: day
1507 * options:
1508 * - day
1509 * - week
1510 * - month
1511 * - year
1512 * ---
1513 *
1514 * [--date=<date>]
1515 * : The latest date to return stats for. Ex. - 2018-01-01.
1516 *
1517 * [--pretty]
1518 * : Will pretty print the results of a successful API call.
1519 *
1520 * [--strip-success]
1521 * : Will remove the green success label from successful API calls.
1522 *
1523 * ## EXAMPLES
1524 *
1525 * wp jetpack get_stats
1526 */
1527 public function get_stats( $args, $named_args ) {
1528 $selected_args = array_intersect_key(
1529 $named_args,
1530 array_flip(
1531 array(
1532 'quantity',
1533 'date',
1534 )
1535 )
1536 );
1537
1538 // The API expects unit, but period seems to be more correct.
1539 $selected_args['unit'] = $named_args['period'];
1540
1541 $command = sprintf(
1542 'jetpack call_api --resource=/sites/%d/stats/%s',
1543 Jetpack_Options::get_option( 'id' ),
1544 add_query_arg( $selected_args, 'visits' )
1545 );
1546
1547 if ( isset( $named_args['pretty'] ) ) {
1548 $command .= ' --pretty';
1549 }
1550
1551 if ( isset( $named_args['strip-success'] ) ) {
1552 $command .= ' --strip-success';
1553 }
1554
1555 WP_CLI::runcommand(
1556 $command,
1557 array(
1558 'launch' => false, // Use the current process.
1559 )
1560 );
1561 }
1562
1563 /**
1564 * Allows management of publicize connections.
1565 *
1566 * ## OPTIONS
1567 *
1568 * <list|disconnect>
1569 * : The action to perform.
1570 * ---
1571 * options:
1572 * - list
1573 * - disconnect
1574 * ---
1575 *
1576 * [<identifier>]
1577 * : The connection ID or service to perform an action on.
1578 *
1579 * [--format=<format>]
1580 * : Allows overriding the output of the command when listing connections.
1581 * ---
1582 * default: table
1583 * options:
1584 * - table
1585 * - json
1586 * - csv
1587 * - yaml
1588 * - ids
1589 * - count
1590 * ---
1591 *
1592 * ## EXAMPLES
1593 *
1594 * # List all publicize connections.
1595 * $ wp jetpack publicize list
1596 *
1597 * # List publicize connections for a given service.
1598 * $ wp jetpack publicize list twitter
1599 *
1600 * # List all publicize connections for a given user.
1601 * $ wp --user=1 jetpack publicize list
1602 *
1603 * # List all publicize connections for a given user and service.
1604 * $ wp --user=1 jetpack publicize list twitter
1605 *
1606 * # Display details for a given connection.
1607 * $ wp jetpack publicize list 123456
1608 *
1609 * # Diconnection a given connection.
1610 * $ wp jetpack publicize disconnect 123456
1611 *
1612 * # Disconnect all connections.
1613 * $ wp jetpack publicize disconnect all
1614 *
1615 * # Disconnect all connections for a given service.
1616 * $ wp jetpack publicize disconnect twitter
1617 */
1618 public function publicize( $args, $named_args ) {
1619 if ( ! Jetpack::is_active() ) {
1620 WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
1621 }
1622
1623 if ( ! Jetpack::is_module_active( 'publicize' ) ) {
1624 WP_CLI::error( __( 'The publicize module is not active.', 'jetpack' ) );
1625 }
1626
1627 if ( ( new Status() )->is_offline_mode() ) {
1628 if (
1629 ! defined( 'JETPACK_DEV_DEBUG' ) &&
1630 ! has_filter( 'jetpack_development_mode' ) &&
1631 ! has_filter( 'jetpack_offline_mode' ) &&
1632 false === strpos( site_url(), '.' )
1633 ) {
1634 WP_CLI::error( __( "Jetpack is current in offline mode because the site url does not contain a '.', which often occurs when dynamically setting the WP_SITEURL constant. While in offline mode, the publicize module will not load.", 'jetpack' ) );
1635 }
1636
1637 WP_CLI::error( __( 'Jetpack is currently in offline mode, so the publicize module will not load.', 'jetpack' ) );
1638 }
1639
1640 if ( ! class_exists( 'Publicize' ) ) {
1641 WP_CLI::error( __( 'The publicize module is not loaded.', 'jetpack' ) );
1642 }
1643
1644 $action = $args[0];
1645 $publicize = new Publicize();
1646 $identifier = ! empty( $args[1] ) ? $args[1] : false;
1647 $services = array_keys( $publicize->get_services() );
1648 $id_is_service = in_array( $identifier, $services, true );
1649
1650 switch ( $action ) {
1651 case 'list':
1652 $connections_to_return = array();
1653
1654 // For the CLI command, let's return all connections when a user isn't specified. This
1655 // differs from the logic in the Publicize class.
1656 $option_connections = is_user_logged_in()
1657 ? (array) $publicize->get_all_connections_for_user()
1658 : (array) $publicize->get_all_connections();
1659
1660 foreach ( $option_connections as $service_name => $connections ) {
1661 foreach ( (array) $connections as $id => $connection ) {
1662 $connection['id'] = $id;
1663 $connection['service'] = $service_name;
1664 $connections_to_return[] = $connection;
1665 }
1666 }
1667
1668 if ( $id_is_service && ! empty( $identifier ) && ! empty( $connections_to_return ) ) {
1669 $temp_connections = $connections_to_return;
1670 $connections_to_return = array();
1671
1672 foreach ( $temp_connections as $connection ) {
1673 if ( $identifier === $connection['service'] ) {
1674 $connections_to_return[] = $connection;
1675 }
1676 }
1677 }
1678
1679 if ( $identifier && ! $id_is_service && ! empty( $connections_to_return ) ) {
1680 $connections_to_return = wp_list_filter( $connections_to_return, array( 'id' => $identifier ) );
1681 }
1682
1683 $expected_keys = array(
1684 'id',
1685 'service',
1686 'user_id',
1687 'provider',
1688 'issued',
1689 'expires',
1690 'external_id',
1691 'external_name',
1692 'external_display',
1693 'type',
1694 'connection_data',
1695 );
1696
1697 // Somehow, a test site ended up in a state where $connections_to_return looked like:
1698 // array( array( array( 'id' => 0, 'service' => 0 ) ) ) // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
1699 // This caused the CLI command to error when running WP_CLI\Utils\format_items() below. So
1700 // to minimize future issues, this nested loop will remove any connections that don't contain
1701 // any keys that we expect.
1702 foreach ( (array) $connections_to_return as $connection_key => $connection ) {
1703 foreach ( $expected_keys as $expected_key ) {
1704 if ( ! isset( $connection[ $expected_key ] ) ) {
1705 unset( $connections_to_return[ $connection_key ] );
1706 continue;
1707 }
1708 }
1709 }
1710
1711 if ( empty( $connections_to_return ) ) {
1712 return false;
1713 }
1714
1715 WP_CLI\Utils\format_items( $named_args['format'], $connections_to_return, $expected_keys );
1716 break; // list.
1717 case 'disconnect':
1718 if ( ! $identifier ) {
1719 WP_CLI::error( __( 'A connection ID must be passed in order to disconnect.', 'jetpack' ) );
1720 }
1721
1722 // If the connection ID is 'all' then delete all connections. If the connection ID
1723 // matches a service, delete all connections for that service.
1724 if ( 'all' === $identifier || $id_is_service ) {
1725 if ( 'all' === $identifier ) {
1726 WP_CLI::log( __( "You're about to delete all publicize connections.", 'jetpack' ) );
1727 } else {
1728 /* translators: %s is a lowercase string for a social network. */
1729 WP_CLI::log( sprintf( __( "You're about to delete all publicize connections to %s.", 'jetpack' ), $identifier ) );
1730 }
1731
1732 jetpack_cli_are_you_sure();
1733
1734 $connections = array();
1735 $service = $identifier;
1736
1737 $option_connections = is_user_logged_in()
1738 ? (array) $publicize->get_all_connections_for_user()
1739 : (array) $publicize->get_all_connections();
1740
1741 if ( 'all' === $service ) {
1742 foreach ( (array) $option_connections as $service_name => $service_connections ) {
1743 foreach ( $service_connections as $id => $connection ) {
1744 $connections[ $id ] = $connection;
1745 }
1746 }
1747 } elseif ( ! empty( $option_connections[ $service ] ) ) {
1748 $connections = $option_connections[ $service ];
1749 }
1750
1751 if ( ! empty( $connections ) ) {
1752 $count = count( $connections );
1753 $progress = \WP_CLI\Utils\make_progress_bar(
1754 /* translators: %s is a lowercase string for a social network. */
1755 sprintf( __( 'Disconnecting all connections to %s.', 'jetpack' ), $service ),
1756 $count
1757 );
1758
1759 foreach ( $connections as $id => $connection ) {
1760 if ( false === $publicize->disconnect( false, $id ) ) {
1761 WP_CLI::error(
1762 sprintf(
1763 /* translators: %1$d is a numeric ID and %2$s is a lowercase string for a social network. */
1764 __( 'Publicize connection %d could not be disconnected', 'jetpack' ),
1765 $id
1766 )
1767 );
1768 }
1769
1770 $progress->tick();
1771 }
1772
1773 $progress->finish();
1774
1775 if ( 'all' === $service ) {
1776 WP_CLI::success( __( 'All publicize connections were successfully disconnected.', 'jetpack' ) );
1777 } else {
1778 /* translators: %s is a lowercase string for a social network. */
1779 WP_CLI::success( __( 'All publicize connections to %s were successfully disconnected.', 'jetpack' ), $service );
1780 }
1781 }
1782 } else {
1783 if ( false !== $publicize->disconnect( false, $identifier ) ) {
1784 /* translators: %d is a numeric ID. Example: 1234. */
1785 WP_CLI::success( sprintf( __( 'Publicize connection %d has been disconnected.', 'jetpack' ), $identifier ) );
1786 } else {
1787 /* translators: %d is a numeric ID. Example: 1234. */
1788 WP_CLI::error( sprintf( __( 'Publicize connection %d could not be disconnected.', 'jetpack' ), $identifier ) );
1789 }
1790 }
1791 break; // disconnect.
1792 }
1793 }
1794
1795 private function get_api_host() {
1796 $env_api_host = getenv( 'JETPACK_START_API_HOST', true );
1797 return $env_api_host ? 'https://' . $env_api_host : JETPACK__WPCOM_JSON_API_BASE;
1798 }
1799
1800 private function partner_provision_error( $error ) {
1801 WP_CLI::log(
1802 json_encode(
1803 array(
1804 'success' => false,
1805 'error_code' => $error->get_error_code(),
1806 'error_message' => $error->get_error_message(),
1807 )
1808 )
1809 );
1810 exit( 1 );
1811 }
1812
1813 /**
1814 * Creates the essential files in Jetpack to start building a Gutenberg block or plugin.
1815 *
1816 * ## TYPES
1817 *
1818 * block: it creates a Jetpack block. All files will be created in a directory under extensions/blocks named based on the block title or a specific given slug.
1819 *
1820 * ## BLOCK TYPE OPTIONS
1821 *
1822 * The first parameter is the block title and it's not associative. Add it wrapped in quotes.
1823 * The title is also used to create the slug and the edit PHP class name. If it's something like "Logo gallery", the slug will be 'logo-gallery' and the class name will be LogoGalleryEdit.
1824 * --slug: Specific slug to identify the block that overrides the one generated based on the title.
1825 * --description: Allows to provide a text description of the block.
1826 * --keywords: Provide up to three keywords separated by comma so users can find this block when they search in Gutenberg's inserter.
1827 * --variation: Allows to decide whether the block should be a production block, experimental, or beta. Defaults to Beta when arg not provided.
1828 *
1829 * ## BLOCK TYPE EXAMPLES
1830 *
1831 * wp jetpack scaffold block "Cool Block"
1832 * wp jetpack scaffold block "Amazing Rock" --slug="good-music" --description="Rock the best music on your site"
1833 * wp jetpack scaffold block "Jukebox" --keywords="music, audio, media"
1834 * wp jetpack scaffold block "Jukebox" --variation="experimental"
1835 *
1836 * @subcommand scaffold block
1837 * @synopsis <type> <title> [--slug] [--description] [--keywords] [--variation]
1838 *
1839 * @param array $args Positional parameters, when strings are passed, wrap them in quotes.
1840 * @param array $assoc_args Associative parameters like --slug="nice-block".
1841 */
1842 public function scaffold( $args, $assoc_args ) {
1843 // It's ok not to check if it's set, because otherwise WPCLI exits earlier.
1844 switch ( $args[0] ) {
1845 case 'block':
1846 $this->block( $args, $assoc_args );
1847 break;
1848 default:
1849 /* translators: %s is the subcommand */
1850 WP_CLI::error( sprintf( esc_html__( 'Invalid subcommand %s.', 'jetpack' ), $args[0] ) . ' 👻' );
1851 exit( 1 );
1852 }
1853 }
1854
1855 /**
1856 * Creates the essential files in Jetpack to build a Gutenberg block.
1857 *
1858 * @param array $args Positional parameters. Only one is used, that corresponds to the block title.
1859 * @param array $assoc_args Associative parameters defined in the scaffold() method.
1860 */
1861 public function block( $args, $assoc_args ) {
1862 if ( isset( $args[1] ) ) {
1863 $title = ucwords( $args[1] );
1864 } else {
1865 WP_CLI::error( esc_html__( 'The title parameter is required.', 'jetpack' ) . ' 👻' );
1866 exit( 1 );
1867 }
1868
1869 $slug = isset( $assoc_args['slug'] )
1870 ? $assoc_args['slug']
1871 : sanitize_title( $title );
1872
1873 $variation_options = array( 'production', 'experimental', 'beta' );
1874 $variation = ( isset( $assoc_args['variation'] ) && in_array( $assoc_args['variation'], $variation_options, true ) )
1875 ? $assoc_args['variation']
1876 : 'beta';
1877
1878 if ( preg_match( '#^jetpack/#', $slug ) ) {
1879 $slug = preg_replace( '#^jetpack/#', '', $slug );
1880 }
1881
1882 if ( ! preg_match( '/^[a-z][a-z0-9\-]*$/', $slug ) ) {
1883 WP_CLI::error( esc_html__( 'Invalid block slug. They can contain only lowercase alphanumeric characters or dashes, and start with a letter', 'jetpack' ) . ' 👻' );
1884 }
1885
1886 global $wp_filesystem;
1887 if ( ! WP_Filesystem() ) {
1888 WP_CLI::error( esc_html__( "Can't write files", 'jetpack' ) . ' 😱' );
1889 }
1890
1891 $path = JETPACK__PLUGIN_DIR . "extensions/blocks/$slug";
1892
1893 if ( $wp_filesystem->exists( $path ) && $wp_filesystem->is_dir( $path ) ) {
1894 /* translators: %s is path to the conflicting block */
1895 WP_CLI::error( sprintf( esc_html__( 'Name conflicts with the existing block %s', 'jetpack' ), $path ) . ' ⛔️' );
1896 exit( 1 );
1897 }
1898
1899 $wp_filesystem->mkdir( $path );
1900
1901 $hasKeywords = isset( $assoc_args['keywords'] );
1902
1903 $files = array(
1904 "$path/$slug.php" => $this->render_block_file(
1905 'block-register-php',
1906 array(
1907 'slug' => $slug,
1908 'title' => $title,
1909 'underscoredSlug' => str_replace( '-', '_', $slug ),
1910 'underscoredTitle' => str_replace( ' ', '_', $title ),
1911 'jetpackVersion' => substr( JETPACK__VERSION, 0, strpos( JETPACK__VERSION, '.' ) ) . '.x',
1912 )
1913 ),
1914 "$path/index.js" => $this->render_block_file(
1915 'block-index-js',
1916 array(
1917 'slug' => $slug,
1918 'title' => $title,
1919 'description' => isset( $assoc_args['description'] )
1920 ? $assoc_args['description']
1921 : $title,
1922 'keywords' => $hasKeywords
1923 ? array_map(
1924 function( $keyword ) {
1925 // Construction necessary for Mustache lists
1926 return array( 'keyword' => trim( $keyword ) );
1927 },
1928 explode( ',', $assoc_args['keywords'], 3 )
1929 )
1930 : '',
1931 'hasKeywords' => $hasKeywords,
1932 )
1933 ),
1934 "$path/editor.js" => $this->render_block_file( 'block-editor-js' ),
1935 "$path/editor.scss" => $this->render_block_file(
1936 'block-editor-scss',
1937 array(
1938 'slug' => $slug,
1939 'title' => $title,
1940 )
1941 ),
1942 "$path/edit.js" => $this->render_block_file(
1943 'block-edit-js',
1944 array(
1945 'title' => $title,
1946 'className' => str_replace( ' ', '', ucwords( str_replace( '-', ' ', $slug ) ) ),
1947 )
1948 ),
1949 "$path/icon.js" => $this->render_block_file( 'block-icon-js' ),
1950 "$path/attributes.js" => $this->render_block_file( 'block-attributes-js' ),
1951 );
1952
1953 $files_written = array();
1954
1955 foreach ( $files as $filename => $contents ) {
1956 if ( $wp_filesystem->put_contents( $filename, $contents ) ) {
1957 $files_written[] = $filename;
1958 } else {
1959 /* translators: %s is a file name */
1960 WP_CLI::error( sprintf( esc_html__( 'Error creating %s', 'jetpack' ), $filename ) );
1961 }
1962 }
1963
1964 if ( empty( $files_written ) ) {
1965 WP_CLI::log( esc_html__( 'No files were created', 'jetpack' ) );
1966 } else {
1967 // Load index.json and insert the slug of the new block in its block variation array.
1968 $block_list_path = JETPACK__PLUGIN_DIR . 'extensions/index.json';
1969 $block_list = $wp_filesystem->get_contents( $block_list_path );
1970 if ( empty( $block_list ) ) {
1971 /* translators: %s is the path to the file with the block list */
1972 WP_CLI::error( sprintf( esc_html__( 'Error fetching contents of %s', 'jetpack' ), $block_list_path ) );
1973 } elseif ( false === stripos( $block_list, $slug ) ) {
1974 $new_block_list = json_decode( $block_list );
1975 $new_block_list->{ $variation }[] = $slug;
1976
1977 // Format the JSON to match our coding standards.
1978 $new_block_list_formatted = wp_json_encode( $new_block_list, JSON_PRETTY_PRINT ) . "\n";
1979 $new_block_list_formatted = preg_replace_callback(
1980 // Find all occurrences of multiples of 4 spaces a the start of the line.
1981 '/^((?: )+)/m',
1982 function ( $matches ) {
1983 // Replace each occurrence of 4 spaces with a tab character.
1984 return str_repeat( "\t", substr_count( $matches[0], ' ' ) );
1985 },
1986 $new_block_list_formatted
1987 );
1988
1989 if ( ! $wp_filesystem->put_contents( $block_list_path, $new_block_list_formatted ) ) {
1990 /* translators: %s is the path to the file with the block list */
1991 WP_CLI::error( sprintf( esc_html__( 'Error writing new %s', 'jetpack' ), $block_list_path ) );
1992 }
1993 }
1994
1995 if ( 'beta' === $variation || 'experimental' === $variation ) {
1996 $block_constant = sprintf(
1997 /* translators: the placeholder is a constant name */
1998 esc_html__( 'To load the block, add the constant %1$s as true to your wp-config.php file', 'jetpack' ),
1999 ( 'beta' === $variation ? 'JETPACK_BETA_BLOCKS' : 'JETPACK_EXPERIMENTAL_BLOCKS' )
2000 );
2001 } else {
2002 $block_constant = '';
2003 }
2004
2005 WP_CLI::success(
2006 sprintf(
2007 /* translators: the placeholders are a human readable title, and a series of words separated by dashes */
2008 esc_html__( 'Successfully created block %1$s with slug %2$s', 'jetpack' ) . ' 🎉' . "\n" .
2009 "--------------------------------------------------------------------------------------------------------------------\n" .
2010 /* translators: the placeholder is a directory path */
2011 esc_html__( 'The files were created at %3$s', 'jetpack' ) . "\n" .
2012 esc_html__( 'To start using the block, build the blocks with yarn run build-extensions', 'jetpack' ) . "\n" .
2013 /* translators: the placeholder is a file path */
2014 esc_html__( 'The block slug has been added to the %4$s list at %5$s', 'jetpack' ) . "\n" .
2015 '%6$s' . "\n" .
2016 /* translators: the placeholder is a URL */
2017 "\n" . esc_html__( 'Read more at %7$s', 'jetpack' ) . "\n",
2018 $title,
2019 $slug,
2020 $path,
2021 $variation,
2022 $block_list_path,
2023 $block_constant,
2024 'https://github.com/Automattic/jetpack/blob/master/extensions/README.md#develop-new-blocks'
2025 ) . '--------------------------------------------------------------------------------------------------------------------'
2026 );
2027 }
2028 }
2029
2030 /**
2031 * Built the file replacing the placeholders in the template with the data supplied.
2032 *
2033 * @param string $template
2034 * @param array $data
2035 *
2036 * @return string mixed
2037 */
2038 private static function render_block_file( $template, $data = array() ) {
2039 return \WP_CLI\Utils\mustache_render( JETPACK__PLUGIN_DIR . "wp-cli-templates/$template.mustache", $data );
2040 }
2041 }
2042
2043 /*
2044 * Standard "ask for permission to continue" function.
2045 * If action cancelled, ask if they need help.
2046 *
2047 * Written outside of the class so it's not listed as an executable command w/ 'wp jetpack'
2048 *
2049 * @param $flagged bool false = normal option | true = flagged by get_jetpack_options_for_reset()
2050 * @param $error_msg string (optional)
2051 */
2052 function jetpack_cli_are_you_sure( $flagged = false, $error_msg = false ) {
2053 $cli = new Jetpack_CLI();
2054
2055 // Default cancellation message
2056 if ( ! $error_msg ) {
2057 $error_msg =
2058 __( 'Action cancelled. Have a question?', 'jetpack' )
2059 . ' '
2060 . $cli->green_open
2061 . 'jetpack.com/support'
2062 . $cli->color_close;
2063 }
2064
2065 if ( ! $flagged ) {
2066 $prompt_message = _x( 'Are you sure? This cannot be undone. Type "yes" to continue:', '"yes" is a command - do not translate.', 'jetpack' );
2067 } else {
2068 $prompt_message = _x( 'Are you sure? Modifying this option may disrupt your Jetpack connection. Type "yes" to continue.', '"yes" is a command - do not translate.', 'jetpack' );
2069 }
2070
2071 WP_CLI::line( $prompt_message );
2072 $handle = fopen( 'php://stdin', 'r' );
2073 $line = fgets( $handle );
2074 if ( 'yes' != trim( $line ) ) {
2075 WP_CLI::error( $error_msg );
2076 }
2077 }
2078