/**
  * Sync database from remote to local
  *
  * ## OPTIONS
  *
  * <remote>
  * : Name of the configured ssh remote.
  *
  * [--new-base-url=<newurl>]
  * : Base url will be replaced by this option. If none given we'll try to guess it using the old database. If none is available we quit.
  *
  * ## EXAMPLES
  *
  *     wp dbsync production
  *
  * @when before_wp_load
  *
  * @param $args
  * @param $assoc_args
  */
 function __invoke($args, $assoc_args)
 {
     // Host is the first argument
     $host = escapeshellarg($args[0]);
     // Just check if the user is sure he wants to whipe his whole database. Can be overriden bye --yes option
     WP_CLI::confirm('Do you want to drop the current database and import a new one from ' . $host . '?', $assoc_args);
     // Read base url. If it's not available try to fall back on (soon to be removed) database siteurl
     $new_base_url = WP_CLI\Utils\get_flag_value($assoc_args, 'new-base-url', false);
     if (!$new_base_url) {
         // Decode JSON string we got from option
         $new_base_url = json_decode(exec('wp option get home --format=json'));
         // Show error and exit if there is no fallback found
         if (!$new_base_url) {
             WP_CLI::error('No base url specified. No option to fallback on. Please specify --new-base-url');
         }
     }
     WP_CLI::log('Syncing: ' . $host);
     // Reset database (does a DROP DATABASE and CREATE DATABASE)
     WP_CLI::log(exec('wp db reset --yes'));
     WP_CLI::log('Database has been reset. Doing import now.');
     // Export external database to STDOUT and pipe it to local STDIN
     WP_CLI::log(exec('wp ssh db export - --host=' . $host . ' | wp db import -'));
     WP_CLI::log('Done importing. Doing search replace now.');
     // Decode JSON string we got from option
     $remote_base_url = json_decode(exec('wp ssh option get home --format=json --host=' . $host));
     // Skip guid because it should never be changed.
     WP_CLI::log(exec("wp search-replace '" . $remote_base_url . "' '" . $new_base_url . "' --skip-columns=guid"));
 }
/**
 * Get the absolute path for the .env file
 *
 * @param $assoc_args
 *
 * @return string
 */
