暂无描述

class.jetpack-cli.php 69KB

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