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