function get_filepath($assoc_args)
{
    $file = \WP_CLI\Utils\get_flag_value($assoc_args, 'file', '.env');
    if ($file instanceof Dotenv_File) {
        return $file->get_filepath();
    }
    // if relative path, or just a file name was passed
    $dirname = dirname($file);
    $filename = basename($file);
    $relpath = $dirname ? "/{$dirname}" : '';
    $path = realpath(getcwd() . $relpath);
    $path .= "/{$filename}";
    return $path;
}
Esempio n. 3
0
 /**
  * Generate Packages files inside package folder or custom folder
  *
  * ## OPTIONS
  *
  * [--directory=<directory>]
  * : Specify the directory on generate WordPress completions, this completions is create inside of the completions folder on directory.
  *
  * [--type=<all|constants|capabilities|functions|hooks|actions|filters|classes|methods>]
  * : Specify the type of the completions.
  *
  * [--update-readme]
  * : Update Readme.md for WordPress Completions Sublime Package and Update /wiki/Home.md if exists
  */
 public function generate($args, $assoc_args)
 {
     $classes = array();
     $directory = \WP_CLI\Utils\get_flag_value($assoc_args, 'directory', '');
     $type = \WP_CLI\Utils\get_flag_value($assoc_args, 'type', 'all');
     $types = array('functions', 'actions', 'filters', 'classes', 'methods', 'constants', 'capabilities');
     if ('all' === $type) {
         foreach ($types as $type) {
             $classes[] = $type;
         }
     } elseif ('hooks' === $type) {
         foreach (array('actions', 'filters') as $type) {
             $classes[] = $type;
         }
     } elseif (in_array($type, $types)) {
         $classes[] = $type;
     } else {
         WP_CLI::error(sprintf('Type %s is undefined.', $type));
     }
     foreach ($classes as $class) {
         $class = "\\Sublime\\" . ucfirst($class);
         call_user_func(array($class, 'run'), $directory, isset($assoc_args['update-readme']));
     }
 }
 /**
  * Backfill Bitly URLs on all post types that support them
  *
  * [--dry-run]
  * : Execute the command without performing any database operations.
  *
  * [--force]
  * : Forcefully update the value in the database with the response from Bitly
  */
 public function backfill($args, $assoc_args)
 {
     global $wpdb;
     foreach (new WP_CLI\Iterators\Query("SELECT ID,post_title,post_type FROM {$wpdb->posts} WHERE post_status='publish'") as $row) {
         if (!Controller::post_type_supports_bitly($row->post_type)) {
             continue;
         }
         $short_url = Controller::get_short_url($row->ID);
         if ($short_url && !\WP_CLI\Utils\get_flag_value($assoc_args, 'force')) {
             WP_CLI::log(sprintf('Skipping - %s %d already has short url: %s', $row->post_type, $row->ID, $short_url));
             continue;
         }
         $short_url = Controller::generate_short_url($row->ID);
         if (is_wp_error($short_url)) {
             WP_CLI::warning(sprintf("Couldn't generate short url for %s %d because: %s", $row->post_type, $row->ID, $short_url->get_error_message()));
         }
         if (\WP_CLI\Utils\get_flag_value($assoc_args, 'dry-run')) {
             WP_CLI::log(sprintf('Dry run - %s %d now has short url: %s', $row->post_type, $row->ID, $short_url));
         } else {
             WP_CLI::log(sprintf('Updating - %s %d now has short url: %s', $row->post_type, $row->ID, $short_url));
             Controller::set_short_url($row->ID, $short_url);
         }
     }
 }
 /**
  * List the defined variables from the environment file
  *
  * [--format=<format>]
  * : Accepted values: table, csv, json, count. Default: table
  *
  * [--file=<path-to-dotenv>]
  * : Path to the environment file.  Default: '.env'
  *
  * @subcommand list
  * @when before_wp_load
  *
  * @param $_
  * @param $assoc_args
  */
 public function _list($_, $assoc_args)
 {
     $dotenv = get_dotenv_for_read_or_fail($assoc_args);
     $keys = \WP_CLI\Utils\get_flag_value($assoc_args, 'keys');
     $keys = is_string($keys) ? explode(',', $keys) : $keys;
     $items = [];
     foreach ($dotenv->get_pairs() as $key => $value) {
         // Skip if not requested
         if (!empty($keys) && !in_array($key, $keys)) {
             continue;
         }
         $items[] = (object) compact('key', 'value');
     }
     $fields = \WP_CLI\Utils\get_flag_value($assoc_args, 'fields', ['key', 'value']);
     $fields = is_string($fields) ? explode(',', $fields) : $fields;
     $formatter = new Formatter($assoc_args, $fields);
     $formatter->display_items($items);
 }
Esempio n. 6
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));
 }
