-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-wpcomsh-cli-commands.php
1448 lines (1284 loc) · 45.7 KB
/
class-wpcomsh-cli-commands.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* CLI commands for wpcomsh.
*
* @package wpcomsh
*/
// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed
/**
* Plugins that shouldn't be deactivated by the deactivate-user-plugins command.
*/
define(
'WPCOMSH_CLI_DONT_DEACTIVATE_PLUGINS',
array(
'akismet',
'classic-editor',
'full-site-editing',
'gutenberg',
'jetpack',
'layout-grid',
'page-optimize',
// Avoid deactivating the file shim before the Atomic media backfill is complete
'wpcom-file-shim',
)
);
/**
* ECommerce plan plugins that shouldn't be deactivated by deactivate-user-plugins
* when the site has an eCommerce plan.
*/
define(
'WPCOMSH_CLI_ECOMMERCE_PLAN_PLUGINS',
array(
'storefront-powerpack',
'woocommerce',
'facebook-for-woocommerce',
'mailchimp-for-woocommerce',
'woocommerce-services',
'woocommerce-product-addons',
'taxjar-simplified-taxes-for-woocommerce',
)
);
/**
* The option where we keep a list of plugins deactivated via wp-cli.
*/
define( 'WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS', 'wpcomsh_deactivated_user_installed_plugins' );
/**
* We keep a record of plugins deactivated via wp-cli so we can reactivate them later
* with `wp wpcomsh reactivate-user-plugins`. This constant is the amount of time we'll
* consider a deactivation valid for reactivation via `reactivate-user-plugins`.
*/
define( 'WPCOMSH_CLI_PLUGIN_REACTIVATION_MAX_AGE', 14 * DAY_IN_SECONDS );
define( 'WPCOMSH_CLI_DEACTIVATED_PLUGIN_RECORD_CLEANUP_JOB', 'wpcomsh_cli_cleanup_deactivated_user_plugin_record' );
/**
* Don't allow `wp core multisite-install` or `wp core multisite-convert` to be run.
*/
WP_CLI::add_hook(
'before_run_command',
function () {
$runner = WP_CLI::get_runner();
$disabled_commands = array(
array( 'core', 'multisite-install' ),
array( 'core', 'multisite-convert' ),
);
foreach ( $disabled_commands as $disabled_command ) {
if ( array_slice( $runner->arguments, 0, count( $disabled_command ) ) === $disabled_command ) {
WP_CLI::error(
sprintf(
'The \'%s\' command is disabled on this platform.',
implode( ' ', $disabled_command )
)
);
}
}
}
);
/**
* Ask the user to confirm a yes/no question.
*
* @param string $question The yes/no question to ask the user.
* @return boolean Whether the user confirmed or not.
*/
function wpcomsh_cli_confirm( $question ) {
fwrite( STDOUT, $question . ' [Y/n] ' ); // phpcs:ignore WordPress.WP.AlternativeFunctions
$answer = strtolower( trim( fgets( STDIN ) ) );
return 'y' === $answer || ! $answer;
}
/**
* Get the names of plugins with the specified status.
*
* @param string $status The plugin status to match.
*
* @return string[]|false An array of plugin names. `false` if there is an error.
*/
function wpcomsh_cli_get_plugins_with_status( $status ) {
$list_result = WP_CLI::runcommand(
"--skip-plugins --skip-themes plugin list --format=json --status=$status",
array(
'launch' => false,
'return' => 'all',
'exit_error' => false,
)
);
if ( 0 !== $list_result->return_code ) {
return false;
}
$decoded_result = json_decode( $list_result->stdout );
if ( null === $decoded_result ) {
return false;
}
if ( ! is_array( $decoded_result ) ) {
return false;
}
return array_map(
function ( $plugin ) {
return $plugin->name; },
$decoded_result
);
}
/**
* Save the latest record of deactivated plugins.
*
* @param array $deactivated_plugins Plugins to deactivate.
*/
function wpcomsh_cli_save_deactivated_plugins_record( $deactivated_plugins ) {
if ( empty( $deactivated_plugins ) ) {
delete_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS );
return;
}
$updated = update_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS, $deactivated_plugins, false /* don't autoload */ );
if (
false === $updated &&
// Make sure the update didn't fail because the option is already set to the desired value.
get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS ) !== $deactivated_plugins
) {
WP_CLI::warning( 'Failed to update deactivated plugins list.' );
}
}
/**
* Removes expired deactivations from the deactivation record.
*/
function wpcomsh_cli_remove_expired_from_deactivation_record() {
$deactivated_plugins = get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS, array() );
$deactivated_plugins_to_remember = array();
$current_time = time();
foreach ( $deactivated_plugins as $plugin_name => $timestamp ) {
if ( ( $current_time - $timestamp ) < WPCOMSH_CLI_PLUGIN_REACTIVATION_MAX_AGE ) {
$deactivated_plugins_to_remember[ $plugin_name ] = $timestamp;
}
}
wpcomsh_cli_save_deactivated_plugins_record( $deactivated_plugins_to_remember );
}
/**
* Keeps a single event scheduled to clean up the deactivated user plugin record.
*
* @return boolean Whether the scheduling update succeeded.
*/
function wpcomsh_cli_reschedule_deactivated_list_cleanup() {
static $rescheduled_cleanup = false;
// Avoid unnecessarily rescheduling multiple times within the same CLI command.
if ( ! $rescheduled_cleanup ) {
if (
false !== wp_next_scheduled( WPCOMSH_CLI_DEACTIVATED_PLUGIN_RECORD_CLEANUP_JOB ) &&
false === wp_unschedule_hook( WPCOMSH_CLI_DEACTIVATED_PLUGIN_RECORD_CLEANUP_JOB )
) {
// Avoid scheduling cleanup if we can't unschedule existing cleanup because scheduled jobs could accumulate.
return false;
}
if ( false === get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS ) ) {
// No need to clean up a nonexistent option.
return true;
}
$rescheduled_cleanup = wp_schedule_single_event(
// Pad scheduled time to give everything time to expire.
time() + WPCOMSH_CLI_PLUGIN_REACTIVATION_MAX_AGE + 15 * MINUTE_IN_SECONDS,
WPCOMSH_CLI_DEACTIVATED_PLUGIN_RECORD_CLEANUP_JOB
);
}
return $rescheduled_cleanup;
}
/**
* Action hook for updating the deactivated plugin record when a plugin is deactivated.
*
* This allows us to maintain the deactivated plugin record in response to both
* the `wp plugin deactivate` and `wp wpcomsh deactivate-user-plugins` commands.
*
* @param string $file Plugin file.
*/
function wpcomsh_cli_remember_plugin_deactivation( $file ) {
$deactivated_plugins = get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS );
$plugin_name = WP_CLI\Utils\get_plugin_name( $file );
$deactivated_plugins[ $plugin_name ] = time();
wpcomsh_cli_save_deactivated_plugins_record( $deactivated_plugins );
wpcomsh_cli_reschedule_deactivated_list_cleanup();
}
/**
* Action hook for pruning the deactivated plugin record when a plugin is activated.
*
* This allows us to neatly maintain the deactivated plugin record in response to both
* the `wp plugin activate` and `wp wpcomsh reactivate-user-plugins` commands.
*
* @param string $file Plugin file.
*/
function wpcomsh_cli_forget_plugin_deactivation( $file ) {
$deactivated_plugins = get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS );
$plugin_name = WP_CLI\Utils\get_plugin_name( $file );
unset( $deactivated_plugins[ $plugin_name ] );
wpcomsh_cli_save_deactivated_plugins_record( $deactivated_plugins );
}
// phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
if ( class_exists( 'WP_CLI_Command' ) ) {
/**
* WPCOMSH-specific CLI commands
*/
class WPCOMSH_CLI_Commands extends WP_CLI_Command {
/**
* Bulk deactivate user installed plugins
*
* Deactivate all user installed plugins except for important ones for Atomic.
*
* ## OPTIONS
*
* [--interactive]
* : Ask for each active plugin whether to deactivate
*
* @subcommand deactivate-user-plugins
*/
public function deactivate_user_installed_plugins( $args, $assoc_args = array() ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
$active_plugins = wpcomsh_cli_get_plugins_with_status( 'active' );
if ( false === $active_plugins ) {
WP_CLI::log( 'Failed to list active plugins.' );
}
$plugins_to_skip = WPCOMSH_CLI_DONT_DEACTIVATE_PLUGINS;
if ( wpcom_site_has_feature( WPCOM_Features::ECOMMERCE_MANAGED_PLUGINS ) ) {
// This site has access to the e-commerce plugin bundle, so we don't want to deactivate them.
$plugins_to_skip = array_unique( array_merge( $plugins_to_skip, WPCOMSH_CLI_ECOMMERCE_PLAN_PLUGINS ) );
}
foreach ( array_intersect( $active_plugins, $plugins_to_skip ) as $skipped ) {
WP_CLI::log( WP_CLI::colorize( " %b- skipping '$skipped'%n" ) );
}
$plugins_to_deactivate = array_diff( $active_plugins, $plugins_to_skip );
if ( empty( $plugins_to_deactivate ) ) {
WP_CLI::warning( 'No active user-installed plugins found.' );
return;
}
$interactive = WP_CLI\Utils\get_flag_value( $assoc_args, 'interactive', false );
$green_check_mark = WP_CLI::colorize( "%G\xE2\x9C\x94%n" );
$red_x = WP_CLI::colorize( '%Rx%n' );
foreach ( $plugins_to_deactivate as $plugin ) {
$deactivate = true;
if ( $interactive ) {
$deactivate = wpcomsh_cli_confirm( 'Deactivate plugin "' . $plugin . '"?' );
}
if ( $deactivate ) {
// Deactivate and print success/failure
$result = WP_CLI::runcommand(
"--skip-plugins --skip-themes plugin deactivate $plugin",
array(
'launch' => false,
'return' => 'all',
'exit_error' => false,
)
);
if ( 0 === $result->return_code ) {
WP_CLI::log( " $green_check_mark deactivated '$plugin'" );
} else {
WP_CLI::log( " $red_x failed to deactivate '$plugin'" );
if ( ! empty( $result->stderr ) ) {
WP_CLI::log( $result->stderr );
}
}
}
}
}
/**
* Bulk re-activate user installed plugins.
*
* If previously user installed plugins had been deactivated, this re-activates these plugins.
*
* ## OPTIONS
*
* [--interactive]
* : Ask for each previously deactivated plugin whether to activate.
*
* @subcommand reactivate-user-plugins
*/
public function reactivate_user_installed_plugins( $args, $assoc_args = array() ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
// Clean up before getting the deactivation list so there are only current entries.
wpcomsh_cli_remove_expired_from_deactivation_record();
$inactive_plugins = wpcomsh_cli_get_plugins_with_status( 'inactive' );
if ( false === $inactive_plugins ) {
WP_CLI::error( 'Failed to list inactive plugins for reactivation.' );
return;
}
$deactivation_records = get_option( WPCOMSH_CLI_OPTION_DEACTIVATED_USER_PLUGINS );
if ( false === $deactivation_records ) {
WP_CLI::warning( "Can't find any previously deactivated plugins to activate." );
return;
}
// TODO: Should we reactivate these in the reverse order that they were deactivated?
// Only try to reactivate plugins that exist and are inactive.
$plugins_to_reactivate = array_keys( $deactivation_records );
$plugins_to_reactivate = array_intersect( $plugins_to_reactivate, $inactive_plugins );
if ( empty( $plugins_to_reactivate ) ) {
WP_CLI::warning( "Can't find any previously deactivated plugins to activate." );
return;
}
$interactive = WP_CLI\Utils\get_flag_value( $assoc_args, 'interactive', false );
if ( ! $interactive ) {
// Since we're not confirming one-by-one, we'll confirm once for all.
WP_CLI::log( 'The following will be reactivated:' );
WP_CLI::log( ' - ' . implode( "\n - ", $plugins_to_reactivate ) );
if ( ! wpcomsh_cli_confirm( 'Do you wish to proceed?' ) ) {
return;
}
}
$green_check_mark = WP_CLI::colorize( "%G\xE2\x9C\x94%n" );
$red_x = WP_CLI::colorize( '%Rx%n' );
foreach ( $plugins_to_reactivate as $plugin ) {
$reactivate = true;
if ( $interactive ) {
$reactivate = wpcomsh_cli_confirm( 'Reactivate plugin "' . $plugin . '"?' );
}
if ( $reactivate ) {
$result = WP_CLI::runcommand(
"--skip-plugins --skip-themes plugin activate $plugin",
array(
'launch' => false,
'return' => 'all',
'exit_error' => false,
)
);
if ( 0 === $result->return_code ) {
WP_CLI::log( " $green_check_mark activated '$plugin'" );
} else {
WP_CLI::log( " $red_x failed to activate '$plugin'" );
if ( ! empty( $result->stderr ) ) {
WP_CLI::log( $result->stderr );
}
}
}
}
}
/**
* Fire the update_option_home action for domain change.
*
* This is necessary for some plugins such as Yoast that looks for this action when a domain is updated,
* and since the Atomic platform uses direct SQL queries to update the URL when it's changed in wpcom,
* this action never fires.
*
* ## OPTIONS
*
* [--old_url=<old_url>]
* : The URL that the domain was changed from
*
* [--new_url=<new_url>]
* : The URL that the domain was changed to
*
* @subcommand domain-name-changed
*/
public function domain_name_changed( $args, $assoc_args = array() ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
$old_domain = WP_CLI\Utils\get_flag_value( $assoc_args, 'old_url', false );
if ( false === $old_domain ) {
WP_CLI::error( 'Missing required --old_url=url value.' );
}
$new_domain = WP_CLI\Utils\get_flag_value( $assoc_args, 'new_url', false );
if ( false === $new_domain ) {
WP_CLI::error( 'Missing required --new_url=url value.' );
}
// Bail if we're getting a value that does not match reality of what's current.
if ( get_home_url() !== $new_domain ) {
WP_CLI::warning( 'Did not send action. New domain does not match current get_home_url value.' );
return;
}
if ( ! defined( 'WP_HOME' ) || WP_HOME !== $new_domain ) {
WP_CLI::warning( 'Did not send action. New domain does not match current WP_HOME value.' );
return;
}
do_action( 'update_option_home', $old_domain, $new_domain );
WP_CLI::success( 'Sent the update_option_home action successfully.' );
}
/**
* This is a post transfer command that is called after a site is transferred.
*
* This is necessary for some plugins that need to perform certain actions after
* a site is transferred, such as WooCommerce Payments that needs to clear its cache.
*
* Note: This command should only be executed from WPCOM as part of a transfer.
*
* @subcommand post-transfer
*/
public function post_transfer( $args, $assoc_args = array() ) {
do_action( 'wpcomsh_woa_post_transfer', $args, $assoc_args );
WP_CLI::success( 'Post transfer completed successfully.' );
}
/**
* This is a post reset command that is called after a site is reset.
*
* This is necessary for some plugins that need to perform certain actions after
* a site is reset, such as WooCommerce Payments that needs to clear its cache.
*
* Note: This command should only be executed from WPCOM as part of a transfer.
*
* @subcommand post-reset
*/
public function post_reset( $args, $assoc_args = array() ) {
do_action( 'wpcomsh_woa_post_reset', $args, $assoc_args );
WP_CLI::success( 'Post reset completed successfully.' );
}
/**
* This is a post clone command that is called after a site is cloned.
*
* This is necessary for some plugins that need to perform certain actions after
* a site is cloned, such as WooCommerce Payments that needs to clear its cache.
*
* Note: This command should only be executed from WPCOM as part of a transfer.
*
* @subcommand post-clone
*/
public function post_clone( $args, $assoc_args = array() ) {
do_action( 'wpcomsh_woa_post_clone', $args, $assoc_args );
WP_CLI::success( 'Post clone completed successfully.' );
}
/**
* Proxies wp language plugin install --all using the active site language.
*
* After switching the site language, language packs for plugins are not automatically downloaded and the user
* has to manually check for and install updates, this command installs language packs for all plugins,
* using the active site language.
*
* @subcommand install-plugin-language-packs
*/
public function install_plugin_language_packs() {
/*
* Query the database directly as we previously hooked into pre_option_WPLANG to always return en_US,
* but now we need the actual site language to figure out what language packs to install.
*/
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$lang = $wpdb->get_var( 'SELECT option_value FROM ' . $wpdb->options . " WHERE option_name = 'WPLANG'" );
if ( empty( $lang ) ) {
$lang = 'en_US';
}
$command = new Plugin_Language_Command();
$command->install(
array( $lang ),
array(
'all' => true,
)
);
}
/**
* Retrieves an Atomic persistent data field.
*
* ## OPTIONS
*
* <name>
* : The name of the data field to retrieve
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: list
* options:
* - list
* - json
* ---
*
* @subcommand persistent-data
*/
public function persistent_data( $args, $assoc_args ) {
if ( empty( $args[0] ) ) {
WP_CLI::error( 'Missing required field name.' );
}
$name = $args[0];
$persistent_data = new Atomic_Persistent_Data();
$output = json_decode( $persistent_data->{ $name } );
if ( null === $output ) {
$output = $persistent_data->{ $name };
}
if ( 'json' === $assoc_args['format'] ) {
$output = wp_json_encode( $output, JSON_PRETTY_PRINT );
}
WP_CLI::log( print_r( $output, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
}
/**
* Retrieves the WPCOM_PURCHASES field from Atomic Persistent Data.
*
* ## OPTIONS
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: list
* options:
* - list
* - json
* ---
*
* @subcommand purchases
*/
public function purchases( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
WP_CLI::runcommand( 'wpcomsh persistent-data WPCOM_PURCHASES --format=' . $assoc_args['format'], array( 'launch' => false ) );
}
/**
* Apply terms and taxonomies from the current theme's annotation file.
*
* In the case of WooCommerce specific terms, they can only be applied
* after WooCommerce is installed, which might happen after a site's theme switch.
* So this is provided as a separate command which can be ran in a post-install job.
*
* @subcommand headstart-terms
*/
public function headstart_terms( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter, VariableAnalysis.CodeAnalysis.VariableAnalysis
$results = wpcomsh_apply_headstart_terms();
$missing_taxonomies = $results['missing_taxonomies'];
$output = wp_json_encode( array( 'missing_taxonomies' => $missing_taxonomies ), JSON_PRETTY_PRINT );
WP_CLI::log( $output );
}
/**
* Import a backup .zip file.
*
* ## OPTIONS
*
* [--source]
* : Source zip file path.
*
* [--dest]
* : destination file path to extract to. (required)
*
* [--skip-clean-up]
* : Skip cleaning up the temprary files. Defaults to false.
*
* [--skip-unpack]
* : Skip unpacking the zip file. Defaults to false.
*
* [--actions]
* : A comma-separated list of actions to perform. Defaults to all actions.
*
* [--dry-run]
* : Run the importer in dry run mode. Defaults to true.
*
* @subcommand backup-import
*/
public function backup_import( $args, $assoc_args ) {
$source = WP_CLI\Utils\get_flag_value( $assoc_args, 'source', '' );
$dest = WP_CLI\Utils\get_flag_value( $assoc_args, 'dest' );
$skip_clean_up = WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-clean-up', false );
$skip_unpack = WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-unpack', false );
$actions = WP_CLI\Utils\get_flag_value( $assoc_args, 'actions', '' );
$dry_run = WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', true );
$skip_unpack = filter_var( $skip_unpack, FILTER_VALIDATE_BOOLEAN );
if ( ! $skip_unpack && empty( $source ) ) {
WP_CLI::error( 'Missing file path passed to --source' );
}
if ( empty( $dest ) ) {
WP_CLI::error( 'Missing file path passed to --dest' );
}
$options = array(
'skip_clean_up' => filter_var( $skip_clean_up, FILTER_VALIDATE_BOOLEAN ),
'skip_unpack' => $skip_unpack,
'actions' => $actions ? explode( ',', $actions ) : array(),
'dry_run' => filter_var( $dry_run, FILTER_VALIDATE_BOOLEAN ),
);
$import_manager = new Imports\Backup_Import_Manager( $source, $dest, $options );
$ret = $import_manager->import();
if ( is_wp_error( $ret ) ) {
WP_CLI::error( $ret->get_error_message() );
}
WP_CLI::success( 'Import completed successfully.' );
}
/**
* Manage user's global styles.
*
* ## OPTIONS
*
* <action>
* : The action you want to run, e.g.: list, update, remove.
*
* [--field=<field>]
* : The path of the data field to retrieve or remove.
*
* [--value=<value>]
* : The value of the data field you want to set.
*
* [--dry-run]
* : Enable dry run mode
*
* @subcommand global-styles
*/
public function global_styles( $args, $assoc_args ) {
if ( empty( $args[0] ) ) {
WP_CLI::error( 'Missing the action.' );
}
$available_actions = array( 'list', 'update', 'remove' );
$action = $args[0];
if ( ! in_array( $action, $available_actions, true ) ) {
WP_CLI::error( 'The action is not supported yet' );
}
/**
* Get the global styles
*/
$active_global_styles_id = WP_Theme_JSON_Resolver::get_user_global_styles_post_id();
$request = new \WP_REST_Request( 'GET', "/wp/v2/global-styles/$active_global_styles_id" );
$request->set_query_params(
array(
'context' => 'edit',
'id' => $active_global_styles_id,
)
);
$global_styles_controller = new WP_REST_Global_Styles_Controller();
$response = $global_styles_controller->get_item( $request );
if ( $response->is_error() ) {
WP_CLI::error( $response->as_error() );
}
$global_styles = $response->get_data();
$field = $assoc_args['field'] ?? '';
$field_path = ! empty( $field ) ? explode( '.', $field ) : array();
if ( $action === 'list' ) {
$global_styles = $response->get_data();
$global_styles = ! empty( $field_path ) ? _wp_array_get( $global_styles, $field_path ) : $global_styles;
WP_CLI::log( wp_json_encode( $global_styles, JSON_PRETTY_PRINT ) );
return;
}
$dry_run = isset( $assoc_args['dry-run'] ) ? filter_var( $assoc_args['dry-run'], FILTER_VALIDATE_BOOLEAN ) : false;
if ( $action === 'update' ) {
if ( empty( $field_path ) ) {
WP_CLI::error( 'Missing the data field you want to remove, e.g.: settings.typography.fontFamilies.theme' );
}
if ( ! isset( $assoc_args['value'] ) ) {
WP_CLI::error( 'Missing the value you want to set.' );
}
$value = json_decode( $assoc_args['value'], true );
$json_decoding_error = json_last_error();
if ( JSON_ERROR_NONE !== $json_decoding_error ) {
WP_CLI::error( 'The provided value is invalid.' );
}
_wp_array_set( $global_styles, $field_path, $value );
if ( $dry_run ) {
WP_CLI::log( wp_json_encode( $global_styles, JSON_PRETTY_PRINT ) );
} else {
$request = new \WP_REST_Request( 'POST', "/wp/v2/global-styles/$active_global_styles_id" );
$request->set_query_params( $global_styles );
$response = $global_styles_controller->update_item( $request );
if ( $response->is_error() ) {
WP_CLI::error( $response->as_error() );
}
WP_CLI::log( wp_json_encode( $response->get_data(), JSON_PRETTY_PRINT ) );
}
WP_CLI::success( "Update the data field `$field` successfully" );
}
if ( $action === 'remove' ) {
if ( empty( $field_path ) ) {
WP_CLI::error( 'Missing the data field you want to remove, e.g.: settings.typography.fontFamilies.theme' );
}
$length = count( $field_path );
$current = &$global_styles;
for ( $i = 0; $i < $length - 1; ++$i ) {
$path = $field_path[ $i ];
if ( ! array_key_exists( $path, $current ) || ! is_array( $current[ $path ] ) ) {
WP_CLI::error( "The data field `$field` doesn't exist" );
}
$current = &$current[ $path ];
}
unset( $current[ $field_path[ $i ] ] );
if ( $dry_run ) {
WP_CLI::log( wp_json_encode( $global_styles, JSON_PRETTY_PRINT ) );
} else {
$request = new \WP_REST_Request( 'POST', "/wp/v2/global-styles/$active_global_styles_id" );
$request->set_query_params( $global_styles );
$response = $global_styles_controller->update_item( $request );
if ( $response->is_error() ) {
WP_CLI::error( $response->as_error() );
}
WP_CLI::log( wp_json_encode( $response->get_data(), JSON_PRETTY_PRINT ) );
}
WP_CLI::success( "Removing the data field `$field` successfully" );
}
}
/**
* List incompatible plugins on the site.
*
* ## OPTIONS
*
* <action>
* : The action you want to run. Only `list` supported at present.
* ---
* options:
* - list
* ---
*
* [--field=<field>]
* : Prints the value of a single field for each incompatible plugin.
*
* [--fields=<fields>]
* : The fields to include in the output.
*
* [--format=<format>]
* : The output format to use.
* ---
* default: table
* options:
* - table
* - csv
* - json
* ---
*
* [--status=<status>]
* : Only return incompatible plugins with a specific status.
* ---
* options:
* - active
* - inactive
* - active-network
* - must-use
*
* ## AVAILABLE FIELDS
*
* These fields will be displayed by default for each plugin:
*
* * name
* * status
* * version
*
* These fields are optionally available:
*
* * message
* * title
* * description
* * file
* * author
*
* @subcommand incompatible-plugins
*/
public function incompatible_plugins( $args, $assoc_args ) {
if ( empty( $args[0] ) ) {
WP_CLI::error( 'No action specified.' );
}
$action = $args[0];
$supported_actions = array( 'list' );
if ( ! in_array( $action, $supported_actions, true ) ) {
WP_CLI::error( "Unsupported action: '{$action}'. Must be one of: " . implode( '|', $supported_actions ) );
}
$jetpack_plugin_compatibility = Jetpack_Plugin_Compatibility::get_instance();
$incompatible_plugins = $jetpack_plugin_compatibility->find_incompatible_plugins();
$status_to_filter = \WP_CLI\Utils\get_flag_value( $assoc_args, 'status' );
if ( ! empty( $status_to_filter ) ) {
$incompatible_plugins = array_filter(
$incompatible_plugins,
function ( $incompatible_plugin_details ) use ( $status_to_filter ) {
return $status_to_filter === ( $incompatible_plugin_details['status'] ?? null );
}
);
}
if ( empty( $incompatible_plugins ) ) {
WP_CLI::success( 'No incompatible plugins found.' );
return;
}
$refined_plugin_list = array();
foreach ( $incompatible_plugins as $plugin_filename => $plugin_details ) {
$refined_plugin_list[] = array(
'name' => \WP_CLI\Utils\get_plugin_name( $plugin_filename ),
'status' => $plugin_details['status'],
'version' => $plugin_details['details']['Version'] ?? '',
'message' => $plugin_details['message'],
'title' => $plugin_details['details']['Name'] ?? '',
'description' => $plugin_details['details']['Description'] ?? '',
'file' => $plugin_filename,
'author' => $plugin_details['details']['Author'] ?? '',
);
}
$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'name', 'status', 'version' ), 'plugin' );
$formatter->display_items( $refined_plugin_list );
}
/**
* Patch js_composer plugin to work with PHP 8.1.
*
* ## OPTIONS
*
* <plugin>
* : The plugin to patch.
*
* @subcommand php81-plugin-patch
*/
public function php_81_plugin_patch( $args, $assoc_args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
if ( 'js_composer' !== $args[0] ) {
WP_CLI::error( 'Wrong plugin to patch.' );
}
$plugins = get_plugins();
$folder = 'js_composer/js_composer.php';
if ( ! isset( $plugins[ $folder ] ) ) {
WP_CLI::error( 'js_composer plugin is not installed.' );
}
$file = WP_PLUGIN_DIR . '/js_composer/include/classes/editors/class-vc-frontend-editor.php';
if ( ! file_exists( $file ) ) {
WP_CLI::error( 'File not found: ' . $file );
}
$search = '$host = isset( $s[\'HTTP_X_FORWARDED_HOST\'] ) ? $s[\'HTTP_X_FORWARDED_HOST\'] : isset( $s[\'HTTP_HOST\'] ) ? $s[\'HTTP_HOST\'] : $s[\'SERVER_NAME\'];';
$substitution = "// The following line has been patched by wpcomsh to let this plugin work with PHP 8.1.\n";
$substitution .= ' $host = isset( $s[\'HTTP_X_FORWARDED_HOST\'] ) ? $s[\'HTTP_X_FORWARDED_HOST\'] : ( isset($s[\'HTTP_HOST\'] ) ? $s[\'HTTP_HOST\'] : $s[\'SERVER_NAME\'] );';
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$file_content = file_get_contents( $file );
if ( false === $file_content ) {
WP_CLI::error( 'File not found: ' . $file );
}
$count = 0;
$file_content = str_replace( $search, $substitution, $file_content, $count );
if ( ! $count ) {
WP_CLI::error( 'String not found on ' . $file );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
if ( ! file_put_contents( $file, $file_content ) ) {
WP_CLI::error( 'Failed to write to ' . $file );
}
WP_CLI::success( 'Success' );
}
/**
* Enable or disable fatal error emails.
*
* ## OPTIONS
*
* <command>
* : The subcommand
* ---
* options:
* - get
* - set
* ---
*
* [--value=<value>]
* : The value (when setting)
* ---
* default: 1
* options:
* - 0
* - 1
* ---
*
* @subcommand disable-fatal-error-emails
*/
public function fatal_error_emails_disable( $args, $assoc_args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$command = $args[0];
$value = (bool) $assoc_args['value'];
switch ( $command ) {
case 'get':
$option = get_option( 'wpcomsh_disable_fatal_error_emails', false );
WP_CLI::log( $option ? 'true' : 'false' );
break;
case 'set':
update_option( 'wpcomsh_disable_fatal_error_emails', $value );
WP_CLI::success( 'Success' );
break;
default:
WP_CLI::error( 'Invalid command' );
}
}
/**
* Check if the site is healthy after activating a plugin.
* This is a helper function for the plugin-dance command.
*
* @return bool
*/
private function do_plugin_dance_health_check() {
$result = WP_CLI::runcommand(
'--skip-themes= --skip-plugins= wpcomsh plugin-dance-health-check', // pass empty values to skip-themes and skip-plugins.
array(
'return' => true,
'launch' => true, // must run in a new process to avoid false positives.
'exit_error' => false,
)
);
return (bool) strpos( $result, 'Healthy' );
}
/**
* Tries disabling all plugins & enabling them one by one to find the plugin causing the issue.
* Outputs a list of plugins that are disabled.
*
* ## OPTIONS
*
* [--strategy=<strategy>]
* : The strategy to use to find the breaking plugin. Defaults to 'one-by-one'.
* ---
* default: one-by-one
* options:
* - one-by-one
* - disable-all
*
* @subcommand plugin-dance
*/