PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 8.1
Jetpack – WP Security, Backup, Speed, & Growth v8.1
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.jetpack-cli.php

class.jetpack-cli.php in Jetpack – WP Security, Backup, Speed, & Growth 8.1, at class.jetpack-cli.php

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