summaryrefslogtreecommitdiff
blob: 653d0f93bbb57136848487f76ee5f901d4d4a062 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
<?php

WP_CLI::add_command( 'jetpack', 'Jetpack_CLI' );

use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
use Automattic\Jetpack\Status;
use Automattic\Jetpack\Sync\Actions;
use Automattic\Jetpack\Sync\Listener;
use Automattic\Jetpack\Sync\Queue;
use Automattic\Jetpack\Sync\Settings;

/**
 * Control your local Jetpack installation.
 */
class Jetpack_CLI extends WP_CLI_Command {
	// Aesthetics.
	public $green_open  = "\033[32m";
	public $red_open    = "\033[31m";
	public $yellow_open = "\033[33m";
	public $color_close = "\033[0m";

	/**
	 * Get Jetpack Details
	 *
	 * ## OPTIONS
	 *
	 * empty: Leave it empty for basic stats
	 *
	 * full: View full stats.  It's the data from the heartbeat
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack status
	 * wp jetpack status full
	 */
	public function status( $args, $assoc_args ) {
		jetpack_require_lib( 'debugger' );

		/* translators: %s is the site URL */
		WP_CLI::line( sprintf( __( 'Checking status for %s', 'jetpack' ), esc_url( get_home_url() ) ) );

		if ( isset( $args[0] ) && 'full' !== $args[0] ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $args[0] ) );
		}

		$master_user_email = Jetpack::get_master_user_email();

		$cxntests = new Jetpack_Cxn_Tests();

		if ( $cxntests->pass() ) {
			$cxntests->output_results_for_cli();

			WP_CLI::success( __( 'Jetpack is currently connected to WordPress.com', 'jetpack' ) );
		} else {
			$error = array();
			foreach ( $cxntests->list_fails() as $fail ) {
				$error[] = $fail['name'] . ': ' . $fail['message'];
			}
			WP_CLI::error_multi_line( $error );

			$cxntests->output_results_for_cli();

			WP_CLI::error( __( 'Jetpack connection is broken.', 'jetpack' ) ); // Exit CLI.
		}

		/* translators: %s is current version of Jetpack, for example 7.3 */
		WP_CLI::line( sprintf( __( 'The Jetpack Version is %s', 'jetpack' ), JETPACK__VERSION ) );
		/* translators: %d is WP.com ID of this blog */
		WP_CLI::line( sprintf( __( 'The WordPress.com blog_id is %d', 'jetpack' ), Jetpack_Options::get_option( 'id' ) ) );
		/* translators: %s is the email address of the connection owner */
		WP_CLI::line( sprintf( __( 'The WordPress.com account for the primary connection is %s', 'jetpack' ), $master_user_email ) );

		/*
		 * Are they asking for all data?
		 *
		 * Loop through heartbeat data and organize by priority.
		 */
		$all_data = ( isset( $args[0] ) && 'full' == $args[0] ) ? 'full' : false;
		if ( $all_data ) {
			// Heartbeat data
			WP_CLI::line( "\n" . __( 'Additional data: ', 'jetpack' ) );

			// Get the filtered heartbeat data.
			// Filtered so we can color/list by severity
			$stats = Jetpack::jetpack_check_heartbeat_data();

			// Display red flags first
			foreach ( $stats['bad'] as $stat => $value ) {
				printf( "$this->red_open%-'.16s %s $this->color_close\n", $stat, $value );
			}

			// Display caution warnings next
			foreach ( $stats['caution'] as $stat => $value ) {
				printf( "$this->yellow_open%-'.16s %s $this->color_close\n", $stat, $value );
			}

			// The rest of the results are good!
			foreach ( $stats['good'] as $stat => $value ) {

				// Modules should get special spacing for aestetics
				if ( strpos( $stat, 'odule-' ) ) {
					printf( "%-'.30s %s\n", $stat, $value );
					usleep( 4000 ); // For dramatic effect lolz
					continue;
				}
				printf( "%-'.16s %s\n", $stat, $value );
				usleep( 4000 ); // For dramatic effect lolz
			}
		} else {
			// Just the basics
			WP_CLI::line( "\n" . _x( "View full status with 'wp jetpack status full'", '"wp jetpack status full" is a command - do not translate', 'jetpack' ) );
		}
	}

	/**
	 * Tests the active connection
	 *
	 * 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.
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack test-connection
	 *
	 * @subcommand test-connection
	 */
	public function test_connection( $args, $assoc_args ) {

		/* translators: %s is the site URL */
		WP_CLI::line( sprintf( __( 'Testing connection for %s', 'jetpack' ), esc_url( get_site_url() ) ) );

		if ( ! Jetpack::is_active() ) {
			WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
		}

		$response = Client::wpcom_json_api_request_as_blog(
			sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
			Client::WPCOM_JSON_API_VERSION
		);

		if ( is_wp_error( $response ) ) {
			/* translators: %1$s is the error code, %2$s is the error message */
			WP_CLI::error( sprintf( __( 'Failed to test connection (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() ) );
		}

		$body = wp_remote_retrieve_body( $response );
		if ( ! $body ) {
			WP_CLI::error( __( 'Failed to test connection (empty response body)', 'jetpack' ) );
		}

		$result       = json_decode( $body );
		$is_connected = (bool) $result->connected;
		$message      = $result->message;

		if ( $is_connected ) {
			WP_CLI::success( $message );
		} else {
			WP_CLI::error( $message );
		}
	}

	/**
	 * Disconnect Jetpack Blogs or Users
	 *
	 * ## OPTIONS
	 *
	 * blog: Disconnect the entire blog.
	 *
	 * user <user_identifier>: Disconnect a specific user from WordPress.com.
	 *
	 * Please note, the primary account that the blog is connected
	 * to WordPress.com with cannot be disconnected without
	 * disconnecting the entire blog.
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack disconnect blog
	 * wp jetpack disconnect user 13
	 * wp jetpack disconnect user username
	 * wp jetpack disconnect user email@domain.com
	 *
	 * @synopsis <blog|user> [<user_identifier>]
	 */
	public function disconnect( $args, $assoc_args ) {
		if ( ! Jetpack::is_active() ) {
			WP_CLI::success( __( 'The site is not currently connected, so nothing to do!', 'jetpack' ) );
			return;
		}

		$action = isset( $args[0] ) ? $args[0] : 'prompt';
		if ( ! in_array( $action, array( 'blog', 'user', 'prompt' ) ) ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
		}

		if ( in_array( $action, array( 'user' ) ) ) {
			if ( isset( $args[1] ) ) {
				$user_id = $args[1];
				if ( ctype_digit( $user_id ) ) {
					$field   = 'id';
					$user_id = (int) $user_id;
				} elseif ( is_email( $user_id ) ) {
					$field   = 'email';
					$user_id = sanitize_user( $user_id, true );
				} else {
					$field   = 'login';
					$user_id = sanitize_user( $user_id, true );
				}
				if ( ! $user = get_user_by( $field, $user_id ) ) {
					WP_CLI::error( __( 'Please specify a valid user.', 'jetpack' ) );
				}
			} else {
				WP_CLI::error( __( 'Please specify a user by either ID, username, or email.', 'jetpack' ) );
			}
		}

		switch ( $action ) {
			case 'blog':
				Jetpack::log( 'disconnect' );
				Jetpack::disconnect();
				WP_CLI::success(
					sprintf(
						/* translators: %s is the site URL */
						__( 'Jetpack has been successfully disconnected for %s.', 'jetpack' ),
						esc_url( get_site_url() )
					)
				);
				break;
			case 'user':
				if ( Connection_Manager::disconnect_user( $user->ID ) ) {
					Jetpack::log( 'unlink', $user->ID );
					WP_CLI::success( __( 'User has been successfully disconnected.', 'jetpack' ) );
				} else {
					/* translators: %s is a username */
					WP_CLI::error( sprintf( __( "User %s could not be disconnected. Are you sure they're connected currently?", 'jetpack' ), "{$user->login} <{$user->email}>" ) );
				}
				break;
			case 'prompt':
				WP_CLI::error( __( 'Please specify if you would like to disconnect a blog or user.', 'jetpack' ) );
				break;
		}
	}

	/**
	 * Reset Jetpack options and settings to default
	 *
	 * ## OPTIONS
	 *
	 * modules: Resets modules to default state ( get_default_modules() )
	 *
	 * options: Resets all Jetpack options except:
	 *  - All private options (Blog token, user token, etc...)
	 *  - id (The Client ID/WP.com Blog ID of this site)
	 *  - master_user
	 *  - version
	 *  - activated
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack reset options
	 * wp jetpack reset modules
	 * wp jetpack reset sync-checksum --dry-run --offset=0
	 *
	 * @synopsis <modules|options|sync-checksum> [--dry-run] [--offset=<offset>]
	 */
	public function reset( $args, $assoc_args ) {
		$action = isset( $args[0] ) ? $args[0] : 'prompt';
		if ( ! in_array( $action, array( 'options', 'modules', 'sync-checksum' ), true ) ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
		}

		$is_dry_run = ! empty( $assoc_args['dry-run'] );

		if ( $is_dry_run ) {
			WP_CLI::warning(
				__( "\nThis is a dry run.\n", 'jetpack' ) .
				__( "No actions will be taken.\n", 'jetpack' ) .
				__( "The following messages will give you preview of what will happen when you run this command.\n\n", 'jetpack' )
			);
		} else {
			// We only need to confirm "Are you sure?" when we are not doing a dry run.
			jetpack_cli_are_you_sure();
		}

		switch ( $action ) {
			case 'options':
				$options_to_reset = Jetpack_Options::get_options_for_reset();
				// Reset the Jetpack options
				WP_CLI::line(
					sprintf(
						/* translators: %s is the site URL */
						__( "Resetting Jetpack Options for %s...\n", 'jetpack' ),
						esc_url( get_site_url() )
					)
				);
				sleep( 1 ); // Take a breath
				foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
					if ( ! $is_dry_run ) {
						Jetpack_Options::delete_option( $option_to_reset );
						usleep( 100000 );
					}

					/* translators: This is the result of an action. The option named %s was reset */
					WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
				}

				// Reset the WP options
				WP_CLI::line( __( "Resetting the jetpack options stored in wp_options...\n", 'jetpack' ) );
				usleep( 500000 ); // Take a breath
				foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
					if ( ! $is_dry_run ) {
						delete_option( $option_to_reset );
						usleep( 100000 );
					}
					/* translators: This is the result of an action. The option named %s was reset */
					WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
				}

				// Reset to default modules
				WP_CLI::line( __( "Resetting default modules...\n", 'jetpack' ) );
				usleep( 500000 ); // Take a breath
				$default_modules = Jetpack::get_default_modules();
				if ( ! $is_dry_run ) {
					Jetpack::update_active_modules( $default_modules );
				}
				WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
				break;
			case 'modules':
				if ( ! $is_dry_run ) {
					$default_modules = Jetpack::get_default_modules();
					Jetpack::update_active_modules( $default_modules );
				}

				WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
				break;
			case 'prompt':
				WP_CLI::error( __( 'Please specify if you would like to reset your options, modules or sync-checksum', 'jetpack' ) );
				break;
			case 'sync-checksum':
				$option = 'jetpack_callables_sync_checksum';

				if ( is_multisite() ) {
					$offset = isset( $assoc_args['offset'] ) ? (int) $assoc_args['offset'] : 0;

					/*
					 * 1000 is a good limit since we don't expect the number of sites to be more than 1000
					 * Offset can be used to paginate and try to clean up more sites.
					 */
					$sites       = get_sites(
						array(
							'number' => 1000,
							'offset' => $offset,
						)
					);
					$count_fixes = 0;
					foreach ( $sites as $site ) {
						switch_to_blog( $site->blog_id );
						$count = self::count_option( $option );
						if ( $count > 1 ) {
							if ( ! $is_dry_run ) {
								delete_option( $option );
							}
							WP_CLI::line(
								sprintf(
									/* translators: %1$d is a number, %2$s is the name of an option, %2$s is the site URL. */
									__( 'Deleted %1$d %2$s options from %3$s', 'jetpack' ),
									$count,
									$option,
									"{$site->domain}{$site->path}"
								)
							);
							$count_fixes++;
							if ( ! $is_dry_run ) {
								/*
								 * We could be deleting a lot of options rows at the same time.
								 * Allow some time for replication to catch up.
								 */
								sleep( 3 );
							}
						}

						restore_current_blog();
					}
					if ( $count_fixes ) {
						WP_CLI::success(
							sprintf(
								/* translators: %1$s is the name of an option, %2$d is a number of sites. */
								__( 'Successfully reset %1$s on %2$d sites.', 'jetpack' ),
								$option,
								$count_fixes
							)
						);
					} else {
						WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
					}
					return;
				}

				$count = self::count_option( $option );
				if ( $count > 1 ) {
					if ( ! $is_dry_run ) {
						delete_option( $option );
					}
					WP_CLI::success(
						sprintf(
							/* translators: %1$d is a number, %2$s is the name of an option. */
							__( 'Deleted %1$d %2$s options', 'jetpack' ),
							$count,
							$option
						)
					);
					return;
				}

				WP_CLI::success( __( 'No options were deleted.', 'jetpack' ) );
				break;

		}
	}

	/**
	 * Return the number of times an option appears
	 * Normally an option would only appear 1 since the option key is supposed to be unique
	 * but if a site hasn't updated the DB schema then that would not be the case.
	 *
	 * @param string $option Option name.
	 *
	 * @return int
	 */
	private static function count_option( $option ) {
		global $wpdb;
		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM $wpdb->options WHERE option_name = %s",
				$option
			)
		);

	}

	/**
	 * Manage Jetpack Modules
	 *
	 * ## OPTIONS
	 *
	 * <list|activate|deactivate|toggle>
	 * : The action to take.
	 * ---
	 * default: list
	 * options:
	 *  - list
	 *  - activate
	 *  - deactivate
	 *  - toggle
	 * ---
	 *
	 * [<module_slug>]
	 * : The slug of the module to perform an action on.
	 *
	 * [--format=<format>]
	 * : Allows overriding the output of the command when listing modules.
	 * ---
	 * default: table
	 * options:
	 *  - table
	 *  - json
	 *  - csv
	 *  - yaml
	 *  - ids
	 *  - count
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack module list
	 * wp jetpack module list --format=json
	 * wp jetpack module activate stats
	 * wp jetpack module deactivate stats
	 * wp jetpack module toggle stats
	 * wp jetpack module activate all
	 * wp jetpack module deactivate all
	 */
	public function module( $args, $assoc_args ) {
		$action = isset( $args[0] ) ? $args[0] : 'list';

		if ( isset( $args[1] ) ) {
			$module_slug = $args[1];
			if ( 'all' !== $module_slug && ! Jetpack::is_module( $module_slug ) ) {
				/* translators: %s is a module slug like "stats" */
				WP_CLI::error( sprintf( __( '%s is not a valid module.', 'jetpack' ), $module_slug ) );
			}
			if ( 'toggle' === $action ) {
				$action = Jetpack::is_module_active( $module_slug )
					? 'deactivate'
					: 'activate';
			}
			if ( 'all' === $args[1] ) {
				$action = ( 'deactivate' === $action )
					? 'deactivate_all'
					: 'activate_all';
			}
		} elseif ( 'list' !== $action ) {
			WP_CLI::line( __( 'Please specify a valid module.', 'jetpack' ) );
			$action = 'list';
		}

		switch ( $action ) {
			case 'list':
				$modules_list = array();
				$modules      = Jetpack::get_available_modules();
				sort( $modules );
				foreach ( (array) $modules as $module_slug ) {
					if ( 'vaultpress' === $module_slug ) {
						continue;
					}
					$modules_list[] = array(
						'slug'   => $module_slug,
						'status' => Jetpack::is_module_active( $module_slug )
							? __( 'Active', 'jetpack' )
							: __( 'Inactive', 'jetpack' ),
					);
				}
				WP_CLI\Utils\format_items( $assoc_args['format'], $modules_list, array( 'slug', 'status' ) );
				break;
			case 'activate':
				$module = Jetpack::get_module( $module_slug );
				Jetpack::log( 'activate', $module_slug );
				if ( Jetpack::activate_module( $module_slug, false, false ) ) {
					/* translators: %s is the name of a Jetpack module */
					WP_CLI::success( sprintf( __( '%s has been activated.', 'jetpack' ), $module['name'] ) );
				} else {
					/* translators: %s is the name of a Jetpack module */
					WP_CLI::error( sprintf( __( '%s could not be activated.', 'jetpack' ), $module['name'] ) );
				}
				break;
			case 'activate_all':
				$modules = Jetpack::get_available_modules();
				Jetpack::update_active_modules( $modules );
				WP_CLI::success( __( 'All modules activated!', 'jetpack' ) );
				break;
			case 'deactivate':
				$module = Jetpack::get_module( $module_slug );
				Jetpack::log( 'deactivate', $module_slug );
				Jetpack::deactivate_module( $module_slug );
				/* translators: %s is the name of a Jetpack module */
				WP_CLI::success( sprintf( __( '%s has been deactivated.', 'jetpack' ), $module['name'] ) );
				break;
			case 'deactivate_all':
				Jetpack::delete_active_modules();
				WP_CLI::success( __( 'All modules deactivated!', 'jetpack' ) );
				break;
			case 'toggle':
				// Will never happen, should have been handled above and changed to activate or deactivate.
				break;
		}
	}

	/**
	 * Manage Protect Settings
	 *
	 * ## OPTIONS
	 *
	 * whitelist: Whitelist an IP address.  You can also read or clear the whitelist.
	 *
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack protect whitelist <ip address>
	 * wp jetpack protect whitelist list
	 * wp jetpack protect whitelist clear
	 *
	 * @synopsis <whitelist> [<ip|ip_low-ip_high|list|clear>]
	 */
	public function protect( $args, $assoc_args ) {
		$action = isset( $args[0] ) ? $args[0] : 'prompt';
		if ( ! in_array( $action, array( 'whitelist' ) ) ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
		}
		// Check if module is active
		if ( ! Jetpack::is_module_active( __FUNCTION__ ) ) {
			/* translators: %s is a module name */
			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__ ) );
		}
		if ( in_array( $action, array( 'whitelist' ) ) ) {
			if ( isset( $args[1] ) ) {
				$action = 'whitelist';
			} else {
				$action = 'prompt';
			}
		}
		switch ( $action ) {
			case 'whitelist':
				$whitelist         = array();
				$new_ip            = $args[1];
				$current_whitelist = get_site_option( 'jetpack_protect_whitelist', array() );

				// Build array of IPs that are already whitelisted.
				// Re-build manually instead of using jetpack_protect_format_whitelist() so we can easily get
				// low & high range params for jetpack_protect_ip_address_is_in_range();
				foreach ( $current_whitelist as $whitelisted ) {

					// IP ranges
					if ( $whitelisted->range ) {

						// Is it already whitelisted?
						if ( jetpack_protect_ip_address_is_in_range( $new_ip, $whitelisted->range_low, $whitelisted->range_high ) ) {
							/* translators: %s is an IP address */
							WP_CLI::error( sprintf( __( '%s has already been whitelisted', 'jetpack' ), $new_ip ) );
							break;
						}
						$whitelist[] = $whitelisted->range_low . ' - ' . $whitelisted->range_high;

					} else { // Individual IPs

						// Check if the IP is already whitelisted (single IP only)
						if ( $new_ip == $whitelisted->ip_address ) {
							/* translators: %s is an IP address */
							WP_CLI::error( sprintf( __( '%s has already been whitelisted', 'jetpack' ), $new_ip ) );
							break;
						}
						$whitelist[] = $whitelisted->ip_address;

					}
				}

				/*
				 * List the whitelist
				 * Done here because it's easier to read the $whitelist array after it's been rebuilt
				 */
				if ( isset( $args[1] ) && 'list' == $args[1] ) {
					if ( ! empty( $whitelist ) ) {
						WP_CLI::success( __( 'Here are your whitelisted IPs:', 'jetpack' ) );
						foreach ( $whitelist as $ip ) {
							WP_CLI::line( "\t" . str_pad( $ip, 24 ) );
						}
					} else {
						WP_CLI::line( __( 'Whitelist is empty.', 'jetpack' ) );
					}
					break;
				}

				/*
				 * Clear the whitelist
				 */
				if ( isset( $args[1] ) && 'clear' == $args[1] ) {
					if ( ! empty( $whitelist ) ) {
						$whitelist = array();
						jetpack_protect_save_whitelist( $whitelist );
						WP_CLI::success( __( 'Cleared all whitelisted IPs', 'jetpack' ) );
					} else {
						WP_CLI::line( __( 'Whitelist is empty.', 'jetpack' ) );
					}
					break;
				}

				// Append new IP to whitelist array
				array_push( $whitelist, $new_ip );

				// Save whitelist if there are no errors
				$result = jetpack_protect_save_whitelist( $whitelist );
				if ( is_wp_error( $result ) ) {
					WP_CLI::error( $result );
				}

				/* translators: %s is an IP address */
				WP_CLI::success( sprintf( __( '%s has been whitelisted.', 'jetpack' ), $new_ip ) );
				break;
			case 'prompt':
				WP_CLI::error(
					__( 'No command found.', 'jetpack' ) . "\n" .
					__( 'Please enter the IP address you want to whitelist.', 'jetpack' ) . "\n" .
					_x( 'You can save a range of IPs {low_range}-{high_range}. No spaces allowed.  (example: 1.1.1.1-2.2.2.2)', 'Instructions on how to whitelist IP ranges - low_range/high_range should be translated.', 'jetpack' ) . "\n" .
					_x( "You can also 'list' or 'clear' the whitelist.", "'list' and 'clear' are commands and should not be translated", 'jetpack' ) . "\n"
				);
				break;
		}
	}

	/**
	 * Manage Jetpack Options
	 *
	 * ## OPTIONS
	 *
	 * list   : List all jetpack options and their values
	 * delete : Delete an option
	 *          - can only delete options that are white listed.
	 * update : update an option
	 *          - can only update option strings
	 * get    : get the value of an option
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack options list
	 * wp jetpack options get    <option_name>
	 * wp jetpack options delete <option_name>
	 * wp jetpack options update <option_name> [<option_value>]
	 *
	 * @synopsis <list|get|delete|update> [<option_name>] [<option_value>]
	 */
	public function options( $args, $assoc_args ) {
		$action         = isset( $args[0] ) ? $args[0] : 'list';
		$safe_to_modify = Jetpack_Options::get_options_for_reset();

		// Is the option flagged as unsafe?
		$flagged = ! in_array( $args[1], $safe_to_modify );

		if ( ! in_array( $action, array( 'list', 'get', 'delete', 'update' ) ) ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
		}

		if ( isset( $args[0] ) ) {
			if ( 'get' == $args[0] && isset( $args[1] ) ) {
				$action = 'get';
			} elseif ( 'delete' == $args[0] && isset( $args[1] ) ) {
				$action = 'delete';
			} elseif ( 'update' == $args[0] && isset( $args[1] ) ) {
				$action = 'update';
			} else {
				$action = 'list';
			}
		}

		// Bail if the option isn't found
		$option = isset( $args[1] ) ? Jetpack_Options::get_option( $args[1] ) : false;
		if ( isset( $args[1] ) && ! $option && 'update' !== $args[0] ) {
			WP_CLI::error( __( 'Option not found or is empty.  Use "list" to list option names', 'jetpack' ) );
		}

		// Let's print_r the option if it's an array
		// Used in the 'get' and 'list' actions
		$option = is_array( $option ) ? print_r( $option ) : $option;

		switch ( $action ) {
			case 'get':
				WP_CLI::success( "\t" . $option );
				break;
			case 'delete':
				jetpack_cli_are_you_sure( $flagged );

				Jetpack_Options::delete_option( $args[1] );
				/* translators: %s is the option name */
				WP_CLI::success( sprintf( __( 'Deleted option: %s', 'jetpack' ), $args[1] ) );
				break;
			case 'update':
				jetpack_cli_are_you_sure( $flagged );

				// Updating arrays would get pretty tricky...
				$value = Jetpack_Options::get_option( $args[1] );
				if ( $value && is_array( $value ) ) {
					WP_CLI::error( __( 'Sorry, no updating arrays at this time', 'jetpack' ) );
				}

				Jetpack_Options::update_option( $args[1], $args[2] );
				/* translators: %1$s is the previous value, %2$s is the new value */
				WP_CLI::success( sprintf( _x( 'Updated option: %1$s to "%2$s"', 'Updating an option from "this" to "that".', 'jetpack' ), $args[1], $args[2] ) );
				break;
			case 'list':
				$options_compact     = Jetpack_Options::get_option_names();
				$options_non_compact = Jetpack_Options::get_option_names( 'non_compact' );
				$options_private     = Jetpack_Options::get_option_names( 'private' );
				$options             = array_merge( $options_compact, $options_non_compact, $options_private );

				// Table headers
				WP_CLI::line( "\t" . str_pad( __( 'Option', 'jetpack' ), 30 ) . __( 'Value', 'jetpack' ) );

				// List out the options and their values
				// Tell them if the value is empty or not
				// Tell them if it's an array
				foreach ( $options as $option ) {
					$value = Jetpack_Options::get_option( $option );
					if ( ! $value ) {
						WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Empty' );
						continue;
					}

					if ( ! is_array( $value ) ) {
						WP_CLI::line( "\t" . str_pad( $option, 30 ) . $value );
					} elseif ( is_array( $value ) ) {
						WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Array - Use "get <option>" to read option array.' );
					}
				}
				$option_text = '{' . _x( 'option', 'a variable command that a user can write, provided in the printed instructions', 'jetpack' ) . '}';
				$value_text  = '{' . _x( 'value', 'the value that they want to update the option to', 'jetpack' ) . '}';

				WP_CLI::success(
					_x( "Above are your options. You may 'get', 'delete', and 'update' them.", "'get', 'delete', and 'update' are commands - do not translate.", 'jetpack' ) . "\n" .
					str_pad( 'wp jetpack options get', 26 ) . $option_text . "\n" .
					str_pad( 'wp jetpack options delete', 26 ) . $option_text . "\n" .
					str_pad( 'wp jetpack options update', 26 ) . "$option_text $value_text" . "\n" .
					_x( "Type 'wp jetpack options' for more info.", "'wp jetpack options' is a command - do not translate.", 'jetpack' ) . "\n"
				);
				break;
		}
	}

	/**
	 * Get the status of or start a new Jetpack sync.
	 *
	 * ## OPTIONS
	 *
	 * status   : Print the current sync status
	 * settings : Prints the current sync settings
	 * start    : Start a full sync from this site to WordPress.com
	 * enable   : Enables sync on the site
	 * disable  : Disable sync on a site
	 * reset    : Disables sync and Resets the sync queues on a site
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack sync status
	 * wp jetpack sync settings
	 * wp jetpack sync start --modules=functions --sync_wait_time=5
	 * wp jetpack sync enable
	 * wp jetpack sync disable
	 * wp jetpack sync reset
	 * wp jetpack sync reset --queue=full or regular
	 *
	 * @synopsis <status|start> [--<field>=<value>]
	 */
	public function sync( $args, $assoc_args ) {

		$action = isset( $args[0] ) ? $args[0] : 'status';

		switch ( $action ) {
			case 'status':
				$status     = Actions::get_sync_status();
				$collection = array();
				foreach ( $status as $key => $item ) {
					$collection[] = array(
						'option' => $key,
						'value'  => is_scalar( $item ) ? $item : json_encode( $item ),
					);
				}
				WP_CLI::log( __( 'Sync Status:', 'jetpack' ) );
				WP_CLI\Utils\format_items( 'table', $collection, array( 'option', 'value' ) );
				break;
			case 'settings':
				WP_CLI::log( __( 'Sync Settings:', 'jetpack' ) );
				foreach ( Settings::get_settings() as $setting => $item ) {
					$settings[] = array(
						'setting' => $setting,
						'value'   => is_scalar( $item ) ? $item : json_encode( $item ),
					);
				}
				WP_CLI\Utils\format_items( 'table', $settings, array( 'setting', 'value' ) );

			case 'disable':
				// Don't set it via the Settings since that also resets the queues.
				update_option( 'jetpack_sync_settings_disable', 1 );
				/* translators: %s is the site URL */
				WP_CLI::log( sprintf( __( 'Sync Disabled on %s', 'jetpack' ), get_site_url() ) );
				break;
			case 'enable':
				Settings::update_settings( array( 'disable' => 0 ) );
				/* translators: %s is the site URL */
				WP_CLI::log( sprintf( __( 'Sync Enabled on %s', 'jetpack' ), get_site_url() ) );
				break;
			case 'reset':
				// Don't set it via the Settings since that also resets the queues.
				update_option( 'jetpack_sync_settings_disable', 1 );

				/* translators: %s is the site URL */
				WP_CLI::log( sprintf( __( 'Sync Disabled on %s. Use `wp jetpack sync enable` to enable syncing again.', 'jetpack' ), get_site_url() ) );
				$listener = Listener::get_instance();
				if ( empty( $assoc_args['queue'] ) ) {
					$listener->get_sync_queue()->reset();
					$listener->get_full_sync_queue()->reset();
					/* translators: %s is the site URL */
					WP_CLI::log( sprintf( __( 'Reset Full Sync and Regular Queues Queue on %s', 'jetpack' ), get_site_url() ) );
					break;
				}

				if ( ! empty( $assoc_args['queue'] ) ) {
					switch ( $assoc_args['queue'] ) {
						case 'regular':
							$listener->get_sync_queue()->reset();
							/* translators: %s is the site URL */
							WP_CLI::log( sprintf( __( 'Reset Regular Sync Queue on %s', 'jetpack' ), get_site_url() ) );
							break;
						case 'full':
							$listener->get_full_sync_queue()->reset();
							/* translators: %s is the site URL */
							WP_CLI::log( sprintf( __( 'Reset Full Sync Queue on %s', 'jetpack' ), get_site_url() ) );
							break;
						default:
							WP_CLI::error( __( 'Please specify what type of queue do you want to reset: `full` or `regular`.', 'jetpack' ) );
							break;
					}
				}

				break;
			case 'start':
				if ( ! Actions::sync_allowed() ) {
					if ( ! Settings::get_setting( 'disable' ) ) {
						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' ) );
						return;
					}
					if ( doing_action( 'jetpack_user_authorized' ) || Jetpack::is_active() ) {
						WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. Jetpack is not connected.', 'jetpack' ) );
						return;
					}
					if ( ( new Status() )->is_development_mode() ) {
						WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in development mode.', 'jetpack' ) );
						return;
					}
					if ( Jetpack::is_staging_site() ) {
						WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site. The site is in staging mode.', 'jetpack' ) );
						return;
					}
				}
				// Get the original settings so that we can restore them later
				$original_settings = Settings::get_settings();

				// Initialize sync settigns so we can sync as quickly as possible
				$sync_settings = wp_parse_args(
					array_intersect_key( $assoc_args, Settings::$valid_settings ),
					array(
						'sync_wait_time'           => 0,
						'enqueue_wait_time'        => 0,
						'queue_max_writes_sec'     => 10000,
						'max_queue_size_full_sync' => 100000,
					)
				);
				Settings::update_settings( $sync_settings );

				// Convert comma-delimited string of modules to an array
				if ( ! empty( $assoc_args['modules'] ) ) {
					$modules = array_map( 'trim', explode( ',', $assoc_args['modules'] ) );

					// Convert the array so that the keys are the module name and the value is true to indicate
					// that we want to sync the module
					$modules = array_map( '__return_true', array_flip( $modules ) );
				}

				foreach ( array( 'posts', 'comments', 'users' ) as $module_name ) {
					if (
						'users' === $module_name &&
						isset( $assoc_args[ $module_name ] ) &&
						'initial' === $assoc_args[ $module_name ]
					) {
						$modules['users'] = 'initial';
					} elseif ( isset( $assoc_args[ $module_name ] ) ) {
						$ids = explode( ',', $assoc_args[ $module_name ] );
						if ( count( $ids ) > 0 ) {
							$modules[ $module_name ] = $ids;
						}
					}
				}

				if ( empty( $modules ) ) {
					$modules = null;
				}

				// Kick off a full sync
				if ( Actions::do_full_sync( $modules ) ) {
					if ( $modules ) {
						/* translators: %s is a comma separated list of Jetpack modules */
						WP_CLI::log( sprintf( __( 'Initialized a new full sync with modules: %s', 'jetpack' ), join( ', ', array_keys( $modules ) ) ) );
					} else {
						WP_CLI::log( __( 'Initialized a new full sync', 'jetpack' ) );
					}
				} else {

					// Reset sync settings to original.
					Settings::update_settings( $original_settings );

					if ( $modules ) {
						/* translators: %s is a comma separated list of Jetpack modules */
						WP_CLI::error( sprintf( __( 'Could not start a new full sync with modules: %s', 'jetpack' ), join( ', ', $modules ) ) );
					} else {
						WP_CLI::error( __( 'Could not start a new full sync', 'jetpack' ) );
					}
				}

				// Keep sending to WPCOM until there's nothing to send
				$i = 1;
				do {
					$result = Actions::$sender->do_full_sync();
					if ( is_wp_error( $result ) ) {
						$queue_empty_error = ( 'empty_queue_full_sync' == $result->get_error_code() );
						if ( ! $queue_empty_error || ( $queue_empty_error && ( 1 == $i ) ) ) {
							/* translators: %s is an error code  */
							WP_CLI::error( sprintf( __( 'Sync errored with code: %s', 'jetpack' ), $result->get_error_code() ) );
						}
					} else {
						if ( 1 == $i ) {
							WP_CLI::log( __( 'Sent data to WordPress.com', 'jetpack' ) );
						} else {
							WP_CLI::log( __( 'Sent more data to WordPress.com', 'jetpack' ) );
						}
					}
					$i++;
				} while ( $result && ! is_wp_error( $result ) );

				// Reset sync settings to original.
				Settings::update_settings( $original_settings );

				WP_CLI::success( __( 'Finished syncing to WordPress.com', 'jetpack' ) );
				break;
		}
	}

	/**
	 * List the contents of a specific Jetpack sync queue.
	 *
	 * ## OPTIONS
	 *
	 * peek : List the 100 front-most items on the queue.
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack sync_queue full_sync peek
	 *
	 * @synopsis <incremental|full_sync> <peek>
	 */
	public function sync_queue( $args, $assoc_args ) {
		if ( ! Actions::sync_allowed() ) {
			WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site.', 'jetpack' ) );
		}

		$queue_name = isset( $args[0] ) ? $args[0] : 'sync';
		$action     = isset( $args[1] ) ? $args[1] : 'peek';

		// We map the queue name that way we can support more friendly queue names in the commands, but still use
		// the queue name that the code expects.
		$queue_name_map    = $allowed_queues = array(
			'incremental' => 'sync',
			'full'        => 'full_sync',
		);
		$mapped_queue_name = isset( $queue_name_map[ $queue_name ] ) ? $queue_name_map[ $queue_name ] : $queue_name;

		switch ( $action ) {
			case 'peek':
				$queue = new Queue( $mapped_queue_name );
				$items = $queue->peek( 100 );

				if ( empty( $items ) ) {
					/* translators: %s is the name of the queue, either 'incremental' or 'full' */
					WP_CLI::log( sprintf( __( 'Nothing is in the queue: %s', 'jetpack' ), $queue_name ) );
				} else {
					$collection = array();
					foreach ( $items as $item ) {
						$collection[] = array(
							'action'          => $item[0],
							'args'            => json_encode( $item[1] ),
							'current_user_id' => $item[2],
							'microtime'       => $item[3],
							'importing'       => (string) $item[4],
						);
					}
					WP_CLI\Utils\format_items(
						'table',
						$collection,
						array(
							'action',
							'args',
							'current_user_id',
							'microtime',
							'importing',
						)
					);
				}
				break;
		}
	}

	/**
	 * Cancel's the current Jetpack plan granted by this partner, if applicable
	 *
	 * Returns success or error JSON
	 *
	 * <token_json>
	 * : JSON blob of WPCOM API token
	 *  [--partner_tracking_id=<partner_tracking_id>]
	 * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
	 *
	 *  * @synopsis <token_json> [--partner_tracking_id=<partner_tracking_id>]
	 */
	public function partner_cancel( $args, $named_args ) {
		list( $token_json ) = $args;

		if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
			/* translators: %s is the invalid JSON string */
			$this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
		}

		if ( isset( $token->error ) ) {
			$this->partner_provision_error( new WP_Error( $token->error, $token->message ) );
		}

		if ( ! isset( $token->access_token ) ) {
			$this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
		}

		if ( Jetpack::validate_sync_error_idc_option() ) {
			$this->partner_provision_error(
				new WP_Error(
					'site_in_safe_mode',
					esc_html__( 'Can not cancel a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
				)
			);
		}

		$site_identifier = Jetpack_Options::get_option( 'id' );

		if ( ! $site_identifier ) {
			$site_identifier = Jetpack::build_raw_urls( get_home_url() );
		}

		$request = array(
			'headers' => array(
				'Authorization' => 'Bearer ' . $token->access_token,
				'Host'          => 'public-api.wordpress.com',
			),
			'timeout' => 60,
			'method'  => 'POST',
		);

		$url = sprintf( 'https://%s/rest/v1.3/jpphp/%s/partner-cancel', $this->get_api_host(), $site_identifier );
		if ( ! empty( $named_args ) && ! empty( $named_args['partner_tracking_id'] ) ) {
			$url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
		}

		$result = Client::_wp_remote_request( $url, $request );

		Jetpack_Options::delete_option( 'onboarding' );

		if ( is_wp_error( $result ) ) {
			$this->partner_provision_error( $result );
		}

		WP_CLI::log( wp_remote_retrieve_body( $result ) );
	}

	/**
	 * Provision a site using a Jetpack Partner license
	 *
	 * Returns JSON blob
	 *
	 * ## OPTIONS
	 *
	 * <token_json>
	 * : JSON blob of WPCOM API token
	 * [--plan=<plan_name>]
	 * : Slug of the requested plan, e.g. premium
	 * [--wpcom_user_id=<user_id>]
	 * : WordPress.com ID of user to connect as (must be whitelisted against partner key)
	 * [--wpcom_user_email=<wpcom_user_email>]
	 * : Override the email we send to WordPress.com for registration
	 * [--onboarding=<onboarding>]
	 * : Guide the user through an onboarding wizard
	 * [--force_register=<register>]
	 * : Whether to force a site to register
	 * [--force_connect=<force_connect>]
	 * : Force JPS to not reuse existing credentials
	 * [--home_url=<home_url>]
	 * : Overrides the home option via the home_url filter, or the WP_HOME constant
	 * [--site_url=<site_url>]
	 * : Overrides the siteurl option via the site_url filter, or the WP_SITEURL constant
	 * [--partner_tracking_id=<partner_tracking_id>]
	 * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
	 *
	 * ## EXAMPLES
	 *
	 *     $ wp jetpack partner_provision '{ some: "json" }' premium 1
	 *     { success: true }
	 *
	 * @synopsis <token_json> [--wpcom_user_id=<user_id>] [--plan=<plan_name>] [--onboarding=<onboarding>] [--force_register=<register>] [--force_connect=<force_connect>] [--home_url=<home_url>] [--site_url=<site_url>] [--wpcom_user_email=<wpcom_user_email>] [--partner_tracking_id=<partner_tracking_id>]
	 */
	public function partner_provision( $args, $named_args ) {
		list( $token_json ) = $args;

		if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
			/* translators: %s is the invalid JSON string */
			$this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
		}

		if ( isset( $token->error ) ) {
			$message = isset( $token->message )
				? $token->message
				: '';
			$this->partner_provision_error( new WP_Error( $token->error, $message ) );
		}

		if ( ! isset( $token->access_token ) ) {
			$this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
		}

		require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';

		$body_json = Jetpack_Provision::partner_provision( $token->access_token, $named_args );

		if ( is_wp_error( $body_json ) ) {
			error_log(
				json_encode(
					array(
						'success'       => false,
						'error_code'    => $body_json->get_error_code(),
						'error_message' => $body_json->get_error_message(),
					)
				)
			);
			exit( 1 );
		}

		WP_CLI::log( json_encode( $body_json ) );
	}

	/**
	 * Manages your Jetpack sitemap
	 *
	 * ## OPTIONS
	 *
	 * rebuild : Rebuild all sitemaps
	 * --purge : if set, will remove all existing sitemap data before rebuilding
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack sitemap rebuild
	 *
	 * @subcommand sitemap
	 * @synopsis <rebuild> [--purge]
	 */
	public function sitemap( $args, $assoc_args ) {
		if ( ! Jetpack::is_active() ) {
			WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
		}
		if ( ! Jetpack::is_module_active( 'sitemaps' ) ) {
			WP_CLI::error( __( 'Jetpack Sitemaps module is not currently active. Activate it first if you want to work with sitemaps.', 'jetpack' ) );
		}
		if ( ! class_exists( 'Jetpack_Sitemap_Builder' ) ) {
			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' ) );
		}

		if ( isset( $assoc_args['purge'] ) && $assoc_args['purge'] ) {
			$librarian = new Jetpack_Sitemap_Librarian();
			$librarian->delete_all_stored_sitemap_data();
		}

		$sitemap_builder = new Jetpack_Sitemap_Builder();
		$sitemap_builder->update_sitemap();
	}

	/**
	 * Allows authorizing a user via the command line and will activate
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack authorize_user --token=123456789abcdef
	 *
	 * @synopsis --token=<value>
	 */
	public function authorize_user( $args, $named_args ) {
		if ( ! is_user_logged_in() ) {
			WP_CLI::error( __( 'Please select a user to authorize via the --user global argument.', 'jetpack' ) );
		}

		if ( empty( $named_args['token'] ) ) {
			WP_CLI::error( __( 'A non-empty token argument must be passed.', 'jetpack' ) );
		}

		$is_master_user  = ! Jetpack::is_active();
		$current_user_id = get_current_user_id();

		Connection_Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $named_args['token'], $current_user_id ), $is_master_user );

		WP_CLI::log( wp_json_encode( $named_args ) );

		if ( $is_master_user ) {
			/**
			 * Auto-enable SSO module for new Jetpack Start connections
			*
			* @since 5.0.0
			*
			* @param bool $enable_sso Whether to enable the SSO module. Default to true.
			*/
			$enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
			Jetpack::handle_post_authorization_actions( $enable_sso, false );

			/* translators: %d is a user ID */
			WP_CLI::success( sprintf( __( 'Authorized %d and activated default modules.', 'jetpack' ), $current_user_id ) );
		} else {
			/* translators: %d is a user ID */
			WP_CLI::success( sprintf( __( 'Authorized %d.', 'jetpack' ), $current_user_id ) );
		}
	}

	/**
	 * Allows calling a WordPress.com API endpoint using the current blog's token.
	 *
	 * ## OPTIONS
	 * --resource=<resource>
	 * : The resource to call with the current blog's token, where `%d` represents the current blog's ID.
	 *
	 * [--api_version=<api_version>]
	 * : The API version to query against.
	 *
	 * [--base_api_path=<base_api_path>]
	 * : The base API path to query.
	 * ---
	 * default: rest
	 * ---
	 *
	 * [--body=<body>]
	 * : A JSON encoded string representing arguments to send in the body.
	 *
	 * [--field=<value>]
	 * : Any number of arguments that should be passed to the resource.
	 *
	 * [--pretty]
	 * : Will pretty print the results of a successful API call.
	 *
	 * [--strip-success]
	 * : Will remove the green success label from successful API calls.
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack call_api --resource='/sites/%d'
	 */
	public function call_api( $args, $named_args ) {
		if ( ! Jetpack::is_active() ) {
			WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
		}

		$consumed_args = array(
			'resource',
			'api_version',
			'base_api_path',
			'body',
			'pretty',
		);

		// Get args that should be passed to resource.
		$other_args = array_diff_key( $named_args, array_flip( $consumed_args ) );

		$decoded_body = ! empty( $named_args['body'] )
			? json_decode( $named_args['body'], true )
			: false;

		$resource_url = ( false === strpos( $named_args['resource'], '%d' ) )
			? $named_args['resource']
			: sprintf( $named_args['resource'], Jetpack_Options::get_option( 'id' ) );

		$response = Client::wpcom_json_api_request_as_blog(
			$resource_url,
			empty( $named_args['api_version'] ) ? Client::WPCOM_JSON_API_VERSION : $named_args['api_version'],
			$other_args,
			empty( $decoded_body ) ? null : $decoded_body,
			empty( $named_args['base_api_path'] ) ? 'rest' : $named_args['base_api_path']
		);

		if ( is_wp_error( $response ) ) {
			WP_CLI::error(
				sprintf(
					/* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an error code, %3$s is an error message. */
					__( 'Request to %1$s returned an error: (%2$d) %3$s.', 'jetpack' ),
					$resource_url,
					$response->get_error_code(),
					$response->get_error_message()
				)
			);
		}

		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
			WP_CLI::error(
				sprintf(
					/* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an HTTP status code. */
					__( 'Request to %1$s returned a non-200 response code: %2$d.', 'jetpack' ),
					$resource_url,
					wp_remote_retrieve_response_code( $response )
				)
			);
		}

		$output = wp_remote_retrieve_body( $response );
		if ( isset( $named_args['pretty'] ) ) {
			$decoded_output = json_decode( $output );
			if ( $decoded_output ) {
				$output = wp_json_encode( $decoded_output, JSON_PRETTY_PRINT );
			}
		}

		if ( isset( $named_args['strip-success'] ) ) {
			WP_CLI::log( $output );
			WP_CLI::halt( 0 );
		}

		WP_CLI::success( $output );
	}

	/**
	 * Allows uploading SSH Credentials to the current site for backups, restores, and security scanning.
	 *
	 * ## OPTIONS
	 *
	 * [--host=<host>]
	 * : The SSH server's address.
	 *
	 * [--ssh-user=<user>]
	 * : The username to use to log in to the SSH server.
	 *
	 * [--pass=<pass>]
	 * : The password used to log in, if using a password. (optional)
	 *
	 * [--kpri=<kpri>]
	 * : The private key used to log in, if using a private key. (optional)
	 *
	 * [--pretty]
	 * : Will pretty print the results of a successful API call. (optional)
	 *
	 * [--strip-success]
	 * : Will remove the green success label from successful API calls. (optional)
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack upload_ssh_creds --host=example.com --ssh-user=example --pass=password
	 * wp jetpack updload_ssh_creds --host=example.com --ssh-user=example --kpri=key
	 */
	public function upload_ssh_creds( $args, $named_args ) {
		if ( ! Jetpack::is_active() ) {
			WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
		}

		$required_args = array(
			'host',
			'ssh-user',
		);

		foreach ( $required_args as $arg ) {
			if ( empty( $named_args[ $arg ] ) ) {
				WP_CLI::error(
					sprintf(
						/* translators: %s is a slug, such as 'host'. */
						__( '`%s` cannot be empty.', 'jetpack' ),
						$arg
					)
				);
			}
		}

		if ( empty( $named_args['pass'] ) && empty( $named_args['kpri'] ) ) {
			WP_CLI::error( __( 'Both `pass` and `kpri` fields cannot be blank.', 'jetpack' ) );
		}

		$values = array(
			'credentials' => array(
				'site_url' => get_site_url(),
				'abspath'  => ABSPATH,
				'protocol' => 'ssh',
				'port'     => 22,
				'role'     => 'main',
				'host'     => $named_args['host'],
				'user'     => $named_args['ssh-user'],
				'pass'     => empty( $named_args['pass'] ) ? '' : $named_args['pass'],
				'kpri'     => empty( $named_args['kpri'] ) ? '' : $named_args['kpri'],
			),
		);

		$named_args = wp_parse_args(
			array(
				'resource'    => '/activity-log/%d/update-credentials',
				'method'      => 'POST',
				'api_version' => '1.1',
				'body'        => wp_json_encode( $values ),
				'timeout'     => 30,
			),
			$named_args
		);

		self::call_api( $args, $named_args );
	}

	/**
	 * API wrapper for getting stats from the WordPress.com API for the current site.
	 *
	 * ## OPTIONS
	 *
	 * [--quantity=<quantity>]
	 * : The number of units to include.
	 * ---
	 * default: 30
	 * ---
	 *
	 * [--period=<period>]
	 * : The unit of time to query stats for.
	 * ---
	 * default: day
	 * options:
	 *  - day
	 *  - week
	 *  - month
	 *  - year
	 * ---
	 *
	 * [--date=<date>]
	 * : The latest date to return stats for. Ex. - 2018-01-01.
	 *
	 * [--pretty]
	 * : Will pretty print the results of a successful API call.
	 *
	 * [--strip-success]
	 * : Will remove the green success label from successful API calls.
	 *
	 * ## EXAMPLES
	 *
	 * wp jetpack get_stats
	 */
	public function get_stats( $args, $named_args ) {
		$selected_args = array_intersect_key(
			$named_args,
			array_flip(
				array(
					'quantity',
					'date',
				)
			)
		);

		// The API expects unit, but period seems to be more correct.
		$selected_args['unit'] = $named_args['period'];

		$command = sprintf(
			'jetpack call_api --resource=/sites/%d/stats/%s',
			Jetpack_Options::get_option( 'id' ),
			add_query_arg( $selected_args, 'visits' )
		);

		if ( isset( $named_args['pretty'] ) ) {
			$command .= ' --pretty';
		}

		if ( isset( $named_args['strip-success'] ) ) {
			$command .= ' --strip-success';
		}

		WP_CLI::runcommand(
			$command,
			array(
				'launch' => false, // Use the current process.
			)
		);
	}

	/**
	 * Allows management of publicize connections.
	 *
	 * ## OPTIONS
	 *
	 * <list|disconnect>
	 * : The action to perform.
	 * ---
	 * options:
	 *   - list
	 *   - disconnect
	 * ---
	 *
	 * [<identifier>]
	 * : The connection ID or service to perform an action on.
	 *
	 * [--format=<format>]
	 * : Allows overriding the output of the command when listing connections.
	 * ---
	 * default: table
	 * options:
	 *   - table
	 *   - json
	 *   - csv
	 *   - yaml
	 *   - ids
	 *   - count
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 *     # List all publicize connections.
	 *     $ wp jetpack publicize list
	 *
	 *     # List publicize connections for a given service.
	 *     $ wp jetpack publicize list twitter
	 *
	 *     # List all publicize connections for a given user.
	 *     $ wp --user=1 jetpack publicize list
	 *
	 *     # List all publicize connections for a given user and service.
	 *     $ wp --user=1 jetpack publicize list twitter
	 *
	 *     # Display details for a given connection.
	 *     $ wp jetpack publicize list 123456
	 *
	 *     # Diconnection a given connection.
	 *     $ wp jetpack publicize disconnect 123456
	 *
	 *     # Disconnect all connections.
	 *     $ wp jetpack publicize disconnect all
	 *
	 *     # Disconnect all connections for a given service.
	 *     $ wp jetpack publicize disconnect twitter
	 */
	public function publicize( $args, $named_args ) {
		if ( ! Jetpack::is_active() ) {
			WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
		}

		if ( ! Jetpack::is_module_active( 'publicize' ) ) {
			WP_CLI::error( __( 'The publicize module is not active.', 'jetpack' ) );
		}

		if ( ( new Status() )->is_development_mode() ) {
			if (
				! defined( 'JETPACK_DEV_DEBUG' ) &&
				! has_filter( 'jetpack_development_mode' ) &&
				false === strpos( site_url(), '.' )
			) {
				WP_CLI::error( __( "Jetpack is current in development mode because the site url does not contain a '.', which often occurs when dynamically setting the WP_SITEURL constant. While in development mode, the publicize module will not load.", 'jetpack' ) );
			}

			WP_CLI::error( __( 'Jetpack is currently in development mode, so the publicize module will not load.', 'jetpack' ) );
		}

		if ( ! class_exists( 'Publicize' ) ) {
			WP_CLI::error( __( 'The publicize module is not loaded.', 'jetpack' ) );
		}

		$action        = $args[0];
		$publicize     = new Publicize();
		$identifier    = ! empty( $args[1] ) ? $args[1] : false;
		$services      = array_keys( $publicize->get_services() );
		$id_is_service = in_array( $identifier, $services, true );

		switch ( $action ) {
			case 'list':
				$connections_to_return = array();

				// For the CLI command, let's return all connections when a user isn't specified. This
				// differs from the logic in the Publicize class.
				$option_connections = is_user_logged_in()
					? (array) $publicize->get_all_connections_for_user()
					: (array) $publicize->get_all_connections();

				foreach ( $option_connections as $service_name => $connections ) {
					foreach ( (array) $connections as $id => $connection ) {
						$connection['id']        = $id;
						$connection['service']   = $service_name;
						$connections_to_return[] = $connection;
					}
				}

				if ( $id_is_service && ! empty( $identifier ) && ! empty( $connections_to_return ) ) {
					$temp_connections      = $connections_to_return;
					$connections_to_return = array();

					foreach ( $temp_connections as $connection ) {
						if ( $identifier === $connection['service'] ) {
							$connections_to_return[] = $connection;
						}
					}
				}

				if ( $identifier && ! $id_is_service && ! empty( $connections_to_return ) ) {
					$connections_to_return = wp_list_filter( $connections_to_return, array( 'id' => $identifier ) );
				}

				$expected_keys = array(
					'id',
					'service',
					'user_id',
					'provider',
					'issued',
					'expires',
					'external_id',
					'external_name',
					'external_display',
					'type',
					'connection_data',
				);

				// Somehow, a test site ended up in a state where $connections_to_return looked like:
				// array( array( array( 'id' => 0, 'service' => 0 ) ) ) // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
				// This caused the CLI command to error when running WP_CLI\Utils\format_items() below. So
				// to minimize future issues, this nested loop will remove any connections that don't contain
				// any keys that we expect.
				foreach ( (array) $connections_to_return as $connection_key => $connection ) {
					foreach ( $expected_keys as $expected_key ) {
						if ( ! isset( $connection[ $expected_key ] ) ) {
							unset( $connections_to_return[ $connection_key ] );
							continue;
						}
					}
				}

				if ( empty( $connections_to_return ) ) {
					return false;
				}

				WP_CLI\Utils\format_items( $named_args['format'], $connections_to_return, $expected_keys );
				break; // list.
			case 'disconnect':
				if ( ! $identifier ) {
					WP_CLI::error( __( 'A connection ID must be passed in order to disconnect.', 'jetpack' ) );
				}

				// If the connection ID is 'all' then delete all connections. If the connection ID
				// matches a service, delete all connections for that service.
				if ( 'all' === $identifier || $id_is_service ) {
					if ( 'all' === $identifier ) {
						WP_CLI::log( __( "You're about to delete all publicize connections.", 'jetpack' ) );
					} else {
						/* translators: %s is a lowercase string for a social network. */
						WP_CLI::log( sprintf( __( "You're about to delete all publicize connections to %s.", 'jetpack' ), $identifier ) );
					}

					jetpack_cli_are_you_sure();

					$connections = array();
					$service     = $identifier;

					$option_connections = is_user_logged_in()
						? (array) $publicize->get_all_connections_for_user()
						: (array) $publicize->get_all_connections();

					if ( 'all' === $service ) {
						foreach ( (array) $option_connections as $service_name => $service_connections ) {
							foreach ( $service_connections as $id => $connection ) {
								$connections[ $id ] = $connection;
							}
						}
					} elseif ( ! empty( $option_connections[ $service ] ) ) {
						$connections = $option_connections[ $service ];
					}

					if ( ! empty( $connections ) ) {
						$count    = count( $connections );
						$progress = \WP_CLI\Utils\make_progress_bar(
							/* translators: %s is a lowercase string for a social network. */
							sprintf( __( 'Disconnecting all connections to %s.', 'jetpack' ), $service ),
							$count
						);

						foreach ( $connections as $id => $connection ) {
							if ( false === $publicize->disconnect( false, $id ) ) {
								WP_CLI::error(
									sprintf(
										/* translators: %1$d is a numeric ID and %2$s is a lowercase string for a social network. */
										__( 'Publicize connection %d could not be disconnected', 'jetpack' ),
										$id
									)
								);
							}

							$progress->tick();
						}

						$progress->finish();

						if ( 'all' === $service ) {
							WP_CLI::success( __( 'All publicize connections were successfully disconnected.', 'jetpack' ) );
						} else {
							/* translators: %s is a lowercase string for a social network. */
							WP_CLI::success( __( 'All publicize connections to %s were successfully disconnected.', 'jetpack' ), $service );
						}
					}
				} else {
					if ( false !== $publicize->disconnect( false, $identifier ) ) {
						/* translators: %d is a numeric ID. Example: 1234. */
						WP_CLI::success( sprintf( __( 'Publicize connection %d has been disconnected.', 'jetpack' ), $identifier ) );
					} else {
						/* translators: %d is a numeric ID. Example: 1234. */
						WP_CLI::error( sprintf( __( 'Publicize connection %d could not be disconnected.', 'jetpack' ), $identifier ) );
					}
				}
				break; // disconnect.
		}
	}

	private function get_api_host() {
		$env_api_host = getenv( 'JETPACK_START_API_HOST', true );
		return $env_api_host ? $env_api_host : JETPACK__WPCOM_JSON_API_HOST;
	}

	private function partner_provision_error( $error ) {
		WP_CLI::log(
			json_encode(
				array(
					'success'       => false,
					'error_code'    => $error->get_error_code(),
					'error_message' => $error->get_error_message(),
				)
			)
		);
		exit( 1 );
	}

	/**
	 * Creates the essential files in Jetpack to start building a Gutenberg block or plugin.
	 *
	 * ## TYPES
	 *
	 * 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.
	 *
	 * ## BLOCK TYPE OPTIONS
	 *
	 * The first parameter is the block title and it's not associative. Add it wrapped in quotes.
	 * 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.
	 * --slug: Specific slug to identify the block that overrides the one generated based on the title.
	 * --description: Allows to provide a text description of the block.
	 * --keywords: Provide up to three keywords separated by comma so users can find this block when they search in Gutenberg's inserter.
	 *
	 * ## BLOCK TYPE EXAMPLES
	 *
	 * wp jetpack scaffold block "Cool Block"
	 * wp jetpack scaffold block "Amazing Rock" --slug="good-music" --description="Rock the best music on your site"
	 * wp jetpack scaffold block "Jukebox" --keywords="music, audio, media"
	 *
	 * @subcommand scaffold block
	 * @synopsis <type> <title> [--slug] [--description] [--keywords]
	 *
	 * @param array $args       Positional parameters, when strings are passed, wrap them in quotes.
	 * @param array $assoc_args Associative parameters like --slug="nice-block".
	 */
	public function scaffold( $args, $assoc_args ) {
		// It's ok not to check if it's set, because otherwise WPCLI exits earlier.
		switch ( $args[0] ) {
			case 'block':
				$this->block( $args, $assoc_args );
				break;
			default:
				/* translators: %s is the subcommand */
				WP_CLI::error( sprintf( esc_html__( 'Invalid subcommand %s.', 'jetpack' ), $args[0] ) . ' 👻' );
				exit( 1 );
		}
	}

	/**
	 * Creates the essential files in Jetpack to build a Gutenberg block.
	 *
	 * @param array $args       Positional parameters. Only one is used, that corresponds to the block title.
	 * @param array $assoc_args Associative parameters defined in the scaffold() method.
	 */
	public function block( $args, $assoc_args ) {
		if ( isset( $args[1] ) ) {
			$title = ucwords( $args[1] );
		} else {
			WP_CLI::error( esc_html__( 'The title parameter is required.', 'jetpack' ) . ' 👻' );
			exit( 1 );
		}

		$slug = isset( $assoc_args['slug'] )
			? $assoc_args['slug']
			: sanitize_title( $title );

		if ( preg_match( '#^jetpack/#', $slug ) ) {
			$slug = preg_replace( '#^jetpack/#', '', $slug );
		}

		if ( ! preg_match( '/^[a-z][a-z0-9\-]*$/', $slug ) ) {
			WP_CLI::error( esc_html__( 'Invalid block slug. They can contain only lowercase alphanumeric characters or dashes, and start with a letter', 'jetpack' ) . ' 👻' );
		}

		global $wp_filesystem;
		if ( ! WP_Filesystem() ) {
			WP_CLI::error( esc_html__( "Can't write files", 'jetpack' ) . ' 😱' );
		}

		$path = JETPACK__PLUGIN_DIR . "extensions/blocks/$slug";

		if ( $wp_filesystem->exists( $path ) && $wp_filesystem->is_dir( $path ) ) {
			/* translators: %s is path to the conflicting block */
			WP_CLI::error( sprintf( esc_html__( 'Name conflicts with the existing block %s', 'jetpack' ), $path ) . ' ⛔️' );
			exit( 1 );
		}

		$wp_filesystem->mkdir( $path );

		$hasKeywords = isset( $assoc_args['keywords'] );

		$files = array(
			"$path/$slug.php"   => $this->render_block_file(
				'block-register-php',
				array(
					'slug'            => $slug,
					'title'           => $title,
					'underscoredSlug' => str_replace( '-', '_', $slug ),
					'jetpackVersion'  => substr( JETPACK__VERSION, 0, strpos( JETPACK__VERSION, '.' ) ) . '.x',
				)
			),
			"$path/index.js"    => $this->render_block_file(
				'block-index-js',
				array(
					'slug'        => $slug,
					'title'       => $title,
					'description' => isset( $assoc_args['description'] )
						? $assoc_args['description']
						: $title,
					'keywords'    => $hasKeywords
					? array_map(
						function( $keyword ) {
								// Construction necessary for Mustache lists
								return array( 'keyword' => trim( $keyword ) );
						},
						explode( ',', $assoc_args['keywords'], 3 )
					)
					: '',
					'hasKeywords' => $hasKeywords,
				)
			),
			"$path/editor.js"   => $this->render_block_file( 'block-editor-js' ),
			"$path/editor.scss" => $this->render_block_file(
				'block-editor-scss',
				array(
					'slug'  => $slug,
					'title' => $title,
				)
			),
			"$path/edit.js"     => $this->render_block_file(
				'block-edit-js',
				array(
					'title'     => $title,
					'className' => str_replace( ' ', '', ucwords( str_replace( '-', ' ', $slug ) ) ),
				)
			),
		);

		$files_written = array();

		foreach ( $files as $filename => $contents ) {
			if ( $wp_filesystem->put_contents( $filename, $contents ) ) {
				$files_written[] = $filename;
			} else {
				/* translators: %s is a file name */
				WP_CLI::error( sprintf( esc_html__( 'Error creating %s', 'jetpack' ), $filename ) );
			}
		}

		if ( empty( $files_written ) ) {
			WP_CLI::log( esc_html__( 'No files were created', 'jetpack' ) );
		} else {
			// Load index.json and insert the slug of the new block in the production array
			$block_list_path = JETPACK__PLUGIN_DIR . 'extensions/index.json';
			$block_list      = $wp_filesystem->get_contents( $block_list_path );
			if ( empty( $block_list ) ) {
				/* translators: %s is the path to the file with the block list */
				WP_CLI::error( sprintf( esc_html__( 'Error fetching contents of %s', 'jetpack' ), $block_list_path ) );
			} elseif ( false === stripos( $block_list, $slug ) ) {
				$new_block_list         = json_decode( $block_list );
				$new_block_list->beta[] = $slug;

				// Format the JSON to match our coding standards.
				$new_block_list_formatted = wp_json_encode( $new_block_list, JSON_PRETTY_PRINT ) . "\n";
				$new_block_list_formatted = preg_replace_callback(
					// Find all occurrences of multiples of 4 spaces a the start of the line.
					'/^((?:    )+)/m',
					function ( $matches ) {
						// Replace each occurrence of 4 spaces with a tab character.
						return str_repeat( "\t", substr_count( $matches[0], '    ' ) );
					},
					$new_block_list_formatted
				);

				if ( ! $wp_filesystem->put_contents( $block_list_path, $new_block_list_formatted ) ) {
					/* translators: %s is the path to the file with the block list */
					WP_CLI::error( sprintf( esc_html__( 'Error writing new %s', 'jetpack' ), $block_list_path ) );
				}
			}

			WP_CLI::success(
				sprintf(
					/* translators: the placeholders are a human readable title, and a series of words separated by dashes */
					esc_html__( 'Successfully created block %1$s with slug %2$s', 'jetpack' ) . ' 🎉' . "\n" .
					"--------------------------------------------------------------------------------------------------------------------\n" .
					/* translators: the placeholder is a directory path */
					esc_html__( 'The files were created at %s', 'jetpack' ) . "\n" .
					esc_html__( 'To start using the block, build the blocks with yarn run build-extensions', 'jetpack' ) . "\n" .
					/* translators: the placeholder is a file path */
					esc_html__( 'The block slug has been added to the beta list at %s', 'jetpack' ) . "\n" .
					esc_html__( 'To load the block, add the constant JETPACK_BETA_BLOCKS as true to your wp-config.php file', 'jetpack' ) . "\n" .
					/* translators: the placeholder is a URL */
					"\n" . esc_html__( 'Read more at %s', 'jetpack' ) . "\n",
					$title,
					$slug,
					$path,
					$block_list_path,
					'https://github.com/Automattic/jetpack/blob/master/extensions/README.md#develop-new-blocks'
				) . '--------------------------------------------------------------------------------------------------------------------'
			);
		}
	}

	/**
	 * Built the file replacing the placeholders in the template with the data supplied.
	 *
	 * @param string $template
	 * @param array  $data
	 *
	 * @return string mixed
	 */
	private static function render_block_file( $template, $data = array() ) {
		return \WP_CLI\Utils\mustache_render( JETPACK__PLUGIN_DIR . "wp-cli-templates/$template.mustache", $data );
	}
}

/*
 * Standard "ask for permission to continue" function.
 * If action cancelled, ask if they need help.
 *
 * Written outside of the class so it's not listed as an executable command w/ 'wp jetpack'
 *
 * @param $flagged   bool   false = normal option | true = flagged by get_jetpack_options_for_reset()
 * @param $error_msg string (optional)
 */
function jetpack_cli_are_you_sure( $flagged = false, $error_msg = false ) {
	$cli = new Jetpack_CLI();

	// Default cancellation message
	if ( ! $error_msg ) {
		$error_msg =
			__( 'Action cancelled. Have a question?', 'jetpack' )
			. ' '
			. $cli->green_open
			. 'jetpack.com/support'
			. $cli->color_close;
	}

	if ( ! $flagged ) {
		$prompt_message = _x( 'Are you sure? This cannot be undone. Type "yes" to continue:', '"yes" is a command - do not translate.', 'jetpack' );
	} else {
		$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' );
	}

	WP_CLI::line( $prompt_message );
	$handle = fopen( 'php://stdin', 'r' );
	$line   = fgets( $handle );
	if ( 'yes' != trim( $line ) ) {
		WP_CLI::error( $error_msg );
	}
}