get_runner() public static method

public static get_runner ( )
Example #1
0
 /**
  * Execute arbitrary PHP code.
  *
  * ## OPTIONS
  *
  * <php-code>
  * : The code to execute, as a string.
  *
  * [--skip-wordpress]
  * : Execute code without loading WordPress.
  *
  * @when before_wp_load
  *
  * ## EXAMPLES
  *
  *     $ wp eval 'echo WP_CONTENT_DIR;'
  *     /var/www/wordpress/wp-content
  *
  *     $ wp eval 'echo rand();' --skip-wordpress
  *     479620423
  */
 public function __invoke($args, $assoc_args)
 {
     if (null === \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-wordpress')) {
         WP_CLI::get_runner()->load_wordpress();
     }
     eval($args[0]);
 }
Example #2
0
 /**
  * Launch PHP's built-in web server for this specific WordPress installation.
  *
  * Uses `php -S` to launch a web server serving the WordPress webroot.
  * <http://php.net/manual/en/features.commandline.webserver.php>
  *
  * ## OPTIONS
  *
  * [--host=<host>]
  * : The hostname to bind the server to.
  * ---
  * default: localhost
  * ---
  *
  * [--port=<port>]
  * : The port number to bind the server to.
  * ---
  * default: 8080
  * ---
  *
  * [--docroot=<path>]
  * : The path to use as the document root.
  *
  * [--config=<file>]
  * : Configure the server with a specific .ini file.
  *
  * ## EXAMPLES
  *
  *     # Make the instance available on any address (with port 8080)
  *     $ wp server --host=0.0.0.0
  *     PHP 5.6.9 Development Server started at Tue May 24 01:27:11 2016
  *     Listening on http://0.0.0.0:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  *     # Run on port 80 (for multisite)
  *     $ sudo wp server --host=localhost.localdomain --port=80
  *     PHP 5.6.9 Development Server started at Tue May 24 01:30:06 2016
  *     Listening on http://localhost1.localdomain1:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  *     # Configure the server with a specific .ini file
  *     $ wp server --config=development.ini
  *     PHP 7.0.9 Development Server started at Mon Aug 22 12:09:04 2016
  *     Listening on http://localhost:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  * @when before_wp_load
  */
 function __invoke($_, $assoc_args)
 {
     $min_version = '5.4';
     if (version_compare(PHP_VERSION, $min_version, '<')) {
         WP_CLI::error("The `wp server` command requires PHP {$min_version} or newer.");
     }
     $defaults = array('host' => 'localhost', 'port' => 8080, 'docroot' => false, 'config' => get_cfg_var('cfg_file_path'));
     $assoc_args = array_merge($defaults, $assoc_args);
     $docroot = $assoc_args['docroot'];
     if (!$docroot) {
         $config_path = WP_CLI::get_runner()->project_config_path;
         if (!$config_path) {
             $docroot = ABSPATH;
         } else {
             $docroot = dirname($config_path);
         }
     }
     $cmd = \WP_CLI\Utils\esc_cmd('%s -S %s -t %s -c %s %s', PHP_BINARY, $assoc_args['host'] . ':' . $assoc_args['port'], $docroot, $assoc_args['config'], \WP_CLI\Utils\extract_from_phar(WP_CLI_ROOT . '/php/router.php'));
     $descriptors = array(STDIN, STDOUT, STDERR);
     // https://bugs.php.net/bug.php?id=60181
     $options = array();
     if (\WP_CLI\Utils\is_windows()) {
         $options["bypass_shell"] = TRUE;
     }
     exit(proc_close(proc_open($cmd, $descriptors, $pipes, NULL, NULL, $options)));
 }
 /**
  * Write a message to STDERR, prefixed with "Debug: ".
  *
  * @param string $message Message to write.
  */
 public function debug($message)
 {
     if (\WP_CLI::get_runner()->config['debug']) {
         $time = round(microtime(true) - WP_CLI_START_MICROTIME, 3);
         $this->_line("{$message} ({$time}s)", 'Debug', '%B', STDERR);
     }
 }
 /**
  * Get a config option.
  *
  * @synopsis <key> [--format=<format>]
  *
  * @when before_wp_load
  */
 public function get($args, $assoc_args)
 {
     list($key) = $args;
     $extra_config = WP_CLI::get_runner()->extra_config;
     if (isset($extra_config[$key])) {
         $this->print_value($extra_config[$key], $assoc_args);
     }
 }
Example #5
0
 function __construct()
 {
     $this->isWpCli = defined('WP_CLI') && WP_CLI;
     if ($this->isWpCli) {
         $runner = \WP_CLI::get_runner();
         $this->wpCliArguments = $runner->arguments;
     }
 }