Esempio n. 7
0
 /**
  * Update the WordPress database.
  *
  * [--network]
  * : Update databases for all sites on a network
  *
  * [--dry-run]
  * : Compare database versions without performing the update.
  *
  * @subcommand update-db
  */
 function update_db($_, $assoc_args)
 {
     global $wpdb, $wp_db_version, $wp_current_db_version;
     $network = Utils\get_flag_value($assoc_args, 'network');
     if ($network && !is_multisite()) {
         WP_CLI::error('This is not a multisite install.');
     }
     $dry_run = Utils\get_flag_value($assoc_args, 'dry-run');
     if ($dry_run) {
         WP_CLI::log('Performing a dry run, with no database modification.');
     }
     if ($network) {
         $iterator_args = array('table' => $wpdb->blogs, 'where' => array('spam' => 0, 'deleted' => 0, 'archived' => 0));
         $it = new \WP_CLI\Iterators\Table($iterator_args);
         $success = $total = 0;
         foreach ($it as $blog) {
             $total++;
             $url = $blog->domain . $blog->path;
             $process = WP_CLI::launch_self('core update-db', array(), array(), false, true, array('url' => $url, 'dry-run' => $dry_run));
             if (0 == $process->return_code) {
                 // See if we can parse the stdout
                 if (preg_match('#Success: (.+)#', $process->stdout, $matches)) {
                     $message = "{$matches[1]} on {$url}";
                 } else {
                     $message = "Database upgraded successfully on {$url}";
                 }
                 WP_CLI::log($message);
                 $success++;
             } else {
                 WP_CLI::warning("Database failed to upgrade on {$url}");
             }
         }
         if (!$dry_run && $total && $success == $total) {
             update_site_option('wpmu_upgrade_site', $wp_db_version);
         }
         WP_CLI::success(sprintf('WordPress database upgraded on %d/%d sites', $success, $total));
     } else {
         require_once ABSPATH . 'wp-admin/includes/upgrade.php';
         $wp_current_db_version = __get_option('db_version');
         if ($wp_db_version != $wp_current_db_version) {
             if (!$dry_run) {
                 wp_upgrade();
             }
             WP_CLI::success("WordPress database upgraded successfully from db version {$wp_current_db_version} to {$wp_db_version}");
         } else {
             WP_CLI::success("WordPress database already at latest db version {$wp_db_version}");
         }
     }
 }
