class.jetpack-cli.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  1. <?php
  2. WP_CLI::add_command( 'jetpack', 'Jetpack_CLI' );
  3. /**
  4. * Control your local Jetpack installation.
  5. */
  6. class Jetpack_CLI extends WP_CLI_Command {
  7. // Aesthetics
  8. public $green_open = "\033[32m";
  9. public $red_open = "\033[31m";
  10. public $yellow_open = "\033[33m";
  11. public $color_close = "\033[0m";
  12. /**
  13. * Get Jetpack Details
  14. *
  15. * ## OPTIONS
  16. *
  17. * empty: Leave it empty for basic stats
  18. *
  19. * full: View full stats. It's the data from the heartbeat
  20. *
  21. * ## EXAMPLES
  22. *
  23. * wp jetpack status
  24. * wp jetpack status full
  25. *
  26. */
  27. public function status( $args, $assoc_args ) {
  28. require_once( JETPACK__PLUGIN_DIR . 'class.jetpack-debugger.php' );
  29. WP_CLI::line( sprintf( __( 'Checking status for %s', 'jetpack' ), esc_url( get_home_url() ) ) );
  30. if ( ! Jetpack::is_active() ) {
  31. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  32. }
  33. if ( isset( $args[0] ) && 'full' !== $args[0] ) {
  34. /* translators: %s is a command like "prompt" */
  35. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $args[0] ) );
  36. }
  37. $master_user_email = Jetpack::get_master_user_email();
  38. $jetpack_self_test = Jetpack_Debugger::run_self_test(); // Performs the same tests as jetpack.com/support/debug/
  39. if ( ! $jetpack_self_test || ! wp_remote_retrieve_response_code( $jetpack_self_test ) ) {
  40. WP_CLI::error( __( 'Jetpack connection status unknown.', 'jetpack' ) );
  41. } else if ( 200 == wp_remote_retrieve_response_code( $jetpack_self_test ) ) {
  42. WP_CLI::success( __( 'Jetpack is currently connected to WordPress.com', 'jetpack' ) );
  43. } else {
  44. WP_CLI::error( __( 'Jetpack connection is broken.', 'jetpack' ) );
  45. }
  46. WP_CLI::line( sprintf( __( 'The Jetpack Version is %s', 'jetpack' ), JETPACK__VERSION ) );
  47. WP_CLI::line( sprintf( __( 'The WordPress.com blog_id is %d', 'jetpack' ), Jetpack_Options::get_option( 'id' ) ) );
  48. WP_CLI::line( sprintf( __( 'The WordPress.com account for the primary connection is %s', 'jetpack' ), $master_user_email ) );
  49. /*
  50. * Are they asking for all data?
  51. *
  52. * Loop through heartbeat data and organize by priority.
  53. */
  54. $all_data = ( isset( $args[0] ) && 'full' == $args[0] ) ? 'full' : false;
  55. if ( $all_data ) {
  56. // Heartbeat data
  57. WP_CLI::line( "\n" . __( 'Additional data: ', 'jetpack' ) );
  58. // Get the filtered heartbeat data.
  59. // Filtered so we can color/list by severity
  60. $stats = Jetpack::jetpack_check_heartbeat_data();
  61. // Display red flags first
  62. foreach ( $stats['bad'] as $stat => $value ) {
  63. printf( "$this->red_open%-'.16s %s $this->color_close\n", $stat, $value );
  64. }
  65. // Display caution warnings next
  66. foreach ( $stats['caution'] as $stat => $value ) {
  67. printf( "$this->yellow_open%-'.16s %s $this->color_close\n", $stat, $value );
  68. }
  69. // The rest of the results are good!
  70. foreach ( $stats['good'] as $stat => $value ) {
  71. // Modules should get special spacing for aestetics
  72. if ( strpos( $stat, 'odule-' ) ) {
  73. printf( "%-'.30s %s\n", $stat, $value );
  74. usleep( 4000 ); // For dramatic effect lolz
  75. continue;
  76. }
  77. printf( "%-'.16s %s\n", $stat, $value );
  78. usleep( 4000 ); // For dramatic effect lolz
  79. }
  80. } else {
  81. // Just the basics
  82. WP_CLI::line( "\n" . _x( "View full status with 'wp jetpack status full'", '"wp jetpack status full" is a command - do not translate', 'jetpack' ) );
  83. }
  84. }
  85. /**
  86. * Tests the active connection
  87. *
  88. * 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.
  89. *
  90. * ## EXAMPLES
  91. *
  92. * wp jetpack test-connection
  93. *
  94. * @subcommand test-connection
  95. */
  96. public function test_connection( $args, $assoc_args ) {
  97. WP_CLI::line( sprintf( __( 'Testing connection for %s', 'jetpack' ), esc_url( get_site_url() ) ) );
  98. if ( ! Jetpack::is_active() ) {
  99. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  100. }
  101. $response = Jetpack_Client::wpcom_json_api_request_as_blog(
  102. sprintf( '/jetpack-blogs/%d/test-connection', Jetpack_Options::get_option( 'id' ) ),
  103. Jetpack_Client::WPCOM_JSON_API_VERSION
  104. );
  105. if ( is_wp_error( $response ) ) {
  106. /* translators: %1$s is the error code, %2$s is the error message */
  107. WP_CLI::error( sprintf( __( 'Failed to test connection (#%1$s: %2$s)', 'jetpack' ), $response->get_error_code(), $response->get_error_message() ) );
  108. }
  109. $body = wp_remote_retrieve_body( $response );
  110. if ( ! $body ) {
  111. WP_CLI::error( __( 'Failed to test connection (empty response body)', 'jetpack' ) );
  112. }
  113. $result = json_decode( $body );
  114. $is_connected = (bool) $result->connected;
  115. $message = $result->message;
  116. if ( $is_connected ) {
  117. WP_CLI::success( $message );
  118. } else {
  119. WP_CLI::error( $message );
  120. }
  121. }
  122. /**
  123. * Disconnect Jetpack Blogs or Users
  124. *
  125. * ## OPTIONS
  126. *
  127. * blog: Disconnect the entire blog.
  128. *
  129. * user <user_identifier>: Disconnect a specific user from WordPress.com.
  130. *
  131. * Please note, the primary account that the blog is connected
  132. * to WordPress.com with cannot be disconnected without
  133. * disconnecting the entire blog.
  134. *
  135. * ## EXAMPLES
  136. *
  137. * wp jetpack disconnect blog
  138. * wp jetpack disconnect user 13
  139. * wp jetpack disconnect user username
  140. * wp jetpack disconnect user email@domain.com
  141. *
  142. * @synopsis <blog|user> [<user_identifier>]
  143. */
  144. public function disconnect( $args, $assoc_args ) {
  145. if ( ! Jetpack::is_active() ) {
  146. WP_CLI::error( __( 'You cannot disconnect, without having first connected.', 'jetpack' ) );
  147. }
  148. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  149. if ( ! in_array( $action, array( 'blog', 'user', 'prompt' ) ) ) {
  150. /* translators: %s is a command like "prompt" */
  151. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  152. }
  153. if ( in_array( $action, array( 'user' ) ) ) {
  154. if ( isset( $args[1] ) ) {
  155. $user_id = $args[1];
  156. if ( ctype_digit( $user_id ) ) {
  157. $field = 'id';
  158. $user_id = (int) $user_id;
  159. } elseif ( is_email( $user_id ) ) {
  160. $field = 'email';
  161. $user_id = sanitize_user( $user_id, true );
  162. } else {
  163. $field = 'login';
  164. $user_id = sanitize_user( $user_id, true );
  165. }
  166. if ( ! $user = get_user_by( $field, $user_id ) ) {
  167. WP_CLI::error( __( 'Please specify a valid user.', 'jetpack' ) );
  168. }
  169. } else {
  170. WP_CLI::error( __( 'Please specify a user by either ID, username, or email.', 'jetpack' ) );
  171. }
  172. }
  173. switch ( $action ) {
  174. case 'blog':
  175. Jetpack::log( 'disconnect' );
  176. Jetpack::disconnect();
  177. WP_CLI::success( sprintf(
  178. __( 'Jetpack has been successfully disconnected for %s.', 'jetpack' ),
  179. esc_url( get_site_url() )
  180. ) );
  181. break;
  182. case 'user':
  183. if ( Jetpack::unlink_user( $user->ID ) ) {
  184. Jetpack::log( 'unlink', $user->ID );
  185. WP_CLI::success( __( 'User has been successfully disconnected.', 'jetpack' ) );
  186. } else {
  187. /* translators: %s is a username */
  188. WP_CLI::error( sprintf( __( "User %s could not be disconnected. Are you sure they're connected currently?", 'jetpack' ), "{$user->login} <{$user->email}>" ) );
  189. }
  190. break;
  191. case 'prompt':
  192. WP_CLI::error( __( 'Please specify if you would like to disconnect a blog or user.', 'jetpack' ) );
  193. break;
  194. }
  195. }
  196. /**
  197. * Reset Jetpack options and settings to default
  198. *
  199. * ## OPTIONS
  200. *
  201. * modules: Resets modules to default state ( get_default_modules() )
  202. *
  203. * options: Resets all Jetpack options except:
  204. * - All private options (Blog token, user token, etc...)
  205. * - id (The Client ID/WP.com Blog ID of this site)
  206. * - master_user
  207. * - version
  208. * - activated
  209. *
  210. * ## EXAMPLES
  211. *
  212. * wp jetpack reset options
  213. * wp jetpack reset modules
  214. *
  215. * @synopsis <modules|options>
  216. */
  217. public function reset( $args, $assoc_args ) {
  218. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  219. if ( ! in_array( $action, array( 'options', 'modules' ) ) ) {
  220. /* translators: %s is a command like "prompt" */
  221. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  222. }
  223. // Are you sure?
  224. jetpack_cli_are_you_sure();
  225. switch ( $action ) {
  226. case 'options':
  227. $options_to_reset = Jetpack_Options::get_options_for_reset();
  228. // Reset the Jetpack options
  229. WP_CLI::line( sprintf(
  230. __( "Resetting Jetpack Options for %s...\n", "jetpack" ),
  231. esc_url( get_site_url() )
  232. ) );
  233. sleep(1); // Take a breath
  234. foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
  235. Jetpack_Options::delete_option( $option_to_reset );
  236. usleep( 100000 );
  237. /* translators: This is the result of an action. The option named %s was reset */
  238. WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
  239. }
  240. // Reset the WP options
  241. WP_CLI::line( __( "Resetting the jetpack options stored in wp_options...\n", "jetpack" ) );
  242. usleep( 500000 ); // Take a breath
  243. foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
  244. delete_option( $option_to_reset );
  245. usleep( 100000 );
  246. /* translators: This is the result of an action. The option named %s was reset */
  247. WP_CLI::success( sprintf( __( '%s option reset', 'jetpack' ), $option_to_reset ) );
  248. }
  249. // Reset to default modules
  250. WP_CLI::line( __( "Resetting default modules...\n", "jetpack" ) );
  251. usleep( 500000 ); // Take a breath
  252. $default_modules = Jetpack::get_default_modules();
  253. Jetpack::update_active_modules( $default_modules );
  254. WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
  255. // Jumpstart option is special
  256. Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
  257. WP_CLI::success( __( 'jumpstart option reset', 'jetpack' ) );
  258. break;
  259. case 'modules':
  260. $default_modules = Jetpack::get_default_modules();
  261. Jetpack::update_active_modules( $default_modules );
  262. WP_CLI::success( __( 'Modules reset to default.', 'jetpack' ) );
  263. break;
  264. case 'prompt':
  265. WP_CLI::error( __( 'Please specify if you would like to reset your options, or modules', 'jetpack' ) );
  266. break;
  267. }
  268. }
  269. /**
  270. * Manage Jetpack Modules
  271. *
  272. * ## OPTIONS
  273. *
  274. * <list|activate|deactivate|toggle>
  275. * : The action to take.
  276. * ---
  277. * default: list
  278. * options:
  279. * - list
  280. * - activate
  281. * - deactivate
  282. * - toggle
  283. * ---
  284. *
  285. * [<module_slug>]
  286. * : The slug of the module to perform an action on.
  287. *
  288. * [--format=<format>]
  289. * : Allows overriding the output of the command when listing modules.
  290. * ---
  291. * default: table
  292. * options:
  293. * - table
  294. * - json
  295. * - csv
  296. * - yaml
  297. * - ids
  298. * - count
  299. * ---
  300. *
  301. * ## EXAMPLES
  302. *
  303. * wp jetpack module list
  304. * wp jetpack module list --format=json
  305. * wp jetpack module activate stats
  306. * wp jetpack module deactivate stats
  307. * wp jetpack module toggle stats
  308. * wp jetpack module activate all
  309. * wp jetpack module deactivate all
  310. */
  311. public function module( $args, $assoc_args ) {
  312. $action = isset( $args[0] ) ? $args[0] : 'list';
  313. if ( isset( $args[1] ) ) {
  314. $module_slug = $args[1];
  315. if ( 'all' !== $module_slug && ! Jetpack::is_module( $module_slug ) ) {
  316. /* translators: %s is a module slug like "stats" */
  317. WP_CLI::error( sprintf( __( '%s is not a valid module.', 'jetpack' ), $module_slug ) );
  318. }
  319. if ( 'toggle' === $action ) {
  320. $action = Jetpack::is_module_active( $module_slug )
  321. ? 'deactivate'
  322. : 'activate';
  323. }
  324. if ( 'all' === $args[1] ) {
  325. $action = ( 'deactivate' === $action )
  326. ? 'deactivate_all'
  327. : 'activate_all';
  328. }
  329. } elseif ( 'list' !== $action ) {
  330. WP_CLI::line( __( 'Please specify a valid module.', 'jetpack' ) );
  331. $action = 'list';
  332. }
  333. switch ( $action ) {
  334. case 'list':
  335. $modules_list = array();
  336. $modules = Jetpack::get_available_modules();
  337. sort( $modules );
  338. foreach ( (array) $modules as $module_slug ) {
  339. if ( 'vaultpress' === $module_slug ) {
  340. continue;
  341. }
  342. $modules_list[] = array(
  343. 'slug' => $module_slug,
  344. 'status' => Jetpack::is_module_active( $module_slug )
  345. ? __( 'Active', 'jetpack' )
  346. : __( 'Inactive', 'jetpack' ),
  347. );
  348. }
  349. WP_CLI\Utils\format_items( $assoc_args['format'], $modules_list, array( 'slug', 'status' ) ); // phpcs:ignore PHPCompatibility
  350. break;
  351. case 'activate':
  352. $module = Jetpack::get_module( $module_slug );
  353. Jetpack::log( 'activate', $module_slug );
  354. if ( Jetpack::activate_module( $module_slug, false, false ) ) {
  355. WP_CLI::success( sprintf( __( '%s has been activated.', 'jetpack' ), $module['name'] ) );
  356. } else {
  357. WP_CLI::error( sprintf( __( '%s could not be activated.', 'jetpack' ), $module['name'] ) );
  358. }
  359. break;
  360. case 'activate_all':
  361. $modules = Jetpack::get_available_modules();
  362. Jetpack::update_active_modules( $modules );
  363. WP_CLI::success( __( 'All modules activated!', 'jetpack' ) );
  364. break;
  365. case 'deactivate':
  366. $module = Jetpack::get_module( $module_slug );
  367. Jetpack::log( 'deactivate', $module_slug );
  368. Jetpack::deactivate_module( $module_slug );
  369. WP_CLI::success( sprintf( __( '%s has been deactivated.', 'jetpack' ), $module['name'] ) );
  370. break;
  371. case 'deactivate_all':
  372. Jetpack::delete_active_modules();
  373. WP_CLI::success( __( 'All modules deactivated!', 'jetpack' ) );
  374. break;
  375. case 'toggle':
  376. // Will never happen, should have been handled above and changed to activate or deactivate.
  377. break;
  378. }
  379. }
  380. /**
  381. * Manage Protect Settings
  382. *
  383. * ## OPTIONS
  384. *
  385. * whitelist: Whitelist an IP address. You can also read or clear the whitelist.
  386. *
  387. *
  388. * ## EXAMPLES
  389. *
  390. * wp jetpack protect whitelist <ip address>
  391. * wp jetpack protect whitelist list
  392. * wp jetpack protect whitelist clear
  393. *
  394. * @synopsis <whitelist> [<ip|ip_low-ip_high|list|clear>]
  395. */
  396. public function protect( $args, $assoc_args ) {
  397. $action = isset( $args[0] ) ? $args[0] : 'prompt';
  398. if ( ! in_array( $action, array( 'whitelist' ) ) ) {
  399. /* translators: %s is a command like "prompt" */
  400. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  401. }
  402. // Check if module is active
  403. if ( ! Jetpack::is_module_active( __FUNCTION__ ) ) {
  404. WP_CLI::error( sprintf( _x( '%s is not active. You can activate it with "wp jetpack module activate %s"', '"wp jetpack module activate" is a command - do not translate', 'jetpack' ), __FUNCTION__, __FUNCTION__ ) );
  405. }
  406. if ( in_array( $action, array( 'whitelist' ) ) ) {
  407. if ( isset( $args[1] ) ) {
  408. $action = 'whitelist';
  409. } else {
  410. $action = 'prompt';
  411. }
  412. }
  413. switch ( $action ) {
  414. case 'whitelist':
  415. $whitelist = array();
  416. $new_ip = $args[1];
  417. $current_whitelist = get_site_option( 'jetpack_protect_whitelist', array() );
  418. // Build array of IPs that are already whitelisted.
  419. // Re-build manually instead of using jetpack_protect_format_whitelist() so we can easily get
  420. // low & high range params for jetpack_protect_ip_address_is_in_range();
  421. foreach( $current_whitelist as $whitelisted ) {
  422. // IP ranges
  423. if ( $whitelisted->range ) {
  424. // Is it already whitelisted?
  425. if ( jetpack_protect_ip_address_is_in_range( $new_ip, $whitelisted->range_low, $whitelisted->range_high ) ) {
  426. /* translators: %s is an IP address */
  427. WP_CLI::error( sprintf( __( '%s has already been whitelisted', 'jetpack' ), $new_ip ) );
  428. break;
  429. }
  430. $whitelist[] = $whitelisted->range_low . " - " . $whitelisted->range_high;
  431. } else { // Individual IPs
  432. // Check if the IP is already whitelisted (single IP only)
  433. if ( $new_ip == $whitelisted->ip_address ) {
  434. /* translators: %s is an IP address */
  435. WP_CLI::error( sprintf( __( '%s has already been whitelisted', 'jetpack' ), $new_ip ) );
  436. break;
  437. }
  438. $whitelist[] = $whitelisted->ip_address;
  439. }
  440. }
  441. /*
  442. * List the whitelist
  443. * Done here because it's easier to read the $whitelist array after it's been rebuilt
  444. */
  445. if ( isset( $args[1] ) && 'list' == $args[1] ) {
  446. if ( ! empty( $whitelist ) ) {
  447. WP_CLI::success( __( 'Here are your whitelisted IPs:', 'jetpack' ) );
  448. foreach ( $whitelist as $ip ) {
  449. WP_CLI::line( "\t" . str_pad( $ip, 24 ) ) ;
  450. }
  451. } else {
  452. WP_CLI::line( __( 'Whitelist is empty.', "jetpack" ) ) ;
  453. }
  454. break;
  455. }
  456. /*
  457. * Clear the whitelist
  458. */
  459. if ( isset( $args[1] ) && 'clear' == $args[1] ) {
  460. if ( ! empty( $whitelist ) ) {
  461. $whitelist = array();
  462. jetpack_protect_save_whitelist( $whitelist );
  463. WP_CLI::success( __( 'Cleared all whitelisted IPs', 'jetpack' ) );
  464. } else {
  465. WP_CLI::line( __( 'Whitelist is empty.', "jetpack" ) ) ;
  466. }
  467. break;
  468. }
  469. // Append new IP to whitelist array
  470. array_push( $whitelist, $new_ip );
  471. // Save whitelist if there are no errors
  472. $result = jetpack_protect_save_whitelist( $whitelist );
  473. if ( is_wp_error( $result ) ) {
  474. WP_CLI::error( __( $result, 'jetpack' ) );
  475. }
  476. /* translators: %s is an IP address */
  477. WP_CLI::success( sprintf( __( '%s has been whitelisted.', 'jetpack' ), $new_ip ) );
  478. break;
  479. case 'prompt':
  480. WP_CLI::error(
  481. __( 'No command found.', 'jetpack' ) . "\n" .
  482. __( 'Please enter the IP address you want to whitelist.', 'jetpack' ) . "\n" .
  483. _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" .
  484. _x( "You can also 'list' or 'clear' the whitelist.", "'list' and 'clear' are commands and should not be translated", 'jetpack' ) . "\n"
  485. );
  486. break;
  487. }
  488. }
  489. /**
  490. * Manage Jetpack Options
  491. *
  492. * ## OPTIONS
  493. *
  494. * list : List all jetpack options and their values
  495. * delete : Delete an option
  496. * - can only delete options that are white listed.
  497. * update : update an option
  498. * - can only update option strings
  499. * get : get the value of an option
  500. *
  501. * ## EXAMPLES
  502. *
  503. * wp jetpack options list
  504. * wp jetpack options get <option_name>
  505. * wp jetpack options delete <option_name>
  506. * wp jetpack options update <option_name> [<option_value>]
  507. *
  508. * @synopsis <list|get|delete|update> [<option_name>] [<option_value>]
  509. */
  510. public function options( $args, $assoc_args ) {
  511. $action = isset( $args[0] ) ? $args[0] : 'list';
  512. $safe_to_modify = Jetpack_Options::get_options_for_reset();
  513. // Jumpstart is special
  514. array_push( $safe_to_modify, 'jumpstart' );
  515. // Is the option flagged as unsafe?
  516. $flagged = ! in_array( $args[1], $safe_to_modify );
  517. if ( ! in_array( $action, array( 'list', 'get', 'delete', 'update' ) ) ) {
  518. /* translators: %s is a command like "prompt" */
  519. WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack' ), $action ) );
  520. }
  521. if ( isset( $args[0] ) ) {
  522. if ( 'get' == $args[0] && isset( $args[1] ) ) {
  523. $action = 'get';
  524. } else if ( 'delete' == $args[0] && isset( $args[1] ) ) {
  525. $action = 'delete';
  526. } else if ( 'update' == $args[0] && isset( $args[1] ) ) {
  527. $action = 'update';
  528. } else {
  529. $action = 'list';
  530. }
  531. }
  532. // Bail if the option isn't found
  533. $option = isset( $args[1] ) ? Jetpack_Options::get_option( $args[1] ) : false;
  534. if ( isset( $args[1] ) && ! $option && 'update' !== $args[0] ) {
  535. WP_CLI::error( __( 'Option not found or is empty. Use "list" to list option names', 'jetpack' ) );
  536. }
  537. // Let's print_r the option if it's an array
  538. // Used in the 'get' and 'list' actions
  539. $option = is_array( $option ) ? print_r( $option ) : $option;
  540. switch ( $action ) {
  541. case 'get':
  542. WP_CLI::success( "\t" . $option );
  543. break;
  544. case 'delete':
  545. jetpack_cli_are_you_sure( $flagged );
  546. Jetpack_Options::delete_option( $args[1] );
  547. WP_CLI::success( sprintf( __( 'Deleted option: %s', 'jetpack' ), $args[1] ) );
  548. break;
  549. case 'update':
  550. jetpack_cli_are_you_sure( $flagged );
  551. // Updating arrays would get pretty tricky...
  552. $value = Jetpack_Options::get_option( $args[1] );
  553. if ( $value && is_array( $value ) ) {
  554. WP_CLI::error( __( 'Sorry, no updating arrays at this time', 'jetpack' ) );
  555. }
  556. Jetpack_Options::update_option( $args[1], $args[2] );
  557. WP_CLI::success( sprintf( _x( 'Updated option: %s to "%s"', 'Updating an option from "this" to "that".', 'jetpack' ), $args[1], $args[2] ) );
  558. break;
  559. case 'list':
  560. $options_compact = Jetpack_Options::get_option_names();
  561. $options_non_compact = Jetpack_Options::get_option_names( 'non_compact' );
  562. $options_private = Jetpack_Options::get_option_names( 'private' );
  563. $options = array_merge( $options_compact, $options_non_compact, $options_private );
  564. // Table headers
  565. WP_CLI::line( "\t" . str_pad( __( 'Option', 'jetpack' ), 30 ) . __( 'Value', 'jetpack' ) );
  566. // List out the options and their values
  567. // Tell them if the value is empty or not
  568. // Tell them if it's an array
  569. foreach ( $options as $option ) {
  570. $value = Jetpack_Options::get_option( $option );
  571. if ( ! $value ) {
  572. WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Empty' );
  573. continue;
  574. }
  575. if ( ! is_array( $value ) ) {
  576. WP_CLI::line( "\t" . str_pad( $option, 30 ) . $value );
  577. } else if ( is_array( $value ) ) {
  578. WP_CLI::line( "\t" . str_pad( $option, 30 ) . 'Array - Use "get <option>" to read option array.' );
  579. }
  580. }
  581. $option_text = '{' . _x( 'option', 'a variable command that a user can write, provided in the printed instructions', 'jetpack' ) . '}';
  582. $value_text = '{' . _x( 'value', 'the value that they want to update the option to', 'jetpack' ) . '}';
  583. WP_CLI::success(
  584. _x( "Above are your options. You may 'get', 'delete', and 'update' them.", "'get', 'delete', and 'update' are commands - do not translate.", 'jetpack' ) . "\n" .
  585. str_pad( 'wp jetpack options get', 26 ) . $option_text . "\n" .
  586. str_pad( 'wp jetpack options delete', 26 ) . $option_text . "\n" .
  587. str_pad( 'wp jetpack options update', 26 ) . "$option_text $value_text" . "\n" .
  588. _x( "Type 'wp jetpack options' for more info.", "'wp jetpack options' is a command - do not translate.", 'jetpack' ) . "\n"
  589. );
  590. break;
  591. }
  592. }
  593. /**
  594. * Get the status of or start a new Jetpack sync.
  595. *
  596. * ## OPTIONS
  597. *
  598. * status : Print the current sync status
  599. * start : Start a full sync from this site to WordPress.com
  600. *
  601. * ## EXAMPLES
  602. *
  603. * wp jetpack sync status
  604. * wp jetpack sync start --modules=functions --sync_wait_time=5
  605. *
  606. * @synopsis <status|start> [--<field>=<value>]
  607. */
  608. public function sync( $args, $assoc_args ) {
  609. if ( ! Jetpack_Sync_Actions::sync_allowed() ) {
  610. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site.', 'jetpack' ) );
  611. }
  612. $action = isset( $args[0] ) ? $args[0] : 'status';
  613. switch ( $action ) {
  614. case 'status':
  615. $status = Jetpack_Sync_Actions::get_sync_status();
  616. $collection = array();
  617. foreach ( $status as $key => $item ) {
  618. $collection[] = array(
  619. 'option' => $key,
  620. 'value' => is_scalar( $item ) ? $item : json_encode( $item )
  621. );
  622. }
  623. WP_CLI\Utils\format_items( 'table', $collection, array( 'option', 'value' ) ); // phpcs:ignore PHPCompatibility
  624. break;
  625. case 'start':
  626. // Get the original settings so that we can restore them later
  627. $original_settings = Jetpack_Sync_Settings::get_settings();
  628. // Initialize sync settigns so we can sync as quickly as possible
  629. $sync_settings = wp_parse_args(
  630. array_intersect_key( $assoc_args, Jetpack_Sync_Settings::$valid_settings ),
  631. array(
  632. 'sync_wait_time' => 0,
  633. 'enqueue_wait_time' => 0,
  634. 'queue_max_writes_sec' => 10000,
  635. 'max_queue_size_full_sync' => 100000
  636. )
  637. );
  638. Jetpack_Sync_Settings::update_settings( $sync_settings );
  639. // Convert comma-delimited string of modules to an array
  640. if ( ! empty( $assoc_args['modules'] ) ) {
  641. $modules = array_map( 'trim', explode( ',', $assoc_args['modules'] ) );
  642. // Convert the array so that the keys are the module name and the value is true to indicate
  643. // that we want to sync the module
  644. $modules = array_map( '__return_true', array_flip( $modules ) );
  645. }
  646. foreach ( array( 'posts', 'comments', 'users' ) as $module_name ) {
  647. if (
  648. 'users' === $module_name &&
  649. isset( $assoc_args[ $module_name ] ) &&
  650. 'initial' === $assoc_args[ $module_name ]
  651. ) {
  652. $modules[ 'users' ] = 'initial';
  653. } elseif ( isset( $assoc_args[ $module_name ] ) ) {
  654. $ids = explode( ',', $assoc_args[ $module_name ] );
  655. if ( count( $ids ) > 0 ) {
  656. $modules[ $module_name ] = $ids;
  657. }
  658. }
  659. }
  660. if ( empty( $modules ) ) {
  661. $modules = null;
  662. }
  663. // Kick off a full sync
  664. if ( Jetpack_Sync_Actions::do_full_sync( $modules ) ) {
  665. if ( $modules ) {
  666. WP_CLI::log( sprintf( __( 'Initialized a new full sync with modules: %s', 'jetpack' ), join( ', ', array_keys( $modules ) ) ) );
  667. } else {
  668. WP_CLI::log( __( 'Initialized a new full sync', 'jetpack' ) );
  669. }
  670. } else {
  671. // Reset sync settings to original.
  672. Jetpack_Sync_Settings::update_settings( $original_settings );
  673. if ( $modules ) {
  674. WP_CLI::error( sprintf( __( 'Could not start a new full sync with modules: %s', 'jetpack' ), join( ', ', $modules ) ) );
  675. } else {
  676. WP_CLI::error( __( 'Could not start a new full sync', 'jetpack' ) );
  677. }
  678. }
  679. // Keep sending to WPCOM until there's nothing to send
  680. $i = 1;
  681. do {
  682. $result = Jetpack_Sync_Actions::$sender->do_full_sync();
  683. if ( is_wp_error( $result ) ) {
  684. $queue_empty_error = ( 'empty_queue_full_sync' == $result->get_error_code() );
  685. if ( ! $queue_empty_error || ( $queue_empty_error && ( 1 == $i ) ) ) {
  686. WP_CLI::error( sprintf( __( 'Sync errored with code: %s', 'jetpack' ), $result->get_error_code() ) );
  687. }
  688. } else {
  689. if ( 1 == $i ) {
  690. WP_CLI::log( __( 'Sent data to WordPress.com', 'jetpack' ) );
  691. } else {
  692. WP_CLI::log( __( 'Sent more data to WordPress.com', 'jetpack' ) );
  693. }
  694. }
  695. $i++;
  696. } while ( $result && ! is_wp_error( $result ) );
  697. // Reset sync settings to original.
  698. Jetpack_Sync_Settings::update_settings( $original_settings );
  699. WP_CLI::success( __( 'Finished syncing to WordPress.com', 'jetpack' ) );
  700. break;
  701. }
  702. }
  703. /**
  704. * List the contents of a specific Jetpack sync queue.
  705. *
  706. * ## OPTIONS
  707. *
  708. * peek : List the 100 front-most items on the queue.
  709. *
  710. * ## EXAMPLES
  711. *
  712. * wp jetpack sync_queue full_sync peek
  713. *
  714. * @synopsis <incremental|full_sync> <peek>
  715. */
  716. public function sync_queue( $args, $assoc_args ) {
  717. if ( ! Jetpack_Sync_Actions::sync_allowed() ) {
  718. WP_CLI::error( __( 'Jetpack sync is not currently allowed for this site.', 'jetpack' ) );
  719. }
  720. $queue_name = isset( $args[0] ) ? $args[0] : 'sync';
  721. $action = isset( $args[1] ) ? $args[1] : 'peek';
  722. // We map the queue name that way we can support more friendly queue names in the commands, but still use
  723. // the queue name that the code expects.
  724. $queue_name_map = $allowed_queues = array(
  725. 'incremental' => 'sync',
  726. 'full' => 'full_sync',
  727. );
  728. $mapped_queue_name = isset( $queue_name_map[ $queue_name ] ) ? $queue_name_map[ $queue_name ] : $queue_name;
  729. switch( $action ) {
  730. case 'peek':
  731. require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-queue.php';
  732. $queue = new Jetpack_Sync_Queue( $mapped_queue_name );
  733. $items = $queue->peek( 100 );
  734. if ( empty( $items ) ) {
  735. /* translators: %s is the name of the queue, either 'incremental' or 'full' */
  736. WP_CLI::log( sprintf( __( 'Nothing is in the queue: %s', 'jetpack' ), $queue_name ) );
  737. } else {
  738. $collection = array();
  739. foreach ( $items as $item ) {
  740. $collection[] = array(
  741. 'action' => $item[0],
  742. 'args' => json_encode( $item[1] ),
  743. 'current_user_id' => $item[2],
  744. 'microtime' => $item[3],
  745. 'importing' => (string) $item[4],
  746. );
  747. }
  748. WP_CLI\Utils\format_items( // phpcs:ignore PHPCompatibility
  749. 'table',
  750. $collection,
  751. array(
  752. 'action',
  753. 'args',
  754. 'current_user_id',
  755. 'microtime',
  756. 'importing',
  757. )
  758. );
  759. }
  760. break;
  761. }
  762. }
  763. /**
  764. * Cancel's the current Jetpack plan granted by this partner, if applicable
  765. *
  766. * Returns success or error JSON
  767. *
  768. * <token_json>
  769. * : JSON blob of WPCOM API token
  770. * [--partner_tracking_id=<partner_tracking_id>]
  771. * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
  772. *
  773. * * @synopsis <token_json> [--partner_tracking_id=<partner_tracking_id>]
  774. */
  775. public function partner_cancel( $args, $named_args ) {
  776. list( $token_json ) = $args;
  777. if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
  778. $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
  779. }
  780. if ( isset( $token->error ) ) {
  781. $this->partner_provision_error( new WP_Error( $token->error, $token->message ) );
  782. }
  783. if ( ! isset( $token->access_token ) ) {
  784. $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
  785. }
  786. if ( Jetpack::validate_sync_error_idc_option() ) {
  787. $this->partner_provision_error( new WP_Error(
  788. 'site_in_safe_mode',
  789. esc_html__( 'Can not cancel a plan while in safe mode. See: https://jetpack.com/support/safe-mode/', 'jetpack' )
  790. ) );
  791. }
  792. $site_identifier = Jetpack_Options::get_option( 'id' );
  793. if ( ! $site_identifier ) {
  794. $site_identifier = Jetpack::build_raw_urls( get_home_url() );
  795. }
  796. $request = array(
  797. 'headers' => array(
  798. 'Authorization' => "Bearer " . $token->access_token,
  799. 'Host' => 'public-api.wordpress.com',
  800. ),
  801. 'timeout' => 60,
  802. 'method' => 'POST',
  803. );
  804. $url = sprintf( 'https://%s/rest/v1.3/jpphp/%s/partner-cancel', $this->get_api_host(), $site_identifier );
  805. if ( ! empty( $named_args ) && ! empty( $named_args['partner_tracking_id'] ) ) {
  806. $url = esc_url_raw( add_query_arg( 'partner_tracking_id', $named_args['partner_tracking_id'], $url ) );
  807. }
  808. $result = Jetpack_Client::_wp_remote_request( $url, $request );
  809. Jetpack_Options::delete_option( 'onboarding' );
  810. if ( is_wp_error( $result ) ) {
  811. $this->partner_provision_error( $result );
  812. }
  813. WP_CLI::log( wp_remote_retrieve_body( $result ) );
  814. }
  815. /**
  816. * Provision a site using a Jetpack Partner license
  817. *
  818. * Returns JSON blob
  819. *
  820. * ## OPTIONS
  821. *
  822. * <token_json>
  823. * : JSON blob of WPCOM API token
  824. * [--plan=<plan_name>]
  825. * : Slug of the requested plan, e.g. premium
  826. * [--wpcom_user_id=<user_id>]
  827. * : WordPress.com ID of user to connect as (must be whitelisted against partner key)
  828. * [--wpcom_user_email=<wpcom_user_email>]
  829. * : Override the email we send to WordPress.com for registration
  830. * [--onboarding=<onboarding>]
  831. * : Guide the user through an onboarding wizard
  832. * [--force_register=<register>]
  833. * : Whether to force a site to register
  834. * [--force_connect=<force_connect>]
  835. * : Force JPS to not reuse existing credentials
  836. * [--home_url=<home_url>]
  837. * : Overrides the home option via the home_url filter, or the WP_HOME constant
  838. * [--site_url=<site_url>]
  839. * : Overrides the siteurl option via the site_url filter, or the WP_SITEURL constant
  840. * [--partner_tracking_id=<partner_tracking_id>]
  841. * : This is an optional ID that a host can pass to help identify a site in logs on WordPress.com
  842. *
  843. * ## EXAMPLES
  844. *
  845. * $ wp jetpack partner_provision '{ some: "json" }' premium 1
  846. * { success: true }
  847. *
  848. * @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>]
  849. */
  850. public function partner_provision( $args, $named_args ) {
  851. list( $token_json ) = $args;
  852. if ( ! $token_json || ! ( $token = json_decode( $token_json ) ) ) {
  853. $this->partner_provision_error( new WP_Error( 'missing_access_token', sprintf( __( 'Invalid token JSON: %s', 'jetpack' ), $token_json ) ) );
  854. }
  855. if ( isset( $token->error ) ) {
  856. $message = isset( $token->message )
  857. ? $token->message
  858. : '';
  859. $this->partner_provision_error( new WP_Error( $token->error, $message ) );
  860. }
  861. if ( ! isset( $token->access_token ) ) {
  862. $this->partner_provision_error( new WP_Error( 'missing_access_token', __( 'Missing or invalid access token', 'jetpack' ) ) );
  863. }
  864. require_once JETPACK__PLUGIN_DIR . '_inc/class.jetpack-provision.php';
  865. $body_json = Jetpack_Provision::partner_provision( $token->access_token, $named_args );
  866. if ( is_wp_error( $body_json ) ) {
  867. error_log( json_encode( array(
  868. 'success' => false,
  869. 'error_code' => $body_json->get_error_code(),
  870. 'error_message' => $body_json->get_error_message()
  871. ) ) );
  872. exit( 1 );
  873. }
  874. WP_CLI::log( json_encode( $body_json ) );
  875. }
  876. /**
  877. * Manages your Jetpack sitemap
  878. *
  879. * ## OPTIONS
  880. *
  881. * rebuild : Rebuild all sitemaps
  882. * --purge : if set, will remove all existing sitemap data before rebuilding
  883. *
  884. * ## EXAMPLES
  885. *
  886. * wp jetpack sitemap rebuild
  887. *
  888. * @subcommand sitemap
  889. * @synopsis <rebuild> [--purge]
  890. */
  891. public function sitemap( $args, $assoc_args ) {
  892. if ( ! Jetpack::is_active() ) {
  893. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  894. }
  895. if ( ! Jetpack::is_module_active( 'sitemaps' ) ) {
  896. WP_CLI::error( __( 'Jetpack Sitemaps module is not currently active. Activate it first if you want to work with sitemaps.', 'jetpack' ) );
  897. }
  898. if ( ! class_exists( 'Jetpack_Sitemap_Builder' ) ) {
  899. 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' ) );
  900. }
  901. if ( isset( $assoc_args['purge'] ) && $assoc_args['purge'] ) {
  902. $librarian = new Jetpack_Sitemap_Librarian();
  903. $librarian->delete_all_stored_sitemap_data();
  904. }
  905. $sitemap_builder = new Jetpack_Sitemap_Builder();
  906. $sitemap_builder->update_sitemap();
  907. }
  908. /**
  909. * Allows authorizing a user via the command line and will activate
  910. *
  911. * ## EXAMPLES
  912. *
  913. * wp jetpack authorize_user --token=123456789abcdef
  914. *
  915. * @synopsis --token=<value>
  916. */
  917. public function authorize_user( $args, $named_args ) {
  918. if ( ! is_user_logged_in() ) {
  919. WP_CLI::error( __( 'Please select a user to authorize via the --user global argument.', 'jetpack' ) );
  920. }
  921. if ( empty( $named_args['token'] ) ) {
  922. WP_CLI::error( __( 'A non-empty token argument must be passed.', 'jetpack' ) );
  923. }
  924. $token = sanitize_text_field( $named_args['token'] );
  925. $is_master_user = ! Jetpack::is_active();
  926. $current_user_id = get_current_user_id();
  927. Jetpack::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
  928. WP_CLI::log( wp_json_encode( $named_args ) );
  929. if ( $is_master_user ) {
  930. /**
  931. * Auto-enable SSO module for new Jetpack Start connections
  932. *
  933. * @since 5.0.0
  934. *
  935. * @param bool $enable_sso Whether to enable the SSO module. Default to true.
  936. */
  937. $enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
  938. Jetpack::handle_post_authorization_actions( $enable_sso, false );
  939. /* translators: %d is a user ID */
  940. WP_CLI::success( sprintf( __( 'Authorized %d and activated default modules.', 'jetpack' ), $current_user_id ) );
  941. } else {
  942. /* translators: %d is a user ID */
  943. WP_CLI::success( sprintf( __( 'Authorized %d.', 'jetpack' ), $current_user_id ) );
  944. }
  945. }
  946. /**
  947. * Allows calling a WordPress.com API endpoint using the current blog's token.
  948. *
  949. * ## OPTIONS
  950. * --resource=<resource>
  951. * : The resource to call with the current blog's token, where `%d` represents the current blog's ID.
  952. *
  953. * [--api_version=<api_version>]
  954. * : The API version to query against.
  955. *
  956. * [--base_api_path=<base_api_path>]
  957. * : The base API path to query.
  958. * ---
  959. * default: rest
  960. * ---
  961. *
  962. * [--body=<body>]
  963. * : A JSON encoded string representing arguments to send in the body.
  964. *
  965. * [--field=<value>]
  966. * : Any number of arguments that should be passed to the resource.
  967. *
  968. * [--pretty]
  969. * : Will pretty print the results of a successful API call.
  970. *
  971. * [--strip-success]
  972. * : Will remove the green success label from successful API calls.
  973. *
  974. * ## EXAMPLES
  975. *
  976. * wp jetpack call_api --resource='/sites/%d'
  977. */
  978. public function call_api( $args, $named_args ) {
  979. if ( ! Jetpack::is_active() ) {
  980. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  981. }
  982. $consumed_args = array(
  983. 'resource',
  984. 'api_version',
  985. 'base_api_path',
  986. 'body',
  987. 'pretty',
  988. );
  989. // Get args that should be passed to resource.
  990. $other_args = array_diff_key( $named_args, array_flip( $consumed_args ) );
  991. $decoded_body = ! empty( $named_args['body'] )
  992. ? json_decode( $named_args['body'] )
  993. : false;
  994. $resource_url = ( false === strpos( $named_args['resource'], '%d' ) )
  995. ? $named_args['resource']
  996. : sprintf( $named_args['resource'], Jetpack_Options::get_option( 'id' ) );
  997. $response = Jetpack_Client::wpcom_json_api_request_as_blog(
  998. $resource_url,
  999. empty( $named_args['api_version'] ) ? Jetpack_Client::WPCOM_JSON_API_VERSION : $named_args['api_version'],
  1000. $other_args,
  1001. empty( $decoded_body ) ? null : $decoded_body,
  1002. $named_args['base_api_path']
  1003. );
  1004. if ( is_wp_error( $response ) ) {
  1005. WP_CLI::error( sprintf(
  1006. /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an error code, %3$s is an error message. */
  1007. __( 'Request to %1$s returned an error: (%2$d) %3$s.', 'jetpack' ),
  1008. $resource_url,
  1009. $response->get_error_code(),
  1010. $response->get_error_message()
  1011. ) );
  1012. }
  1013. if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
  1014. WP_CLI::error( sprintf(
  1015. /* translators: %1$s is an endpoint route (ex. /sites/123456), %2$d is an HTTP status code. */
  1016. __( 'Request to %1$s returned a non-200 response code: %2$d.', 'jetpack' ),
  1017. $resource_url,
  1018. wp_remote_retrieve_response_code( $response )
  1019. ) );
  1020. }
  1021. $output = wp_remote_retrieve_body( $response );
  1022. if ( isset( $named_args['pretty'] ) ) {
  1023. $decoded_output = json_decode( $output );
  1024. if ( $decoded_output ) {
  1025. $output = wp_json_encode( $decoded_output, JSON_PRETTY_PRINT ); // phpcs:ignore PHPCompatibility
  1026. }
  1027. }
  1028. if ( isset( $named_args['strip-success'] ) ) {
  1029. WP_CLI::log( $output );
  1030. WP_CLI::halt( 0 );
  1031. }
  1032. WP_CLI::success( $output );
  1033. }
  1034. /**
  1035. * API wrapper for getting stats from the WordPress.com API for the current site.
  1036. *
  1037. * ## OPTIONS
  1038. *
  1039. * [--quantity=<quantity>]
  1040. * : The number of units to include.
  1041. * ---
  1042. * default: 30
  1043. * ---
  1044. *
  1045. * [--period=<period>]
  1046. * : The unit of time to query stats for.
  1047. * ---
  1048. * default: day
  1049. * options:
  1050. * - day
  1051. * - week
  1052. * - month
  1053. * - year
  1054. * ---
  1055. *
  1056. * [--date=<date>]
  1057. * : The latest date to return stats for. Ex. - 2018-01-01.
  1058. *
  1059. * [--pretty]
  1060. * : Will pretty print the results of a successful API call.
  1061. *
  1062. * [--strip-success]
  1063. * : Will remove the green success label from successful API calls.
  1064. *
  1065. * ## EXAMPLES
  1066. *
  1067. * wp jetpack get_stats
  1068. */
  1069. public function get_stats( $args, $named_args ) {
  1070. $selected_args = array_intersect_key(
  1071. $named_args,
  1072. array_flip( array(
  1073. 'quantity',
  1074. 'date',
  1075. ) )
  1076. );
  1077. // The API expects unit, but period seems to be more correct.
  1078. $selected_args['unit'] = $named_args['period'];
  1079. $command = sprintf(
  1080. 'jetpack call_api --resource=/sites/%d/stats/%s',
  1081. Jetpack_Options::get_option( 'id' ),
  1082. add_query_arg( $selected_args, 'visits' )
  1083. );
  1084. if ( isset( $named_args['pretty'] ) ) {
  1085. $command .= ' --pretty';
  1086. }
  1087. if ( isset( $named_args['strip-success'] ) ) {
  1088. $command .= ' --strip-success';
  1089. }
  1090. WP_CLI::runcommand(
  1091. $command,
  1092. array(
  1093. 'launch' => false, // Use the current process.
  1094. )
  1095. );
  1096. }
  1097. /**
  1098. * Allows management of publicize connections.
  1099. *
  1100. * ## OPTIONS
  1101. *
  1102. * <list|disconnect>
  1103. * : The action to perform.
  1104. * ---
  1105. * options:
  1106. * - list
  1107. * - disconnect
  1108. * ---
  1109. *
  1110. * [<identifier>]
  1111. * : The connection ID or service to perform an action on.
  1112. *
  1113. * [--format=<format>]
  1114. * : Allows overriding the output of the command when listing connections.
  1115. * ---
  1116. * default: table
  1117. * options:
  1118. * - table
  1119. * - json
  1120. * - csv
  1121. * - yaml
  1122. * - ids
  1123. * - count
  1124. * ---
  1125. *
  1126. * ## EXAMPLES
  1127. *
  1128. * # List all publicize connections.
  1129. * $ wp jetpack publicize list
  1130. *
  1131. * # List publicize connections for a given service.
  1132. * $ wp jetpack publicize list twitter
  1133. *
  1134. * # List all publicize connections for a given user.
  1135. * $ wp --user=1 jetpack publicize list
  1136. *
  1137. * # List all publicize connections for a given user and service.
  1138. * $ wp --user=1 jetpack publicize list twitter
  1139. *
  1140. * # Display details for a given connection.
  1141. * $ wp jetpack publicize list 123456
  1142. *
  1143. * # Diconnection a given connection.
  1144. * $ wp jetpack publicize disconnect 123456
  1145. *
  1146. * # Disconnect all connections.
  1147. * $ wp jetpack publicize disconnect all
  1148. *
  1149. * # Disconnect all connections for a given service.
  1150. * $ wp jetpack publicize disconnect twitter
  1151. */
  1152. public function publicize( $args, $named_args ) {
  1153. if ( ! Jetpack::is_active() ) {
  1154. WP_CLI::error( __( 'Jetpack is not currently connected to WordPress.com', 'jetpack' ) );
  1155. }
  1156. if ( ! Jetpack::is_module_active( 'publicize' ) ) {
  1157. WP_CLI::error( __( 'The publicize module is not active.', 'jetpack' ) );
  1158. }
  1159. if ( Jetpack::is_development_mode() ) {
  1160. if (
  1161. ! defined( 'JETPACK_DEV_DEBUG' ) &&
  1162. ! has_filter( 'jetpack_development_mode' ) &&
  1163. false === strpos( site_url(), '.' )
  1164. ) {
  1165. 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' ) );
  1166. }
  1167. WP_CLI::error( __( 'Jetpack is currently in development mode, so the publicize module will not load.', 'jetpack' ) );
  1168. }
  1169. if ( ! class_exists( 'Publicize' ) ) {
  1170. WP_CLI::error( __( 'The publicize module is not loaded.', 'jetpack' ) );
  1171. }
  1172. $action = $args[0];
  1173. $publicize = new Publicize();
  1174. $identifier = ! empty( $args[1] ) ? $args[1] : false;
  1175. $services = array_keys( $publicize->get_services() );
  1176. $id_is_service = in_array( $identifier, $services, true );
  1177. switch ( $action ) {
  1178. case 'list':
  1179. $connections_to_return = array();
  1180. // For the CLI command, let's return all connections when a user isn't specified. This
  1181. // differs from the logic in the Publicize class.
  1182. $option_connections = is_user_logged_in()
  1183. ? (array) $publicize->get_all_connections_for_user()
  1184. : (array) $publicize->get_all_connections();
  1185. foreach ( $option_connections as $service_name => $connections ) {
  1186. foreach ( (array) $connections as $id => $connection ) {
  1187. $connection['id'] = $id;
  1188. $connection['service'] = $service_name;
  1189. $connections_to_return[] = $connection;
  1190. }
  1191. }
  1192. if ( $id_is_service && ! empty( $identifier ) && ! empty( $connections_to_return ) ) {
  1193. $temp_connections = $connections_to_return;
  1194. $connections_to_return = array();
  1195. foreach ( $temp_connections as $connection ) {
  1196. if ( $identifier === $connection['service'] ) {
  1197. $connections_to_return[] = $connection;
  1198. }
  1199. }
  1200. }
  1201. if ( $identifier && ! $id_is_service && ! empty( $connections_to_return ) ) {
  1202. $connections_to_return = wp_list_filter( $connections_to_return, array( 'id' => $identifier ) );
  1203. }
  1204. $expected_keys = array(
  1205. 'id',
  1206. 'service',
  1207. 'user_id',
  1208. 'provider',
  1209. 'issued',
  1210. 'expires',
  1211. 'external_id',
  1212. 'external_name',
  1213. 'external_display',
  1214. 'type',
  1215. 'connection_data',
  1216. );
  1217. // Somehow, a test site ended up in a state where $connections_to_return looked like:
  1218. // array( array( array( 'id' => 0, 'service' => 0 ) ) ) // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
  1219. // This caused the CLI command to error when running WP_CLI\Utils\format_items() below. So
  1220. // to minimize future issues, this nested loop will remove any connections that don't contain
  1221. // any keys that we expect.
  1222. foreach ( (array) $connections_to_return as $connection_key => $connection ) {
  1223. foreach ( $expected_keys as $expected_key ) {
  1224. if ( ! isset( $connection[ $expected_key ] ) ) {
  1225. unset( $connections_to_return[ $connection_key ] );
  1226. continue;
  1227. }
  1228. }
  1229. }
  1230. if ( empty( $connections_to_return ) ) {
  1231. return false;
  1232. }
  1233. WP_CLI\Utils\format_items( $named_args['format'], $connections_to_return, $expected_keys ); // phpcs:ignore PHPCompatibility
  1234. break; // list.
  1235. case 'disconnect':
  1236. if ( ! $identifier ) {
  1237. WP_CLI::error( __( 'A connection ID must be passed in order to disconnect.', 'jetpack' ) );
  1238. }
  1239. // If the connection ID is 'all' then delete all connections. If the connection ID
  1240. // matches a service, delete all connections for that service.
  1241. if ( 'all' === $identifier || $id_is_service ) {
  1242. if ( 'all' === $identifier ) {
  1243. WP_CLI::log( __( "You're about to delete all publicize connections.", 'jetpack' ) );
  1244. } else {
  1245. /* translators: %s is a lowercase string for a social network. */
  1246. WP_CLI::log( sprintf( __( "You're about to delete all publicize connections to %s.", 'jetpack' ), $identifier ) );
  1247. }
  1248. jetpack_cli_are_you_sure();
  1249. $connections = array();
  1250. $service = $identifier;
  1251. $option_connections = is_user_logged_in()
  1252. ? (array) $publicize->get_all_connections_for_user()
  1253. : (array) $publicize->get_all_connections();
  1254. if ( 'all' === $service ) {
  1255. foreach ( (array) $option_connections as $service_name => $service_connections ) {
  1256. foreach ( $service_connections as $id => $connection ) {
  1257. $connections[ $id ] = $connection;
  1258. }
  1259. }
  1260. } elseif ( ! empty( $option_connections[ $service ] ) ) {
  1261. $connections = $option_connections[ $service ];
  1262. }
  1263. if ( ! empty( $connections ) ) {
  1264. $count = count( $connections );
  1265. $progress = \WP_CLI\Utils\make_progress_bar( // phpcs:ignore PHPCompatibility
  1266. /* translators: %s is a lowercase string for a social network. */
  1267. sprintf( __( 'Disconnecting all connections to %s.', 'jetpack' ), $service ),
  1268. $count
  1269. );
  1270. foreach ( $connections as $id => $connection ) {
  1271. if ( false === $publicize->disconnect( false, $id ) ) {
  1272. WP_CLI::error( sprintf(
  1273. /* translators: %1$d is a numeric ID and %2$s is a lowercase string for a social network. */
  1274. __( 'Publicize connection %d could not be disconnected', 'jetpack' ),
  1275. $id
  1276. ) );
  1277. }
  1278. $progress->tick();
  1279. }
  1280. $progress->finish();
  1281. if ( 'all' === $service ) {
  1282. WP_CLI::success( __( 'All publicize connections were successfully disconnected.', 'jetpack' ) );
  1283. } else {
  1284. /* translators: %s is a lowercase string for a social network. */
  1285. WP_CLI::success( __( 'All publicize connections to %s were successfully disconnected.', 'jetpack' ), $service );
  1286. }
  1287. }
  1288. } else {
  1289. if ( false !== $publicize->disconnect( false, $identifier ) ) {
  1290. /* translators: %d is a numeric ID. Example: 1234. */
  1291. WP_CLI::success( sprintf( __( 'Publicize connection %d has been disconnected.', 'jetpack' ), $identifier ) );
  1292. } else {
  1293. /* translators: %d is a numeric ID. Example: 1234. */
  1294. WP_CLI::error( sprintf( __( 'Publicize connection %d could not be disconnected.', 'jetpack' ), $identifier ) );
  1295. }
  1296. }
  1297. break; // disconnect.
  1298. }
  1299. }
  1300. private function get_api_host() {
  1301. $env_api_host = getenv( 'JETPACK_START_API_HOST', true );
  1302. return $env_api_host ? $env_api_host : JETPACK__WPCOM_JSON_API_HOST;
  1303. }
  1304. private function partner_provision_error( $error ) {
  1305. WP_CLI::log( json_encode( array(
  1306. 'success' => false,
  1307. 'error_code' => $error->get_error_code(),
  1308. 'error_message' => $error->get_error_message()
  1309. ) ) );
  1310. exit( 1 );
  1311. }
  1312. }
  1313. /*
  1314. * Standard "ask for permission to continue" function.
  1315. * If action cancelled, ask if they need help.
  1316. *
  1317. * Written outside of the class so it's not listed as an executable command w/ 'wp jetpack'
  1318. *
  1319. * @param $flagged bool false = normal option | true = flagged by get_jetpack_options_for_reset()
  1320. * @param $error_msg string (optional)
  1321. */
  1322. function jetpack_cli_are_you_sure( $flagged = false, $error_msg = false ) {
  1323. $cli = new Jetpack_CLI();
  1324. // Default cancellation message
  1325. if ( ! $error_msg ) {
  1326. $error_msg =
  1327. __( 'Action cancelled. Have a question?', 'jetpack' )
  1328. . ' '
  1329. . $cli->green_open
  1330. . 'jetpack.com/support'
  1331. . $cli->color_close;
  1332. }
  1333. if ( ! $flagged ) {
  1334. $prompt_message = _x( 'Are you sure? This cannot be undone. Type "yes" to continue:', '"yes" is a command - do not translate.', 'jetpack' );
  1335. } else {
  1336. $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' );
  1337. }
  1338. WP_CLI::line( $prompt_message );
  1339. $handle = fopen( "php://stdin", "r" );
  1340. $line = fgets( $handle );
  1341. if ( 'yes' != trim( $line ) ){
  1342. WP_CLI::error( $error_msg );
  1343. }
  1344. }