Example #6
0
 /**
  * Load and execute a PHP file.
  *
  * ## OPTIONS
  *
  * <file>
  * : The path to the PHP file to execute.
  *
  * [<arg>...]
  * : One or more arguments to pass to the file. They are placed in the $args variable.
  *
  * [--skip-wordpress]
  * : Load and execute file without loading WordPress.
  *
  * @when before_wp_load
  *
  * ## EXAMPLES
  *
  *     wp eval-file my-code.php value1 value2
  */
 public function __invoke($args, $assoc_args)
 {
     $file = array_shift($args);
     if (!file_exists($file)) {
         WP_CLI::error("'{$file}' does not exist.");
     }
     if (null === \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-wordpress')) {
         WP_CLI::get_runner()->load_wordpress();
     }
     self::_eval($file, $args);
 }
Example #7
0
 public function __construct($parent, $name, $docparser)
 {
     $this->parent = $parent;
     $this->name = $name;
     $this->shortdesc = $docparser->get_shortdesc();
     $this->longdesc = $docparser->get_longdesc();
     $when_to_invoke = $docparser->get_tag('when');
     if ($when_to_invoke) {
         \WP_CLI::get_runner()->register_early_invoke($when_to_invoke, $this);
     }
 }
function is_plugin_skipped($file)
{
    $name = get_plugin_name(str_replace(WP_PLUGIN_DIR . '/', '', $file));
    $skipped_plugins = \WP_CLI::get_runner()->config['skip-plugins'];
    if (true === $skipped_plugins) {
        return true;
    }
    if (!is_array($skipped_plugins)) {
        $skipped_plugins = explode(',', $skipped_plugins);
    }
    return in_array($name, array_filter($skipped_plugins));
}
Example #9
0
 /**
  * Start a development server.
  *
  * ## OPTIONS
  *
  * --host=<host>
  * : The hostname to bind the server to. Default: localhost
  *
  * --port=<port>
  * : The port number to bind the server to. Default: 8080
  *
  * ## EXAMPLES
  *
  *     # Make the instance available on any address (with port 8080)
  *     wp server --host=0.0.0.0
  *
  *     # Run on port 80 (for multisite)
  *     sudo wp server --host=localhost.localdomain --port=80
  *
  * @when before_wp_load
  * @synopsis [--host=<host>] [--port=<port>]
  */
 function __invoke($_, $assoc_args)
 {
     $defaults = array('host' => 'localhost', 'port' => 8080);
     $assoc_args = array_merge($defaults, $assoc_args);
     $cmd = \WP_CLI\Utils\esc_cmd(PHP_BINARY . ' -S %s %s', $assoc_args['host'] . ':' . $assoc_args['port'], __DIR__ . '/router.php');
     $config_path = WP_CLI::get_runner()->project_config_path;
     if (!$config_path) {
         $docroot = ABSPATH;
     } else {
         $docroot = dirname($config_path);
     }
     $descriptors = array(STDIN, STDOUT, STDERR);
     exit(proc_close(proc_open($cmd, $descriptors, $pipes, $docroot)));
 }
Example #10
0
 /**
  * Print various data about the CLI environment.
  *
  * ## OPTIONS
  *
  * [--format=<format>]
  * : Accepted values: json
  */
 public function info($_, $assoc_args)
 {
     $php_bin = defined('PHP_BINARY') ? PHP_BINARY : getenv('WP_CLI_PHP_USED');
     $runner = WP_CLI::get_runner();
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'format') === 'json') {
         $info = array('php_binary_path' => $php_bin, 'global_config_path' => $runner->global_config_path, 'project_config_path' => $runner->project_config_path, 'wp_cli_dir_path' => WP_CLI_ROOT, 'wp_cli_version' => WP_CLI_VERSION);
         WP_CLI::line(json_encode($info));
     } else {
         WP_CLI::line("PHP binary:\t" . $php_bin);
         WP_CLI::line("PHP version:\t" . PHP_VERSION);
         WP_CLI::line("php.ini used:\t" . get_cfg_var('cfg_file_path'));
         WP_CLI::line("WP-CLI root dir:\t" . WP_CLI_ROOT);
         WP_CLI::line("WP-CLI global config:\t" . $runner->global_config_path);
         WP_CLI::line("WP-CLI project config:\t" . $runner->project_config_path);
         WP_CLI::line("WP-CLI version:\t" . WP_CLI_VERSION);
     }
 }
Example #11
0
 private function get_command($words)
 {
     $positional_args = $assoc_args = array();
     foreach ($words as $arg) {
         if (preg_match('|^--([^=]+)=?|', $arg, $matches)) {
             $assoc_args[$matches[1]] = true;
         } else {
             $positional_args[] = $arg;
         }
     }
     $r = \WP_CLI::get_runner()->find_command_to_run($positional_args);
     if (!is_array($r) && array_pop($positional_args) == $this->cur_word) {
         $r = \WP_CLI::get_runner()->find_command_to_run($positional_args);
     }
     if (!is_array($r)) {
         return $r;
     }
     list($command, $args) = $r;
     return array($command, $args, $assoc_args);
 }