Esempio n. 8
0
 /**
  * Create attachments from local files or URLs.
  *
  * ## OPTIONS
  *
  * <file>...
  * : Path to file or files to be imported. Supports the glob(3) capabilities of the current shell.
  *     If file is recognized as a URL (for example, with a scheme of http or ftp), the file will be
  *     downloaded to a temp file before being sideloaded.
  *
  * [--post_id=<post_id>]
  * : ID of the post to attach the imported files to.
  *
  * [--title=<title>]
  * : Attachment title (post title field).
  *
  * [--caption=<caption>]
  * : Caption for attachent (post excerpt field).
  *
  * [--alt=<alt_text>]
  * : Alt text for image (saved as post meta).
  *
  * [--desc=<description>]
  * : "Description" field (post content) of attachment post.
  *
  * [--featured_image]
  * : If set, set the imported image as the Featured Image of the post its attached to.
  *
  * [--porcelain]
  * : Output just the new attachment ID.
  *
  * ## EXAMPLES
  *
  *     # Import all jpgs in the current user's "Pictures" directory, not attached to any post.
  *     $ wp media import ~/Pictures/**\/*.jpg
  *     Imported file '/home/person/Pictures/beautiful-youg-girl-in-ivy.jpg' as attachment ID 1751.
  *     Imported file '/home/person/Pictures/fashion-girl.jpg' as attachment ID 1752.
  *     Success: Imported 2 of 2 images.
  *
  *     # Import a local image and set it to be the post thumbnail for a post.
  *     $ wp media import ~/Downloads/image.png --post_id=123 --title="A downloaded picture" --featured_image
  *     Imported file '/home/person/Downloads/image.png' as attachment ID 1753 and attached to post 123 as featured image.
  *     Success: Imported 1 of 1 images.
  *
  *     # Import a local image, but set it as the featured image for all posts.
  *     # 1. Import the image and get its attachment ID.
  *     # 2. Assign the attachment ID as the featured image for all posts.
  *     $ ATTACHMENT_ID="$(wp media import ~/Downloads/image.png --porcelain)"
  *     $ wp post list --post_type=post --format=ids | xargs -d ' ' -I % wp post meta add % _thumbnail_id $ATTACHMENT_ID
  *     Success: Added custom field.
  *     Success: Added custom field.
  *
  *     # Import an image from the web.
  *     $ wp media import http://s.wordpress.org/style/images/wp-header-logo.png --title='The WordPress logo' --alt="Semantic personal publishing"
  *     Imported file 'http://s.wordpress.org/style/images/wp-header-logo.png' as attachment ID 1755.
  *     Success: Imported 1 of 1 images.
  */
 function import($args, $assoc_args = array())
 {
     $assoc_args = wp_parse_args($assoc_args, array('title' => '', 'caption' => '', 'alt' => '', 'desc' => ''));
     if (isset($assoc_args['post_id'])) {
         if (!get_post($assoc_args['post_id'])) {
             WP_CLI::warning("Invalid --post_id");
             $assoc_args['post_id'] = false;
         }
     } else {
         $assoc_args['post_id'] = false;
     }
     $successes = $errors = 0;
     foreach ($args as $file) {
         $is_file_remote = parse_url($file, PHP_URL_HOST);
         $orig_filename = $file;
         if (empty($is_file_remote)) {
             if (!file_exists($file)) {
                 WP_CLI::warning("Unable to import file '{$file}'. Reason: File doesn't exist.");
                 $errors++;
                 break;
             }
             $tempfile = $this->make_copy($file);
         } else {
             $tempfile = download_url($file);
         }
         $file_array = array('tmp_name' => $tempfile, 'name' => basename($file));
         $post_array = array('post_title' => $assoc_args['title'], 'post_excerpt' => $assoc_args['caption'], 'post_content' => $assoc_args['desc']);
         $post_array = wp_slash($post_array);
         // use image exif/iptc data for title and caption defaults if possible
         if (empty($post_array['post_title']) || empty($post_array['post_excerpt'])) {
             // @codingStandardsIgnoreStart
             $image_meta = @wp_read_image_metadata($tempfile);
             // @codingStandardsIgnoreEnd
             if (!empty($image_meta)) {
                 if (empty($post_array['post_title']) && trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
                     $post_array['post_title'] = $image_meta['title'];
                 }
                 if (empty($post_array['post_excerpt']) && trim($image_meta['caption'])) {
                     $post_array['post_excerpt'] = $image_meta['caption'];
                 }
             }
         }
         if (empty($post_array['post_title'])) {
             $post_array['post_title'] = preg_replace('/\\.[^.]+$/', '', basename($file));
         }
         // Deletes the temporary file.
         $success = media_handle_sideload($file_array, $assoc_args['post_id'], $assoc_args['title'], $post_array);
         if (is_wp_error($success)) {
             WP_CLI::warning(sprintf("Unable to import file '%s'. Reason: %s", $orig_filename, implode(', ', $success->get_error_messages())));
             $errors++;
             continue;
         }
         // Set alt text
         if ($assoc_args['alt']) {
             update_post_meta($success, '_wp_attachment_image_alt', wp_slash($assoc_args['alt']));
         }
         // Set as featured image, if --post_id and --featured_image are set
         if ($assoc_args['post_id'] && \WP_CLI\Utils\get_flag_value($assoc_args, 'featured_image')) {
             update_post_meta($assoc_args['post_id'], '_thumbnail_id', $success);
         }
         $attachment_success_text = '';
         if ($assoc_args['post_id']) {
             $attachment_success_text = " and attached to post {$assoc_args['post_id']}";
             if (\WP_CLI\Utils\get_flag_value($assoc_args, 'featured_image')) {
                 $attachment_success_text .= ' as featured image';
             }
         }
         if (\WP_CLI\Utils\get_flag_value($assoc_args, 'porcelain')) {
             WP_CLI::line($success);
         } else {
             WP_CLI::log(sprintf("Imported file '%s' as attachment ID %d%s.", $orig_filename, $success, $attachment_success_text));
         }
         $successes++;
     }
     if (!Utils\get_flag_value($assoc_args, 'porcelain')) {
         Utils\report_batch_operation_results('image', 'import', count($args), $successes, $errors);
     }
 }
 /**
  * Get flag value
  *
  * @param      $flag
  * @param null $default
  *
  * @return mixed
  */
 protected function get_flag($flag, $default = null)
 {
     return \WP_CLI\Utils\get_flag_value($this->args->args, $flag, $default);
 }
