Warning message is written to STDERR.
Use instead of WP_CLI::debug() when script execution should be permitted
to continue.
# wp plugin activate skips activation when plugin is network active.
$status = $this->get_status( $plugin->file );
Network-active is the highest level of activation status
if ( 'active-network' === $status ) {
WP_CLI::warning( "Plugin '{$plugin->name}' is already network active." );
continue;
}
/** * Checks one or more comments against the Akismet API. * * ## OPTIONS * <comment_id>... * : The ID(s) of the comment(s) to check. * * [--noaction] * : Don't change the status of the comment. Just report what Akismet thinks it is. * * ## EXAMPLES * * wp akismet check 12345 * * @alias comment-check */ public function check($args, $assoc_args) { foreach ($args as $comment_id) { if (isset($assoc_args['noaction'])) { // Check the comment, but don't reclassify it. $api_response = Akismet::check_db_comment($comment_id, 'wp-cli'); } else { $api_response = Akismet::recheck_comment($comment_id, 'wp-cli'); } if ('true' === $api_response) { WP_CLI::line(sprintf(__("Comment #%d is spam.", 'akismet'), $comment_id)); } else { if ('false' === $api_response) { WP_CLI::line(sprintf(__("Comment #%d is not spam.", 'akismet'), $comment_id)); } else { if (false === $api_response) { WP_CLI::error(__("Failed to connect to Akismet.", 'akismet')); } else { if (is_wp_error($api_response)) { WP_CLI::warning(sprintf(__("Comment #%d could not be checked.", 'akismet'), $comment_id)); } } } } } }
/** * 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(); }
/** * Run wp_install. Assumes that wp-config.php is already in place. */ public function install($args, $assoc_args) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; if (is_blog_installed()) { WP_CLI::error('WordPress is already installed.'); } extract(wp_parse_args($assoc_args, array('site_url' => defined('WP_SITEURL') ? WP_SITEURL : '', 'site_title' => '', 'admin_name' => 'admin', 'admin_email' => '', 'admin_password' => '')), EXTR_SKIP); $missing = false; foreach (array('site_url', 'site_title', 'admin_email', 'admin_password') as $required_arg) { if (empty(${$required_arg})) { WP_CLI::warning("missing --{$required_arg} parameter"); $missing = true; } } if ($site_url) { WP_CLI::set_url($site_url); } if ($missing) { exit(1); } $public = true; $result = wp_install($site_title, $admin_name, $admin_email, $public, '', $admin_password); if (is_wp_error($result)) { WP_CLI::error('Installation failed (' . WP_CLI::errorToString($result) . ').'); } else { WP_CLI::success('WordPress installed successfully.'); } }
/** * Export the translation set * * ## OPTIONS * * <project> * : Project path * * <locale> * : Locale to export * * [--set=<set>] * : Translation set slug; default is "default" * * [--format=<format>] * : Format for output (one of "po", "mo", "android", "resx", "strings"; default is "po") * * [--search=<search>] * : Search term * * [--status=<status>] * : Translation string status; default is "current" * * [--priority=<priorities>] * : Original priorities, comma separated. Possible values are "hidden,low,normal,high" */ public function export($args, $assoc_args) { $set_slug = isset($assoc_args['set']) ? $assoc_args['set'] : 'default'; $translation_set = $this->get_translation_set($args[0], $args[1], $set_slug); if (is_wp_error($translation_set)) { WP_CLI::error($translation_set->get_error_message()); } $format = isset($assoc_args['format']) ? $assoc_args['format'] : 'po'; $format = gp_array_get(GP::$formats, $format, null); if (!$format) { WP_CLI::error(__('No such format.', 'glotpress')); } $filters = array(); if (isset($assoc_args['search'])) { $filters['term'] = $assoc_args['search']; } $filters['status'] = isset($assoc_args['status']) ? $assoc_args['status'] : 'current'; if (isset($assoc_args['priority'])) { $filters['priority'] = array(); $priorities = explode(',', $assoc_args['priority']); $valid_priorities = GP::$original->get_static('priorities'); foreach ($priorities as $priority) { $key = array_search($priority, $valid_priorities); if (false === $key) { WP_CLI::warning(sprintf('Invalid priority %s', $priority)); } else { $filters['priority'][] = $key; } } } $entries = GP::$translation->for_export($this->project, $translation_set, $filters); WP_CLI::line($format->print_exported_file($this->project, $this->locale, $translation_set, $entries)); }
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'); } } }
/** * 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'); } }
/** * 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')); }
private function log($msg, $error = false) { if ($error) { WP_CLI::error($msg); } WP_CLI::warning($msg); }
/** * Grant super-admin privileges to one or more users. * * <user>... * : One or more user IDs, user emails, or user logins. */ public function add($args, $_) { $users = $this->fetcher->get_many($args); $user_logins = wp_list_pluck($users, 'user_login'); $super_admins = self::get_admins(); $num_super_admins = count($super_admins); foreach ($user_logins as $user_login) { $user = get_user_by('login', $user_login); if (!$user) { WP_CLI::warning("Couldn't find {$user_login} user."); continue; } if (in_array($user->user_login, $super_admins)) { WP_CLI::warning("User {$user_login} already has super-admin capabilities."); continue; } $super_admins[] = $user->user_login; } if ($num_super_admins === count($super_admins)) { WP_CLI::log('No changes.'); } else { if (update_site_option('site_admins', $super_admins)) { WP_CLI::success('Granted super-admin capabilities.'); } else { WP_CLI::error('Site options update failed!'); } } }
function error($error) { if (!$error) { return; } // TODO: show all errors, not just the first one WP_CLI::warning(WP_CLI::errorToString($error)); }
function wp_redirect_handler($url) { \WP_CLI::warning('Some code is trying to do a URL redirect. Backtrace:'); ob_start(); debug_print_backtrace(); fwrite(STDERR, ob_get_clean()); return $url; }
/** * Flush the cache * * @subcommand flush */ public function flush_internal_caches($args, $assoc_args) { $flushed = \Automattic\WP\Cron_Control\_flush_internal_caches(); if ($flushed) { \WP_CLI::success(__('Internal caches cleared', 'automattic-cron-control')); } else { \WP_CLI::warning(__('No caches to clear', 'automattic-cron-control')); } }
/** * Run a migration. * * ## OPTIONS * * <profile> * : ID of the profile to use for the migration. * * ## EXAMPLES * * wp wpmdb migrate 1 * * @synopsis <profile> * * @since 1.0 */ public function migrate($args, $assoc_args) { $profile = $args[0]; $result = wpmdb_migrate($profile); if (true === $result) { WP_CLI::success(__('Migration successful.', 'wp-migrate-db-pro-cli')); return; } WP_CLI::warning($result->get_error_message()); return; }
function error($error) { if (!$error) { return; } if (is_string($error) && isset($this->upgrader->strings[$error])) { $error = $this->upgrader->strings[$error]; } // TODO: show all errors, not just the first one \WP_CLI::warning($error); }
protected function success_or_failure($r) { list($type, $msg) = $r; if ('success' == $type) { \WP_CLI::success($msg); $status = 0; } else { \WP_CLI::warning($msg); $status = 1; } return $status; }
private static function maybe_load_man_page($args) { $man_dir = WP_CLI_ROOT . "../../../man/"; if (!is_dir($man_dir)) { WP_CLI::warning("man pages do not seem to be installed."); } else { $man_file = $man_dir . implode('-', $args) . '.1'; if (is_readable($man_file)) { exit(WP_CLI::launch("man {$man_file}")); } } }
/** * Clears Timber's Cache * * ## EXAMPLES * * wp timber clear_cache_timber * */ function clear_cache_timber() { $clear = TimberCommand::clear_cache_timber(); $message = 'Failed to clear timber cache'; if ($clear) { $message = "Cleared contents of Timber's Cache"; WP_CLI::success($messsage); } else { WP_CLI::warning($message); } return $message; }
/** * @param array The raw CLI arguments * @return array The list of found items */ public function get_many($args) { $items = array(); foreach ($args as $arg) { $item = $this->get($arg); if ($item) { $items[] = $item; } else { \WP_CLI::warning(sprintf($this->msg, $arg)); } } return $items; }
/** * Activate a theme * * @param array $args **/ public function activate($args = array()) { list($stylesheet, $child) = $this->parse_name($args, __FUNCTION__); $details = get_theme_data($stylesheet); $parent = $details['Template']; if (empty($parent)) { $parent = $child; } elseif (!is_readable($this->get_stylesheet_path($parent))) { WP_CLI::warning('parent theme not found'); exit; } switch_theme($parent, $child); }
/** * Delete a transient value. * * @synopsis <key> */ public function delete($args) { list($key) = $args; if (delete_transient($key)) { WP_CLI::success('Transient deleted.'); } else { if (get_transient($key)) { WP_CLI::error('Transient was not deleted even though the transient appears to exist.'); } else { WP_CLI::warning('Transient was not deleted; however, the transient does not appear to exist.'); } } }
function error($error) { if (!$error) { return; } if (isset($this->upgrader->strings[$error])) { $string = $this->upgrader->strings[$error]; } else { $string = $error; } // TODO: show all errors, not just the first one WP_CLI::warning($string); }
/** * Insert a single redirect * * @subcommand insert-redirect * @synopsis <from_url> <to_url> */ function insert_redirect($args, $assoc_args) { $from_url = esc_url_raw($args[0]); if (is_numeric($args[1])) { $to_url = absint($args[1]); } else { $to_url = esc_url_raw($args[1]); } $inserted = WPCOM_Legacy_Redirector::insert_legacy_redirect($from_url, $to_url); if (!$inserted || is_wp_error($inserted)) { WP_CLI::warning(sprintf("Couldn't insert %s -> %s", $from_url, $to_url)); } WP_CLI::success(sprintf("Inserted %s -> %s", $from_url, $to_url)); }
/** * Delete one or more menus. * * ## OPTIONS * * <menu>... * : The name, slug, or term ID for the menu(s). * * ## EXAMPLES * * $ wp menu delete "My Menu" * Success: 1 menu deleted. */ public function delete($args, $_) { $count = $errors = 0; foreach ($args as $arg) { $ret = wp_delete_nav_menu($arg); if (!$ret || is_wp_error($ret)) { WP_CLI::warning("Couldn't delete menu '{$arg}'."); $errors++; } else { WP_CLI::log("Deleted menu '{$arg}'."); $count++; } } Utils\report_batch_operation_results('menu', 'delete', count($args), $count, $errors); }
/** * Handle notice messages according to the appropriate context (WP-CLI or the WP Admin) * * @param string $message * @param bool $is_error * @return void */ public static function notice($message, $is_error = true) { if (defined('WP_CLI')) { $message = strip_tags($message); if ($is_error) { WP_CLI::warning($message); } else { WP_CLI::success($message); } } else { // Trigger admin notices add_action('all_admin_notices', array(__CLASS__, 'admin_notices')); self::$notices[] = compact('message', 'is_error'); } }
/** * Grant super-admin privileges to one or more users. * * <user>... * : One or more user IDs, user emails, or user logins. */ public function add($args, $_) { $users = $this->fetcher->get_many($args); $user_logins = wp_list_pluck($users, 'user_login'); $super_admins = self::get_admins(); foreach ($user_logins as $user_login) { $user = get_user_by('login', $user_login); if (!$user) { WP_CLI::warning("Couldn't find {$user_login} user."); } else { $super_admins[] = $user->user_login; } } update_site_option('site_admins', $super_admins); WP_CLI::success('Granted super-admin capabilities.'); }
/** * @param string $level * @param string $message * @param array $context * * @return void */ public function log($level, $message, array $context = array()) { switch ($level) { case LogLevel::WARNING: \WP_CLI::warning($message); break; case LogLevel::ERROR: case LogLevel::ALERT: case LogLevel::EMERGENCY: case LogLevel::CRITICAL: \WP_CLI::error($message); break; default: \WP_CLI::log($message); } }
/** * Install a given language. * * <language> * : Language code to install. * * @subcommand install */ public function install($args, $assoc_args) { list($language_code) = $args; $available = wp_get_installed_translations($this->obj_type); $available = !empty($available['default']) ? array_keys($available['default']) : array(); if (in_array($language_code, $available)) { \WP_CLI::warning("Language already installed."); exit; } require_once ABSPATH . '/wp-admin/includes/translation-install.php'; $response = wp_download_language_pack($language_code); if ($response == $language_code) { \WP_CLI::success("Language installed."); } else { \WP_CLI::error("Couldn't install language."); } }
private function update_multiple($args, $assoc_args) { // Grab all items that need updates // If we have no sub-arguments, add them to the output list. $item_list = "Available {$this->item_type} updates:"; $items_to_update = array(); foreach ($this->get_item_list() as $file) { if ($this->get_update_status($file)) { $items_to_update[] = $file; if (empty($assoc_args)) { if (false === strpos($file, '/')) { $name = str_replace('.php', '', basename($file)); } else { $name = dirname($file); } $item_list .= "\n\t%y{$name}%n"; } } } if (empty($items_to_update)) { WP_CLI::line("No {$this->item_type} updates available."); return; } // If --all, UPDATE ALL THE THINGS if (isset($assoc_args['all'])) { $upgrader = WP_CLI::get_upgrader($this->upgrader); $result = $upgrader->bulk_upgrade($items_to_update); // 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); } } // Else list items that require updates } else { WP_CLI::line($item_list); } }
public function __invoke() { $sets = GP::$translation_set->all(); foreach ($sets as $set) { /* translators: %d: Set ID */ WP_CLI::log(sprintf(__('Processing set #%d..', 'glotpress'), $set->id)); $translations = GP::$translation->find(array('translation_set_id' => $set->id, 'status' => 'current'), 'original_id ASC'); $prev_original_id = null; foreach ($translations as $translation) { if ($translation->original_id == $prev_original_id) { WP_CLI::warning(sprintf(__('Duplicate with original_id #%1$d. Translation #%2$d', 'glotpress'), $prev_original_id, $translation->id)); $translation->delete(); } $prev_original_id = $translation->original_id; } } WP_CLI::success('Multiple currents are cleaned up.'); }
private function _generate_c($ctype) { $extra_qv = array('p2p:per_page' => 10); $candidate = $ctype->set_direction('from')->get_connectable('any', $extra_qv, 'abstract'); $count = 0; foreach ($candidate->items as $from) { $eligible = $ctype->get_connectable($from, array('p2p:per_page' => rand(0, 5)), 'abstract'); foreach ($eligible->items as $to) { $r = $ctype->connect($from, $to); if (is_wp_error($r)) { WP_CLI::warning($r); } else { $count++; } } } return $count; }