Example #12
0
 /**
  * Launch PHP's built-in web server for this specific WordPress installation.
  *
  * <http://php.net/manual/en/features.commandline.webserver.php>
  *
  * ## OPTIONS
  *
  * [--host=<host>]
  * : The hostname to bind the server to. Default: localhost
  *
  * [--port=<port>]
  * : The port number to bind the server to. Default: 8080
  *
  * [--docroot=<path>]
  * : The path to use as the document root.
  *
  * ## EXAMPLES
  *
  *     # Make the instance available on any address (with port 8080)
  *     wp server --host=0.0.0.0
  *
  *     # Run on port 80 (for multisite)
  *     sudo wp server --host=localhost.localdomain --port=80
  *
  * @when before_wp_load
  */
 function __invoke($_, $assoc_args)
 {
     $min_version = '5.4';
     if (version_compare(PHP_VERSION, $min_version, '<')) {
         WP_CLI::error("The `wp server` command requires PHP {$min_version} or newer.");
     }
     $defaults = array('host' => 'localhost', 'port' => 8080, 'docroot' => false);
     $assoc_args = array_merge($defaults, $assoc_args);
     $docroot = $assoc_args['docroot'];
     if (!$docroot) {
         $config_path = WP_CLI::get_runner()->project_config_path;
         if (!$config_path) {
             $docroot = ABSPATH;
         } else {
             $docroot = dirname($config_path);
         }
     }
     $cmd = \WP_CLI\Utils\esc_cmd(PHP_BINARY . ' -S %s -t %s %s', $assoc_args['host'] . ':' . $assoc_args['port'], $docroot, \WP_CLI\Utils\extract_from_phar(WP_CLI_ROOT . '/php/router.php'));
     $descriptors = array(STDIN, STDOUT, STDERR);
     exit(proc_close(proc_open($cmd, $descriptors, $pipes)));
 }
Example #13
0
 public static function runWpCliCommand($command, $subcommand, $args = array(), $cwd = null)
 {
     $cliCommand = "wp {$command}";
     if ($subcommand) {
         $cliCommand .= " {$subcommand}";
     }
     // Colorize the output
     if (defined('WP_CLI') && WP_CLI && \WP_CLI::get_runner()->in_color()) {
         $args['color'] = null;
     }
     foreach ($args as $name => $value) {
         if (is_int($name)) {
             // positional argument
             $cliCommand .= " " . escapeshellarg($value);
         } elseif ($value !== null) {
             $cliCommand .= " --{$name}=" . escapeshellarg($value);
         } else {
             $cliCommand .= " --{$name}";
         }
     }
     return self::exec($cliCommand, $cwd);
 }
Example #14
0
 /**
  * List available WP-CLI aliases.
  *
  * Aliases are shorthand references to WordPress installs. For instance,
  * `@dev` could refer to a development install and `@prod` could refer to
  * a production install. This command gives you visibility in what
  * registered aliases you have available.
  *
  * ## OPTIONS
  *
  * [--format=<format>]
  * : Render output in a particular format.
  * ---
  * default: yaml
  * options:
  *   - yaml
  *   - json
  * ---
  *
  * ## EXAMPLES
  *
  *     # List all available aliases.
  *     $ wp cli alias
  *     ---
  *     @all: Run command against every registered alias.
  *     @prod:
  *       ssh: runcommand@runcommand.io~/webapps/production
  *     @dev:
  *       ssh: vagrant@192.168.50.10/srv/www/runcommand.dev
  *     @both:
  *       - @prod
  *       - @dev
  *
  * @alias aliases
  */
 public function alias($_, $assoc_args)
 {
     WP_CLI::print_value(WP_CLI::get_runner()->aliases, $assoc_args);
 }
Example #15
0
<?php

// Can be used by plugins/themes to check if WP-CLI is running or not
define('WP_CLI', true);
define('WP_CLI_VERSION', '0.21.3');
define('WP_CLI_START_MICROTIME', microtime(true));
// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
include WP_CLI_ROOT . '/php/utils.php';
include WP_CLI_ROOT . '/php/dispatcher.php';
include WP_CLI_ROOT . '/php/class-wp-cli.php';
include WP_CLI_ROOT . '/php/class-wp-cli-command.php';
\WP_CLI\Utils\load_dependencies();
WP_CLI::get_runner()->start();
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
  *
  * [--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));
 }
