confirm() public static method

If 'y' is provided to the question, the script execution continues. If 'n' or any other response is provided to the question, script exits. # wp db drop asks for confirmation before dropping the database. WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args );
public static confirm ( string $question, array $assoc_args = [] )
$question string Question to display before the prompt.
$assoc_args array Skips prompt if 'yes' is provided.
Example #1
0
 /**
  * Regenerate thumbnail(s).
  *
  * ## OPTIONS
  *
  * [<attachment-id>...]
  * : One or more IDs of the attachments to regenerate.
  *
  * [--skip-delete]
  * : Skip deletion of the original thumbnails. If your thumbnails are linked from sources outside your control, it's likely best to leave them around. Defaults to false.
  *
  * [--only-missing]
  * : Only generate thumbnails for images missing image sizes.
  *
  * [--yes]
  * : Answer yes to the confirmation message.
  *
  * ## EXAMPLES
  *
  *     # re-generate all thumbnails, without confirmation
  *     wp media regenerate --yes
  *
  *     # re-generate all thumbnails that have IDs between 1000 and 2000
  *     seq 1000 2000 | xargs wp media regenerate
  */
 function regenerate($args, $assoc_args = array())
 {
     if (empty($args)) {
         WP_CLI::confirm('Do you really want to regenerate all images?', $assoc_args);
     }
     $skip_delete = \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-delete');
     $only_missing = \WP_CLI\Utils\get_flag_value($assoc_args, 'only-missing');
     if ($only_missing) {
         $skip_delete = true;
     }
     $query_args = array('post_type' => 'attachment', 'post__in' => $args, 'post_mime_type' => 'image', 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids');
     $images = new WP_Query($query_args);
     $count = $images->post_count;
     if (!$count) {
         WP_CLI::warning('No images found.');
         return;
     }
     WP_CLI::log(sprintf('Found %1$d %2$s to regenerate.', $count, _n('image', 'images', $count)));
     $errored = false;
     foreach ($images->posts as $id) {
         if (!$this->_process_regeneration($id, $skip_delete, $only_missing)) {
             $errored = true;
         }
     }
     if ($errored) {
         WP_CLI::log(_n('An error occurred with image regeneration.', 'An error occurred regenerating one or more images.', $count));
     } else {
         WP_CLI::success(sprintf('Finished regenerating %1$s.', _n('the image', 'all images', $count)));
     }
 }
Example #2
0
 /**
  * Remove all tables from the database.
  *
  * @synopsis [--yes]
  */
 function reset($args, $assoc_args)
 {
     WP_CLI::confirm("Are you sure you want to reset the database?", $assoc_args);
     WP_CLI::launch(self::create_cmd('mysql --host=%s --user=%s --password=%s --execute=%s', DB_HOST, DB_USER, DB_PASSWORD, 'DROP DATABASE IF EXISTS ' . DB_NAME));
     WP_CLI::launch(self::create_cmd('mysql --host=%s --user=%s --password=%s --execute=%s', DB_HOST, DB_USER, DB_PASSWORD, 'CREATE DATABASE ' . DB_NAME));
     WP_CLI::success("Database reset.");
 }
Example #3
0
 /**
  * Regenerate thumbnails for one or more attachments.
  *
  * ## OPTIONS
  *
  * [<attachment-id>...]
  * : One or more IDs of the attachments to regenerate.
  *
  * [--skip-delete]
  * : Skip deletion of the original thumbnails. If your thumbnails are linked from sources outside your control, it's likely best to leave them around. Defaults to false.
  *
  * [--only-missing]
  * : Only generate thumbnails for images missing image sizes.
  *
  * [--yes]
  * : Answer yes to the confirmation message. Confirmation only shows when no IDs passed as arguments.
  *
  * ## EXAMPLES
  *
  *     # Regenerate thumbnails for given attachment IDs.
  *     $ wp media regenerate 123 124 125
  *     Found 3 images to regenerate.
  *     1/3 Regenerated thumbnails for "Vertical Image" (ID 123).
  *     2/3 Regenerated thumbnails for "Horizontal Image" (ID 124).
  *     3/3 Regenerated thumbnails for "Beautiful Picture" (ID 125).
  *     Success: Regenerated 3 of 3 images.
  *
  *     # Regenerate all thumbnails, without confirmation.
  *     $ wp media regenerate --yes
  *     Found 3 images to regenerate.
  *     1/3 Regenerated thumbnails for "Sydney Harbor Bridge" (ID 760).
  *     2/3 Regenerated thumbnails for "Boardwalk" (ID 757).
  *     3/3 Regenerated thumbnails for "Sunburst Over River" (ID 756).
  *     Success: Regenerated 3 of 3 images.
  *
  *     # Re-generate all thumbnails that have IDs between 1000 and 2000.
  *     $ seq 1000 2000 | xargs wp media regenerate
  *     Found 4 images to regenerate.
  *     1/4 Regenerated thumbnails for "Vertical Featured Image" (ID 1027).
  *     2/4 Regenerated thumbnails for "Horizontal Featured Image" (ID 1022).
  *     3/4 Regenerated thumbnails for "Unicorn Wallpaper" (ID 1045).
  *     4/4 Regenerated thumbnails for "I Am Worth Loving Wallpaper" (ID 1023).
  *     Success: Regenerated 4 of 4 images.
  */
 function regenerate($args, $assoc_args = array())
 {
     if (empty($args)) {
         WP_CLI::confirm('Do you really want to regenerate all images?', $assoc_args);
     }
     $skip_delete = \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-delete');
     $only_missing = \WP_CLI\Utils\get_flag_value($assoc_args, 'only-missing');
     if ($only_missing) {
         $skip_delete = true;
     }
     $query_args = array('post_type' => 'attachment', 'post__in' => $args, 'post_mime_type' => 'image', 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids');
     $images = new WP_Query($query_args);
     $count = $images->post_count;
     if (!$count) {
         WP_CLI::warning('No images found.');
         return;
     }
     WP_CLI::log(sprintf('Found %1$d %2$s to regenerate.', $count, _n('image', 'images', $count)));
     $errored = false;
     $successes = $errors = 0;
     foreach ($images->posts as $number => $id) {
         if ($this->process_regeneration($id, $skip_delete, $only_missing, $number + 1 . '/' . $count)) {
             $successes++;
         } else {
             $errors++;
         }
     }
     Utils\report_batch_operation_results('image', 'regenerate', count($images->posts), $successes, $errors);
 }
Example #4
0
File: db.php Project: wp-cli/wp-cli
 /**
  * Remove all tables from the database.
  *
  * Runs `DROP_DATABASE` and `CREATE_DATABASE` SQL statements using
  * `DB_HOST`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
  * specified in wp-config.php.
  *
  * ## OPTIONS
  *
  * [--yes]
  * : Answer yes to the confirmation message.
  *
  * ## EXAMPLES
  *
  *     $ wp db reset --yes
  *     Success: Database reset.
  */
 public function reset($_, $assoc_args)
 {
     WP_CLI::confirm("Are you sure you want to reset the database?", $assoc_args);
     self::run_query(sprintf('DROP DATABASE IF EXISTS `%s`', DB_NAME));
     self::run_query(self::get_create_query());
     WP_CLI::success("Database reset.");
 }
Example #5
0
 public function __invoke()
 {
     WP_CLI::confirm("This will erase all current permissions!\nAre you sure you want to delete them?");
     if (!GP::$permission->delete_all()) {
         WP_CLI::error(__('Error in deleting permissions.', 'glotpress'));
     }
     WP_CLI::success(__('Permissions were deleted. Now you can use `wp glotpress add-admin` to add a new administrator.', 'glotpress'));
 }
Example #6
0
 /**
  * Regenerate thumbnail(s).
  *
  * ## OPTIONS
  *
  * [<attachment-id>...]
  * : One or more IDs of the attachments to regenerate.
  *
  * [--yes]
  * : Answer yes to the confirmation message.
  *
  * ## EXAMPLES
  *
  *     # re-generate all thumbnails, without confirmation
  *     wp media regenerate --yes
  *
  *     # re-generate all thumbnails that have IDs between 1000 and 2000
  *     seq 1000 2000 | xargs wp media regenerate
  */
 function regenerate($args, $assoc_args = array())
 {
     if (empty($args)) {
         WP_CLI::confirm('Do you realy want to regenerate all images?', $assoc_args);
     }
     $query_args = array('post_type' => 'attachment', 'post__in' => $args, 'post_mime_type' => 'image', 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids');
     $images = new WP_Query($query_args);
     $count = $images->post_count;
     if (!$count) {
         WP_CLI::warning('No images found.');
         return;
     }
     WP_CLI::log(sprintf('Found %1$d %2$s to regenerate.', $count, _n('image', 'images', $count)));
     foreach ($images->posts as $id) {
         $this->_process_regeneration($id);
     }
     WP_CLI::success(sprintf('Finished regenerating %1$s.', _n('the image', 'all images', $count)));
 }
 /**
  * Export the State of WordPress to a state file.
  * 
  * ## OPTIONS
  * 
  * <state>
  * : State to export
  * 
  * <file>
  * : Where the state should be exported to
  * 
  * [--regions=<regions>]
  * : Limit the export to one or more regions.
  * 
  * [--force]
  * : Forcefully overwrite an existing state file if one exists.
  * 
  * @subcommand export
  */
 public function export($args, $assoc_args)
 {
     list($state, $file) = $args;
     if (file_exists($file) && !isset($assoc_args['force'])) {
         WP_CLI::confirm("Are you sure you want to overwrite the existing state file?");
     }
     $state_obj = Dictator::get_state_obj($state);
     if (!$state_obj) {
         WP_CLI::error("Invalid state supplied.");
     }
     $limited_regions = !empty($assoc_args['regions']) ? explode(',', $assoc_args['regions']) : array();
     // Build the state's data
     $state_data = array('state' => $state);
     foreach ($state_obj->get_regions() as $region_obj) {
         $region_name = $state_obj->get_region_name($region_obj);
         if ($limited_regions && !in_array($region_name, $limited_regions)) {
             continue;
         }
         $state_data[$region_name] = $region_obj->get_current_data();
     }
     $this->write_state_file($state_data, $file);
     WP_CLI::success("State written to file.");
 }
 /**
  * Retrieve a lock's current value, or reset it
  */
 private function get_reset_lock($args, $assoc_args, $lock_name, $lock_limit, $lock_description)
 {
     // Output information about the lock
     \WP_CLI::line($lock_description . "\n");
     \WP_CLI::line(sprintf(__('Maximum: %s', 'automattic-cron-control'), number_format_i18n($lock_limit)) . "\n");
     // Reset requested
     if (isset($assoc_args['reset'])) {
         \WP_CLI::warning(__('Resetting lock...', 'automattic-cron-control') . "\n");
         $lock = \Automattic\WP\Cron_Control\Lock::get_lock_value($lock_name);
         $timestamp = \Automattic\WP\Cron_Control\Lock::get_lock_timestamp($lock_name);
         \WP_CLI::line(sprintf(__('Previous value: %s', 'automattic-cron-control'), number_format_i18n($lock)));
         \WP_CLI::line(sprintf(__('Previously modified: %s GMT', 'automattic-cron-control'), date(TIME_FORMAT, $timestamp)) . "\n");
         \WP_CLI::confirm(sprintf(__('Are you sure you want to reset this lock?', 'automattic-cron-control')));
         \WP_CLI::line('');
         \Automattic\WP\Cron_Control\Lock::reset_lock($lock_name);
         \WP_CLI::success(__('Lock reset', 'automattic-cron-control') . "\n");
         \WP_CLI::line(__('New lock values:', 'automattic-cron-control'));
     }
     // Output lock state
     $lock = \Automattic\WP\Cron_Control\Lock::get_lock_value($lock_name);
     $timestamp = \Automattic\WP\Cron_Control\Lock::get_lock_timestamp($lock_name);
     \WP_CLI::line(sprintf(__('Current value: %s', 'automattic-cron-control'), number_format_i18n($lock)));
     \WP_CLI::line(sprintf(__('Last modified: %s GMT', 'automattic-cron-control'), date(TIME_FORMAT, $timestamp)));
 }
Example #9
0
 /**
  * Reset the WP Easy Mode plugin and WordPress to default values
  *
  * ## OPTIONS
  *
  * [--yes]
  * : Answer yes to the confirmation message.
  *
  * ## EXAMPLES
  *
  *     wp easy-mode reset [--yes]
  */
 public function reset($args, $assoc_args)
 {
     global $wpdb;
     if (!defined('WP_DEBUG') || !WP_DEBUG) {
         WP_CLI::error('WP_DEBUG must be enabled to reset WP Easy Mode.');
     }
     /**
      * Confirm
      */
     if (!isset($assoc_args['yes'])) {
         WP_CLI::confirm('Are you sure you want to reset the plugin? This cannot be undone.');
     }
     /**
      * Plugins
      */
     WP_CLI::line('Deleting plugin: ninja-forms ...');
     WP_CLI::launch_self('plugin deactivate ninja-forms', [], [], false);
     WP_CLI::launch_self('plugin delete ninja-forms', [], [], false);
     WP_CLI::line('Deleting plugin: woocommerce ...');
     WP_CLI::launch_self('plugin deactivate woocommerce', [], [], false);
     WP_CLI::launch_self('plugin delete woocommerce', [], [], false);
     WP_CLI::line('Dropping custom database tables ...');
     $mysql = $wpdb->get_results("SELECT GROUP_CONCAT( table_name ) AS query FROM INFORMATION_SCHEMA.TABLES\n\t\t\t\tWHERE ( table_name LIKE '{$wpdb->prefix}nf_%' )\n\t\t\t\t\tOR ( table_name LIKE '{$wpdb->prefix}ninja_forms_%' )\n\t\t\t\t\tOR ( table_name LIKE '{$wpdb->prefix}woocommerce_%' );");
     if (isset($mysql[0]->query)) {
         $tables = implode(',', array_unique(explode(',', $mysql[0]->query)));
         $wpdb->query("DROP TABLE IF EXISTS {$tables};");
     }
     $wpdb->query("DELETE FROM {$wpdb->options} WHERE ( option_name LIKE 'nf_%' ) OR ( option_name LIKE '%ninja_forms%' ) OR ( option_name LIKE '%woocommerce%' );");
     /**
      * Themes
      */
     WP_CLI::line(sprintf('Activating default theme: %s ...', WP_DEFAULT_THEME));
     WP_CLI::launch_self('theme install ' . WP_DEFAULT_THEME . ' --activate', [], [], false);
     WP_CLI::line('Deleting non-default themes ...');
     $inactive = shell_exec('wp theme list --status=inactive --field=name --format=csv');
     $inactive = array_filter(explode("\n", $inactive));
     $default_themes = array_filter($inactive, function ($theme) {
         return 'twenty' === substr($theme, 0, 6);
     });
     $inactive = implode("\n", array_diff($inactive, $default_themes));
     WP_CLI::launch_self("theme delete {$inactive}", [], [], false);
     /**
      * Users
      */
     WP_CLI::line('Removing all users except main admin ...');
     $wpdb->query("DELETE FROM {$wpdb->users} WHERE ID > 1");
     /**
      * Settings
      */
     WP_CLI::line('Restoring default settings ...');
     $wpdb->query("DELETE FROM {$wpdb->options}\n\t\t\tWHERE ( option_name LIKE 'wpem_%' )\n\t\t\tOR ( option_name LIKE '%_transient_%' )\n\t\t\tOR ( option_name LIKE 'theme_mods_%' );");
     update_option('WPLANG', '');
     update_option('blogname', 'My Site');
     update_option('blogdescription', 'Just another WordPress site');
     $wpdb->query("DELETE FROM {$wpdb->usermeta}\n\t\t\tWHERE ( meta_key = 'sk_ignore_notice' )\n\t\t\tOR ( meta_key = 'dismissed_wp_pointers'\n\t\t\tAND meta_value\n\t\t\tLIKE '%wpem_%' );");
     WP_CLI::line('Deleting all sidebar widgets ...');
     update_option('sidebars_widgets', array('wp_inactive_widgets' => array()));
     /**
      * Site content
      */
     WP_CLI::line('Resetting site content ...');
     $wpdb->query("TRUNCATE TABLE {$wpdb->posts}");
     $wpdb->query("TRUNCATE TABLE {$wpdb->postmeta}");
     $wpdb->query("TRUNCATE TABLE {$wpdb->terms}");
     $wpdb->query("TRUNCATE TABLE {$wpdb->term_taxonomy}");
     $wpdb->query("TRUNCATE TABLE {$wpdb->term_relationships}");
     $wpdb->query("TRUNCATE TABLE {$wpdb->termmeta}");
     /**
      * Success
      */
     WP_CLI::success('DONE!');
 }
Example #10
0
 /**
  * Fetch most recent update matching the requirements. Returns the available versions if there are updates, or empty if no update available.
  *
  * ## OPTIONS
  *
  * [--patch]
  * : Only perform patch updates
  *
  * [--minor]
  * : Only perform minor updates
  *
  * [--major]
  * : Only perform major updates
  *
  * [--nightly]
  * : Update to the latest built version of the master branch. Potentially unstable.
  *
  * [--yes]
  * : Do not prompt for confirmation
  */
 public function update($_, $assoc_args)
 {
     if (!Utils\inside_phar()) {
         WP_CLI::error("You can only self-update Phar files.");
     }
     $old_phar = realpath($_SERVER['argv'][0]);
     if (!is_writable($old_phar)) {
         WP_CLI::error(sprintf("%s is not writable by current user", $old_phar));
     } else {
         if (!is_writeable(dirname($old_phar))) {
             WP_CLI::error(sprintf("%s is not writable by current user", dirname($old_phar)));
         }
     }
     if (isset($assoc_args['nightly'])) {
         WP_CLI::confirm(sprintf('You have version %s. Would you like to update to the latest nightly?', WP_CLI_VERSION), $assoc_args);
         $download_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar';
     } else {
         $updates = $this->get_updates($assoc_args);
         if (empty($updates)) {
             $update_type = $this->get_update_type_str($assoc_args);
             WP_CLI::success("WP-CLI is at the latest{$update_type}version.");
             exit(0);
         }
         $newest = $updates[0];
         WP_CLI::confirm(sprintf('You have version %s. Would you like to update to %s?', WP_CLI_VERSION, $newest['version']), $assoc_args);
         $download_url = $newest['package_url'];
     }
     WP_CLI::log(sprintf('Downloading from %s...', $download_url));
     $temp = \WP_CLI\Utils\get_temp_dir() . uniqid('wp_') . '.phar';
     $headers = array();
     $options = array('timeout' => 600, 'filename' => $temp);
     Utils\http_request('GET', $download_url, null, $headers, $options);
     $allow_root = WP_CLI::get_runner()->config['allow-root'] ? '--allow-root' : '';
     $php_binary = WP_CLI::get_php_binary();
     $process = WP_CLI\Process::create("{$php_binary} {$temp} --version {$allow_root}");
     $result = $process->run();
     if (0 !== $result->return_code) {
         $multi_line = explode(PHP_EOL, $result->stderr);
         WP_CLI::error_multi_line($multi_line);
         WP_CLI::error('The downloaded PHAR is broken, try running wp cli update again.');
     }
     WP_CLI::log('New version works. Proceeding to replace.');
     $mode = fileperms($old_phar) & 511;
     if (false === @chmod($temp, $mode)) {
         WP_CLI::error(sprintf("Cannot chmod %s", $temp));
     }
     class_exists('\\cli\\Colors');
     // this autoloads \cli\Colors - after we move the file we no longer have access to this class
     if (false === @rename($temp, $old_phar)) {
         WP_CLI::error(sprintf("Cannot move %s to %s", $temp, $old_phar));
     }
     if (isset($assoc_args['nightly'])) {
         $updated_version = 'the latest nightly release';
     } else {
         $updated_version = $newest['version'];
     }
     WP_CLI::success(sprintf('Updated WP-CLI to %s', $updated_version));
 }
 public static function repair()
 {
     if (!function_exists('posix_geteuid')) {
         AC_Inspector::log('Repairing file permissions requires a POSIX-enabled PHP server.', __CLASS__, array('error' => true));
         return;
     }
     if (posix_geteuid() !== 0) {
         AC_Inspector::log('Repairing file permissions must be performed as root.', __CLASS__, array('error' => true));
         return;
     }
     $group = '';
     $owner = '';
     if (defined('HTTPD_USER')) {
         $group = HTTPD_USER;
     } else {
         AC_Inspector::log('Unable to determine the user your web server is running as, define HTTPD_USER in your wp-config.php to correct this.', __CLASS__, array('log_level' => 'warning'));
     }
     if (defined('FS_USER')) {
         $owner = FS_USER;
     } else {
         if (defined('FTP_USER')) {
             $owner = FTP_USER;
         } else {
             AC_Inspector::log('Unable to determine the appropriate file system owner, define FS_USER in your wp-config.php to correct this.', __CLASS__, array('log_level' => 'warning'));
         }
     }
     if (empty($group) && empty($owner)) {
         WP_CLI::confirm("Skip setting ownerships (chown) and attempt to repair file permissions (chmod) anyway?");
     } else {
         if (empty($group)) {
             WP_CLI::confirm("Skip setting group permissions and attempt to set just user permissions instead?");
         } else {
             if (empty($owner)) {
                 WP_CLI::confirm("Skip setting user permissions and attempt to set just group permissions instead?");
             }
         }
     }
     if (false === self::chown(self::$_real_abspath, $owner, $group, true, true)) {
         if (defined('WP_CLI') && WP_CLI) {
             WP_CLI::confirm("There where errors while trying to set file ownerships (chown), proceed with setting file permissions (chmod) anyway?");
         } else {
             return false;
         }
     }
     if (count(self::$_options['allowed_dirs']) != 1 || !in_array('/*', self::$_options['allowed_dirs'])) {
         self::chmod(self::$_real_abspath, 0644, 0755, true, true);
     }
     foreach (self::$_options['allowed_dirs'] as $folder) {
         $folder_base = trim(str_replace('/*', '', str_replace('//', '/', str_replace(self::$_real_abspath, '', $folder))), '/');
         if (!file_exists(self::$_real_abspath . '/' . $folder_base) && file_exists('/' . $folder_base)) {
             $folder_base = '/' . $folder_base;
             if (is_link($folder_base)) {
                 $resolved_folder_path = realpath(readlink($folder_base));
             } else {
                 $resolved_folder_path = $folder_base;
             }
         } else {
             if (is_link(self::$_real_abspath . '/' . $folder_base)) {
                 $resolved_folder_path = realpath(readlink(self::$_real_abspath . '/' . $folder_base));
             } else {
                 $resolved_folder_path = self::$_real_abspath . '/' . $folder_base;
             }
         }
         if (!self::$_force_default_allowed_dirs && !file_exists($resolved_folder_path)) {
             continue;
         }
         $recursive = substr($folder, -2) == "/*" ? true : false;
         self::chmod($resolved_folder_path, 0664, 0775, $recursive, true);
     }
     return "";
 }
Example #12
0
// WP-CLI: Handle db error ourselves, instead of waiting for dead_db()
global $wpdb;
if (!empty($wpdb->error)) {
    wp_die($wpdb->error);
}
// Set the database table prefix and the format specifiers for database table columns.
// @codingStandardsIgnoreStart
$GLOBALS['table_prefix'] = $table_prefix;
// @codingStandardsIgnoreEnd
wp_set_wpdb_vars();
// Start the WordPress object cache, or an external object cache if the drop-in is present.
wp_start_object_cache();
// WP-CLI: the APC cache is not available on the command-line, so bail, to prevent cache poisoning
if ($GLOBALS['_wp_using_ext_object_cache'] && class_exists('APC_Object_Cache')) {
    WP_CLI::warning('Running WP-CLI while the APC object cache is activated can result in cache corruption.');
    WP_CLI::confirm('Given the consequences, do you wish to continue?');
}
// Attach the default filters.
require ABSPATH . WPINC . '/default-filters.php';
// Initialize multisite if enabled.
if (is_multisite()) {
    require ABSPATH . WPINC . '/ms-blogs.php';
    require ABSPATH . WPINC . '/ms-settings.php';
} elseif (!defined('MULTISITE')) {
    define('MULTISITE', false);
}
register_shutdown_function('shutdown_action_hook');
// Stop most of WordPress from being loaded if we just want the basics.
if (SHORTINIT) {
    return false;
}
Example #13
0
 /**
  * Delete a blog in a multisite install.
  *
  * @synopsis --slug=<slug> [--yes] [--keep-tables]
  */
 function delete($_, $assoc_args)
 {
     $slug = '/' . trim($assoc_args['slug'], '/') . '/';
     $blog_id = self::get_blog_id_by_slug($slug);
     if (!$blog_id) {
         WP_CLI::error(sprintf("'%s' blog not found.", $slug));
     }
     WP_CLI::confirm("Are you sure you want to delete the '{$slug}' blog?", $assoc_args);
     wpmu_delete_blog($blog_id, !isset($assoc_args['keep-tables']));
     WP_CLI::success("Blog '{$slug}' deleted.");
 }
 /**
  * Performs a full inspection and outputs the inspection log.
  *
  * ## OPTIONS
  *
  * [<routine>]
  * : The inspection routine to perform.
  *
  * ## EXAMPLES
  *
  *     wp angry-inspector inspect file-permissions
  *
  * @synopsis [--force] [<routine>] [<other-routine>]
  */
 function inspect($routines = array(), $assoc_args)
 {
     $all_routines = ACI_Routine_Handler::get_inspection_routines();
     $all_routine_slugs = array();
     $routine_repair_methods = array();
     $force_inspect = true;
     foreach ($all_routines as $key => $routine) {
         $all_routine_slugs[$key] = str_replace('_', '-', str_replace('aci_routine_', '', str_replace('aci_routine_check_', '', strtolower($routine))));
     }
     if (empty($routines) || !is_array($routines) || 0 == count($routines)) {
         $force_inspect = false;
         $routines = $all_routine_slugs;
     }
     if (array_key_exists('force', $assoc_args) && !empty($assoc_args['force'])) {
         $force_inspect = true;
     }
     foreach ($routines as $routine) {
         if (in_array($routine, $all_routine_slugs)) {
             $total_log_count = AC_Inspector::$log_count;
             $routine_key = array_search($routine, $all_routine_slugs);
             $routine_options = ACI_Routine_Handler::get_options($all_routines[$routine_key]);
             $inspection_method = ACI_Routine_Handler::get_inspection_method($all_routines[$routine_key], $routine_options);
             $enabled_routine = false;
             if ($force_inspect) {
                 $enabled_routine = true;
                 ACI_Routine_Handler::force_enable($all_routines[$routine_key]);
             } else {
                 if (!empty($routine_options['site_specific_settings']) && is_multisite() && is_plugin_active_for_network(ACI_PLUGIN_BASENAME)) {
                     $current_site_id = get_current_blog_id();
                     if ($routine_options[$current_site_id]['log_level'] != 'ignore') {
                         $enabled_routine = true;
                     }
                 } else {
                     if ($routine_options['log_level'] != 'ignore') {
                         $enabled_routine = true;
                     }
                 }
             }
             if (!$enabled_routine) {
                 echo "Skipping disabled routine {$routine}...\n\n";
                 continue;
             }
             if (empty($inspection_method)) {
                 WP_CLI::error("Failed to determine the inspection method for {$routine}.");
             }
             if (is_array($inspection_method)) {
                 if (class_exists($inspection_method[0]) && method_exists($inspection_method[0], $inspection_method[1])) {
                     echo "Calling inspection method {$routine}...\n";
                     call_user_func($inspection_method);
                 } else {
                     WP_CLI::error("Failed to load the inspection method for {$routine}.");
                 }
             } else {
                 if (function_exists($inspection_method)) {
                     echo "Calling inspection method {$routine}...\n";
                     call_user_func($inspection_method);
                 } else {
                     WP_CLI::error("Failed to load the inspection method for {$routine}.");
                     break;
                 }
             }
             if (AC_Inspector::$error_count) {
                 AC_Inspector::$error_count = 0;
                 continue;
             }
             $routine_log_count = AC_Inspector::$log_count - $total_log_count;
             WP_CLI::success("Inspected {$routine} with {$routine_log_count} remark(s).\n");
             if ($routine_log_count > 0) {
                 $repair_method = ACI_Routine_Handler::get_repair_method($all_routines[$routine_key], $routine_options);
                 if (!empty($repair_method)) {
                     $routine_repair_methods[$routine] = $repair_method;
                 }
             }
         } else {
             WP_CLI::error("Unrecognized inspection routine '{$routine}'.");
         }
     }
     if (count($routine_repair_methods) > 0) {
         WP_CLI::confirm("One or more of your inspection routines has a repair method that may or may not fix the problem(s) for you.\n" . "Have you made a backup of your website's entire source code, uploaded files and database and want me to\n" . "try and repair with the risk of me messing everything up?");
         foreach ($routine_repair_methods as $routine => $repair_method) {
             $total_log_count = AC_Inspector::$log_count;
             $total_error_count = AC_Inspector::$error_count;
             $total_success_count = AC_Inspector::$success_count;
             call_user_func($repair_method);
             $routine_log_count = AC_Inspector::$log_count - $total_log_count;
             $routine_error_count = AC_Inspector::$error_count - $total_error_count;
             $routine_success_count = AC_Inspector::$success_count - $total_success_count;
             if ($routine_error_count > 0) {
                 WP_CLI::error("Repair method for routine '{$routine}' yielded {$routine_error_count} error(s).\n");
             } else {
                 if ($routine_success_count > 0 || $routine_log_count > 0) {
                     WP_CLI::success("Successfully performed repair method for routine '{$routine}' with no errors.\n");
                 } else {
                     WP_CLI::success("Nothing seems broken. If it ain't broke, don't fix it.\n");
                 }
             }
         }
     }
 }
 /**
  * Convert site using `utf8` to use `utf8mb4`
  *
  * @subcommand convert
  */
 public function convert($args, $assoc_args)
 {
     global $wpdb;
     WP_CLI::line('CONVERSION TO `utf8mb4` REQUESTED');
     // Parse arguments
     if (is_array($assoc_args) && !empty($assoc_args)) {
         if (isset($assoc_args['dry-run']) && 'false' === $assoc_args['dry-run']) {
             $this->dry_run = false;
         }
     }
     WP_CLI::line('');
     WP_CLI::line('ARGUMENTS');
     WP_CLI::line('* dry run: ' . ($this->dry_run ? 'yes' : 'no'));
     WP_CLI::line('');
     // Validate starting charset to avoid catastrophe
     WP_CLI::line('PREFLIGHT CHECKS');
     if ('utf8' === $wpdb->charset) {
         WP_CLI::line('* Expected charset (`utf8`) found.');
     } elseif ('utf8mb4' === $wpdb->charset) {
         WP_CLI::error('Site is already using `utf8mb4`. Aborting!');
         return;
     } else {
         WP_CLI::error("Unacceptable starting encoding: `{$wpdb->charset}`. Aborting!");
         return;
     }
     // Describe scope
     if (is_multisite()) {
         WP_CLI::line('* Multisite detected, so this process will convert all network and global tables, along with the blog tables for all sites.');
     } else {
         WP_CLI::line('* Single site detected, so global and blog-specific tables will be converted. Any multisite tables will be skipped.');
     }
     // Describe tables to be converted
     $this->get_tables();
     $tables_count = number_format(count($this->tables));
     $tables_string = implode(', ', $this->tables);
     WP_CLI::line("* Found {$tables_count} tables to check and potentially convert: {$tables_string}.");
     WP_CLI::line('');
     // Provide an opportunity to abort
     WP_CLI::confirm("Proceed with " . ($this->dry_run ? 'DRY' : 'LIVE') . " RUN and " . ($this->dry_run ? 'test converting' : 'potentially convert') . " {$tables_count} tables from `utf8` to `utf8mb4`?");
     if (!$this->dry_run) {
         WP_CLI::confirm('ARE YOU REALLY SURE?');
     }
     WP_CLI::line('');
     WP_CLI::line('Proceeding...');
     WP_CLI::line('');
     unset($tables_count, $tables_string);
     // Do the work we came here for
     foreach ($this->tables as $table) {
         WP_CLI::line("Converting {$table}...");
         $converted = $this->maybe_convert_table_to_utf8mb4($table);
         if (true === $converted) {
             WP_CLI::line("Done with {$table}.");
         } elseif (false === $converted) {
             if ($this->dry_run) {
                 WP_CLI::line("Table {$table} not converted during dry run.");
             } else {
                 WP_CLI::line("Table {$table} not converted because it doesn't exist or doesn't contain convertible columns.");
             }
         } else {
             WP_CLI::line('Unknown response: ' . var_export($converted, true));
         }
         WP_CLI::line('');
     }
     // Wrap up
     WP_CLI::line('');
     WP_CLI::line('');
     WP_CLI::line('DONE!');
     WP_CLI::line('Time to update sitemeta and reload web configs.');
 }
Example #16
0
 /**
  * Fetch most recent update matching the requirements. Returns the available versions if there are updates, or empty if no update available.
  *
  * ## OPTIONS
  *
  * [--patch]
  * : Only perform patch updates
  *
  * [--minor]
  * : Only perform minor updates
  *
  * [--yes]
  * : Do not prompt for confirmation
  *
  * @subcommand update
  */
 public function update($_, $assoc_args)
 {
     if (!Utils\inside_phar()) {
         WP_CLI::error("You can only self-update Phar files.");
     }
     $old_phar = realpath($_SERVER['argv'][0]);
     if (!is_writable($old_phar)) {
         WP_CLI::error(sprintf("%s is not writable by current user", $old_phar));
     }
     $updates = $this->get_updates($assoc_args);
     if (empty($updates)) {
         WP_CLI::success("WP-CLI is at the latest version.");
         exit(0);
     }
     $newest = $updates[0];
     WP_CLI::confirm(sprintf('You have version %s. Would you like to update to %s?', WP_CLI_VERSION, $newest['version']), $assoc_args);
     $download_url = $newest['package_url'];
     WP_CLI::log(sprintf('Downloading from %s...', $download_url));
     $temp = sys_get_temp_dir() . '/' . uniqid('wp_') . '.phar';
     $headers = array();
     $options = array('timeout' => 600, 'filename' => $temp);
     Utils\http_request('GET', $download_url, null, $headers, $options);
     exec("php {$temp} --version", $output, $status);
     if (0 !== $status) {
         WP_CLI::error_multi_line($output);
         WP_CLI::error('The downloaded PHAR is broken, try running wp cli update again.');
     }
     WP_CLI::log('New version works. Proceeding to replace.');
     $mode = fileperms($old_phar) & 511;
     if (false === @chmod($temp, $mode)) {
         WP_CLI::error(sprintf("Cannot chmod %s", $temp));
     }
     class_exists('\\cli\\Colors');
     // this autoloads \cli\Colors - after we move the file we no longer have access to this class
     if (false === @rename($temp, $old_phar)) {
         WP_CLI::error(sprintf("Cannot move %s to %s", $temp, $old_phar));
     }
     WP_CLI::success(sprintf('Updated WP-CLI to %s', $newest['version']));
 }
 /**
  * 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;
 }
 /**
  * Migrate all FM term meta to core term meta
  *
  * ## OPTIONS
  *
  * [--destructive]
  * : If present, FM term meta will be deleted after it is migrated, and
  * each FM term meta post will be deleted once its meta is migrated.
  *
  * [--dry-run]
  * : If present, no updates will be made.
  *
  * [--verbose]
  * : If present, script will output additional details.
  *
  * ## EXAMPLES
  *
  *     wp fm-term-meta migrate_term_meta
  *
  * @synopsis [--destructive] [--dry-run] [--verbose]
  */
 public function migrate_term_meta($args, $assoc_args)
 {
     $dry_run = !empty($assoc_args['dry-run']);
     $verbose = !empty($assoc_args['verbose']);
     $destructive = !empty($assoc_args['destructive']);
     WP_CLI::line("Starting term meta migration");
     if ($dry_run) {
         WP_CLI::warning('THIS IS A DRY RUN');
     } elseif ($destructive) {
         WP_CLI::warning('With the --destructive flag set, this will delete all FM term meta after it is successfully migrated. There is no undo for this.');
         WP_CLI::confirm('Do you want to continue?');
     }
     if (get_option('db_version') < 34370) {
         WP_CLI::error('This WordPress installation is not ready for term meta! You must be running WordPress 4.4 and the database update must be complete.');
     }
     WP_CLI::warning("Muting user-generated PHP notices for this command in order to hide deprecation notices");
     error_reporting(error_reporting() & ~E_USER_NOTICE);
     $terms = $this->get_terms_with_fm_term_meta();
     foreach ($terms as $term) {
         if ($verbose) {
             WP_CLI::line("Processing {$term->taxonomy} `{$term->name}' ({$term->slug}, {$term->term_id})");
         }
         $term_meta = fm_get_term_meta($term->term_id, $term->taxonomy);
         if ($verbose) {
             WP_CLI::line(sprintf("\tFound %d meta entries", count($term_meta)));
         }
         foreach ($term_meta as $meta_key => $meta_values) {
             if ($verbose) {
                 WP_CLI::line(sprintf("\tMigrating %d meta values for meta key %s", count($meta_values), $meta_key));
             }
             $result = true;
             foreach ($meta_values as $meta_value) {
                 if ($dry_run || $verbose) {
                     WP_CLI::line(sprintf("\tadd_term_meta( %d, '%s', '%s' );", $term->term_id, $meta_key, strlen($meta_value) < 50 ? $meta_value : '[too long to output]'));
                 }
                 if (!$dry_run) {
                     $this_result = add_term_meta($term->term_id, $meta_key, $meta_value);
                     if (!is_int($this_result)) {
                         $result = false;
                         WP_CLI::warning(sprintf("\tError running add_term_meta( %d, '%s', '%s' );", $term->term_id, $meta_key, $meta_value));
                         if (is_wp_error($this_result)) {
                             WP_CLI::warning(sprintf("\t\t%s: %s", $this_result->get_error_code(), $this_result->get_error_message()));
                         } else {
                             WP_CLI::warning(sprintf("\t\t%s", var_export($this_result, 1)));
                         }
                     }
                 }
             }
             if ($destructive) {
                 if (!$result) {
                     WP_CLI::warning("\tSkipping FM term meta deletion for {$meta_key} because an error was encountered while adding data");
                 } else {
                     if ($dry_run || $verbose) {
                         WP_CLI::line("\tDeleting this term's FM term meta for {$meta_key}");
                     }
                     if (!$dry_run) {
                         fm_delete_term_meta($term->term_id, $term->taxonomy, $meta_key);
                     }
                 }
             }
         }
         if (empty($term_meta)) {
             WP_CLI::line("\tNo FM term meta remaining for this term.");
             if ($destructive && get_post($term->post_id)) {
                 if ($verbose || $dry_run) {
                     WP_CLI::line("\tDeleting post ID {$term->post_id}");
                 }
                 if (!$dry_run) {
                     wp_delete_post($term->post_id, true);
                 }
             }
         }
     }
     // Print a success message
     WP_CLI::success("Process complete!");
     if (!$dry_run) {
         WP_CLI::line("\n");
         WP_CLI::line("You're almost done! To use the new term meta, you need to update Fieldmanager, then update your code accordingly:");
         WP_CLI::line("- Replace any call to Fieldmanager_Field::add_term_form() with Fieldmanager_Field::add_term_meta_box().");
         WP_CLI::line("- You need to update the arguments anywhere you're instantiating Fieldmanager_Context_Term directly.");
         WP_CLI::line("See https://github.com/alleyinteractive/wordpress-fieldmanager/issues/400 for details.");
         WP_CLI::line("Happy coding!");
         WP_CLI::line("\n");
     }
 }
Example #19
0
 /**
  * Implementation of command 'upgrade'
  */
 private function upgrade()
 {
     # todo: use wp-cli to download tarfile.
     # todo: if tarfile is not specified, see if the code already exists and use that instead.
     if (!$this->getOption('tarfile', false) and !$this->getOption('zipfile', false)) {
         return WP_CLI::error('Must specify either --tarfile or --zipfile');
     }
     # fixme: throw error if tarfile is not in a valid format.
     if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
         define('CIVICRM_UPGRADE_ACTIVE', 1);
     }
     $wp_root = ABSPATH;
     $settings_path = ABSPATH . '/wp-content/plugins/civicrm/civicrm.settings.php';
     if (!file_exists($settings_path)) {
         return WP_CLI::error('Unable to locate settings file at ' . $settings_path);
     }
     # nb: we don't want to require civicrm.settings.php here, because ..
     #
     # a) this is the old environment we're going to replace
     # b) upgrade-db needs to bootstrap the new environment, so requiring the file
     #    now will create multiple inclusion problems later on
     #
     # however, all we're really after is $civicrm_root and CIVICRM_DSN, so we're going to
     # pull out the lines we need using a regex and run them - yes, it's pretty silly ..
     # don't try this at home, kids.
     $settings = file_get_contents($settings_path);
     $settings = str_replace("\r", '', $settings);
     $settings = explode("\n", $settings);
     if ($civicrm_root_code = reset(preg_grep('/^\\s*\\$civicrm_root\\s*=.*$/', $settings))) {
         eval($civicrm_root_code);
     } else {
         return WP_CLI::error('Unable to read $civicrm_root from civicrm.settings.php');
     }
     if ($civicrm_dsn_code = reset(preg_grep('/^\\s*define.*CIVICRM_DSN.*$/', $settings))) {
         $civicrm_dsn_code = str_replace('CIVICRM_DSN', 'CIVICRM_OLD_DSN', $civicrm_dsn_code);
         eval($civicrm_dsn_code);
     } else {
         return WP_CLI::error('Unable to read CIVICRM_DSN from civicrm.settings.php');
     }
     if (!defined('CIVICRM_OLD_DSN')) {
         return WP_CLI::error('Unable to set CIVICRM_OLD_DSN');
     }
     $date = date('YmdHis');
     $backup_file = "civicrm";
     $basepath = explode('/', $civicrm_root);
     if (!end($basepath)) {
         array_pop($basepath);
     }
     array_pop($basepath);
     $project_path = implode('/', $basepath) . '/';
     array_pop($basepath);
     $plugin_path = implode('/', $basepath) . '/';
     $backup_dir = $this->getOption('backup-dir', $wp_root . '../backup');
     $backup_dir = rtrim($backup_dir, '/');
     WP_CLI::line("\nThe upgrade process involves - ");
     WP_CLI::line(sprintf("1. Backing up current CiviCRM code as => %s", "{$backup_dir}/plugins/{$date}/{$backup_file}"));
     WP_CLI::line(sprintf("2. Backing up database as => %s", "{$backup_dir}/plugins/{$date}/{$backup_file}.sql"));
     WP_CLI::line(sprintf("3. Unpacking tarfile to => %s", $plugin_path));
     WP_CLI::line("4. Executing civicrm/upgrade?reset=1 just as a browser would.\n");
     WP_CLI::confirm('Do you really want to continue?');
     # begin upgrade
     $backup_dir .= '/plugins/' . $date;
     if (!mkdir($backup_dir, 777, true)) {
         return WP_CLI::error('Failed creating directory: ' . $backup_dir);
     }
     $backup_target = $backup_dir . '/' . $backup_file;
     if (!rename($project_path, $backup_target)) {
         return WP_CLI::error(sprintf("Failed to backup CiviCRM project directory %s to %s", $project_path, $backup_target));
     }
     WP_CLI::line();
     WP_CLI::success("1. Code backed up.");
     WP_CLI::run_command(array('civicrm', 'sql-dump'), array('result-file' => $backup_target . '.sql'));
     WP_CLI::success('2. Database backed up.');
     # decompress
     if ($this->getOption('tarfile', false)) {
         # should probably never get to here, as looks like Wordpress Civi comes
         # in a zip file
         if (!$this->untar($plugin_path)) {
             return WP_CLI::error("Error extracting tarfile");
         }
     } elseif ($this->getOption('zipfile', false)) {
         if (!$this->unzip($plugin_path)) {
             return WP_CLI::error("Error extracting zipfile");
         }
     } else {
         return WP_CLI::error("No zipfile specified, use --zipfile=path/to/zipfile");
     }
     WP_CLI::success('3. Archive unpacked.');
     WP_CLI::line('Copying civicrm.settings.php to ' . $project_path . '..');
     define('CIVICRM_SETTINGS_PATH', $project_path . 'civicrm.settings.php');
     if (!copy($backup_dir . '/civicrm/civicrm.settings.php', CIVICRM_SETTINGS_PATH)) {
         return WP_CLI::error('Failed to copy file');
     }
     WP_CLI::success("4. ");
     WP_CLI::run_command(array('civicrm', 'upgrade-db'), array());
     WP_CLI::success("Process completed.");
 }
 /**
  * Remove corrupt Cron Control data resulting from initial plugin deployment
  *
  * @subcommand remove-all-plugin-data
  * @synopsis [--batch-size=<batch-size>] [--dry-run=<dry-run>]
  */
 public function purge($args, $assoc_args)
 {
     global $wpdb;
     // Are we actually destroying any data?
     $dry_run = true;
     if (isset($assoc_args['dry-run']) && 'false' === $assoc_args['dry-run']) {
         $dry_run = false;
     }
     // Provide some idea of what's going on
     \WP_CLI::line(__('CRON CONTROL', 'automattic-cron-control') . "\n");
     $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = %s;", 'a8c_cron_ctrl_event'));
     if (is_numeric($count)) {
         $count = (int) $count;
         \WP_CLI::line(sprintf(__('Found %s total items', 'automattic-cron-control'), number_format_i18n($count)) . "\n\n");
         \WP_CLI::confirm(__('Proceed?', 'automattic-cron-control'));
     } else {
         \WP_CLI::error(__('Something went wrong...aborting!', 'automattic-cron-control'));
     }
     // Should we really destroy all this data?
     if (!$dry_run) {
         \WP_CLI::line(__('This process will remove all CPT data for the Cron Control plugin', 'automattic-cron-control'));
         \WP_CLI::confirm(__('Proceed?', 'automattic-cron-control'));
         \WP_CLI::line("\n" . __('Starting...', 'automattic-cron-control') . "\n");
     }
     // Determine how many batches this will take
     if (isset($assoc_args['batch-size'])) {
         $page_size = max(1, min(absint($assoc_args['batch-size']), 500));
     } else {
         $page_size = 250;
     }
     \WP_CLI::line(sprintf(__('Processing in batches of %s', 'automattic-cron-control'), number_format_i18n($page_size)) . "\n\n");
     $pages = 1;
     $page = 1;
     if ($count > $page_size) {
         $pages = ceil($count / $page_size);
     }
     // Let's get on with it
     do {
         \WP_CLI::line("\n\n" . sprintf(__('Processing page %1$s of %2$s', 'automattic-cron-control'), number_format_i18n($page), number_format_i18n($pages)) . "\n");
         $items = $wpdb->get_results($wpdb->prepare("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s LIMIT %d,%d", 'a8c_cron_ctrl_event', absint(($page - 1) * $page_size), $page_size));
         // Nothing more to do
         if (!is_array($items) || empty($items)) {
             \WP_CLI::line(__('No more items found!', 'automattic-cron-control'));
             break;
         }
         \WP_CLI::line(sprintf(__('Found %s items in this batch'), number_format_i18n(count($items))));
         foreach ($items as $item) {
             \WP_CLI::line("{$item->ID}, `{$item->post_title}`");
             if (!$dry_run) {
                 wp_delete_post($item->ID, true);
             }
         }
         // Some cleanup
         unset($items);
         stop_the_insanity();
         // Prepare for the next batch
         $page++;
         if ($page > $pages) {
             break;
         }
         // Don't rush into the next batch, unless we haven't done anything
         if (!$dry_run) {
             sleep(5);
         }
     } while (true);
     // Remove the now-stale cache when actively run
     if (!$dry_run) {
         wp_cache_delete('a8c_cron_ctrl_option');
         \WP_CLI::line("\n" . sprintf(__('Cleared the %s cache', 'automattic-cron-control'), 'Cron Control'));
     }
     // Fin
     \WP_CLI::success(__('All done.', 'automattic-cron-control'));
 }
 /**
  * Synchronize your WordPress database with the Swiftype search engine configured in the WordPress admin.
  *
  * ## OPTIONS
  *
  * <index-batch-size>
  * : The number of posts to index at once. Defaults to 15.
  *
  * <delete-batch-size>
  * : The number of non-published posts to delete at once. Defaults to 100.
  *
  * <destructive>
  * : Delete the posts DocumentType and re-index all published posts from scratch.
  *
  * ## EXAMPLES
  *
  * Synchronize with the default settings:
  *
  *     wp swiftype sync
  *
  * Destructively synchronize with a large index batch size. This will be faster, but large batch sizes only work with small post data.
  *
  *     wp swiftype sync --destructive --index-batch-size=100
  *
  * @synopsis [--destructive] [--delete-batch-size=<number>] [--index-batch-size=<number>]
  */
 function sync($args, $assoc_args)
 {
     global $swiftype_plugin;
     $destructive = $assoc_args['destructive'];
     if ($destructive) {
         WP_CLI::confirm("Delete all documents and re-index?");
         $engine_slug = get_option('swiftype_engine_slug');
         WP_CLI::log("Deleting existing documents...");
         try {
             $swiftype_plugin->client()->delete_document_type($engine_slug, 'posts');
         } catch (SwiftypeError $e) {
             if ($e->getCode() == 404) {
                 WP_CLI::warning("No 'posts' DocumentType, ignoring.");
             } else {
                 WP_CLI::log($e);
                 WP_CLI::error("Could not delete 'posts' DocumentType, aborting.");
             }
         }
         while (true) {
             try {
                 $swiftype_plugin->client()->find_document_type($engine_slug, 'posts');
             } catch (SwiftypeError $e) {
                 // DocumentType is gone now.
                 break;
             }
         }
         $response = NULL;
         $retries = 0;
         $max_retries = 3;
         $retry_delay = 5;
         while (is_null($response)) {
             try {
                 $response = $swiftype_plugin->client()->create_document_type($engine_slug, 'posts');
             } catch (SwiftypeError $e) {
                 if ($retries >= $max_retries) {
                     WP_CLI::log($e);
                     WP_CLI::error("Could not create 'posts' DocumentType, aborting. Re-create your search engine to continue.");
                 } else {
                     $retries++;
                     sleep($retry_delay);
                 }
             }
         }
     }
     if (!$destructive) {
         $offset = 0;
         $posts_deleted_in_batch = 0;
         $delete_batch_size = $this->integer_argument($assoc_args['delete-batch-size'], 100);
         do {
             $end_count = $offset + $delete_batch_size;
             WP_CLI::log("Deleting trashed posts from " . $offset . " to " . $end_count);
             $posts_deleted_in_batch = $swiftype_plugin->delete_batch_of_trashed_posts($offset, $delete_batch_size);
             $offset += $posts_deleted_in_batch;
             WP_CLI::log("Successfully deleted " . $posts_deleted_in_batch . " trashed posts.");
         } while ($posts_deleted_in_batch != 0);
         WP_CLI::log("Deleted up to " . $offset . " posts");
     }
     $offset = 0;
     $index_batch_size = $this->integer_argument($assoc_args['index-batch-size'], 15);
     do {
         WP_CLI::log("Indexing " . $index_batch_size . " posts from offset " . $offset);
         $this->clear_caches();
         list($num_written, $posts_indexed_in_batch) = $swiftype_plugin->index_batch_of_posts($offset, $index_batch_size);
         $offset += $posts_indexed_in_batch;
         WP_CLI::log("Successfully indexed " . $posts_indexed_in_batch . " posts");
     } while ($posts_indexed_in_batch != 0);
     WP_CLI::log("Indexed " . $offset . " posts");
 }
Example #22
0
 /**
  * parse headers
  * @access private
  * @return bool true on success
  */
 private function _headers()
 {
     $this->_read();
     foreach ($this->csv as $raw_header) {
         $header = explode('-', $raw_header);
         if (in_array($header[0], array('blank', ''))) {
             $this->headers[] = array('type' => 'blank', 'sanitize' => 'esc_attr', 'name' => 'blank');
             continue;
         }
         if (!isset($header[0]) || !in_array($header[0], array('post', 'meta', 'taxonomy', 'thumbnail', 'blank'))) {
             WP_CLI::warning($raw_header . ' - ' . $header[0] . ' is an unsupported field type. Possible types are meta, post, taxonomy, thumbnail!');
         }
         if ($header[1] != 'blank' && (!isset($header[1]) || !function_exists($header[1]))) {
             WP_CLI::error($raw_header . ' - ' . $header[1] . ' is an undefined function. ensure your sanitization function exists!');
             continue;
         }
         // Rebuild $header[ 2 ] so it supports keys and taxonomies with dashes
         $header[2] = implode('-', array_slice($header, 2));
         if (!isset($header[0]) || $header[0] == 'taxonomy' && !taxonomy_exists($header[2])) {
             WP_CLI::error($raw_header . ' - ' . $header[2] . ' is an not a registered taxonomy!');
             continue;
         }
         $validated_header = array('type' => $header[0], 'sanitize' => $header[1], 'name' => $header[2]);
         $this->headers[] = $validated_header;
         WP_CLI::line('header ' . $validated_header['type'] . ' ' . $validated_header['name'] . ' value will be sanitized with ' . $validated_header['sanitize']);
     }
     if (count($this->csv) !== count($this->headers)) {
         return WP_CLI::error('headers are incorrectly formatted, try again!');
     }
     WP_CLI::confirm('Is this what you had in mind? ', '');
     WP_CLI::success('headers are correctly formatted, great job!');
     return true;
 }
Example #23
0
 /**
  * Update WP-CLI to the latest release.
  *
  * Default behavior is to check the releases API for the newest stable
  * version, and prompt if one is available.
  *
  * Use `--stable` to install or reinstall the latest stable version.
  *
  * Use `--nightly` to install the latest built version of the master branch.
  * While not recommended for production, nightly contains the latest and
  * greatest, and should be stable enough for development and staging
  * environments.
  *
  * Only works for the Phar installation mechanism.
  *
  * ## OPTIONS
  *
  * [--patch]
  * : Only perform patch updates.
  *
  * [--minor]
  * : Only perform minor updates.
  *
  * [--major]
  * : Only perform major updates.
  *
  * [--stable]
  * : Update to the latest stable release. Skips update check.
  *
  * [--nightly]
  * : Update to the latest built version of the master branch. Potentially unstable.
  *
  * [--yes]
  * : Do not prompt for confirmation.
  *
  * ## EXAMPLES
  *
  *     # Update CLI.
  *     $ wp cli update
  *     You have version 0.24.0. Would you like to update to 0.24.1? [y/n] y
  *     Downloading from https://github.com/wp-cli/wp-cli/releases/download/v0.24.1/wp-cli-0.24.1.phar...
  *     New version works. Proceeding to replace.
  *     Success: Updated WP-CLI to 0.24.1.
  */
 public function update($_, $assoc_args)
 {
     if (!Utils\inside_phar()) {
         WP_CLI::error("You can only self-update Phar files.");
     }
     $old_phar = realpath($_SERVER['argv'][0]);
     if (!is_writable($old_phar)) {
         WP_CLI::error(sprintf("%s is not writable by current user.", $old_phar));
     } else {
         if (!is_writeable(dirname($old_phar))) {
             WP_CLI::error(sprintf("%s is not writable by current user.", dirname($old_phar)));
         }
     }
     if (Utils\get_flag_value($assoc_args, 'nightly')) {
         WP_CLI::confirm(sprintf('You have version %s. Would you like to update to the latest nightly?', WP_CLI_VERSION), $assoc_args);
         $download_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar';
         $md5_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli-nightly.phar.md5';
     } else {
         if (Utils\get_flag_value($assoc_args, 'stable')) {
             WP_CLI::confirm(sprintf('You have version %s. Would you like to update to the latest stable release?', WP_CLI_VERSION), $assoc_args);
             $download_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar';
             $md5_url = 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar.md5';
         } else {
             $updates = $this->get_updates($assoc_args);
             if (empty($updates)) {
                 $update_type = $this->get_update_type_str($assoc_args);
                 WP_CLI::success("WP-CLI is at the latest{$update_type}version.");
                 return;
             }
             $newest = $updates[0];
             WP_CLI::confirm(sprintf('You have version %s. Would you like to update to %s?', WP_CLI_VERSION, $newest['version']), $assoc_args);
             $download_url = $newest['package_url'];
             $md5_url = str_replace('.phar', '.phar.md5', $download_url);
         }
     }
     WP_CLI::log(sprintf('Downloading from %s...', $download_url));
     $temp = \WP_CLI\Utils\get_temp_dir() . uniqid('wp_') . '.phar';
     $headers = array();
     $options = array('timeout' => 600, 'filename' => $temp);
     Utils\http_request('GET', $download_url, null, $headers, $options);
     $md5_response = Utils\http_request('GET', $md5_url);
     if (20 != substr($md5_response->status_code, 0, 2)) {
         WP_CLI::error("Couldn't access md5 hash for release (HTTP code {$md5_response->status_code}).");
     }
     $md5_file = md5_file($temp);
     $release_hash = trim($md5_response->body);
     if ($md5_file === $release_hash) {
         WP_CLI::log('md5 hash verified: ' . $release_hash);
     } else {
         WP_CLI::error("md5 hash for download ({$md5_file}) is different than the release hash ({$release_hash}).");
     }
     $allow_root = WP_CLI::get_runner()->config['allow-root'] ? '--allow-root' : '';
     $php_binary = WP_CLI::get_php_binary();
     $process = WP_CLI\Process::create("{$php_binary} {$temp} --info {$allow_root}");
     $result = $process->run();
     if (0 !== $result->return_code || false === stripos($result->stdout, 'WP-CLI version:')) {
         $multi_line = explode(PHP_EOL, $result->stderr);
         WP_CLI::error_multi_line($multi_line);
         WP_CLI::error('The downloaded PHAR is broken, try running wp cli update again.');
     }
     WP_CLI::log('New version works. Proceeding to replace.');
     $mode = fileperms($old_phar) & 511;
     if (false === @chmod($temp, $mode)) {
         WP_CLI::error(sprintf("Cannot chmod %s.", $temp));
     }
     class_exists('\\cli\\Colors');
     // This autoloads \cli\Colors - after we move the file we no longer have access to this class.
     if (false === @rename($temp, $old_phar)) {
         WP_CLI::error(sprintf("Cannot move %s to %s", $temp, $old_phar));
     }
     if (Utils\get_flag_value($assoc_args, 'nightly')) {
         $updated_version = 'the latest nightly release';
     } else {
         if (Utils\get_flag_value($assoc_args, 'stable')) {
             $updated_version = 'the latest stable release';
         } else {
             $updated_version = $newest['version'];
         }
     }
     WP_CLI::success(sprintf('Updated WP-CLI to %s.', $updated_version));
 }
Example #24
0
 /**
  * @param string $question
  * @param array  $assoc_args
  */
 public function confirm($question, $assoc_args = array())
 {
     \WP_CLI::confirm($question, $assoc_args);
 }
Example #25
0
 /**
  * Delete one or more users from the current site.
  *
  * ## OPTIONS
  *
  * <user>...
  * : The user login, user email, or user ID of the user(s) to delete.
  *
  * [--network]
  * : On multisite, delete the user from the entire network.
  *
  * [--reassign=<user-id>]
  * : User ID to reassign the posts to.
  *
  * [--yes]
  * : Answer yes to any confirmation prompts.
  *
  * ## EXAMPLES
  *
  *     # Delete user 123 and reassign posts to user 567
  *     $ wp user delete 123 --reassign=567
  *     Success: Removed user 123 from http://example.com
  */
 public function delete($args, $assoc_args)
 {
     $network = \WP_CLI\Utils\get_flag_value($assoc_args, 'network') && is_multisite();
     $reassign = \WP_CLI\Utils\get_flag_value($assoc_args, 'reassign');
     if ($network && $reassign) {
         WP_CLI::error('Reassigning content to a different user is not supported on multisite.');
     }
     if (!$reassign) {
         WP_CLI::confirm('--reassign parameter not passed. All associated posts will be deleted. Proceed?', $assoc_args);
     }
     $users = $this->fetcher->get_many($args);
     parent::_delete($users, $assoc_args, function ($user) use($network, $reassign) {
         $user_id = $user->ID;
         if ($network) {
             $r = wpmu_delete_user($user_id);
             $message = "Deleted user {$user_id}.";
         } else {
             $r = wp_delete_user($user_id, $reassign);
             $message = "Removed user {$user_id} from " . home_url() . ".";
         }
         if ($r) {
             return array('success', $message);
         } else {
             return array('error', "Failed deleting user {$user_id}.");
         }
     });
 }
 /**
  * Generate Hash for current/specified WordPress.
  *
  *## OPTIONS
  *
  * [<wordpress-path>]
  * : WordPress Directory Path to generate hash for
  *
  * ## EXAMPLES
  *
  *     wp exploit-scanner generate <dir-name>
  *
  * @synopsis
  */
 function generate($args, $assoc_args)
 {
     if (count($args) > 0) {
         $path = $args[0];
     } else {
         $path = ABSPATH;
     }
     $path = trailingslashit(realpath($path));
     WP_CLI::warning('Scan Path : ' . $path);
     //Detect Version
     if (!file_exists($path . 'wp-includes/version.php')) {
         WP_CLI::error('Not able to determine WordPress Version: Please check if it is valid WordPress directory');
         return;
     }
     preg_match_all("/wp_version([^\\']+)\\'([^\\']+)'/im", file_get_contents($path . 'wp-includes/version.php'), $version_matches);
     $wordpress_version = $version_matches[2][0];
     WP_CLI::warning('WordPress Version : ' . $wordpress_version);
     $directory_it = new RecursiveDirectoryIterator($path);
     $file_name = 'hashes-' . $wordpress_version . '.php';
     $full_hash_file_path = trailingslashit(dirname(__FILE__)) . 'hashes/' . $file_name;
     if (file_exists($full_hash_file_path)) {
         WP_CLI::confirm(sprintf('%s already exist, Are you sure you want to regenerate it again ?', $file_name));
     }
     $hash_file = fopen($full_hash_file_path, "w");
     fwrite($hash_file, '<?php' . PHP_EOL . '$filehashes = array(');
     $file_progress = new \cli\progress\Bar('Progress', 1100);
     foreach (new RecursiveIteratorIterator($directory_it) as $file) {
         fwrite($hash_file, "'" . str_replace($path, '', $file) . "' => '" . md5_file($file) . "'," . PHP_EOL);
         $file_progress->tick();
     }
     fwrite($hash_file, ');' . PHP_EOL);
     fclose($file);
     WP_CLI::success(sprintf("File created: %s", $file_name));
 }
Example #27
0
 /**
  * Bulk Optimize Images
  *
  * ## OPTIONS
  *
  * <library>
  * : valid values are 'all' (default), 'media', 'nextgen', 'flagallery', and 'other'
  * : media: Media Library only
  * : nextgen: Nextcellent and NextGEN 2.x
  * : flagallery: Grand FlaGallery
  * : other: everything else including theme images and other specified folders
  *
  * <delay>
  * : optional, number of seconds to pause between images
  *
  * <force>
  * : optional, should the plugin re-optimize images that have already been processed.
  *
  * <reset>
  * : optional, start the optimizer back at the beginning instead of resuming from last position
  *
  * <noprompt>
  * : do not prompt, just start optimizing
  *
  * ## EXAMPLES
  *
  *     wp-cli ewwwio optimize media 5 --force --reset --noprompt
  *
  * @synopsis <library> [<delay>] [--force] [--reset] [--noprompt]
  */
 function optimize($args, $assoc_args)
 {
     global $ewww_defer;
     $ewww_defer = false;
     // because NextGEN hasn't flushed it's buffers...
     while (@ob_end_flush()) {
     }
     $library = $args[0];
     if (empty($args[1])) {
         $delay = ewww_image_optimizer_get_option('ewww_image_optimizer_delay');
     } else {
         $delay = $args[1];
     }
     $ewww_reset = false;
     if (!empty($assoc_args['reset'])) {
         $ewww_reset = true;
     }
     if (!empty($assoc_args['force'])) {
         WP_CLI::line(__('Forcing re-optimization of previously processed images.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
         $_REQUEST['ewww_force'] = true;
     }
     WP_CLI::line(sprintf(_x('Optimizing %1$s with a %2$d second pause between images.', 'string will be something like "media" or "nextgen"', EWWW_IMAGE_OPTIMIZER_DOMAIN), $library, $delay));
     // let's get started, shall we?
     ewww_image_optimizer_admin_init();
     // and what shall we do?
     switch ($library) {
         case 'all':
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_bulk_resume', '');
                 update_option('ewww_image_optimizer_aux_resume', '');
                 update_option('ewww_image_optimizer_bulk_ngg_resume', '');
                 update_option('ewww_image_optimizer_bulk_flag_resume', '');
                 WP_CLI::line(__('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             WP_CLI::line(__('Scanning, this could take a while', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('media');
             WP_CLI::line(sprintf(__('%1$d images in the Media Library have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
             if (class_exists('EwwwNgg')) {
                 global $ngg;
                 if (preg_match('/^2/', $ngg->version)) {
                     list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('ngg');
                     WP_CLI::line('Nextgen: ' . sprintf(__('%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
                 } else {
                     $attachments = ewww_image_optimizer_scan_next();
                     WP_CLI::line('Nextgen: ' . sprintf(__('We have %d images to optimize.', EWWW_IMAGE_OPTIMIZER_DOMAIN), count($attachments)));
                 }
             }
             if (class_exists('ewwwflag')) {
                 list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('flag');
                 WP_CLI::line('Flagallery: ' . sprintf(__('%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
             }
             $other_attachments = ewww_image_optimizer_scan_other();
             if (empty($assoc_args['noprompt'])) {
                 WP_CLI::confirm(sprintf(__('%1$d images in other folders need optimizing.', EWWW_IMAGE_OPTIMIZER_DOMAIN), count($other_attachments)));
             }
             ewww_image_optimizer_bulk_media($delay);
             if (class_exists('Ewwwngg')) {
                 global $ngg;
                 if (preg_match('/^2/', $ngg->version)) {
                     ewww_image_optimizer_bulk_ngg($delay);
                 } else {
                     $attachments = ewww_image_optimizer_scan_next();
                     ewww_image_optimizer_bulk_next($delay, $attachments);
                 }
             }
             if (class_exists('ewwwflag')) {
                 ewww_image_optimizer_bulk_flag($delay);
             }
             ewww_image_optimizer_bulk_other($delay, $other_attachments);
             break;
         case 'media':
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_bulk_resume', '');
                 WP_CLI::line(__('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('media');
             if (empty($assoc_args['noprompt'])) {
                 WP_CLI::confirm(sprintf(__('%1$d images in the Media Library have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
             }
             ewww_image_optimizer_bulk_media($delay);
             break;
         case 'nextgen':
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_bulk_ngg_resume', '');
                 WP_CLI::line(__('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             if (class_exists('EwwwNgg')) {
                 global $ngg;
                 if (preg_match('/^2/', $ngg->version)) {
                     list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('ngg');
                     if (empty($assoc_args['noprompt'])) {
                         WP_CLI::confirm(sprintf(__('%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
                     }
                     ewww_image_optimizer_bulk_ngg($delay);
                 } else {
                     $attachments = ewww_image_optimizer_scan_next();
                     if (empty($assoc_args['noprompt'])) {
                         WP_CLI::confirm(sprintf(__('We have %d images to optimize.', EWWW_IMAGE_OPTIMIZER_DOMAIN), count($attachments)));
                     }
                     ewww_image_optimizer_bulk_next($delay, $attachments);
                 }
             } else {
                 WP_CLI::error(__('NextGEN/Nextcellent not installed.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             break;
         case 'flagallery':
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_bulk_flag_resume', '');
                 WP_CLI::line(__('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             if (class_exists('ewwwflag')) {
                 list($fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count) = ewww_image_optimizer_count_optimized('flag');
                 if (empty($assoc_args['noprompt'])) {
                     WP_CLI::confirm(sprintf(__('%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count));
                 }
                 ewww_image_optimizer_bulk_flag($delay);
             } else {
                 WP_CLI::error(__('Grand Flagallery not installed.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             break;
         case 'other':
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_aux_resume', '');
                 WP_CLI::line(__('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
             WP_CLI::line(__('Scanning, this could take a while', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             $other_attachments = ewww_image_optimizer_scan_other();
             if (empty($assoc_args['noprompt'])) {
                 WP_CLI::confirm(sprintf(__('%1$d images in other folders need optimizing.', EWWW_IMAGE_OPTIMIZER_DOMAIN), count($other_attachments)));
             }
             ewww_image_optimizer_bulk_other($delay, $other_attachments);
             break;
         default:
             if ($ewww_reset) {
                 update_option('ewww_image_optimizer_bulk_resume', '');
                 update_option('ewww_image_optimizer_aux_resume', '');
                 update_option('ewww_image_optimizer_bulk_ngg_resume', '');
                 update_option('ewww_image_optimizer_bulk_flag_resume', '');
                 WP_CLI::success(__('Bulk status has been reset, the next bulk operation will start from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             } else {
                 WP_CLI::line(__('Please specify a valid library option, see "wp-cli help ewwwio optimize" for more information.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
             }
     }
 }
Example #28
0
 /**
  * Delete a site in a multisite install.
  *
  * ## OPTIONS
  *
  * [<site-id>]
  * : The id of the site to delete. If not provided, you must set the --slug parameter.
  *
  * [--slug=<slug>]
  * : Path of the blog to be deleted. Subdomain on subdomain installs, directory on subdirectory installs.
  *
  * [--yes]
  * : Answer yes to the confirmation message.
  *
  * [--keep-tables]
  * : Delete the blog from the list, but don't drop it's tables.
  */
 function delete($args, $assoc_args)
 {
     if (!is_multisite()) {
         WP_CLI::error('This is not a multisite install.');
     }
     if (isset($assoc_args['slug'])) {
         $blog = get_blog_details(trim($assoc_args['slug'], '/'));
     } else {
         if (empty($args)) {
             WP_CLI::error("Need to specify a blog id.");
         }
         $blog_id = $args[0];
         $blog = get_blog_details($blog_id);
     }
     if (!$blog) {
         WP_CLI::error("Site not found.");
     }
     WP_CLI::confirm("Are you sure you want to delete the {$blog->siteurl} site?", $assoc_args);
     wpmu_delete_blog($blog->blog_id, !\WP_CLI\Utils\get_flag_value($assoc_args, 'keep-tables'));
     WP_CLI::success("The site at {$blog->siteurl} was deleted.");
 }
Example #29
0
 /**
  * Purge cache files
  *
  * ## OPTIONS
  *
  * [--post_id=<post_id>]
  * : List posts to purge cache files.
  *
  * [--permalink=<permalink>]
  * : List permalinks to purge cache files. Trumps --post_id.
  *
  * [--lang=<lang>]
  * : List langs to purge cache files. Trumps --post_id & --permalink.
  *
  * [--blog_id=<blog_id>]
  * : List blogs to purge cache files. Trumps --post_id & --permalink & lang.
  *
  * ## EXAMPLES
  *
  *     wp rocket clean
  *     wp rocket clean --post_id=2
  *     wp rocket clean --post_id=2,4,6,8
  *     wp rocket clean --permalink=http://example.com
  *     wp rocket clean --permalink=http://example.com, http://example.com/category/(.*)
  *	   wp rocket clean --lang=fr
  *     wp rocket clean --lang=fr,de,en,it
  *	   wp rocket clean --blog_id=2
  *     wp rocket clean --blog_id=2,4,6,8
  *
  * @subcommand clean
  */
 public function clean($args = array(), $assoc_args = array())
 {
     if (!empty($assoc_args['blog_id'])) {
         if (!defined('MULTISITE') || !MULTISITE) {
             WP_CLI::error('This installation doesn\'t multisite support.');
         }
         $blog_ids = explode(',', $assoc_args['blog_id']);
         $blog_ids = array_map('trim', $blog_ids);
         $total = 0;
         $notify = \WP_CLI\Utils\make_progress_bar('Delete cache files', count($blog_ids));
         foreach ($blog_ids as $blog_id) {
             if ($bloginfo = get_blog_details((int) $blog_id, false)) {
                 switch_to_blog($blog_id);
                 rocket_clean_domain();
                 WP_CLI::line('Cache cleared for "' . esc_url('http://' . $bloginfo->domain . $bloginfo->path) . '".');
                 restore_current_blog();
                 $total++;
             } else {
                 WP_CLI::line('This blog ID "' . $blog_id . '" doesn\'t exist.');
             }
             $notify->tick();
         }
         $notify->finish();
         WP_CLI::success('Cache cleared for ' . $total . ' blog(s).');
     } else {
         if (!empty($assoc_args['lang'])) {
             if (!rocket_has_translation_plugin_active()) {
                 WP_CLI::error('No WPML or qTranslate in this website.');
             }
             $langs = explode(',', $assoc_args['lang']);
             $langs = array_map('trim', $langs);
             $total = count($langs);
             $notify = \WP_CLI\Utils\make_progress_bar('Delete cache files', $total);
             foreach ($langs as $lang) {
                 rocket_clean_domain_for_selected_lang($lang);
                 $notify->tick();
             }
             $notify->finish();
             WP_CLI::success('Cache files cleared for ' . $total . ' lang(s).');
         } else {
             if (!empty($assoc_args['permalink'])) {
                 $permalinks = explode(',', $assoc_args['permalink']);
                 $permalinks = array_map('trim', $permalinks);
                 $total = count($permalinks);
                 $notify = \WP_CLI\Utils\make_progress_bar('Delete cache files', $total);
                 foreach ($permalinks as $permalink) {
                     rocket_clean_files($permalink);
                     WP_CLI::line('Cache cleared for "' . $permalink . '".');
                     $notify->tick();
                 }
                 $notify->finish();
                 WP_CLI::success('Cache files cleared for ' . $total . ' permalink(s).');
             } else {
                 if (!empty($assoc_args['post_id'])) {
                     $total = 0;
                     $post_ids = explode(',', $assoc_args['post_id']);
                     $post_ids = array_map('trim', $post_ids);
                     $notify = \WP_CLI\Utils\make_progress_bar('Delete cache files', count($post_ids));
                     foreach ($post_ids as $post_id) {
                         global $wpdb;
                         $post_exists = $wpdb->get_row("SELECT ID FROM {$wpdb->posts} WHERE id = '" . (int) $post_id . "'");
                         if ($post_exists) {
                             if (get_post_type($post_id) == 'attachment') {
                                 WP_CLI::line('This post ID "' . $post_id . '" is an attachment.');
                             } else {
                                 rocket_clean_post($post_id);
                                 WP_CLI::line('Cache cleared for post ID "' . $post_id . '".');
                                 $total++;
                             }
                         } else {
                             WP_CLI::line('This post ID "' . $post_id . '" doesn\'t exist.');
                         }
                         $notify->tick();
                     }
                     if ($total) {
                         $notify->finish();
                         if ($total == 1) {
                             WP_CLI::success('1 post is cleared.');
                         } else {
                             WP_CLI::success($total . ' posts are cleared.');
                         }
                     } else {
                         WP_CLI::error('No cache files are cleared.');
                     }
                 } else {
                     WP_CLI::confirm('Delete all cache files ?');
                     if (rocket_has_translation_plugin_active()) {
                         rocket_clean_domain_for_all_langs();
                     } else {
                         rocket_clean_domain();
                     }
                     WP_CLI::success('All cache files cleared.');
                 }
             }
         }
     }
 }
Example #30
-1
 /**
  * Deletes all users excepts administrators.
  *
  * ## EXAMPLES
  *
  *     wp usergen purge
  *
  * @access		public
  * @param		  array $args
  * @param		  array $assoc_args
  * @return		void
  */
 public function purge($args, $assoc_args)
 {
     WP_CLI::line('');
     WP_CLI::confirm('Are you sure you want to remove all users? This will NOT delete administrators.');
     $roles_to_delete = $this->get_roles();
     foreach ($roles_to_delete as $role => $name) {
         $query_args = array('role' => $role, 'number' => 99999999);
         $user_query = new WP_User_Query($query_args);
         $results = $user_query->get_results();
         $total = $user_query->get_total();
         if (!empty($results)) {
             WP_CLI::line('');
             $notify = \WP_CLI\Utils\make_progress_bar("Deleting {$total} {$name}(s)", $total);
             for ($i = 0; $i < count($results); $i++) {
                 $notify->tick();
                 wp_delete_user($results[$i]->data->ID, null);
             }
             $notify->finish();
         }
     }
     WP_CLI::line('');
     WP_CLI::success('Done.');
     WP_CLI::line('');
 }