PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.8.4
Jetpack – WP Security, Backup, Speed, & Growth v11.8.4
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 11.8.4, at class.jetpack-cli.php

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