Example #17
0
 /**
  * Verify WordPress files against WordPress.org's checksums.
  *
  * Specify version to verify checksums without loading WordPress.
  *
  * [--version=<version>]
  * : Verify checksums against a specific version of WordPress.
  *
  * [--locale=<locale>]
  * : Verify checksums against a specific locale of WordPress.
  *
  * @when before_wp_load
  *
  * @subcommand verify-checksums
  */
 public function verify_checksums($args, $assoc_args)
 {
     global $wp_version, $wp_local_package;
     if (!empty($assoc_args['version'])) {
         $wp_version = $assoc_args['version'];
     }
     if (!empty($assoc_args['locale'])) {
         $wp_local_package = $assoc_args['locale'];
     }
     if (empty($wp_version)) {
         WP_CLI::get_runner()->load_wordpress();
     }
     $checksums = self::get_core_checksums($wp_version, isset($wp_local_package) ? $wp_local_package : 'en_US');
     if (!is_array($checksums)) {
         WP_CLI::error("Couldn't get checksums from WordPress.org.");
     }
     $has_errors = false;
     foreach ($checksums as $file => $checksum) {
         // Skip files which get updated
         if ('wp-content' == substr($file, 0, 10)) {
             continue;
         }
         if (!file_exists(ABSPATH . $file)) {
             WP_CLI::warning("File doesn't exist: {$file}");
             $has_errors = true;
             continue;
         }
         $md5_file = md5_file(ABSPATH . $file);
         if ($md5_file !== $checksum) {
             WP_CLI::warning("File doesn't verify against checksum: {$file}");
             $has_errors = true;
         }
     }
     if (!$has_errors) {
         WP_CLI::success("WordPress install verifies against checksums.");
     } else {
         WP_CLI::error("WordPress install doesn't verify against checksums.");
     }
 }
Example #18
0
<?php

