/** * Calls back to ProudCity API to get initial config settings * * ## OPTIONS * * ## EXAMPLES * * wp proudpack phonehome * * @synopsis */ function phonehome($args, $assoc_args) { //list( $name ) = $args; $request = wp_remote_get(PROUD_URL . '/sites/' . PROUD_ID . '/launched'); $response = json_decode(wp_remote_retrieve_body($request)); // Set options update_option('blogname', $response->location->city); update_option('lat', $response->location->lat); update_option('lng', $response->location->lng); update_option('city', $response->location->city); update_option('state', $response->location->stateFull); // Set theme settings $mods = get_option('theme_mods_wp-proud-theme', array()); if (!empty($response->settings->colors->main)) { $mods['color_main'] = $response->settings->colors->main; } if (!empty($response->settings->colors->secondary)) { $mods['color_secondary'] = $response->settings->colors->secondary; } if (!empty($response->settings->colors->highlight)) { $mods['color_highlight'] = $response->settings->colors->highlight; } update_option('theme_mods_wp-proud-theme', $mods); // Print a success message WP_CLI::success(print_r($response, 1)); WP_CLI::success(PROUD_URL . '/sites/' . PROUD_ID . '/launched' . $response->color->highlight . print_r(get_option('theme_mods_wp-proud-theme', array()), 1)); }
/** * Reset the post_date field on your posts. * A sadly necessary step after you change your timezone in WordPress * * @synopsis --post_type=<post-type> */ public function __invoke($args, $assoc_args) { global $wpdb; $query_args = array('post_type' => $assoc_args['post_type'], 'posts_per_page' => -1, 'post_status' => 'publish'); $query = new WP_Query($query_args); if (empty($query->posts)) { WP_CLI::error("No posts found"); } WP_CLI::line(sprintf("Updating post_date on %d posts.", count($query->posts))); foreach ($query->posts as $key => $post) { if (empty($post->post_date_gmt) || "0000-00-00 00:00:00" == $post->post_date_gmt) { WP_CLI::line(sprintf("Error: Post %d is missing a publish date.", $post->ID)); continue; } $original = $post->post_date; $new = get_date_from_gmt($post->post_date_gmt); if ($new == $original) { WP_CLI::line(sprintf("No Change: Post %d has the correct post_date of %s", $post->ID, $original)); continue; } $wpdb->update($wpdb->posts, array('post_date' => $new), array('ID' => $post->ID)); clean_post_cache($post->ID); WP_CLI::line(sprintf("Updated: Post %d changed from %s to %s", $post->ID, $original, $new)); if ($key && $key % 10 == 0) { sleep(1); } } WP_CLI::success("Posts were updated with the correct post_date."); }
/** * Recheck all comments in the Pending queue. * * ## EXAMPLES * * wp akismet recheck_queue * * @alias recheck-queue */ public function recheck_queue() { $batch_size = 100; $start = 0; $total_counts = array(); do { $result_counts = Akismet_Admin::recheck_queue_portion($start, $batch_size); if ($result_counts['processed'] > 0) { foreach ($result_counts as $key => $count) { if (!isset($total_counts[$key])) { $total_counts[$key] = $count; } else { $total_counts[$key] += $count; } } $start += $batch_size; $start -= $result_counts['spam']; // These comments will have been removed from the queue. } } while ($result_counts['processed'] > 0); WP_CLI::line(sprintf(_n("Processed %d comment.", "Processed %d comments.", $total_counts['processed'], 'akismet'), number_format($total_counts['processed']))); WP_CLI::line(sprintf(_n("%d comment moved to Spam.", "%d comments moved to Spam.", $total_counts['spam'], 'akismet'), number_format($total_counts['spam']))); if ($total_counts['error']) { WP_CLI::line(sprintf(_n("%d comment could not be checked.", "%d comments could not be checked.", $total_counts['error'], 'akismet'), number_format($total_counts['error']))); } }
/** * Perform an option action on a remote site */ private function perform_option_action($action, $args, $assoc_args) { $site_id = $assoc_args['site-id']; unset($assoc_args['site-id']); list($option_name) = $args; $this->set_account(); $method = strtoupper($action); if ('update' == $action) { $method = 'POST'; $api_args = array('option_value' => WP_CLI::read_value($args[1], $assoc_args)); } else { $api_args = array(); } $args = array('endpoint' => 'site/' . (int) $site_id . '/option/' . $option_name, 'method' => $method, 'body' => $api_args); $response = $this->api_request($args); if (is_wp_error($response)) { WP_CLI::error($response->get_error_message()); } switch ($action) { case 'get': if (empty($response)) { die(1); } WP_CLI::print_value($response, $assoc_args); break; case 'update': WP_CLI::success("Updated '{$option_name}' option."); break; case 'delete': WP_CLI::success("Deleted '{$option_name}' option."); break; } }
/** * Registers just a 'list' and 'run' command to the WC CLI * since we only want to enable certain actions on the system status * tools endpoints. */ public static function register_commands() { global $wp_rest_server; $request = new WP_REST_Request('OPTIONS', '/wc/v1/system_status/tools'); $response = $wp_rest_server->dispatch($request); $response_data = $response->get_data(); $parent = "wc tool"; $supported_commands = array('list', 'run'); foreach ($supported_commands as $command) { $synopsis = array(); if ('run' === $command) { $synopsis[] = array('name' => 'id', 'type' => 'positional', 'description' => __('The id for the resource.', 'woocommerce'), 'optional' => false); $method = 'update_item'; $route = '/wc/v1/system_status/tools/(?P<id>[\\w-]+)'; } elseif ('list' === $command) { $synopsis[] = array('name' => 'fields', 'type' => 'assoc', 'description' => __('Limit response to specific fields. Defaults to all fields.', 'woocommerce'), 'optional' => true); $synopsis[] = array('name' => 'field', 'type' => 'assoc', 'description' => __('Get the value of an individual field.', 'woocommerce'), 'optional' => true); $synopsis[] = array('name' => 'format', 'type' => 'assoc', 'description' => __('Render response in a particular format.', 'woocommerce'), 'optional' => true, 'default' => 'table', 'options' => array('table', 'json', 'csv', 'ids', 'yaml', 'count', 'headers', 'body', 'envelope')); $method = 'list_items'; $route = '/wc/v1/system_status/tools'; } $before_invoke = null; if (empty($command_args['when']) && WP_CLI::get_config('debug')) { $before_invoke = function () { if (!defined('SAVEQUERIES')) { define('SAVEQUERIES', true); } }; } $rest_command = new WC_CLI_REST_Command('system_status_tool', $route, $response_data['schema']); WP_CLI::add_command("{$parent} {$command}", array($rest_command, $method), array('synopsis' => $synopsis, 'when' => !empty($command_args['when']) ? $command_args['when'] : '', 'before_invoke' => $before_invoke)); } }
protected function __construct() { if (false !== get_transient('_my-wp-backup-activated')) { delete_transient('_my-wp-backup-activated'); wp_redirect(Admin::get_page_url('')); } self::$info = get_file_data(__FILE__, array('name' => 'Plugin Name', 'pluginUri' => 'Plugin URI', 'supportUri' => 'Support URI', 'version' => 'Version', 'description' => 'Description', 'author' => 'Author', 'authorUri' => 'Author URI', 'textDomain' => 'Text Domain', 'domainPath' => 'Domain Path', 'slug' => 'Slug', 'license' => 'License', 'licenseUri' => 'License URI')); Admin::get_instance(); $options = get_site_option('my-wp-backup-options', Admin::$options); self::$info['baseDir'] = plugin_dir_path(__FILE__); self::$info['baseDirUrl'] = plugin_dir_url(__FILE__); self::$info['backup_dir'] = trailingslashit(ABSPATH) . trailingslashit(ltrim($options['backup_dir'], '/')); self::$info['root_dir'] = trailingslashit(ABSPATH); if (defined('WP_CLI') && WP_CLI) { \WP_CLI::add_command('job', new Cli\Job()); \WP_CLI::add_command('backup', new Cli\Backup()); } add_action('wp_backup_run_job', array(Job::get_instance(), 'cron_run')); add_action('wp_backup_restore_backup', array(Backup::get_instance(), 'cron_run')); $version = get_site_option(self::KEY_VERSION); if (!$version || self::$info['version'] !== $version) { if ($this->update_options()) { update_site_option(self::KEY_VERSION, self::$info['version']); } } }
/** * Class constructor */ public function __construct() { $locate = $this->locate_plugin(); $this->locations = array('plugin' => $locate['plugin_basename'], 'dir' => $locate['dir_path'], 'url' => $locate['dir_url'], 'inc_dir' => $locate['dir_path'] . 'includes/', 'class_dir' => $locate['dir_path'] . 'classes/'); spl_autoload_register(array($this, 'autoload')); // Load helper functions require_once $this->locations['inc_dir'] . 'functions.php'; // Load DB helper interface/class $driver = '\\WP_Stream\\DB'; if (class_exists($driver)) { $this->db = new DB($this); } if (!$this->db) { wp_die(esc_html__('Stream: Could not load chosen DB driver.', 'stream'), esc_html__('Stream DB Error', 'stream')); } // Load languages add_action('plugins_loaded', array($this, 'i18n')); // Load logger class $this->log = apply_filters('wp_stream_log_handler', new Log($this)); // Load settings and connectors after widgets_init and before the default init priority add_action('init', array($this, 'init'), 9); // Add frontend indicator add_action('wp_head', array($this, 'frontend_indicator')); // Load admin area classes if (is_admin() || defined('WP_STREAM_DEV_DEBUG') && WP_STREAM_DEV_DEBUG) { $this->admin = new Admin($this); $this->install = new Install($this); } // Load WP-CLI command if (defined('WP_CLI') && WP_CLI) { \WP_CLI::add_command(self::WP_CLI_COMMAND, 'WP_Stream\\CLI'); } }
/** * Lists one-time logins * * ## EXAMPLES * * wp one-time-login list * * @subcommand list */ function _list($args, $assoc_args) { // Get all one-time logins $otl_posts = get_posts(array('posts_per_page' => -1, 'post_type' => 'onetimelogin', 'order' => ASC)); // Error if no logins found if (empty($otl_posts)) { WP_CLI::error(__('No one time logins found.', 'one-time-login')); } // Set table headers $headers = array(__('ID', 'one-time-login'), __('Password', 'one-time-login'), __('User ID', 'one-time-login'), __('Date Generated', 'one-time-login'), __('Status', 'one-time-login'), __('Date Used', 'one-time-login')); $data = array(); // loop through logins and format foreach ($otl_posts as $otl) { $id = $otl->ID; $password = $otl->post_title; $user_id = get_post_meta($otl->ID, 'otl_user', true); $generated = $otl->post_date; $status = '0' === get_post_meta($otl->ID, 'otl_times_used', true) ? __('Available', 'one-time-login') : __('Expired', 'one-time-login'); $used = get_post_meta($otl->ID, 'otl_datetime_used', true); $data[] = array($id, $password, $user_id, $generated, $status, $used); } // Output table $table = new \cli\Table(); $table->setHeaders($headers); $table->setRows($data); $table->display(); }
public function run() { if (!function_exists('get_plugins')) { require_once \WP_CLI::get_config('path') . '/wp-admin/includes/plugin.php'; } $all_plugins = get_plugins(); $update = get_plugin_updates(); $report = array(); foreach ($all_plugins as $plugin_path => $data) { $slug = $plugin_path; if (stripos($plugin_path, '/')) { $slug = substr($plugin_path, 0, stripos($plugin_path, '/')); } $vulnerable = $this->is_vulnerable($slug, $data['Version']); $needs_update = 0; $available = '-'; if (isset($update[$plugin_path])) { $needs_update = 1; $available = $update[$plugin_path]->update->new_version; } if (false === $vulnerable) { $vulnerable = "None"; } else { $vulnerable = sprintf('<a href="https://wpvulndb.com/plugins/%s" target="_blank" >more info</a>', $slug); } $report[$slug] = array('slug' => $slug, 'installed' => (string) $data['Version'], 'available' => (string) $available, 'needs_update' => (string) $needs_update, 'vulnerable' => $vulnerable); } $this->alerts = $report; }
/** * Initial player sync * * Retrieve all player and create/update when necessary. * * @since 1.0.0 * * @param bool $is_cli whether the call is coming via WP_CLI * * @return bool True on success or false */ public function handle_initial_sync($is_cli = false) { if (true === $is_cli) { WP_CLI::line(esc_html__('Starting Player Sync', 'brightcove')); } $players = $this->players_api->player_list(); $players = $this->sort_api_response($players); if (!is_array($players)) { return false; } if (true === $is_cli) { WP_CLI::line(esc_html__(sprintf('There are %d players to sync for this account. Please be patient.', sizeof($players)), 'brightcove')); } $player_ids_to_keep = array(); // for deleting outdated players /* process all players */ foreach ($players as $player) { $this->add_or_update_wp_player($player); $player_ids_to_keep[] = BC_Utility::sanitize_subscription_id($player['id']); } BC_Utility::remove_deleted_players($player_ids_to_keep); BC_Utility::store_hash('players', $players, $this->cms_api->account_id); if (true === $is_cli) { WP_CLI::line(esc_html__('Player Sync Complete', 'brightcove')); } return true; }
/** * Forces a full Varnish Purge of the entire site (provided * regex is supported). * * ## EXAMPLES * * wp varnish purge * * wp varnish purge http://example.com/wp-content/themes/twentyeleventy/style.css * * wp vanrish purge "/wp-content/themes/twentysixty/style.css" * * wp varnish purge http://example.com/wp-content/themes/ --wildcard * * wp varnish purge "/wp-content/themes/" --wildcard * */ function purge($args, $assoc_args) { $wp_version = get_bloginfo('version'); $cli_version = WP_CLI_VERSION; // Set the URL/path list($url) = $args; // If wildcard is set, or the URL argument is empty // then treat this as a full purge if (isset($assoc_args['wildcard']) || empty($url)) { $pregex = '/?vhp-regex'; $wild = ".*"; } else { $pregex = $wild = ''; } wp_create_nonce('vhp-flush-cli'); // Make sure the URL is a URL: if (!empty($url)) { // If the URL isn't a URL, make it a URL if (empty(esc_url($url))) { $url = $this->varnish_purge->the_home_url() . $url; } } else { $url = $this->varnish_purge->the_home_url(); } if (version_compare($wp_version, '4.6', '>=') && (version_compare($cli_version, '0.25.0', '<') || version_compare($cli_version, '0.25.0-alpha', 'eq'))) { WP_CLI::log(sprintf('This plugin does not work on WP 4.6 and up, unless WP-CLI is version 0.25.0 or greater. You\'re using WP-CLI %s and WordPress %s.', $cli_version, $wp_version)); WP_CLI::log('To flush your cache, please run the following command:'); WP_CLI::log(sprintf('$ curl -X PURGE "%s"', $url . $wild)); WP_CLI::error('Varnish Cache must be purged manually.'); } $this->varnish_purge->purgeUrl($url . $pregex); WP_CLI::success('The Varnish cache was purged.'); }
/** * Flush cache by hash, post id, url or all posts. * * ## OPTIONS * * [--all] * : Flush all posts. * * [--hash=<hash>] * : Flush by cache hash. * * [--post_id=<post_id>] * : Flush by post id * * [--url=<url>] * : Flush by url. * * @param array $args * @param array $assoc_args */ public function flush($args, $assoc_args) { // Flush all posts. if (isset($assoc_args['all'])) { if (cachetop_flush_all_posts()) { WP_CLI::success('Cache flushed'); } else { WP_CLI::error('Cached not flushed'); } } // Flush by hash. if (isset($assoc_args['hash'])) { if (cachetop_flush_hash($assoc_args['hash'])) { WP_CLI::success(sprintf('Cache flushed for hash: %s', $assoc_args['hash'])); } else { WP_CLI::error('Cached not flushed'); } } // Flush post by id. if (isset($assoc_args['post_id']) && is_numeric($assoc_args['post_id'])) { if (cachetop_flush_post($args[0])) { WP_CLI::success(sprintf('Cache flushed for post id: %s', $assoc_args['post_id'])); } else { WP_CLI::error('Cached not flushed'); } } // Flush by url. if (isset($assoc_args['url'])) { if (cachetop_flush_url($assoc_args['url'])) { WP_CLI::success(sprintf('Cache flushed for url: %s', $assoc_args['url'])); } else { WP_CLI::error('Cached not flushed'); } } }
/** * Sets up Developer Plugin * @subcommand install-plugins * @synopsis --type=<type> [--activate] */ function install_plugins($args, $assoc_args) { global $automattic_developer; // wp-cli doesn't fire admin_init since 0.11.2 if (!did_action('admin_init')) { $automattic_developer->admin_init(); } $type = $assoc_args['type']; $activate = isset($assoc_args['activate']) && $assoc_args['activate'] == "true"; $reco_plugins = $automattic_developer->recommended_plugins; $installed_plugins = array_keys(get_plugins()); $types = array_keys($automattic_developer->get_project_types()); if (in_array($type, $types)) { $automattic_developer->save_project_type($type); foreach ($reco_plugins as $slug => $plugin) { $path = $automattic_developer->get_path_for_recommended_plugin($slug); $activate_plugin = $activate && ('all' == $plugin['project_type'] || $type == $plugin['project_type']); // Download the plugin if we don't already have it if (!in_array($path, $installed_plugins)) { WP_CLI::run_command(explode(" ", "plugin install {$slug}")); } // Install the plugin if --activate and it's the right type if (is_plugin_inactive($path) && $activate_plugin) { if (NULL == activate_plugin($path)) { WP_CLI::success("Activated " . $plugin['name']); } } } } else { WP_CLI::error("Specify a valid type to install: <" . implode("|", $types) . ">"); } }
/** * Fixes issues with slow saving in wp-admin due to no audio/video media files * * Core Ticket: https://core.trac.wordpress.org/ticket/31071 * * eg.: `wp vip-go-one-time-fixers blank-media-fix --allow-root --url=beta.thesun.co.uk` * * @subcommand blank-media-fix */ public function blank_media_fix($args, $assoc_args) { if (!function_exists('wpcom_vip_download_image')) { WP_CLI::error('This script requires the wpcom_vip_download_image() function, https://vip.wordpress.com/functions/wpcom_vip_download_image/'); } $audio_file_url = 'https://cldup.com/xmre07YagX.mp3'; // 1sec.mp3 $video_file_url = 'https://cldup.com/KHsK5yZkvv.avi'; // 1sec.avi $args = array('post_type' => 'attachment', 'post_status' => 'inherit', 'meta_query' => array(array('key' => '_vip_blank_media_fix', 'value' => 'video'))); $video_query = new WP_Query($args); if (!$video_query->post_count) { WP_CLI::log('Video fix not found, applying...'); $video_file_id = $this->wpcom_vip_download_image($video_file_url, 0, 'VIP: Fix for slow post saving'); if (!is_wp_error($video_file_id)) { $args = array('ID' => $video_file_id, 'post_date' => '2000-01-01', 'post_date_gmt' => '2000-01-01', 'post_modified' => '2000-01-01', 'post_modified_gmt' => '2000-01-01'); $updated_video_file_id = wp_update_post($args, true); if (!is_wp_error($updated_video_file_id)) { WP_CLI::success('Video fix applied'); $video_meta = update_post_meta($updated_video_file_id, '_vip_blank_media_fix', 'video'); if (false === $video_meta) { WP_CLI::warning('Could not update video _vip_blank_media_fix meta'); } } else { // Video date was not updated WP_CLI::error($updated_video_file_id->get_error_message()); } } else { // Sideload failed WP_CLI::error($video_file_id->get_error_message()); } } else { WP_CLI::warning('Blank video fix already exists for this site'); } $args = array('post_type' => 'attachment', 'post_status' => 'inherit', 'meta_query' => array(array('key' => '_vip_blank_media_fix', 'value' => 'audio'))); $audio_query = new WP_Query($args); if (!$audio_query->post_count) { WP_CLI::log('Audio fix not found, applying...'); $audio_file_id = $this->wpcom_vip_download_image($audio_file_url, 0, 'VIP: Fix for slow post saving'); if (!is_wp_error($audio_file_id)) { $args = array('ID' => $audio_file_id, 'post_date' => '2000-01-01', 'post_date_gmt' => '2000-01-01', 'post_modified' => '2000-01-01', 'post_modified_gmt' => '2000-01-01'); $updated_audio_file_id = wp_update_post($args, true); if (!is_wp_error($updated_audio_file_id)) { WP_CLI::success('Audio fix applied'); $audio_meta = update_post_meta($updated_audio_file_id, '_vip_blank_media_fix', 'audio'); if (false === $audio_meta) { WP_CLI::warning('Could not update audio _vip_blank_media_fix meta'); } } else { // Audio date was not updated WP_CLI::error($updated_audio_file_id->get_error_message()); } } else { // Sideload failed WP_CLI::error($video_file_id->get_error_message()); } } else { WP_CLI::warning('Blank video fix already exists for this site'); } }
/** * Bulk import redirects from a CSV file matching the following structure: * * redirect_from_path,(redirect_to_post_id|redirect_to_path|redirect_to_url) * * @subcommand import-from-csv * @synopsis --csv=<path-to-csv> */ function import_from_csv($args, $assoc_args) { define('WP_IMPORTING', true); if (empty($assoc_args['csv']) || !file_exists($assoc_args['csv'])) { WP_CLI::error("Invalid 'csv' file"); } global $wpdb; if (($handle = fopen($assoc_args['csv'], "r")) !== FALSE) { while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) { $row++; $redirect_from = $data[0]; $redirect_to = $data[1]; WP_CLI::line("Adding (CSV) redirect for {$redirect_from} to {$redirect_to}"); WP_CLI::line("-- at {$row}"); WPCOM_Legacy_Redirector::insert_legacy_redirect($redirect_from, $redirect_to); if (0 == $row % 100) { if (function_exists('stop_the_insanity')) { stop_the_insanity(); } sleep(1); } } fclose($handle); } }
/** * Clear the product/shop transients cache. * * ## EXAMPLES * * wp wc tool clear_transients * * @since 2.5.0 */ public function clear_transients($args, $assoc_args) { wc_delete_product_transients(); wc_delete_shop_order_transients(); WC_Cache_Helper::get_transient_version('shipping', true); WP_CLI::success('Product transients and shop order transients were cleared.'); }
/** * Generate users * * @param array $args * @param array $assoc_args **/ public function users($args, $assoc_args) { global $blog_id; $defaults = array('count' => 100, 'role' => get_option('default_role')); extract(wp_parse_args($assoc_args, $defaults), EXTR_SKIP); if ('none' == $role) { $role = false; } elseif (is_null(get_role($role))) { WP_CLI::warning("invalid role."); exit; } $user_count = count_users(); $total = $user_count['total_users']; $limit = $count + $total; $notify = new \cli\progress\Bar('Generating users', $count); for ($i = $total; $i < $limit; $i++) { $login = sprintf('user_%d_%d', $blog_id, $i); $name = "User {$i}"; $user_id = wp_insert_user(array('user_login' => $login, 'user_pass' => $login, 'nickname' => $name, 'display_name' => $name, 'role' => $role)); if (false === $role) { delete_user_option($user_id, 'capabilities'); delete_user_option($user_id, 'user_level'); } $notify->tick(); } $notify->finish(); }
/** * Migrate meta values to taxonomy terms. Delete meta after import * * ## OPTIONS * * <meta-key> * : Meta key to convert * * <taxonomy-slug> * : Taxonomy to move values into * * [--<field>=<value>] * : One or more args to pass to WP_Query. * * ## EXAMPLES * * wp mtt migrate meta_key taxonomy_slug * wp mtt migrate meta_key taxonomy_slug --posts_per_page=200 --paged=2 * */ function migrate($args, $assoc_args) { list($meta_key, $taxonomy) = $args; if (!($taxonomy_object = get_taxonomy($taxonomy))) { WP_CLI::error(sprintf("The taxonomy '%s' doesn't exist", $taxonomy)); } $defaults = array('post_type' => $taxonomy_object->object_type, 'posts_per_page' => -1, 'post_status' => 'any'); $query_args = array_merge($defaults, $assoc_args); $query = new WP_Query($query_args); // summary WP_CLI::log(sprintf("---\nPer page: %d \nPage: %d \nTotal pages: %d\n---", $query_args['posts_per_page'], isset($query_args['paged']) ? $query_args['paged'] : 1, $query->max_num_pages)); while ($query->have_posts()) { $query->the_post(); $id = get_the_id(); // get meta $metas = get_post_meta($id, $meta_key); // create term if (!$metas) { WP_CLI::log(WP_CLI::colorize("%c[{$id}]%n No meta, skipped")); } else { if (!is_wp_error(wp_set_object_terms($id, $metas, $taxonomy, true))) { WP_CLI::log(WP_CLI::colorize("%g[{$id}]%n Migrated: " . implode(', ', $metas))); // clean meta delete_post_meta($id, $meta_key); } else { WP_CLI::log(WP_CLI::colorize("%r[{$id}]%n Error: Could not set terms for post")); } } } }
/** * Execute arbitrary PHP code. * * ## OPTIONS * * <php-code> * : The code to execute, as a string. * * [--skip-wordpress] * : Execute code without loading WordPress. * * @when before_wp_load * * ## EXAMPLES * * $ wp eval 'echo WP_CONTENT_DIR;' * /var/www/wordpress/wp-content * * $ wp eval 'echo rand();' --skip-wordpress * 479620423 */ public function __invoke($args, $assoc_args) { if (null === \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-wordpress')) { WP_CLI::get_runner()->load_wordpress(); } eval($args[0]); }
/** * Write a message to STDERR, prefixed with "Debug: ". * * @param string $message Message to write. */ public function debug($message) { if (\WP_CLI::get_runner()->config['debug']) { $time = round(microtime(true) - WP_CLI_START_MICROTIME, 3); $this->_line("{$message} ({$time}s)", 'Debug', '%B', STDERR); } }
/** * Launch PHP's built-in web server for this specific WordPress installation. * * Uses `php -S` to launch a web server serving the WordPress webroot. * <http://php.net/manual/en/features.commandline.webserver.php> * * ## OPTIONS * * [--host=<host>] * : The hostname to bind the server to. * --- * default: localhost * --- * * [--port=<port>] * : The port number to bind the server to. * --- * default: 8080 * --- * * [--docroot=<path>] * : The path to use as the document root. * * [--config=<file>] * : Configure the server with a specific .ini file. * * ## EXAMPLES * * # Make the instance available on any address (with port 8080) * $ wp server --host=0.0.0.0 * PHP 5.6.9 Development Server started at Tue May 24 01:27:11 2016 * Listening on http://0.0.0.0:8080 * Document root is / * Press Ctrl-C to quit. * * # Run on port 80 (for multisite) * $ sudo wp server --host=localhost.localdomain --port=80 * PHP 5.6.9 Development Server started at Tue May 24 01:30:06 2016 * Listening on http://localhost1.localdomain1:8080 * Document root is / * Press Ctrl-C to quit. * * # Configure the server with a specific .ini file * $ wp server --config=development.ini * PHP 7.0.9 Development Server started at Mon Aug 22 12:09:04 2016 * Listening on http://localhost:8080 * Document root is / * Press Ctrl-C to quit. * * @when before_wp_load */ function __invoke($_, $assoc_args) { $min_version = '5.4'; if (version_compare(PHP_VERSION, $min_version, '<')) { WP_CLI::error("The `wp server` command requires PHP {$min_version} or newer."); } $defaults = array('host' => 'localhost', 'port' => 8080, 'docroot' => false, 'config' => get_cfg_var('cfg_file_path')); $assoc_args = array_merge($defaults, $assoc_args); $docroot = $assoc_args['docroot']; if (!$docroot) { $config_path = WP_CLI::get_runner()->project_config_path; if (!$config_path) { $docroot = ABSPATH; } else { $docroot = dirname($config_path); } } $cmd = \WP_CLI\Utils\esc_cmd('%s -S %s -t %s -c %s %s', PHP_BINARY, $assoc_args['host'] . ':' . $assoc_args['port'], $docroot, $assoc_args['config'], \WP_CLI\Utils\extract_from_phar(WP_CLI_ROOT . '/php/router.php')); $descriptors = array(STDIN, STDOUT, STDERR); // https://bugs.php.net/bug.php?id=60181 $options = array(); if (\WP_CLI\Utils\is_windows()) { $options["bypass_shell"] = TRUE; } exit(proc_close(proc_open($cmd, $descriptors, $pipes, NULL, NULL, $options))); }
/** * Generate tab completion strings. */ function completions() { foreach (WP_CLI::get_root_command()->get_subcommands() as $name => $command) { $subcommands = $command->get_subcommands(); WP_CLI::line($name . ' ' . implode(' ', array_keys($subcommands))); } }
/** * Setup Elasticsearch. * * ## OPTIONS * * [--host=<url>] * : The name of the person to greet. * * [--port=<number>] * : Accepted values: csv, json. Default: csv * * ## EXAMPLES * * wp elasticsearch setup --host=example.com --port=9200 * * @subcommand setup */ function setup($args, $assoc_args) { $param = array(); $param['endpoint'] = preg_replace('/(^https:\\/\\/|^http:\\/\\/)/is', '', $assoc_args['host']); $param['port'] = $assoc_args['port']; $tries = 5; $sleep = 3; do { $response = wp_remote_get(esc_url($assoc_args['host']) . ':' . $assoc_args['port']); if (200 == wp_remote_retrieve_response_code($response)) { // Looks good! break; } else { WP_CLI::log("\nInvalid response from ES, sleeping {$sleep} seconds and trying again...\n"); sleep($sleep); } } while (--$tries); if (200 != wp_remote_retrieve_response_code($response)) { WP_CLI::error('Could not connect to Elasticsearch server.'); exit; } update_option('wpels_settings', $param); try { if (!\MegumiTeam\WooCommerceElasticsearch\Loader::get_instance()->data_sync()) { WP_CLI::error('Elasticsearch built index failed.'); } } catch (Exception $e) { WP_CLI::error($e->getMessage()); exit; } WP_CLI::success("Elasticsearch built index completed."); }
private static function maybe_load_man_page($args) { $man_file = \WP_CLI\Man\get_path($args); if (is_readable($man_file)) { exit(WP_CLI::launch("man {$man_file}")); } }
public function sync($args, $assoc_args) { $websites = MainWP_DB::Instance()->query(MainWP_DB::Instance()->getSQLWebsitesForCurrentUser()); WP_CLI::line('Syncing ' . MainWP_DB::num_rows($websites) . ' sites'); $warnings = 0; $errors = 0; while ($websites && ($website = @MainWP_DB::fetch_object($websites))) { WP_CLI::line(' -> ' . $website->name . ' (' . $website->url . ')'); try { if (MainWP_Sync::syncSite($website)) { WP_CLI::success(' Sync succeeded'); } else { WP_CLI::warning(' Sync failed'); $warnings++; } } catch (Exception $e) { WP_CLI::error(' Sync failed'); $errors++; } } @MainWP_DB::free_result($websites); if ($errors > 0) { WP_CLI::error('Sync completed with errors'); } else { if ($warnings > 0) { WP_CLI::warning('Sync completed with warnings'); } else { WP_CLI::success('Sync completed'); } } }
/** * Delete an option * * @synopsis <key> */ public function delete($args) { list($key) = $args; if (!delete_option($key)) { WP_CLI::error("Could not delete '{$key}' option. Does it exist?"); } }
public function init() { add_action('init', array($this, 'maybe_init_integrations')); if (class_exists('WP_CLI_Command')) { \WP_CLI::add_command('timber', 'Timber\\Integrations\\Timber_WP_CLI_Command'); } }
/** * Emit the message in specified format * * @params $format string optional - options are "raw","json" */ public static function emit($format = 'raw') { $messenger = self::instance(); switch ($format) { case 'pantheon': case 'json': $formatted = array(); foreach ($messenger->messages as $message) { $formatted[$message['name']] = $message; } \WP_CLI::print_value($formatted, array('format' => 'json')); break; case 'raw': case 'default': foreach ($messenger->messages as $message) { // colorize if ($message['score'] == 2) { $color = "%G"; } elseif ($message['score'] == 0) { $color = "%C"; } else { $color = "%R"; } // @todo might be a better way to do this echo \cli\Colors::colorize(sprintf(str_repeat('-', 80) . PHP_EOL . "%s: (%s) \n%s\nResult:%s %s\nRecommendation: %s\n\n" . PHP_EOL, strtoupper($message['label']), $message['description'], str_repeat('-', 80), $color, $message['result'] . '%n', $message['action'])); } break; } }
/** * * Assigns random terms to all posts in a taxonomy. * * By default all objects of the 'post' post type will be randomized, use the * --post_type flag to target pages or a custom post type. Use the --include * and --exclude flags to filter or ignore specific object IDs and the --before * and --after flags to specify a date range. Also, optionally pass --terms as * a list of terms you want to use for the randomization. If terms exist in the * target taxonomy, those terms will be used. If not, a string of 6 words * generated randomly will be used for the randomization. * * ## Options * * <taxonomy> * : The taxonomy that should get randomized * * ## Exmples * * wp randomize category * * @synopsis <taxonomy> [--include=<bar>] [--exclude=<foo>] [--post_type=<foo>] * [--before=<bar>] [--after=<date>] [--terms=<terms>] * **/ public function taxonomy($args, $assoc_args) { $taxonomy = $args[0]; $get_posts = $this->get_specified_posts($assoc_args); $message = $get_posts['message']; $posts = $get_posts['posts']; $args = $get_posts['args']; $preamble = "Will assign random {$taxonomy} terms"; print_r("{$preamble} {$message}.\n"); if (isset($assoc_args['terms'])) { $terms = explode(',', $assoc_args['terms']); \WP_CLI::log('Using terms ' . $assoc_args['terms']); } else { \WP_CLI::log('Gathering and processing random terms.'); $terms = $this->get_random_terms(); \WP_CLI::log('No term list given, using random terms.'); } foreach ($posts as $p) { $index = array_rand($terms); $term = $terms[$index]; \WP_CLI::log("Assigning {$term} to taxonomy {$taxonomy} for {$p->post_type} {$p->ID}"); if (!term_exists($term, $taxonomy)) { wp_insert_term($term, $taxonomy); } wp_set_object_terms($p->ID, $term, $taxonomy, $append = false); } }
protected function _url($args, $callback) { foreach ($args as $obj_id) { $object = $this->fetcher->get_check($obj_id); \WP_CLI::line($callback($object->{$this->obj_id_key})); } }