Esempio n. 10
0
 /**
  * List options and their values.
  *
  * ## OPTIONS
  *
  * [--search=<pattern>]
  * : Use wildcards ( * and ? ) to match option name.
  *
  * [--exclude=<pattern>]
  * : Pattern to exclude. Use wildcards ( * and ? ) to match option name.
  *
  * [--autoload=<value>]
  * : Match only autoload options when value is on, and only not-autoload option when off.
  *
  * [--transients]
  * : List only transients. Use `--no-transients` to ignore all transients.
  *
  * [--field=<field>]
  * : Prints the value of a single field.
  *
  * [--fields=<fields>]
  * : Limit the output to specific object fields.
  *
  * [--format=<format>]
  * : The serialization format for the value. total_bytes displays the total size of matching options in bytes.
  * ---
  * default: table
  * options:
  *   - table
  *   - json
  *   - csv
  *   - count
  *   - yaml
  *   - total_bytes
  * ---
  *
  * ## AVAILABLE FIELDS
  *
  * This field will be displayed by default for each matching option:
  *
  * * option_name
  * * option_value
  *
  * These fields are optionally available:
  *
  * * autoload
  * * size_bytes
  *
  * ## EXAMPLES
  *
  *     # Get the total size of all autoload options.
  *     $ wp option list --autoload=on --format=total_bytes
  *     33198
  *
  *     # Find biggest transients.
  *     $ wp option list --search="*_transient_*" --fields=option_name,size_bytes | sort -n -k 2 | tail
  *     option_name size_bytes
  *     _site_transient_timeout_theme_roots 10
  *     _site_transient_theme_roots 76
  *     _site_transient_update_themes   181
  *     _site_transient_update_core 808
  *     _site_transient_update_plugins  6645
  *
  *     # List all options begining with "i2f_".
  *     $ wp option list --search="i2f_*"
  *     +-------------+--------------+
  *     | option_name | option_value |
  *     +-------------+--------------+
  *     | i2f_version | 0.1.0        |
  *     +-------------+--------------+
  *
  *     # Delete all options begining with "theme_mods_".
  *     $ wp option list --search="theme_mods_*" --field=option_name | xargs -I % wp option delete %
  *     Success: Deleted 'theme_mods_twentysixteen' option.
  *     Success: Deleted 'theme_mods_twentyfifteen' option.
  *     Success: Deleted 'theme_mods_twentyfourteen' option.
  *
  * @subcommand list
  */
 public function list_($args, $assoc_args)
 {
     global $wpdb;
     $pattern = '%';
     $exclude = '';
     $fields = array('option_name', 'option_value');
     $size_query = ",LENGTH(option_value) AS `size_bytes`";
     $autoload_query = '';
     if (isset($assoc_args['search'])) {
         $pattern = self::esc_like($assoc_args['search']);
         // substitute wildcards
         $pattern = str_replace('*', '%', $pattern);
         $pattern = str_replace('?', '_', $pattern);
     }
     if (isset($assoc_args['exclude'])) {
         $exclude = self::esc_like($assoc_args['exclude']);
         $exclude = str_replace('*', '%', $exclude);
         $exclude = str_replace('?', '_', $exclude);
     }
     if (isset($assoc_args['fields'])) {
         $fields = explode(',', $assoc_args['fields']);
     }
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'format') === 'total_bytes') {
         $fields = array('size_bytes');
         $size_query = ",SUM(LENGTH(option_value)) AS `size_bytes`";
     }
     if (isset($assoc_args['autoload'])) {
         if ('on' === $assoc_args['autoload']) {
             $autoload_query = " AND autoload='yes'";
         } elseif ('off' === $assoc_args['autoload']) {
             $autoload_query = " AND autoload='no'";
         } else {
             WP_CLI::error("Value of '--autoload' should be on or off.");
         }
     }
     $transients_query = '';
     if (true === Utils\get_flag_value($assoc_args, 'transients', null)) {
         $transients_query = " AND option_name LIKE '\\_transient\\_%'\n\t\t\tOR option_name LIKE '\\_site\\_transient\\_%'";
     } else {
         if (false === Utils\get_flag_value($assoc_args, 'transients', null)) {
             $transients_query = " AND option_name NOT LIKE '\\_transient\\_%'\n\t\t\tAND option_name NOT LIKE '\\_site\\_transient\\_%'";
         }
     }
     $where = '';
     if ($pattern) {
         $where .= $wpdb->prepare("WHERE `option_name` LIKE %s", $pattern);
     }
     if ($exclude) {
         $where .= $wpdb->prepare(" AND `option_name` NOT LIKE %s", $exclude);
     }
     $where .= $autoload_query . $transients_query;
     $results = $wpdb->get_results("SELECT `option_name`,`option_value`,`autoload`" . $size_query . " FROM `{$wpdb->options}` {$where}");
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'format') === 'total_bytes') {
         WP_CLI::line($results[0]->size_bytes);
     } else {
         $formatter = new \WP_CLI\Formatter($assoc_args, $fields);
         $formatter->display_items($results);
     }
 }