global $argc, $argv;
define('WPBOOT_BASEPATH', getcwd());
define('WPBOOT_LAUNCHER', 'wpcli');
require_once WPBOOT_BASEPATH . '/vendor/autoload.php';
if (isset($argv[1]) && $argv[1] == 'bootstrap') {
    $runner = WP_CLI::get_runner();
    $config = $runner->config;
    $assocArgs = $runner->assoc_args;
    // check if we got environment from cmd line args before
    // reading the localsettings for the first time
    if (isset($assocArgs['env'])) {
        define('WPBOOT_ENVIRONMENT', $assocArgs['env']);
    }
    $localSettings = new \Wpbootstrap\Settings('local');
    if (rtrim($localSettings->wppath, '/') != rtrim($config['path'], '/') && $localSettings->wppath != '[wppath]') {
        wpbstrp_rewritePath($localSettings->wppath);
        $cmd = join(' ', $argv);
        $output = [];
        exec($cmd, $output);
        echo join("\n", $output) . "\n";
        WP_CLI::line("Path in wp-cli.yml is now set to {$localSettings->wppath}");
        die;
    }
}
WP_CLI::add_command('bootstrap', 'Wpbootstrap\\WpCli');
function wpbstrp_rewritePath($newPath)
{
    $lines = file(WPBOOT_BASEPATH . '/wp-cli.yml');
    $buffer = '';
Example #19
0
<?php

// Workaround to boot individual bootstrap
$args = WP_CLI::get_runner()->arguments;
if (isset($args[2])) {
    $file = sprintf('%s/%s/_bootstrap.php', self::$config['paths']['tests'], trim($args[2]));
    if (file_exists($file)) {
        require $file;
    }
}
if (!isset($args[2])) {
    require self::$config['paths']['tests'] . '/acceptance/_bootstrap.php';
    require self::$config['paths']['tests'] . '/functional/_bootstrap.php';
}
Example #20
0
 /**
  * @return \WP_CLI\Runner
  */
 public function get_runner()
 {
     return \WP_CLI::get_runner();
 }
Example #21
0
 /**
  * Retrieve the runner instance from the base CLI object. This facilitates
  * unit testing, where the WP_CLI instance isn't available
  *
  * @return Runner Instance of the runner class
  */
 protected function get_runner()
 {
     return \WP_CLI::get_runner();
 }
Example #22
0
 /**
  * Show the usage for all subcommands contained
  * by the composite command.
  */
 public function show_usage()
 {
     $methods = $this->get_subcommands();
     $i = 0;
     foreach ($methods as $name => $subcommand) {
         $prefix = 0 == $i++ ? 'usage: ' : '   or: ';
         if (\WP_CLI::get_runner()->is_command_disabled($subcommand)) {
             continue;
         }
         \WP_CLI::line($subcommand->get_usage($prefix));
     }
     $cmd_name = implode(' ', array_slice(get_path($this), 1));
     \WP_CLI::line();
     \WP_CLI::line("See 'wp help {$cmd_name} <command>' for more information on a specific command.");
 }
Example #23
0
 private static function render_subcommands($command)
 {
     $subcommands = array();
     foreach ($command->get_subcommands() as $subcommand) {
         if (WP_CLI::get_runner()->is_command_disabled($subcommand)) {
             continue;
         }
         $subcommands[$subcommand->get_name()] = $subcommand->get_shortdesc();
     }
     $max_len = self::get_max_len(array_keys($subcommands));
     $lines = array();
     foreach ($subcommands as $name => $desc) {
         $lines[] = str_pad($name, $max_len) . "\t\t\t" . $desc;
     }
     return $lines;
 }
Example #24
0
function is_theme_skipped($path)
{
    $name = get_theme_name($path);
    $skipped_themes = \WP_CLI::get_runner()->config['skip-themes'];
    if (true === $skipped_themes) {
        return true;
    }
    if (!is_array($skipped_themes)) {
        $skipped_themes = explode(',', $skipped_themes);
    }
    return in_array($name, array_filter($skipped_themes));
}
Example #25
0
 public function start()
 {
     $this->init_config();
     $this->init_colorization();
     $this->init_logger();
     WP_CLI::debug($this->_global_config_path_debug, 'bootstrap');
     WP_CLI::debug($this->_project_config_path_debug, 'bootstrap');
     $this->check_root();
     if (empty($this->arguments)) {
         $this->arguments[] = 'help';
     }
     // Protect 'cli info' from most of the runtime
     if ('cli' === $this->arguments[0] && !empty($this->arguments[1]) && 'info' === $this->arguments[1]) {
         $this->_run_command();
         exit;
     }
     // Protect 'package' commands from most of the runtime too
     if ('package' === $this->arguments[0]) {
         $this->_run_command();
         exit;
     }
     // Load bundled commands early, so that they're forced to use the same
     // APIs as non-bundled commands.
     Utils\load_all_commands();
     $skip_packages = \WP_CLI::get_runner()->config['skip-packages'];
     if (true === $skip_packages) {
         WP_CLI::debug('Skipped loading packages.', 'bootstrap');
     } else {
         $package_autoload = $this->get_packages_dir_path() . 'vendor/autoload.php';
         if (file_exists($package_autoload)) {
             WP_CLI::debug('Loading packages from: ' . $package_autoload, 'bootstrap');
             require_once $package_autoload;
         } else {
             WP_CLI::debug('No package autoload found to load.', 'bootstrap');
         }
     }
     if (isset($this->config['require'])) {
         foreach ($this->config['require'] as $path) {
             if (!file_exists($path)) {
                 $context = '';
                 foreach (array('global', 'project', 'runtime') as $scope) {
                     if (in_array($path, $this->_required_files[$scope])) {
                         switch ($scope) {
                             case 'global':
                                 $context = ' (from global ' . basename($this->global_config_path) . ')';
                                 break;
                             case 'project':
                                 $context = ' (from project\'s ' . basename($this->project_config_path) . ')';
                                 break;
                             case 'runtime':
                                 $context = ' (from runtime argument)';
                                 break;
                         }
                         break;
                     }
                 }
                 WP_CLI::error(sprintf("Required file '%s' doesn't exist%s.", basename($path), $context));
             }
             Utils\load_file($path);
             WP_CLI::debug('Required file from config: ' . $path, 'bootstrap');
         }
     }
     // Show synopsis if it's a composite command.
     $r = $this->find_command_to_run($this->arguments);
     if (is_array($r)) {
         list($command) = $r;
         if ($command->can_have_subcommands()) {
             $command->show_usage();
             exit;
         }
     }
     // Handle --path parameter
     self::set_wp_root($this->find_wp_root());
     // First try at showing man page
     if (!empty($this->arguments[0]) && 'help' === $this->arguments[0] && (!$this->wp_exists() || !Utils\locate_wp_config() || !empty($this->arguments[1]) && !empty($this->arguments[2]) && 'core' === $this->arguments[1] && in_array($this->arguments[2], array('config', 'install', 'multisite-install', 'verify-checksums', 'version')))) {
         $this->auto_check_update();
         $this->_run_command();
     }
     // Handle --url parameter
     $url = self::guess_url($this->config);
     if ($url) {
         \WP_CLI::set_url($url);
     }
     $this->do_early_invoke('before_wp_load');
     $this->check_wp_version();
     if ($this->cmd_starts_with(array('core', 'config'))) {
         $this->_run_command();
         exit;
     }
     if (!Utils\locate_wp_config()) {
         WP_CLI::error("wp-config.php not found.\n" . "Either create one manually or use `wp core config`.");
     }
     if ($this->cmd_starts_with(array('db')) && !$this->cmd_starts_with(array('db', 'tables'))) {
         eval($this->get_wp_config_code());
         $this->_run_command();
         exit;
     }
     if ($this->cmd_starts_with(array('core', 'is-installed'))) {
         define('WP_INSTALLING', true);
     }
     if (count($this->arguments) >= 2 && $this->arguments[0] == 'core' && in_array($this->arguments[1], array('install', 'multisite-install'))) {
         define('WP_INSTALLING', true);
         // We really need a URL here
         if (!isset($_SERVER['HTTP_HOST'])) {
             $url = 'http://example.com';
             \WP_CLI::set_url($url);
         }
         if ('multisite-install' == $this->arguments[1]) {
             // need to fake some globals to skip the checks in wp-includes/ms-settings.php
             $url_parts = Utils\parse_url($url);
             self::fake_current_site_blog($url_parts);
             if (!defined('COOKIEHASH')) {
                 define('COOKIEHASH', md5($url_parts['host']));
             }
         }
     }
     if ($this->cmd_starts_with(array('import'))) {
         define('WP_LOAD_IMPORTERS', true);
         define('WP_IMPORTING', true);
     }
     if ($this->cmd_starts_with(array('plugin'))) {
         $GLOBALS['pagenow'] = 'plugins.php';
     }
     $this->load_wordpress();
     $this->_run_command();
 }
Example #26
0
    /**
     * Forward command to remote host
     *
     * ## OPTIONS
     *
     * <command>...
     * : The command to run.
     * 
     * [--<field>=<value>...]
     * : associative args to pass to the command
     *
     * [--flag...]
     * : flag to pass to the command
     *
     * --host=<host>
     * : name of the host to connect to
     *
     * ## EXAMPLES
     *
     *     wp ssh plugin status --host=vagrant
     *
     * @when before_wp_load
     */
    public function __invoke($args, $assoc_args)
    {
        $runner = WP_CLI::get_runner();
        /**
         * This script can either be supplied via a WP-CLI --require config, or
         * it can be loaded via a Composer package.
         * YES, the result is that this file is required twice. YES, this is hacky!
         */
        $require_arg = sprintf('--require=%s', __FILE__);
        if (empty($runner)) {
            $GLOBALS['argv'][] = $require_arg;
            return;
        }
        // Parse cli args to push to server
        $has_url = false;
        $path = null;
        $target_server = null;
        $cli_args = array();
        // @todo Better to use WP_CLI::get_configurator()->parse_args() here?
        foreach (array_slice($GLOBALS['argv'], 2) as $arg) {
            // Remove what we added above the first time this file was loaded
            if ($arg === $require_arg) {
                continue;
            } else {
                if (preg_match('#^--host=(.+)$#', $arg, $matches)) {
                    $target_server = $matches[1];
                } else {
                    if (preg_match('#^--path=(.+)$#', $arg, $matches)) {
                        $path = $matches[1];
                    } else {
                        if (preg_match('#^--url=#', $arg)) {
                            $has_url = true;
                        }
                        $cli_args[] = $arg;
                    }
                }
            }
        }
        // Remove duplicated ssh when there is a forgotten `alias wp="wp ssh --host=vagrant"`
        while (!empty($cli_args) && $cli_args[0] === 'ssh') {
            array_shift($cli_args);
        }
        // Check if a target is specified or fallback on local if not.
        if (!isset($assoc_args[$target_server])) {
            // Run local wp cli command
            $php_bin = defined('PHP_BINARY') ? PHP_BINARY : getenv('WP_CLI_PHP_USED');
            $cmd = sprintf('%s %s %s', $php_bin, $GLOBALS['argv'][0], implode(' ', $cli_args));
            passthru($cmd, $exit_code);
            exit($exit_code);
        } else {
            $ssh_config = $assoc_args[$target_server];
        }
        // Check if command is valid or disabled
        // Will output an error if the command has been disabled
        $r = $this->check_disabled_commands(array_values($cli_args), $ssh_config);
        // Add default url from config is one is not set
        if (!$has_url && !empty($ssh_config['url'])) {
            $cli_args[] = '--url=' . $ssh_config['url'];
        }
        if (!$path && !empty($ssh_config['path'])) {
            $path = $ssh_config['path'];
        } else {
            WP_CLI::error('No path is specified');
        }
        // Inline bash script
        $cmd = '
			set -e;
			if command -v wp >/dev/null 2>&1; then
				wp_command=wp;
			else
				wp_command=/tmp/wp-cli.phar;
				if [ ! -e $wp_command ]; then
					curl -L https://github.com/wp-cli/builds/blob/gh-pages/phar/wp-cli.phar?raw=true > $wp_command;
					chmod +x $wp_command;
				fi;
			fi;
			cd %s;
			$wp_command
		';
        // Replace path
        $cmd = sprintf($cmd, escapeshellarg($path));
        // Remove newlines in Bash script added just for readability
        $cmd = trim(preg_replace('/\\s+/', ' ', $cmd));
        // Append WP-CLI args to command
        $cmd .= ' ' . join(' ', array_map('escapeshellarg', $cli_args));
        // Escape command argument for each level of SSH tunnel inception, and pass along TTY state
        $is_tty = function_exists('posix_isatty') && posix_isatty(STDOUT);
        $cmd_prefix = $ssh_config['cmd'];
        $cmd_prefix = str_replace('%pseudotty%', $is_tty ? '-t' : '-T', $cmd_prefix);
        $tunnel_depth = preg_match_all('/(^|\\s)(ssh|slogin)\\s/', $cmd_prefix);
        for ($i = 0; $i < $tunnel_depth; $i += 1) {
            $cmd = escapeshellarg($cmd);
        }
        // Replace placeholder with command
        $cmd = str_replace('%cmd%', $cmd, $cmd_prefix);
        if ($is_tty) {
            // they probably want this to be --quiet
            WP_CLI::log(sprintf('Connecting via ssh to host: %s', $target_server));
        }
        // Execute WP-CLI on remote server
        passthru($cmd, $exit_code);
        // Prevent local machine's WP-CLI from executing further
        exit($exit_code);
    }
Example #27
0
 /**
  * Get the path to an installed WP-CLI package, or the package directory.
  *
  * If you want to contribute to a package, this is a great way to jump to it.
  *
  * ## OPTIONS
  *
  * [<name>]
  * : Name of the package to get the directory for.
  *
  * ## EXAMPLES
  *
  *     # Get package path
  *     $ wp package path
  *     /home/person/.wp-cli/packages/
  *
  *     # Change directory to package path
  *     $ cd $(wp package path) && pwd
  *     /home/vagrant/.wp-cli/packages
  */
 function path($args)
 {
     $packages_dir = WP_CLI::get_runner()->get_packages_dir_path();
     if (!empty($args)) {
         $packages_dir .= 'vendor/' . $args[0];
         if (!is_dir($packages_dir)) {
             WP_CLI::error('Invalid package name.');
         }
     }
     WP_CLI::line($packages_dir);
 }
Example #28
0
 /**
  * Runs through the entirety of the WP bootstrap process
  */
 private function load_wordpress_with_template()
 {
     global $wp_query;
     WP_CLI::get_runner()->load_wordpress();
     // Set up the main WordPress query.
     wp();
     $interpreted = array();
     foreach ($wp_query as $key => $value) {
         if (0 === stripos($key, 'is_') && $value) {
             $interpreted[] = $key;
         }
     }
     WP_CLI::debug('Main WP_Query: ' . implode(', ', $interpreted), 'redis-debug');
     define('WP_USE_THEMES', true);
     add_filter('template_include', function ($template) {
         $display_template = str_replace(dirname(get_template_directory()) . '/', '', $template);
         WP_CLI::debug("Theme template: {$display_template}", 'redis-debug');
         return $template;
     }, 999);
     // Template is normally loaded in global scope, so we need to replicate
     foreach ($GLOBALS as $key => $value) {
         global ${$key};
     }
     // Load the theme template.
     ob_start();
     require_once ABSPATH . WPINC . '/template-loader.php';
     ob_get_clean();
 }
Example #29
0
<?php

// Can be used by plugins/themes to check if WP-CLI is running or not
define('WP_CLI', true);
define('WP_CLI_VERSION', trim(file_get_contents(WP_CLI_ROOT . '/VERSION')));
// Set common headers, to prevent warnings from plugins
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
include WP_CLI_ROOT . '/php/utils.php';
include WP_CLI_ROOT . '/php/dispatcher.php';
include WP_CLI_ROOT . '/php/class-wp-cli.php';
include WP_CLI_ROOT . '/php/class-wp-cli-command.php';
\WP_CLI\Utils\load_dependencies();
WP_CLI::get_runner()->before_wp_load();
// Load wp-config.php code, in the global scope
eval(WP_CLI::get_runner()->get_wp_config_code());
WP_CLI::get_runner()->maybe_update_url_from_domain_constant();
// Load Core, mu-plugins, plugins, themes etc.
require WP_CLI_ROOT . '/php/wp-settings-cli.php';
// Fix memory limit. See http://core.trac.wordpress.org/ticket/14889
@ini_set('memory_limit', -1);
// Load all the admin APIs, for convenience
require ABSPATH . 'wp-admin/includes/admin.php';
WP_CLI::get_runner()->after_wp_load();
Example #30
0
 public function start()
 {
     $this->init_config();
     $this->init_colorization();
     $this->init_logger();
     WP_CLI::debug($this->_global_config_path_debug, 'bootstrap');
     WP_CLI::debug($this->_project_config_path_debug, 'bootstrap');
     $this->check_root();
     if ($this->alias) {
         if ('@all' === $this->alias && !isset($this->aliases['@all'])) {
             WP_CLI::error("Cannot use '@all' when no aliases are registered.");
         }
         if ('@all' === $this->alias && is_string($this->aliases['@all'])) {
             $aliases = array_keys($this->aliases);
             $k = array_search('@all', $aliases);
             unset($aliases[$k]);
             $this->run_alias_group($aliases);
             exit;
         }
         if (!array_key_exists($this->alias, $this->aliases)) {
             WP_CLI::error("Alias '{$this->alias}' not found.");
         }
         // Numerically indexed means a group of aliases
         if (isset($this->aliases[$this->alias][0])) {
             $group_aliases = $this->aliases[$this->alias];
             $all_aliases = array_keys($this->aliases);
             if ($diff = array_diff($group_aliases, $all_aliases)) {
                 WP_CLI::error("Group '{$this->alias}' contains one or more invalid aliases: " . implode(', ', $diff));
             }
             $this->run_alias_group($group_aliases);
             exit;
         } else {
             $this->set_alias($this->alias);
         }
     }
     if (empty($this->arguments)) {
         $this->arguments[] = 'help';
     }
     // Protect 'cli info' from most of the runtime,
     // except when the command will be run over SSH
     if ('cli' === $this->arguments[0] && !empty($this->arguments[1]) && 'info' === $this->arguments[1] && !$this->config['ssh']) {
         $this->_run_command();
         exit;
     }
     // Protect 'package' commands from most of the runtime too,
     // except when the command will be run over SSH
     if ('package' === $this->arguments[0] && !$this->config['ssh']) {
         $this->_run_command();
         exit;
     }
     // Load bundled commands early, so that they're forced to use the same
     // APIs as non-bundled commands.
     Utils\load_all_commands();
     $skip_packages = \WP_CLI::get_runner()->config['skip-packages'];
     if (true === $skip_packages) {
         WP_CLI::debug('Skipped loading packages.', 'bootstrap');
     } else {
         $package_autoload = $this->get_packages_dir_path() . 'vendor/autoload.php';
         if (file_exists($package_autoload)) {
             WP_CLI::debug('Loading packages from: ' . $package_autoload, 'bootstrap');
             require_once $package_autoload;
         } else {
             WP_CLI::debug('No package autoload found to load.', 'bootstrap');
         }
     }
     if (isset($this->config['http']) && !class_exists('\\WP_REST_CLI\\Runner')) {
         WP_CLI::error("RESTful WP-CLI needs to be installed. Try 'wp package install wp-cli/restful'.");
     }
     if (isset($this->config['require'])) {
         foreach ($this->config['require'] as $path) {
             if (!file_exists($path)) {
                 $context = '';
                 foreach (array('global', 'project', 'runtime') as $scope) {
                     if (in_array($path, $this->_required_files[$scope])) {
                         switch ($scope) {
                             case 'global':
                                 $context = ' (from global ' . basename($this->global_config_path) . ')';
                                 break;
                             case 'project':
                                 $context = ' (from project\'s ' . basename($this->project_config_path) . ')';
                                 break;
                             case 'runtime':
                                 $context = ' (from runtime argument)';
                                 break;
                         }
                         break;
                     }
                 }
                 WP_CLI::error(sprintf("Required file '%s' doesn't exist%s.", basename($path), $context));
             }
             Utils\load_file($path);
             WP_CLI::debug('Required file from config: ' . $path, 'bootstrap');
         }
     }
     if ($this->config['ssh']) {
         $this->run_ssh_command($this->config['ssh']);
         return;
     }
     // Show synopsis if it's a composite command.
     $r = $this->find_command_to_run($this->arguments);
     if (is_array($r)) {
         list($command) = $r;
         if ($command->can_have_subcommands()) {
             $command->show_usage();
             exit;
         }
     }
     // Handle --path parameter
     self::set_wp_root($this->find_wp_root());
     // First try at showing man page
     if (!empty($this->arguments[0]) && 'help' === $this->arguments[0] && (!$this->wp_exists() || !Utils\locate_wp_config() || !empty($this->arguments[1]) && !empty($this->arguments[2]) && 'core' === $this->arguments[1] && in_array($this->arguments[2], array('config', 'install', 'multisite-install', 'verify-checksums', 'version')))) {
         $this->auto_check_update();
         $this->_run_command();
     }
     // Handle --url parameter
     $url = self::guess_url($this->config);
     if ($url) {
         \WP_CLI::set_url($url);
     }
     $this->do_early_invoke('before_wp_load');
     $this->check_wp_version();
     if ($this->cmd_starts_with(array('core', 'config'))) {
         $this->_run_command();
         exit;
     }
     if (!Utils\locate_wp_config()) {
         WP_CLI::error("'wp-config.php' not found.\n" . "Either create one manually or use `wp core config`.");
     }
     if ($this->cmd_starts_with(array('db')) && !$this->cmd_starts_with(array('db', 'tables'))) {
         eval($this->get_wp_config_code());
         $this->_run_command();
         exit;
     }
     if ($this->cmd_starts_with(array('core', 'is-installed')) || $this->cmd_starts_with(array('core', 'update-db'))) {
         define('WP_INSTALLING', true);
     }
     if (count($this->arguments) >= 2 && $this->arguments[0] == 'core' && in_array($this->arguments[1], array('install', 'multisite-install'))) {
         define('WP_INSTALLING', true);
         // We really need a URL here
         if (!isset($_SERVER['HTTP_HOST'])) {
             $url = 'http://example.com';
             \WP_CLI::set_url($url);
         }
         if ('multisite-install' == $this->arguments[1]) {
             // need to fake some globals to skip the checks in wp-includes/ms-settings.php
             $url_parts = Utils\parse_url($url);
             self::fake_current_site_blog($url_parts);
             if (!defined('COOKIEHASH')) {
                 define('COOKIEHASH', md5($url_parts['host']));
             }
         }
     }
     if ($this->cmd_starts_with(array('import'))) {
         define('WP_LOAD_IMPORTERS', true);
         define('WP_IMPORTING', true);
     }
     if ($this->cmd_starts_with(array('cron', 'event', 'run'))) {
         define('DOING_CRON', true);
     }
     $this->load_wordpress();
     $this->_run_command();
 }