/**
  * get status of settings
  *
  * ## EXAMPLES
  *
  *     wp multi-device status
  *
  */
 public function status($args, $assoc_args)
 {
     $options = get_option($this->options);
     $rows = array();
     $slug_table = array('None' => '');
     $themes = wp_get_themes();
     foreach ($themes as $theme_slug => $header) {
         $slug_table[$header->get('Name')] = $theme_slug;
     }
     $rows[] = array('Device' => 'smartphone (Smart Phone)', 'Theme' => $options['theme_smartphone'], 'Slug' => $slug_table[$options['theme_smartphone']], 'UserAgent' => $options['userAgent_smart']);
     $rows[] = array('Device' => 'tablet (Tablet PC)', 'Theme' => $options['theme_tablet'], 'Slug' => $slug_table[$options['theme_tablet']], 'UserAgent' => $options['userAgent_tablet']);
     $rows[] = array('Device' => 'mobile (Mobile Phone)', 'Theme' => $options['theme_mobile'], 'Slug' => $slug_table[$options['theme_mobile']], 'UserAgent' => $options['userAgent_mobile']);
     $rows[] = array('Device' => 'game (Game Platforms)', 'Theme' => $options['theme_game'], 'Slug' => $slug_table[$options['theme_game']], 'UserAgent' => $options['userAgent_game']);
     foreach ($options as $custom_switcher_option => $custom_switcher_theme) {
         if (!preg_match('/^custom_switcher_theme_/', $custom_switcher_option)) {
             continue;
         }
         $custom_switcher_name = preg_replace('/^custom_switcher_theme_/', '', $custom_switcher_option);
         $rows[] = array('Device' => $custom_switcher_name, 'Theme' => $options['custom_switcher_theme_' . $custom_switcher_name], 'Slug' => $slug_table[$options['custom_switcher_theme_' . $custom_switcher_name]], 'UserAgent' => $options['custom_switcher_userAgent_' . $custom_switcher_name]);
     }
     $default_theme = wp_get_theme()->get('Name');
     $default_theme .= ' | ';
     $default_theme .= get_stylesheet();
     WP_CLI::line('Active Theme: ' . $default_theme);
     WP_CLI\Utils\format_items('table', $rows, array('Device', 'Theme', 'Slug', 'UserAgent'));
     $line = '';
     $line .= 'PC Switcher: ';
     $line .= $options['pc_switcher'] ? 'on' : 'off';
     $line .= "\n";
     $line .= 'default CSS: ';
     $line .= $options['default_css'] ? 'on' : 'off';
     WP_CLI::line($line);
 }
 /**
  * Retrieve the current event queue
  *
  * @subcommand get-queue
  */
 public function get_queue($args, $assoc_args)
 {
     // Build and make request
     $queue_request = new \WP_REST_Request('POST', '/' . \Automattic\WP\Cron_Control\REST_API::API_NAMESPACE . '/' . \Automattic\WP\Cron_Control\REST_API::ENDPOINT_LIST);
     $queue_request->add_header('Content-Type', 'application/json');
     $queue_request->set_body(wp_json_encode(array('secret' => \WP_CRON_CONTROL_SECRET)));
     $queue_request = rest_do_request($queue_request);
     // Oh well
     if ($queue_request->is_error()) {
         \WP_CLI::error($queue_request->as_error()->get_error_message());
     }
     // Get the decoded JSON object returned by the API
     $queue_response = $queue_request->get_data();
     // No events, nothing more to do
     if (empty($queue_response['events'])) {
         \WP_CLI::warning(__('No events in the current queue', 'automattic-cron-control'));
         return;
     }
     // Prepare items for display
     $events_for_display = $this->format_events($queue_response['events']);
     $total_events_to_display = count($events_for_display);
     \WP_CLI::line(sprintf(_n('Displaying one event', 'Displaying %s events', $total_events_to_display, 'automattic-cron-control'), number_format_i18n($total_events_to_display)));
     // And reformat
     $format = 'table';
     if (isset($assoc_args['format'])) {
         if ('ids' === $assoc_args['format']) {
             \WP_CLI::error(__('Invalid output format requested', 'automattic-cron-control'));
         } else {
             $format = $assoc_args['format'];
         }
     }
     \WP_CLI\Utils\format_items($format, $events_for_display, array('timestamp', 'action', 'instance', 'scheduled_for', 'internal_event', 'schedule_name', 'event_args'));
 }
 /**
  * View the history for a given site.
  *
  * @subcommand list-history
  * @synopsis [--site-id=<site-id>] [--type=<type>] [--action=<action>] [--start-date=<start-date>] [--end-date=<end-date>] [--per-page=<per-page>] [--page=<page>] [--format=<format>]
  */
 public function list_history($args, $assoc_args)
 {
     if (empty($assoc_args['site-id']) || count(explode(',', $assoc_args['site-id'])) != 1) {
         array_unshift($this->history_fields, 'site_name');
     }
     $defaults = array('per-page' => 10, 'page' => 1, 'type' => '', 'action' => '', 'start-date' => false, 'end-date' => false, 'fields' => implode(',', $this->history_fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $this->set_account();
     $args = array('endpoint' => '/site/history/', 'method' => 'GET', 'body' => array('per_page' => (int) $assoc_args['per-page'], 'page' => (int) $assoc_args['page'], 'type' => $assoc_args['type'], 'action' => $assoc_args['action'], 'start_timestamp' => $assoc_args['start-date'] ? strtotime($assoc_args['start-date']) : '', 'end_timestamp' => $assoc_args['end-date'] ? strtotime($assoc_args['end-date']) : ''));
     if (!empty($assoc_args['site-id'])) {
         $args['body']['site_id'] = $assoc_args['site-id'];
     }
     $response = $this->api_request($args);
     if (is_wp_error($response)) {
         WP_CLI::error($response->get_error_message());
     }
     $site_history_items = array();
     foreach ($response as $response_history_item) {
         $site_history_item = new stdClass();
         foreach (explode(',', $assoc_args['fields']) as $field) {
             $site_history_item->{$field} = $response_history_item->{$field};
         }
         // 'description' sometimes has HTML
         $site_history_item->description = strip_tags($site_history_item->description);
         // 'date' is already delivered as a timestamp
         $site_history_item->date = date('Y-m-d H:i:s', $site_history_item->date) . ' GMT';
         if ($continue) {
             continue;
         }
         $site_history_items[] = $site_history_item;
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $site_history_items, $assoc_args['fields']);
 }
 /**
  * List all terms with term meta
  *
  * ## OPTIONS
  *
  * [--format=<format>]
  * : Accepted values: table, csv, json, count. Default: table
  *
  * ## EXAMPLES
  *
  *     wp fm-term-meta list_terms
  *
  * @synopsis [--format=<value>]
  */
 public function list_terms($args, $assoc_args)
 {
     $assoc_args = wp_parse_args($assoc_args, array('format' => 'table'));
     WP_CLI::warning("Muting user-generated PHP notices for this command in order to hide deprecation notices");
     error_reporting(error_reporting() & ~E_USER_NOTICE);
     $display = array();
     $terms = $this->get_terms_with_fm_term_meta();
     foreach ($terms as $term) {
         $display[] = array('Post ID' => $term->post_id, 'Taxonomy' => $term->taxonomy, 'Term ID' => $term->term_id, 'Term Slug' => $term->slug, 'Term Name' => $term->name, 'Meta Entries' => count(fm_get_term_meta($term->term_id, $term->taxonomy)));
     }
     \WP_CLI\Utils\format_items($assoc_args['format'], $display, array('Post ID', 'Taxonomy', 'Term ID', 'Term Slug', 'Term Name', 'Meta Entries'));
 }
 /**
  * Show list of all proxy caches.
  *
  * ## EXAMPLES
  *
  *     wp nginx list
  *
  * @subcommand list
  */
 function _list($args, $assoc_args)
 {
     global $nginxchampuru;
     $format = strtolower(isset($assoc_args['format']) ? $assoc_args['format'] : 'csv');
     $items = (array) $nginxchampuru->get_cached_objects();
     $fields = array("cache_id", "post_type", "cache_url", "cache_saved");
     switch ($format) {
         case 'csv':
         case 'json':
             \WP_CLI\Utils\format_items($format, $items, $fields);
             break;
         default:
             WP_CLI::error(sprintf('Invalid format "%s".', $format));
     }
     exit;
 }
 /**
  * Perform checks on a theme
  *
  * [--theme=<theme>]
  * : Theme to scan. Defaults to current.
  *
  * [--scan_type=<scan_type>]
  * : Type of scan to perform. Defaults to "WP.org Theme Review"
  *
  * [--summary]
  * : Summarize the results.
  *
  * [--format=<format>]
  * : Output results to a given format: table, JSON, CSV. Defaults to table.
  *
  * @subcommand scan-theme
  */
 public function scan_theme($args, $assoc_args)
 {
     $defaults = array('theme' => get_option('stylesheet'), 'scan_type' => 'VIP Theme Review', 'format' => 'table');
     $args = wp_parse_args($assoc_args, $defaults);
     $scanner = VIP_Scanner::get_instance()->run_theme_review($args['theme'], $args['scan_type'], array('checks'));
     if (!$scanner) {
         WP_CLI::error(sprintf('Scanning of %s failed', $args['theme']));
     }
     if (isset($args['summary'])) {
         $results = $scanner->get_results();
         $data = array();
         $data[] = array('key' => __('Result'), 'value' => $results['result']);
         $data[] = array('key' => __('Total Files'), 'value' => $results['total_files']);
         $data[] = array('key' => __('Total Checks'), 'value' => $results['total_checks']);
         $data[] = array('key' => __('Total Errors'), 'value' => count($results['errors']));
         foreach ($scanner->get_error_levels() as $level) {
             $label = __(ucfirst($level) . 's');
             $error_count = count($scanner->get_errors(array($level)));
             $data[] = array('key' => $label, 'value' => $error_count);
         }
         WP_CLI\Utils\format_items($args['format'], $data, array('key', 'value'));
     } else {
         $data = array();
         foreach ($scanner->get_error_levels() as $level) {
             $errors = $scanner->get_errors(array($level));
             foreach ($errors as $error) {
                 $lines = array();
                 // Not all errors have lines -- assign a null line if we lack lines entirely
                 $lines = isset($error['lines']) ? $error['lines'] : array('');
                 // In JSON output, group the lines together
                 if ('json' == $args['format']) {
                     $data[] = array('level' => $error['level'], 'description' => $error['description'], 'lines' => $lines, 'file' => $error['file']);
                 } else {
                     // In other output, each line gets its own entry
                     foreach ($lines as $line) {
                         $data[] = array('level' => $error['level'], 'description' => $error['description'], 'lines' => $line, 'file' => $error['file']);
                     }
                 }
             }
         }
         WP_CLI\Utils\format_items($args['format'], $data, array('level', 'description', 'lines', 'file'));
     }
 }
 /**
  * Get a specific webhook for a given site or account
  * 
  * @synopsis <webhook-id> [--site-id=<site-id>] [--<field>=<value>] [--format=<format>]
  */
 public function get($args, $assoc_args)
 {
     $webhook_id = $args[0];
     $defaults = array('fields' => implode(',', $this->fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $this->set_account();
     $site_id = isset($assoc_args['site-id']) ? $assoc_args['site-id'] : false;
     unset($assoc_args['site-id']);
     if (!empty($site_id)) {
         $endpoint = '/site/' . $site_id . '/webhook/' . $webhook_id;
     } else {
         $endpoint = '/account/webhook/' . $webhook_id;
     }
     $args = array('endpoint' => $endpoint, 'method' => 'GET');
     $webhook = $this->api_request($args);
     if (is_wp_error($webhook)) {
         WP_CLI::error($webhook->get_error_message());
     }
     WP_CLI\Utils\format_items($assoc_args['format'], array($webhook), $assoc_args['fields']);
 }
 /**
  * Themes and plugins use roughly the same object model.
  */
 protected function list_plugins_or_themes_for_site($object, $site_id, $assoc_args)
 {
     $this->set_account();
     $args = array('endpoint' => '/site/' . $site_id . '/' . str_replace('s', '', $object), 'method' => 'GET');
     $response = $this->api_request($args);
     if (is_wp_error($response)) {
         WP_CLI::error($response->get_error_message());
     }
     $items = array();
     foreach ($response as $response_item) {
         $item = new stdClass();
         $item->name = $response_item->name;
         $item->slug = $response_item->slug;
         $item->status = $response_item->is_active ? 'active' : 'inactive';
         $item->update = version_compare($response_item->latest_version, $response_item->version, '>') ? 'available' : 'none';
         $item->version = $response_item->version;
         $item->update_locked = $response_item->is_locked ? 'true' : 'false';
         $items[] = $item;
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $items, $assoc_args['fields']);
 }
 /**
  * List all of the sites in your WP Remote account.
  * 
  * @subcommand list-sites
  * @synopsis [--fields=<fields>] [--format=<format>]
  */
 public function list_sites($args, $assoc_args)
 {
     $defaults = array('fields' => implode(',', $this->site_fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $this->set_account();
     $args = array('endpoint' => '/site/', 'method' => 'GET');
     $response = $this->api_request($args);
     if (is_wp_error($response)) {
         WP_CLI::error($response->get_error_message());
     }
     $sites = array();
     foreach ($response as $response_site) {
         $site_item = new stdClass();
         foreach (explode(',', $assoc_args['fields']) as $field) {
             if ($field == 'is_premium') {
                 $site_item->{$field} = $response_site->{$field} ? 'true' : 'false';
             } else {
                 $site_item->{$field} = $response_site->{$field};
             }
         }
         $site_items[] = $site_item;
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $site_items, $assoc_args['fields']);
 }
Exemple #10
0
 /**
  * Convert the NextGen Gallery Shortcodes in posts in this site into WordPress gallery shortcodes.
  *
  * ## OPTIONS
  *
  * ## EXAMPLES
  *
  * wp escape-ngg convert
  * 
  */
 public function convert()
 {
     $count = Escape_NextGen_Gallery::init()->count();
     WP_CLI::log(sprintf('Processing %d posts with NextGen Gallery shortcodes', $count));
     set_time_limit(0);
     $uploads = wp_upload_dir();
     $baseurl = $uploads['baseurl'];
     $post_ids = Escape_NextGen_Gallery::init()->get_post_ids();
     $progress = new \cli\progress\Bar('Progress', $count);
     foreach ($post_ids as $post_id) {
         $progress->tick();
         Escape_NextGen_Gallery::init()->process_post($post_id);
     }
     $progress->finish();
     foreach (Escape_NextGen_Gallery::init()->infos as $info) {
         WP_CLI::log($info);
     }
     foreach (Escape_NextGen_Gallery::init()->warnings as $warning) {
         WP_CLI::warning($warning);
     }
     $lines = array((object) array('Converted' => 'posts converted', 'Count' => Escape_NextGen_Gallery::init()->posts_count), (object) array('Converted' => 'images converted', 'Count' => Escape_NextGen_Gallery::init()->images_count));
     $fields = array('Converted', 'Count');
     \WP_CLI\Utils\format_items('table', $lines, $fields);
 }
 /**
  * Returns a list of profiles.
  *
  * @since 1.2.4
  */
 public function profiles()
 {
     $wpmdb_settings = get_site_option('wpmdb_settings');
     // Display error if no profiles are present
     if (!isset($wpmdb_settings['profiles']) || !is_array($wpmdb_settings['profiles']) || empty($wpmdb_settings['profiles'])) {
         WP_CLI::error(__('There are no saved profiles for this site.', 'wp-migrate-db-pro-cli'));
         return;
     }
     // Get profile information in CLI format
     $cli_items = array();
     foreach ($wpmdb_settings['profiles'] as $key => $profile) {
         ++$key;
         // Get remote and set empty if action is export/safefile
         $connection_info = $profile['connection_info'];
         $connection_info = explode("\n", $connection_info);
         $remote = '---';
         if (is_array($connection_info) && 2 === count($connection_info)) {
             $remote = esc_url_raw($connection_info[0]);
         }
         // Allow actions to be translated for output
         $action_strings = array('push' => _x('push', 'Export data to remote database', 'wp-migrate-db-pro-cli'), 'pull' => _x('pull', 'Import data from remote database', 'wp-migrate-db-pro-cli'), 'savefile' => _x('export', 'Export file from local database', 'wp-migrate-db-pro-cli'), 'find_replace' => _x('find & replace', 'Run a find & replace on local database', 'wp-migrate-db-pro-cli'));
         if (isset($action_strings[$profile['action']])) {
             $profile['action'] = $action_strings[$profile['action']];
         } else {
             $profile['action'] = '---';
         }
         $profile['action'] = strtoupper($profile['action']);
         //Populate CLI items with saved profile information
         $cli_items[] = array(_x('ID', 'Profile list column heading', 'wp-migrate-db-pro-cli') => $key, _x('NAME', 'Profile list column heading', 'wp-migrate-db-pro-cli') => $profile['name'], _x('ACTION', 'Profile list column heading', 'wp-migrate-db-pro-cli') => $profile['action'], _x('REMOTE', 'Profile list column heading', 'wp-migrate-db-pro-cli') => $remote);
     }
     // Set CLI column headers. Must match `cli_items` keys
     $cli_keys = array_keys(reset($cli_items));
     WP_CLI\Utils\format_items('table', $cli_items, $cli_keys);
 }
Exemple #12
0
 /**
  * List available cron schedules.
  *
  * @since 1.2
  *
  * @subcommand list-schedules
  * @synopsis [--format=<format>]
  */
 public function list_schedules($args, $assoc_args)
 {
     $defaults = array('format' => 'table');
     $values = wp_parse_args($assoc_args, $defaults);
     $schedules = $this->crontrol->get_schedules();
     $schedules = array_map(array($this, '_map_schedule'), $schedules, array_keys($schedules));
     $fields = array('name', 'display', 'interval');
     \WP_CLI\Utils\format_items($values['format'], $schedules, $fields);
 }
 protected function assoc_array_to_table($obj_data)
 {
     $rows = array();
     foreach ($obj_data as $field => $value) {
         if (!is_string($value)) {
             $value = json_encode($value);
         }
         $rows[] = (object) array('Key' => $field, 'Value' => $value);
     }
     WP_CLI\Utils\format_items('table', $rows, array('Key', 'Value'));
 }
 /**
  * Stats for posts
  *
  * @subcommand post
  * @synopsis <datum> [--group-by=<post-arg>] [--period=<period>] [--start-date=<yyyy-mm-dd>] [--end-date=<yyyy-mm-dd>] [--format=<format>]
  */
 public function post($args, $assoc_args)
 {
     list($datum) = $args;
     $defaults = array('group-by' => '', 'period' => 'day', 'start-date' => date('Y-m-d', current_time('timestamp')), 'end-date' => date('Y-m-d', current_time('timestamp')), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $datum = sanitize_key($datum);
     $group_by = sanitize_key($assoc_args['group-by']);
     $period = sanitize_key($assoc_args['period']);
     $start_date = date('Y-m-d H:i:s', strtotime($assoc_args['start-date']));
     $end_date = date('Y-m-d H:i:s', strtotime('+1 day ' . $assoc_args['end-date']));
     $format = sanitize_key($assoc_args['format']);
     foreach (array('datum', 'group_by', 'period', 'format') as $argument) {
         $class_var = $argument . 's';
         if (!in_array(${$argument}, self::${$class_var})) {
             WP_CLI::error("Invalid {$argument} specified. Acceptable {$class_var}: " . implode(', ', self::${$class_var}));
         }
     }
     if (!in_array($format, self::$formats)) {
         WP_CLI::error("Invalid format specified. Acceptable foramts: " . implode(', ', self::$formats));
     }
     if (empty($start_date) || empty($end_date)) {
         WP_CLI::error("Invalid start_date or end_date.");
     }
     $columns = array('period');
     $fields = array();
     switch ($group_by) {
         case 'category':
         case 'post_tag':
             $terms = get_terms($group_by);
             foreach ($terms as $term) {
                 $column = $term->slug . ':' . $datum;
                 $columns[] = $column;
                 $fields[$column] = $term->slug;
             }
             break;
         case 'post_author':
             $users = get_users();
             foreach ($users as $user) {
                 $column = $user->user_login . ':' . $datum;
                 $columns[] = $column;
                 $fields[$column] = $user->user_login;
             }
             break;
         default:
             $columns[] = $datum;
             $group_by = '';
             break;
     }
     $where_filter = function ($where) use($start_date, $end_date) {
         global $wpdb;
         $end_date = date("Y-m-d H:i:s", strtotime("+1 day", strtotime($end_date)));
         $where .= $wpdb->prepare(" AND ({$wpdb->posts}.post_date >= %s AND {$wpdb->posts}.post_date < %s)", $start_date, $end_date);
         return $where;
     };
     add_filter('posts_where', $where_filter);
     $args = array('post_type' => 'post', 'post_status' => 'publish', 'order' => 'ASC', 'orderby' => 'date', 'update_term_cache' => false, 'update_meta_cache' => false, 'no_found_rows' => true, 'posts_per_page' => -1);
     $post_query = new WP_Query($args);
     remove_filter('posts_where', $where_filter);
     $raw_posts = $post_query->posts;
     $period_posts = array();
     foreach ($raw_posts as $post) {
         $post_period = $this->get_period_increment($period, strtotime($post->post_date));
         if (!empty($group_by)) {
             foreach ($fields as $column => $value) {
                 if ($this->is_post_valid($post, $group_by, $value)) {
                     $period_posts[$post_period][$column][] = $post;
                 }
             }
         } else {
             $period_posts[$post_period][] = $post;
         }
     }
     $output_stats = array();
     $period_increments = $this->get_period_increments($period, $start_date, $end_date);
     foreach ($period_increments as $increment) {
         $output_stat = new stdClass();
         $output_stat->period = $increment;
         if (!isset($period_posts[$increment])) {
             $period_posts[$increment] = array();
         }
         if (!empty($group_by)) {
             foreach ($fields as $column => $value) {
                 $output_stat->{$column} = $this->get_posts_datum($datum, $period_posts[$increment][$column]);
             }
         } else {
             $output_stat->{$datum} = $this->get_posts_datum($datum, $period_posts[$increment]);
         }
         $output_stats[] = $output_stat;
     }
     WP_CLI\Utils\format_items($format, $columns, $output_stats);
 }
Exemple #15
0
 protected function update_many($args, $assoc_args)
 {
     call_user_func($this->upgrade_refresh);
     $items = $this->get_item_list();
     if (!isset($assoc_args['all'])) {
         $items = $this->filter_item_list($items, $args);
     }
     $items_to_update = wp_list_filter($items, array('update' => true));
     if (isset($assoc_args['dry-run'])) {
         if (empty($items_to_update)) {
             \WP_CLI::line("No {$this->item_type} updates available.");
             return;
         }
         \WP_CLI::line("Available {$this->item_type} updates:");
         \WP_CLI\Utils\format_items('table', $items_to_update, array('name', 'status', 'version', 'update_version'));
         return;
     }
     $result = array();
     // Only attempt to update if there is something to update
     if (!empty($items_to_update)) {
         $cache_manager = \WP_CLI::get_http_cache_manager();
         foreach ($items_to_update as $item) {
             $cache_manager->whitelist_package($item['update_package'], $this->item_type, $item['name'], $item['update_version']);
         }
         $upgrader = $this->get_upgrader($assoc_args);
         $result = $upgrader->bulk_upgrade(wp_list_pluck($items_to_update, 'update_id'));
     }
     // Let the user know the results.
     $num_to_update = count($items_to_update);
     $num_updated = count(array_filter($result));
     $line = "Updated {$num_updated}/{$num_to_update} {$this->item_type}s.";
     if ($num_to_update == $num_updated) {
         \WP_CLI::success($line);
     } else {
         if ($num_updated > 0) {
             \WP_CLI::warning($line);
         } else {
             \WP_CLI::error($line);
         }
     }
 }
 /**
  * Delete all events of the same action
  */
 private function delete_event_by_action($args, $assoc_args)
 {
     $action = $assoc_args['action'];
     // Validate entry
     if (empty($action)) {
         \WP_CLI::error(__('Invalid action', 'automattic-cron-control'));
     }
     // Warning about Internal Events
     if (\Automattic\WP\Cron_Control\is_internal_event($action)) {
         \WP_CLI::warning(__('This is an event created by the Cron Control plugin. It will recreated automatically.', 'automattic-cron-control'));
     }
     // Set defaults needed to gather all events
     $assoc_args['page'] = 1;
     $assoc_args['limit'] = 50;
     // Gather events
     \WP_CLI::line(__('Gathering events...', 'automattic-cron-control'));
     $events_to_delete = array();
     $events = $this->get_events($args, $assoc_args);
     \WP_CLI::line(sprintf(_n('Found one event to check', 'Found %s events to check', $events['total_items'], 'automattic-cron-control'), number_format_i18n($events['total_items'])));
     $search_progress = \WP_CLI\Utils\make_progress_bar(sprintf(__('Searching events for those with the action `%s`', 'automattic-cron-control'), $action), $events['total_items']);
     // Loop and pull out events to be deleted
     do {
         if (!is_array($events) || empty($events['items'])) {
             break;
         }
         // Check events for those that should be deleted
         foreach ($events['items'] as $single_event) {
             $event_details = $this->get_event_details_from_post_title($single_event->post_title);
             if ($event_details['action'] === $action) {
                 $events_to_delete[] = array_merge($event_details, array('ID' => (int) $single_event->ID, 'post_date_gmt' => $single_event->post_date_gmt, 'post_modified_gmt' => $single_event->post_modified_gmt));
             }
             $search_progress->tick();
         }
         // Proceed to next batch
         $assoc_args['page']++;
         if ($assoc_args['page'] > $events['total_pages']) {
             break;
         }
         $events = $this->get_events($args, $assoc_args);
     } while ($events['page'] <= $events['total_pages']);
     $search_progress->finish();
     \WP_CLI::line('');
     // Nothing more to do
     if (empty($events_to_delete)) {
         \WP_CLI::error(sprintf(__('No events with action `%s` found', 'automattic-cron-control'), $action));
     }
     // List the items to remove
     $total_to_delete = count($events_to_delete);
     \WP_CLI::line(sprintf(_n('Found one event with action `%2$s`:', 'Found %1$s events with action `%2$s`:', $total_to_delete, 'automattic-cron-control'), number_format_i18n($total_to_delete), $action));
     if ($total_to_delete <= $assoc_args['limit']) {
         \WP_CLI\Utils\format_items('table', $events_to_delete, array('ID', 'post_date_gmt', 'post_modified_gmt', 'timestamp', 'instance'));
     } else {
         \WP_CLI::warning(sprintf(__('Events are not displayed as there are more than %s to remove', 'automattic-cron-control'), number_format_i18n($assoc_args['limit'])));
     }
     \WP_CLI::line('');
     \WP_CLI::confirm(_n('Are you sure you want to delete this event?', 'Are you sure you want to delete these events?', $total_to_delete, 'automattic-cron-control'));
     // Remove the items
     $delete_progress = \WP_CLI\Utils\make_progress_bar(__('Deleting events', 'automattic-cron-control'), $total_to_delete);
     $events_deleted = array();
     $events_deleted_count = $events_failed_delete = 0;
     foreach ($events_to_delete as $event_to_delete) {
         $deleted = wp_delete_post($event_to_delete['ID'], true);
         $events_deleted[] = array('ID' => $event_to_delete['ID'], 'deleted' => false === $deleted ? 'no' : 'yes');
         if ($deleted) {
             $events_deleted_count++;
         } else {
             $events_failed_delete++;
         }
         $delete_progress->tick();
     }
     $delete_progress->finish();
     // When deletes succeed, sync internal caches
     if ($events_deleted_count > 0) {
         \Automattic\WP\Cron_Control\_flush_internal_caches();
     }
     // List the removed items
     \WP_CLI::line("\n" . __('RESULTS:', 'automattic-cron-control'));
     if (1 === $total_to_delete && 1 === $events_deleted_count) {
         \WP_CLI::success(sprintf(__('Deleted one event: %d', 'automattic-cron-control'), $events_deleted[0]['ID']));
     } else {
         if ($events_deleted_count === $total_to_delete) {
             \WP_CLI::success(sprintf(__('Deleted %s events', 'automattic-cron-control'), number_format_i18n($events_deleted_count)));
         } else {
             \WP_CLI::warning(sprintf(__('Expected to delete %1$s events, but could only delete %2$s events. It\'s likely that some events were executed while this command ran.', 'automattic-cron-control'), number_format_i18n($total_to_delete), number_format_i18n($events_deleted_count)));
         }
         // Limit just to failed deletes when many events are removed
         if (count($events_deleted) > $assoc_args['limit']) {
             $events_deleted_unfiltered = $events_deleted;
             $events_deleted = array_filter($events_deleted, function ($event) {
                 if ('no' === $event['deleted']) {
                     return $event;
                 } else {
                     return false;
                 }
             });
             if (count($events_deleted) > 0) {
                 \WP_CLI::line("\n" . __('Events that couldn\'t be deleted:', 'automattic-cron-control'));
             }
         } else {
             \WP_CLI::line("\n" . __('Events deleted:', 'automattic-cron-control'));
         }
         // Don't display a table if there's nothing to display
         if (count($events_deleted) > 0) {
             \WP_CLI\Utils\format_items('table', $events_deleted, array('ID', 'deleted'));
         }
     }
     return;
 }
 /**
  * Display errors found by the given scanner
  * @param BaseScanner $scanner the scanner whose errors to display
  * @param string $format 'table', 'JSON', or 'CSV'
  */
 protected static function display_errors($scanner, $format)
 {
     $data = array();
     foreach ($scanner->get_error_levels() as $level) {
         $errors = $scanner->get_errors(array($level));
         foreach ($errors as $error) {
             $lines = array();
             // Not all errors have lines -- assign a null line if we lack lines entirely
             $lines = isset($error['lines']) ? $error['lines'] : array('');
             // In JSON output, group the lines together
             if ('json' == $format) {
                 $data[] = array('level' => $error['level'], 'description' => $error['description'], 'lines' => $lines, 'file' => $error['file']);
             } else {
                 // In other output, each line gets its own entry
                 foreach ($lines as $line) {
                     $data[] = array('level' => $error['level'], 'description' => $error['description'], 'lines' => $line, 'file' => $error['file']);
                 }
             }
         }
     }
     WP_CLI\Utils\format_items($format, $data, array('level', 'description', 'lines', 'file'));
 }
 /**
  * Create an AWS IAM user for S3 Uploads to user
  *
  * @subcommand create-iam-user
  * @synopsis --admin-key=<key> --admin-secret=<secret> [--username=<username>] [--format=<format>]
  */
 public function create_iam_user($args, $args_assoc)
 {
     $args_assoc = wp_parse_args($args_assoc, array('format' => 'table'));
     if (empty($args_assoc['username'])) {
         $username = '******' . sanitize_title(home_url());
     } else {
         $username = $args_assoc['username'];
     }
     try {
         $iam = Aws\Common\Aws::factory(array('key' => $args_assoc['admin-key'], 'secret' => $args_assoc['admin-secret']))->get('iam');
         $iam->createUser(array('UserName' => $username));
         $credentials = $iam->createAccessKey(array('UserName' => $username));
         $credentials = $credentials['AccessKey'];
         $iam->putUserPolicy(array('UserName' => $username, 'PolicyName' => $username . '-policy', 'PolicyDocument' => $this->get_iam_policy()));
     } catch (Exception $e) {
         WP_CLI::error($e->getMessage());
     }
     WP_CLI\Utils\format_items($args_assoc['format'], array((object) $credentials), array('AccessKeyId', 'SecretAccessKey'));
 }
 /**
  * Update installed languages.
  *
  * Updates installed languages for core, plugins and themes.
  *
  * [--dry-run]
  * : Preview which translations would be updated.
  *
  * ## EXAMPLES
  *
  *     $ wp core language update
  *     Updating 'Japanese' translation for Akismet 3.1.11...
  *     Downloading translation from https://downloads.wordpress.org/translation/plugin/akismet/3.1.11/ja.zip...
  *     Translation updated successfully.
  *     Updating 'Japanese' translation for Twenty Fifteen 1.5...
  *     Downloading translation from https://downloads.wordpress.org/translation/theme/twentyfifteen/1.5/ja.zip...
  *     Translation updated successfully.
  *     Success: Updated 2/2 translations.
  *
  * @subcommand update
  */
 public function update($args, $assoc_args)
 {
     $updates = $this->get_translation_updates();
     if (empty($updates)) {
         \WP_CLI::success('Translations are up to date.');
         return;
     }
     // Gets a list of all languages.
     $all_languages = $this->get_all_languages();
     // Formats the updates list.
     foreach ($updates as $update) {
         if ('plugin' == $update->type) {
             $plugins = get_plugins('/' . $update->slug);
             $plugin_data = array_shift($plugins);
             $name = $plugin_data['Name'];
         } elseif ('theme' == $update->type) {
             $theme_data = wp_get_theme($update->slug);
             $name = $theme_data['Name'];
         } else {
             // Core
             $name = 'WordPress';
         }
         // Gets the translation data.
         $translation = wp_list_filter($all_languages, array('language' => $update->language));
         $translation = (object) reset($translation);
         $update->Type = ucfirst($update->type);
         $update->Name = $name;
         $update->Version = $update->version;
         $update->Language = $translation->english_name;
     }
     // Only preview which translations would be updated.
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'dry-run')) {
         \WP_CLI::line(sprintf('Available %d translations updates:', count($updates)));
         \WP_CLI\Utils\format_items('table', $updates, array('Type', 'Name', 'Version', 'Language'));
         return;
     }
     $upgrader = 'WP_CLI\\LanguagePackUpgrader';
     $results = array();
     // Update translations.
     foreach ($updates as $update) {
         \WP_CLI::line("Updating '{$update->Language}' translation for {$update->Name} {$update->Version}...");
         $result = Utils\get_upgrader($upgrader)->upgrade($update);
         $results[] = $result;
     }
     $num_to_update = count($updates);
     $num_updated = count(array_filter($results));
     $line = "Updated {$num_updated}/{$num_to_update} translations.";
     if ($num_to_update == $num_updated) {
         \WP_CLI::success($line);
     } else {
         if ($num_updated > 0) {
             \WP_CLI::warning($line);
         } else {
             \WP_CLI::error($line);
         }
     }
 }
Exemple #20
0
 /**
  * Print current rewrite rules.
  *
  * ## OPTIONS
  *
  * [--match=<url>]
  * : Show rewrite rules matching a particular URL.
  *
  * [--source=<source>]
  * : Show rewrite rules from a particular source.
  *
  * [--fields=<fields>]
  * : Limit the output to specific fields. Defaults to match,query,source.
  *
  * [--format=<format>]
  * : Accepted values: table, csv, json, count. Default: table
  *
  * ## EXAMPLES
  *
  *     wp rewrite list --format=csv
  *
  * @subcommand list
  */
 public function list_($args, $assoc_args)
 {
     global $wp_rewrite;
     $rules = get_option('rewrite_rules');
     if (!$rules) {
         $rules = array();
         WP_CLI::warning('No rewrite rules.');
     }
     $defaults = array('source' => '', 'match' => '', 'format' => 'table', 'fields' => 'match,query,source');
     $assoc_args = array_merge($defaults, $assoc_args);
     $rewrite_rules_by_source = array();
     $rewrite_rules_by_source['post'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->permalink_structure, EP_PERMALINK);
     $rewrite_rules_by_source['date'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->get_date_permastruct(), EP_DATE);
     $rewrite_rules_by_source['root'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->root . '/', EP_ROOT);
     $rewrite_rules_by_source['comments'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->root . $wp_rewrite->comments_base, EP_COMMENTS, true, true, true, false);
     $rewrite_rules_by_source['search'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->get_search_permastruct(), EP_SEARCH);
     $rewrite_rules_by_source['author'] = $wp_rewrite->generate_rewrite_rules($wp_rewrite->get_author_permastruct(), EP_AUTHORS);
     $rewrite_rules_by_source['page'] = $wp_rewrite->page_rewrite_rules();
     // Extra permastructs including tags, categories, etc.
     foreach ($wp_rewrite->extra_permastructs as $permastructname => $permastruct) {
         if (is_array($permastruct)) {
             $rewrite_rules_by_source[$permastructname] = $wp_rewrite->generate_rewrite_rules($permastruct['struct'], $permastruct['ep_mask'], $permastruct['paged'], $permastruct['feed'], $permastruct['forcomments'], $permastruct['walk_dirs'], $permastruct['endpoints']);
         } else {
             $rewrite_rules_by_source[$permastructname] = $wp_rewrite->generate_rewrite_rules($permastruct, EP_NONE);
         }
     }
     // Apply the filters used in core just in case
     foreach ($rewrite_rules_by_source as $source => $source_rules) {
         $rewrite_rules_by_source[$source] = apply_filters($source . '_rewrite_rules', $source_rules);
         if ('post_tag' == $source) {
             $rewrite_rules_by_source[$source] = apply_filters('tag_rewrite_rules', $source_rules);
         }
     }
     $rule_list = array();
     foreach ($rules as $match => $query) {
         if (!empty($assoc_args['match']) && !preg_match("!^{$match}!", trim($assoc_args['match'], '/'))) {
             continue;
         }
         $source = 'other';
         foreach ($rewrite_rules_by_source as $rules_source => $source_rules) {
             if (array_key_exists($match, $source_rules)) {
                 $source = $rules_source;
             }
         }
         if (!empty($assoc_args['source']) && $source != $assoc_args['source']) {
             continue;
         }
         $rule_list[] = compact('match', 'query', 'source');
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $rule_list, explode(',', $assoc_args['fields']));
 }
 /**
  * Output items in a table, JSON, CSV, ids, or the total count
  *
  * @param string        $format     Format to use: 'table', 'json', 'csv', 'ids', 'count'
  * @param array         $items      Data to output
  * @param array|string  $fields     Named fields for each item of data. Can be array or comma-separated list
  */
 public function format_items($format, $items, $fields)
 {
     \WP_CLI\Utils\format_items($format, $items, $fields);
 }
Exemple #22
0
 /**
  * Get a plugin information specific plugin.
  *
  * ## OPTIONS
  *
  * <slug>
  * : The slug of the plugin.
  *
  * ## EXAMPLES
  *
  *    wp plugins-api info wp-total-hacks
  *
  * @subcommand info
  */
 public function info($args, $assoc_args)
 {
     $result = Plugins_API::info($args, $format);
     if (is_wp_error($result)) {
         WP_CLI::error($result->get_error_message());
     } else {
         WP_CLI\Utils\format_items($format, $result, array('Field', 'Value'));
     }
 }
 /**
  * Create an AWS IAM user for S3 Uploads to user
  *
  * @subcommand create-iam-user
  * @synopsis --admin-key=<key> --admin-secret=<secret> [--username=<username>]
  */
 public function create_iam_user($args, $args_assoc)
 {
     require_once dirname(__FILE__) . '/aws-sdk/aws-autoloader.php';
     if (empty($args_assoc['username'])) {
         $username = '******' . sanitize_title(home_url());
     } else {
         $username = $args_assoc['username'];
     }
     try {
         $iam = Aws\Common\Aws::factory(array('key' => $args_assoc['admin-key'], 'secret' => $args_assoc['admin-secret']))->get('iam');
         $iam->createUser(array('UserName' => $username));
         $credentials = $iam->createAccessKey(array('UserName' => $username));
         $credentials = $credentials['AccessKey'];
         $iam->putUserPolicy(array('UserName' => $username, 'PolicyName' => $username . '-policy', 'PolicyDocument' => $this->get_iam_policy()));
     } catch (Exception $e) {
         WP_CLI::error($e->getMessage());
     }
     WP_CLI::success(sprintf('Created new IAM user %s. The Access Credentials are displayed below', $username));
     WP_CLI\Utils\format_items('table', array((object) $credentials), array('AccessKeyId', 'SecretAccessKey'));
 }
 /**
  * Restore media attachments with WP CLI.
  *
  * ### Config
  *
  * Example of `~/.wp-cli/config.yml`:
  *
  *     media:
  *     	restore:
  *       generate: false
  *       uploads_url: http://www.bedrock.com/app/uploads/
  *
  * ### Options
  *
  * #### `[--generate=false]`
  * Set this optional parameter if you want to (re)generate all the different image sizes. Defaults to not generating thumbnails.
  *
  * #### `[--uploads-url]`
  * The URL to the uploads directory, not including any date based folder structure.
  *
  * ### Examples
  *
  *     wp media restore --uploads_url=http://www.bedrock.com/app/uploads/
  *
  * @param array $args
  * @param array $assoc_args
  */
 public function __invoke(array $args = [], array $assoc_args = [])
 {
     require_once ABSPATH . 'wp-admin/includes/media.php';
     require_once ABSPATH . 'wp-admin/includes/file.php';
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Merge default arguments.
     $assoc_args = array_merge($this->default_assoc_args, $assoc_args);
     // Get generate thumbnails value from WP CLI config or cmd argument.
     $generate = $assoc_args['generate'] === false ? $this->get_config_value('generate') : $assoc_args['generate'];
     $generate = is_string($generate) ? $generate === 'true' : (bool) $generate;
     // Get url base value from WP CLI config or cmd argument.
     $url_base = empty($assoc_args['uploads-url']) ? $this->get_config_value('uploads_url') : $assoc_args['uploads-url'];
     // Don't continue without a url.
     if (empty($url_base)) {
         WP_CLI::error('Missing url');
     }
     $warnings = [];
     $attachments = $this->get_attachments();
     $content_dir = CONTENT_DIR;
     $url_base = trailingslashit($url_base);
     $dir = wp_upload_dir();
     $base_dir = trailingslashit($dir['basedir']);
     $results = ['attachments' => count($attachments), 'exists' => 0, 'downloaded' => 0, 'failed' => 0, 'generated' => 0];
     // Output information about what the CLI command is doing.
     WP_CLI::line(sprintf('Downloading %d attachments%s', $results['attachments'], $generate ? ' and generating thumbnails.' : '.'));
     // Create a progress bar.
     $progress = new \cli\progress\Bar('Progress', $results['attachments']);
     try {
         foreach ($attachments as $id) {
             $progress->tick();
             $attachment = get_post($id);
             $attached_file = get_post_meta($id, '_wp_attached_file', true);
             if (!empty($attached_file)) {
                 $guid = $attachment->guid;
                 $scheme = parse_url($url_base, PHP_URL_SCHEME);
                 $domain = $scheme . '://' . parse_url($url_base, PHP_URL_HOST);
                 $remote_url = $domain . parse_url($guid, PHP_URL_PATH);
                 $response = wp_remote_head($remote_url);
                 if (is_wp_error($response)) {
                     $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP error "%s"', $id, $response->get_error_message());
                 } else {
                     if (200 != wp_remote_retrieve_response_code($response)) {
                         $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP response code %d', $id, wp_remote_retrieve_response_code($response));
                         continue;
                     }
                 }
                 if (strpos($attached_file, $domain . '/uploads') !== false) {
                     $attached_file = ltrim(str_replace($domain . '/uploads', '', $attached_file), '/');
                 } else {
                     $attached_file = ltrim(str_replace($url_base, '', $attached_file), '/');
                 }
                 $local_path = str_replace('/' . $content_dir . '/uploads/', '', $base_dir) . $attached_file;
                 update_post_meta($id, '_wp_attached_file', $attached_file);
             } else {
                 $remote_url = $url_base . $attached_file;
                 $local_path = $base_dir . $attached_file;
             }
             // Check if the file already exists
             if (file_exists($local_path)) {
                 $results['exists']++;
                 continue;
             }
             // Create directory if it don't exists.
             wp_mkdir_p(dirname($local_path));
             // Download attachment.
             $response = wp_safe_remote_get($remote_url, ['timeout' => 300, 'stream' => true, 'filename' => $local_path]);
             // If'ts a error, add a warning and a failed file.
             if (is_wp_error($response)) {
                 if (file_exists($local_path)) {
                     unlink($local_path);
                 }
                 $warnings[] = sprintf('Could not download %s, got error: %s', $remote_url, $response->get_error_message());
                 $results['failed']++;
                 continue;
             } else {
                 if (200 != wp_remote_retrieve_response_code($response)) {
                     $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP response code %d', $id, wp_remote_retrieve_response_code($response));
                     continue;
                 }
             }
             // Generate thumbnails if enabled and the attachment is a image.
             if ($generate && $attachment && 'attachment' === $attachment->post_type && strpos($attachment->post_mime_type, 'image/') !== false) {
                 @set_time_limit(900);
                 $metadata = wp_generate_attachment_metadata($id, $local_path);
                 update_post_meta($id, '_wp_attachment_metadata', $metadata);
                 if (is_wp_error($metadata)) {
                     $warnings[] = sprintf('Error generating image thumbnails for attachment ID %d: %s', $id, $metadata->get_error_message());
                 } else {
                     if (empty($metadata)) {
                         $warnings[] = sprintf('Unknown error generating image thumbnails for attachment ID %d', $id);
                     } else {
                         $results['generated']++;
                     }
                 }
             }
             $results['downloaded']++;
         }
     } catch (Exception $e) {
         WP_CLI::error($e->getMessage());
     }
     $progress->finish();
     foreach ($warnings as $warning) {
         WP_CLI::warning($warning);
     }
     $lines = [];
     foreach ($results as $name => $count) {
         $lines[] = (object) ['Item' => $name, 'Count' => $count];
     }
     \WP_CLI\Utils\format_items('table', $lines, ['Item', 'Count']);
 }
Exemple #25
0
 /**
  * Display a set of packages
  *
  * @param array
  * @param array
  */
 private function show_packages($packages, $assoc_args)
 {
     $defaults = array('fields' => implode(',', $this->fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $list = array();
     foreach ($packages as $package) {
         $name = $package->getName();
         if (isset($list[$name])) {
             $list[$name]['version'][] = $package->getPrettyVersion();
         } else {
             $package_output = array();
             $package_output['name'] = $package->getName();
             $package_output['description'] = $package->getDescription();
             $package_output['authors'] = implode(', ', array_column((array) $package->getAuthors(), 'name'));
             $package_output['version'] = array($package->getPrettyVersion());
             $list[$package_output['name']] = $package_output;
         }
     }
     $list = array_map(function ($package) {
         $package['version'] = implode(', ', $package['version']);
         return $package;
     }, $list);
     ksort($list);
     if ('ids' === $assoc_args['format']) {
         $list = array_keys($list);
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $list, $assoc_args['fields']);
 }
Exemple #26
0
 /**
  * Display a set of packages
  *
  * @param array
  * @param array
  */
 private function show_packages($packages, $assoc_args)
 {
     $defaults = array('fields' => implode(',', $this->fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $list = array();
     foreach ($packages as $package) {
         $package_output = new stdClass();
         $package_output->name = $package->getName();
         $package_output->description = $package->getDescription();
         $package_output->authors = implode(',', array_column((array) $package->getAuthors(), 'name'));
         $package_output->version = $package->getPrettyVersion();
         $list[$package_output->name] = $package_output;
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $list, $assoc_args['fields']);
 }
Exemple #27
0
 /**
  * Display a set of packages
  *
  * @param string $context
  * @param array
  * @param array
  */
 private function show_packages($context, $packages, $assoc_args)
 {
     if ('list' === $context) {
         $default_fields = array('name', 'authors', 'version', 'update', 'update_version');
     } else {
         if ('browse' === $context) {
             $default_fields = array('name', 'description', 'authors', 'version');
         }
     }
     $defaults = array('fields' => implode(',', $default_fields), 'format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $list = array();
     foreach ($packages as $package) {
         $name = $package->getName();
         if (isset($list[$name])) {
             $list[$name]['version'][] = $package->getPrettyVersion();
         } else {
             $package_output = array();
             $package_output['name'] = $package->getName();
             $package_output['description'] = $package->getDescription();
             $package_output['authors'] = implode(', ', array_column((array) $package->getAuthors(), 'name'));
             $package_output['version'] = array($package->getPrettyVersion());
             $update = 'none';
             $update_version = '';
             if ('list' === $context) {
                 $latest = $this->find_latest_package($package, $this->get_composer(), null);
                 if ($latest && $latest->getFullPrettyVersion() !== $package->getFullPrettyVersion()) {
                     $update = 'available';
                     $update_version = $latest->getPrettyVersion();
                 }
             }
             $package_output['update'] = $update;
             $package_output['update_version'] = $update_version;
             $list[$package_output['name']] = $package_output;
         }
     }
     $list = array_map(function ($package) {
         $package['version'] = implode(', ', $package['version']);
         return $package;
     }, $list);
     ksort($list);
     if ('ids' === $assoc_args['format']) {
         $list = array_keys($list);
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $list, $assoc_args['fields']);
 }
 /**
  * Updates the active translation of core, plugins, and themes.
  *
  * [--dry-run]
  * : Preview which translations would be updated.
  *
  * @subcommand update
  */
 public function update($args, $assoc_args)
 {
     // Ignore updates for the default locale.
     if ('en_US' == get_locale()) {
         \WP_CLI::success("Translations updates are not needed for the 'English (US)' locale.");
         return;
     }
     $this->wp_clean_update_cache();
     // Clear existing update caches.
     wp_version_check();
     // Check for Core translation updates.
     wp_update_themes();
     // Check for Theme translation updates.
     wp_update_plugins();
     // Check for Plugin translation updates.
     $updates = wp_get_translation_updates();
     // Retrieves a list of all translations updates available.
     if (empty($updates)) {
         \WP_CLI::success('Translations are up to date.');
         return;
     }
     // Gets a list of all languages.
     $all_languages = $this->get_all_languages();
     // Formats the updates list.
     foreach ($updates as $update) {
         if ('plugin' == $update->type) {
             $plugin_data = array_shift(get_plugins('/' . $update->slug));
             $name = $plugin_data['Name'];
         } elseif ('theme' == $update->type) {
             $theme_data = wp_get_theme($update->slug);
             $name = $theme_data['Name'];
         } else {
             // Core
             $name = 'WordPress';
         }
         // Gets the translation data.
         $translation = (object) reset(wp_list_filter($all_languages, array('language' => $update->language)));
         $update->Type = ucfirst($update->type);
         $update->Name = $name;
         $update->Version = $update->version;
         $update->Language = $translation->english_name;
     }
     // Only preview which translations would be updated.
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'dry-run')) {
         \WP_CLI::line(sprintf('Available %d translations updates:', count($updates)));
         \WP_CLI\Utils\format_items('table', $updates, array('Type', 'Name', 'Version', 'Language'));
         return;
     }
     require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
     $upgrader = new \Language_Pack_Upgrader(new \Automatic_Upgrader_Skin());
     $results = array();
     // Update translations.
     foreach ($updates as $update) {
         \WP_CLI::line("Updating '{$update->Language}' translation for {$update->Name} {$update->Version}...");
         \WP_CLI::line("Downloading translation from {$update->package}...");
         $result = $upgrader->upgrade($update);
         if ($result) {
             \WP_CLI::line('Translation updated successfully.');
         } else {
             \WP_CLI::line('Translation update failed.');
         }
         $results[] = $result;
     }
     $num_to_update = count($updates);
     $num_updated = count(array_filter($results));
     $line = "Updated {$num_updated}/{$num_to_update} translations.";
     if ($num_to_update == $num_updated) {
         \WP_CLI::success($line);
     } else {
         if ($num_updated > 0) {
             \WP_CLI::warning($line);
         } else {
             \WP_CLI::error($line);
         }
     }
 }
 protected function update_many($args, $assoc_args)
 {
     call_user_func($this->upgrade_refresh);
     if (!empty($assoc_args['format']) && in_array($assoc_args['format'], array('json', 'csv'))) {
         $logger = new \WP_CLI\Loggers\Quiet();
         \WP_CLI::set_logger($logger);
     }
     if (!\WP_CLI\Utils\get_flag_value($assoc_args, 'all') && empty($args)) {
         \WP_CLI::error("Please specify one or more {$this->item_type}s, or use --all.");
     }
     $items = $this->get_item_list();
     if (!\WP_CLI\Utils\get_flag_value($assoc_args, 'all')) {
         $items = $this->filter_item_list($items, $args);
     }
     $items_to_update = wp_list_filter($items, array('update' => true));
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'dry-run')) {
         if (empty($items_to_update)) {
             \WP_CLI::line("No {$this->item_type} updates available.");
             return;
         }
         if (!empty($assoc_args['format']) && in_array($assoc_args['format'], array('json', 'csv'))) {
             \WP_CLI\Utils\format_items($assoc_args['format'], $items_to_update, array('name', 'status', 'version', 'update_version'));
         } else {
             if (!empty($assoc_args['format']) && 'summary' === $assoc_args['format']) {
                 \WP_CLI::line("Available {$this->item_type} updates:");
                 foreach ($items_to_update as $item_to_update => $info) {
                     \WP_CLI::log("{$info['title']} update from version {$info['version']} to version {$info['update_version']}");
                 }
             } else {
                 \WP_CLI::line("Available {$this->item_type} updates:");
                 \WP_CLI\Utils\format_items('table', $items_to_update, array('name', 'status', 'version', 'update_version'));
             }
         }
         return;
     }
     $result = array();
     // Only attempt to update if there is something to update
     if (!empty($items_to_update)) {
         $cache_manager = \WP_CLI::get_http_cache_manager();
         foreach ($items_to_update as $item) {
             $cache_manager->whitelist_package($item['update_package'], $this->item_type, $item['name'], $item['update_version']);
         }
         $upgrader = $this->get_upgrader($assoc_args);
         $result = $upgrader->bulk_upgrade(wp_list_pluck($items_to_update, 'update_id'));
     }
     // Let the user know the results.
     $num_to_update = count($items_to_update);
     $num_updated = count(array_filter($result));
     $line = "Updated {$num_updated}/{$num_to_update} {$this->item_type}s.";
     if ($num_to_update == $num_updated) {
         \WP_CLI::success($line);
     } else {
         if ($num_updated > 0) {
             \WP_CLI::warning($line);
         } else {
             \WP_CLI::error($line);
         }
     }
     if ($num_to_update > 0) {
         if (!empty($assoc_args['format']) && 'summary' === $assoc_args['format']) {
             foreach ($items_to_update as $item_to_update => $info) {
                 $message = $result[$info['update_id']] !== null ? 'updated successfully' : 'did not update';
                 \WP_CLI::log("{$info['title']} {$message} from version {$info['version']} to version {$info['update_version']}");
             }
         } else {
             $status = array();
             foreach ($items_to_update as $item_to_update => $info) {
                 $status[$item_to_update] = array('name' => $info['name'], 'old_version' => $info['version'], 'new_version' => $info['update_version'], 'status' => $result[$info['update_id']] !== null ? 'Updated' : 'Error');
             }
             $format = 'table';
             if (!empty($assoc_args['format']) && in_array($assoc_args['format'], array('json', 'csv'))) {
                 $format = $assoc_args['format'];
             }
             \WP_CLI\Utils\format_items($format, $status, array('name', 'old_version', 'new_version', 'status'));
         }
     }
 }
 /**
  * List the exclude rules for backups
  * 
  * @subcommand list-excludes
  * @synopsis --site-id=<site-id> [--format=<format>]
  */
 public function list_excludes($args, $assoc_args)
 {
     $site_id = $assoc_args['site-id'];
     $this->set_account();
     unset($assoc_args['site-id']);
     $defaults = array('format' => 'table');
     $assoc_args = array_merge($defaults, $assoc_args);
     $args = array('endpoint' => '/site/' . $site_id . '/backup/exclude', 'method' => 'GET');
     $response = $this->api_request($args);
     if (is_wp_error($response)) {
         WP_CLI::error($response->get_error_message());
     }
     $rules = array();
     foreach ($response as $rule) {
         $rules[] = (object) array('Rule' => $rule);
     }
     WP_CLI\Utils\format_items($assoc_args['format'], $rules, array('Rule'));
 }