Esempio n. 11
0
 /**
  * Search wordpress.org repo.
  *
  * @param  array $args       A arguments array containing the search term in the first element.
  * @param  array $assoc_args Data passed in from command.
  */
 protected function _search($args, $assoc_args)
 {
     $term = $args[0];
     $defaults = array('per-page' => 10, 'page' => 1, 'fields' => implode(',', array('name', 'slug', 'rating')));
     $assoc_args = array_merge($defaults, $assoc_args);
     $fields = array();
     foreach (explode(',', $assoc_args['fields']) as $field) {
         $fields[$field] = true;
     }
     $formatter = $this->get_formatter($assoc_args);
     $api_args = array('per_page' => (int) $assoc_args['per-page'], 'page' => (int) $assoc_args['page'], 'search' => $term, 'fields' => $fields);
     if ('plugin' == $this->item_type) {
         $api = plugins_api('query_plugins', $api_args);
     } else {
         $api = themes_api('query_themes', $api_args);
     }
     if (is_wp_error($api)) {
         \WP_CLI::error($api->get_error_message() . __(' Try again'));
     }
     $plural = $this->item_type . 's';
     if (!isset($api->{$plural})) {
         \WP_CLI::error(__('API error. Try Again.'));
     }
     $items = $api->{$plural};
     $count = \WP_CLI\Utils\get_flag_value($api->info, 'results', 'unknown');
     \WP_CLI::success(sprintf('Showing %s of %s %s.', count($items), $count, $plural));
     $formatter->display_items($items);
 }
Esempio n. 12
0
 /**
  * Update the WordPress database.
  *
  * [--network]
  * : Update databases for all sites on a network
  *
  * @subcommand update-db
  */
 function update_db($_, $assoc_args)
 {
     global $wpdb, $wp_db_version;
     $network = Utils\get_flag_value($assoc_args, 'network');
     if ($network && !is_multisite()) {
         WP_CLI::error('This is not a multisite install.');
     }
     if ($network) {
         $iterator_args = array('table' => $wpdb->blogs, 'where' => array('spam' => 0, 'deleted' => 0, 'archived' => 0));
         $it = new \WP_CLI\Iterators\Table($iterator_args);
         $success = $total = 0;
         foreach ($it as $blog) {
             $total++;
             $url = $blog->domain . $blog->path;
             $process = WP_CLI::launch_self('core update-db', array(), array(), false, true, array('url' => $url));
             if (0 == $process->return_code) {
                 WP_CLI::log("Database upgraded successfully on {$url}");
                 $success++;
             } else {
                 WP_CLI::warning("Database failed to upgrade on {$url}");
             }
         }
         if ($total && $success == $total) {
             update_site_option('wpmu_upgrade_site', $wp_db_version);
         }
         WP_CLI::success(sprintf('WordPress database upgraded on %d/%d sites.', $success, $total));
     } else {
         require_once ABSPATH . 'wp-admin/includes/upgrade.php';
         wp_upgrade();
         WP_CLI::success('WordPress database upgraded successfully.');
     }
 }
 /**
  * Get flag value for command line option.
  *
  * @param      $key
  * @param null $default
  *
  * @return mixed
  */
 protected function get_flag($key, $default = null)
 {
     return \WP_CLI\Utils\get_flag_value($this->args->original(), $key, $default);
 }