drush.inc

  1. 8.0.x includes/drush.inc
  2. 6.x includes/drush.inc
  3. 7.x includes/drush.inc
  4. 3.x includes/drush.inc
  5. 4.x includes/drush.inc
  6. 5.x includes/drush.inc
  7. master includes/drush.inc

The drush API implementation and helpers.

Functions

Namesort descending Description
dlm Run print_r on a variable and log the output.
drush_backend_packet_log Backend command callback. Add a log message to the log history.
drush_call_user_func_array Mimic cufa but still call function directly. See http://drupal.org/node/329012#comment-1260752
drush_choice Ask the user to select an item from a list. From a provided associative array, drush_choice will display all of the questions, numbered from 1 to N, and return the item the user selected. "0" is always cancel; entering a blank line is also…
drush_choice_multiple Ask the user to select multiple items from a list. This is a wrapper around drush_choice, that repeats the selection process, allowing users to toggle a number of items in a list. The number of values that can be constrained by both min and max: the…
drush_clear_error Clear error context.
drush_cmp_error Check if a specific error status has been set.
drush_complete_cache_clear Clears completion caches.
drush_confirm Asks the user a basic yes/no question.
drush_die Exits with a message. In general, you should use drush_set_error() instead of this function. That lets drush proceed with other tasks. TODO: Exit with a correct status code.
drush_download_file Download a file using wget, curl or file_get_contents, or via download cache.
drush_download_file_name Helper function to determine name of cached file.
drush_do_command_redispatch Redispatch the specified command using the same options that were passed to this invocation of drush.
drush_do_multiple_command Used by functions that operate on lists of sites, moving information from the source to the destination. Currenlty this includes 'drush rsync' and 'drush sql sync'.
drush_errors_off Turn PHP error handling off.
drush_errors_on Turn PHP error handling on.
drush_export_info Generate code friendly to the Drupal .info format from a structured array. Mostly copied from http://drupalcode.org/viewvc/drupal/contributions/modules/features/featu....
drush_export_ini Generate an .ini file. used by archive-dump."
drush_file_is_tarball Check whether a file is a supported tarball.
drush_flatten_array Convert a nested array into a flat array. Thows away the array keys, returning only the values.
drush_format_size
drush_generate_password Generate a random alphanumeric password. Copied from user.module.
drush_get_class Provide a version-specific class instance.
drush_get_error Return the current error handling status
drush_get_error_log Return the current list of errors that have occurred.
drush_get_global_options Get the available global options. Used by help command. Command files may modify this list using hook_drush_help_alter().
drush_get_log Retrieve the log messages from the log history
drush_include Include a file, selecting a version specific file if available.
drush_lib_fetch Download and extract a tarball to the lib directory.
drush_log Add a log message to the log history.
drush_map_assoc Form an associative array from a linear array.
drush_memory_limit Get the PHP memory_limit value in bytes.
drush_mime_content_type Determines the MIME content type of the specified file.
drush_op Calls a given function, passing through all arguments unchanged.
drush_pipe_output Display the pipe output for the current request.
drush_preflight_command_dispatch Handle any command preprocessing that may need to be done, including potentially redispatching the command immediately (e.g. for remote commands).
drush_print_timers
drush_prompt Prompt the user for input
drush_set_error Set an error code for the error handling system.
drush_tarball_extract Extract a tarball.
drush_unset_recursive Unset the named key anywhere in the provided data structure.
drush_user_abort Exit due to user declining a confirmation prompt.
drush_version_control_reserved_files Return a list of VCSs reserved files and directories.
_convert_csv_to_array Convert a csv string, or an array of items which may contain csv strings, into an array of items.
_drush_download_file Download a file using wget, curl or file_get_contents. Does not use download cache.
_drush_is_drush_shebang_line Check to see if the provided line is a "#!/usr/bin/env drush" "shebang" script line.
_drush_is_drush_shebang_script Check to see if the provided script file is a "#!/usr/bin/env drush" "shebang" script line.
_drush_is_url Check whether the given path is just a url or a local path
_drush_log_drupal_messages Turn drupal_set_message errors into drush_log errors
_drush_print_log Display the log message
_drush_should_remove_command_arg Determine whether or not an argument should be removed from the DRUSH_COMMAND_ARGS context. This method is used when a Drush command has set the 'strict-option-handling' flag indicating that it will pass through all commandline arguments…

Constants

Namesort descending Description
DRUSH_APPLICATION_ERROR The command that was executed resulted in an application error, The most commom causes for this is invalid PHP or a broken SSH pipe when using drush_backend_invoke in a distributed manner.
DRUSH_CACHE_LIFETIME_DEFAULT Default amount of time, in seconds, to cache downloads via drush_download_file(). One day is 86400 seconds.
DRUSH_DRUPAL_KILOBYTE The number of bytes in a kilobyte. Copied from Drupal.
DRUSH_FRAMEWORK_ERROR The command could not be completed because the framework has specified errors that have occured.
DRUSH_SUCCESS The command completed successfully.

File

includes/drush.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * The drush API implementation and helpers.
  5. */
  6. /**
  7. * @name Error status definitions
  8. * @{
  9. * Error code definitions for interpreting the current error status.
  10. * @see drush_set_error(), drush_get_error(), drush_get_error_log(), drush_cmp_error()
  11. */
  12. /** The command completed successfully. */
  13. define('DRUSH_SUCCESS', 0);
  14. /** The command could not be completed because the framework has specified errors that have occured. */
  15. define('DRUSH_FRAMEWORK_ERROR', 1);
  16. /** The command that was executed resulted in an application error,
  17. The most commom causes for this is invalid PHP or a broken SSH
  18. pipe when using drush_backend_invoke in a distributed manner. */
  19. define('DRUSH_APPLICATION_ERROR', 255);
  20. /**
  21. * @} End of "name Error status defintions".
  22. */
  23. /**
  24. * The number of bytes in a kilobyte. Copied from Drupal.
  25. */
  26. define('DRUSH_DRUPAL_KILOBYTE', 1024);
  27. /**
  28. * Default amount of time, in seconds, to cache downloads via
  29. * drush_download_file(). One day is 86400 seconds.
  30. */
  31. define('DRUSH_CACHE_LIFETIME_DEFAULT', 86400);
  32. /**
  33. * Include a file, selecting a version specific file if available.
  34. *
  35. * For example, if you pass the path "/var/drush" and the name
  36. * "update" when bootstrapped on a Drupal 6 site it will first check for
  37. * the presence of "/var/drush/update_6.inc" in include it if exists. If this
  38. * file does NOT exist it will proceed and check for "/var/drush/update.inc".
  39. * If neither file exists, it will return FALSE.
  40. *
  41. * @param $path
  42. * The path you want to search.
  43. * @param $name
  44. * The file base name you want to include (not including a version suffix
  45. * or extension).
  46. * @param $version
  47. * The version suffix you want to include (could be specific to the software
  48. * or platform your are connecting to) - defaults to the current Drupal core
  49. * major version.
  50. * @param $extension
  51. * The extension - defaults to ".inc".
  52. *
  53. * @return
  54. * TRUE if the file was found and included.
  55. */
  56. function drush_include($path, $name, $version = NULL, $extension = 'inc') {
  57. $version = ($version) ? $version : drush_drupal_major_version();
  58. $file = sprintf("%s/%s_%s.%s", $path, str_replace('-', '_', $name), $version, $extension);
  59. if (file_exists($file)) {
  60. //drush_log(dt('Including version specific file : @file', array('@file' => $file)));
  61. include_once($file);
  62. return TRUE;
  63. }
  64. $file = sprintf("%s/%s.%s", $path, str_replace('-', '_', $name), $extension);
  65. if (file_exists($file)) {
  66. //drush_log(dt('Including non-version specific file : @file', array('@file' => $file)));
  67. include_once($file);
  68. return TRUE;
  69. }
  70. }
  71. /**
  72. * Provide a version-specific class instance.
  73. *
  74. * @param $class_name
  75. * The name of the class to instantiate. Appends the Drupal
  76. * major version number to the end of the class name before instantiation.
  77. * @param $constructor_args
  78. * An array of arguments to pass to the class constructor.
  79. * @param $class_dir
  80. * The directory where the commandfile stores its classes.
  81. * For Drush Core, using the default value will search the
  82. * 'classes' directory in the Drupal root. If the class file(s) are
  83. * stored in the same directory as your commandfile, pass
  84. * dirname(__FILE__) here.
  85. *
  86. * Example wrapper class to instantiate a widget, called with the
  87. * arguments for the WIDGET_CLASS constructor:
  88. *
  89. * function drush_WIDGET_CLASS_get_class($widgetName, $widgetStyle) {
  90. * retrun drush_get_class('Widget_Class', func_get_args()));
  91. * }
  92. */
  93. function drush_get_class($class_name, $constructor_args, $class_dir = NULL) {
  94. if (!isset($class_dir)) {
  95. $class_dir = DRUSH_BASE_PATH . '/classes';
  96. }
  97. $version = drush_drupal_major_version();
  98. drush_include($class_dir, $class_name, $version, 'php');
  99. $version_specific_class_name = $class_name . $version;
  100. if (class_exists($version_specific_class_name)) {
  101. $reflectionClass = new ReflectionClass($version_specific_class_name);
  102. return $reflectionClass->newInstanceArgs($constructor_args);
  103. }
  104. else {
  105. return drush_set_error('DRUSH_GET_CLASS_ERROR', dt('Drupal %d not supported!', array('%d' => $version)));
  106. }
  107. }
  108. /**
  109. * Generate an .ini file. used by archive-dump."
  110. *
  111. * @param array $ini
  112. * A two dimensional associative array where top level are sections and
  113. * second level are key => value pairs.
  114. *
  115. * @return string
  116. * .ini formatted text.
  117. */
  118. function drush_export_ini($ini) {
  119. $output = '';
  120. foreach ($ini as $section => $pairs) {
  121. if ($section) {
  122. $output .= "[$section]\n";
  123. }
  124. foreach ($pairs as $k => $v) {
  125. if ($v) {
  126. $output .= "$k = \"$v\"\n";
  127. }
  128. }
  129. }
  130. return $output;
  131. }
  132. /**
  133. * Generate code friendly to the Drupal .info format from a structured array.
  134. * Mostly copied from http://drupalcode.org/viewvc/drupal/contributions/modules/features/features.export.inc.
  135. *
  136. * @param $info
  137. * An array or single value to put in a module's .info file.
  138. *
  139. * @param boolean $integer_keys
  140. * Use integer in keys.
  141. *
  142. * @param $parents
  143. * Array of parent keys (internal use only).
  144. *
  145. * @return
  146. * A code string ready to be written to a module's .info file.
  147. */
  148. function drush_export_info($info, $integer_keys = FALSE, $parents = array()) {
  149. $output = '';
  150. if (is_array($info)) {
  151. foreach ($info as $k => $v) {
  152. $child = $parents;
  153. $child[] = $k;
  154. $output .= drush_export_info($v, $integer_keys, $child);
  155. }
  156. }
  157. else if (!empty($info) && count($parents)) {
  158. $line = array_shift($parents);
  159. foreach ($parents as $key) {
  160. $line .= (!$integer_keys && is_numeric($key)) ? "[]" : "[{$key}]";
  161. }
  162. $line .= " = \"{$info}\"\n";
  163. return $line;
  164. }
  165. return $output;
  166. }
  167. /**
  168. * Convert a csv string, or an array of items which
  169. * may contain csv strings, into an array of items.
  170. *
  171. * @param $args
  172. * A simple csv string; e.g. 'a,b,c'
  173. * or a simple list of items; e.g. array('a','b','c')
  174. * or some combination; e.g. array('a,b','c') or array('a,','b,','c,')
  175. *
  176. * @returns array
  177. * A simple list of items (e.g. array('a','b','c')
  178. */
  179. function _convert_csv_to_array($args) {
  180. //
  181. // Step 1: implode(',',$args) converts from, say, array('a,','b,','c,') to 'a,,b,,c,'
  182. // Step 2: explode(',', ...) converts to array('a','','b','','c','')
  183. // Step 3: array_filter(...) removes the empty items
  184. // Step 4: array_map(...) trims extra whitespace from each item
  185. // (handles csv strings with extra whitespace, e.g. 'a, b, c')
  186. //
  187. return array_map('trim', array_filter(explode(',', is_array($args) ? implode(',',$args) : $args)));
  188. }
  189. /**
  190. * Convert a nested array into a flat array. Thows away
  191. * the array keys, returning only the values.
  192. *
  193. * @param $args
  194. * An array that may potentially be nested.
  195. * e.g. array('a', array('b', 'c'))
  196. *
  197. * @returns array
  198. * A simple list of items (e.g. array('a','b','c')
  199. */
  200. function drush_flatten_array($a) {
  201. $result = array();
  202. if (!is_array($a)) {
  203. return array($a);
  204. }
  205. foreach ($a as $value) {
  206. $result = array_merge($result, drush_flatten_array($value));
  207. }
  208. return $result;
  209. }
  210. /**
  211. * Get the available global options. Used by help command. Command files may
  212. * modify this list using hook_drush_help_alter().
  213. *
  214. * @param boolean $brief
  215. * Return a reduced set of important options. Used by help command.
  216. *
  217. * @return
  218. * An associative array containing the option definition as the key,
  219. * and a descriptive array for each of the available options. The array
  220. * elements for each item are:
  221. *
  222. * - short-form: The shortcut form for specifying the key on the commandline.
  223. * - context: The drush context where the value of this item is cached. Used
  224. * by backend invoke to propagate values set in code.
  225. * - never-post: If TRUE, backend invoke will never POST this item's value
  226. * on STDIN; it will always be sent as a commandline option.
  227. * - never-propagate: If TRUE, backend invoke will never pass this item on
  228. * to the subcommand being executed.
  229. * - local-context-only: Backend invoke will only pass this value on for local calls.
  230. * - merge: For options such as $options['shell-aliases'] that consist of an array
  231. * of items, make a merged array that contains all of the values specified for
  232. * all of the contexts (config files) where the option is defined. The value is stored in
  233. * the specified 'context', or in a context named after the option itself if the
  234. * context flag is not specified.
  235. * IMPORTANT: When the merge flag is used, the option value must be obtained via
  236. * drush_get_context('option') rather than drush_get_option('option').
  237. * - merge-pathlist: For options such as --include and --config, make a merged list
  238. * of options from all contexts; works like the 'merge' flag, but also handles string
  239. * values separated by the PATH_SEPARATOR.
  240. * - merge-associative: Like 'merge-pathlist', but key values are preserved.
  241. * - propagate-cli-value: Used to tell backend invoke to include the value for
  242. * this item as specified on the cli. This can either override 'context'
  243. * (e.g., propagate --include from cli value instead of DRUSH_INCLUDE context),
  244. * or for an independent global setting (e.g. --user)
  245. * - description: The help text for this item. displayed by `drush help`.
  246. */
  247. function drush_get_global_options($brief = FALSE) {
  248. $options['root'] = array('short-form' => 'r', 'short-has-arg' => TRUE, 'never-post' => TRUE, 'description' => "Drupal root directory to use (default: current directory).", 'example-value' => 'path');
  249. $options['uri'] = array('short-form' => 'l', 'short-has-arg' => TRUE, 'never-post' => TRUE, 'description' => 'URI of the drupal site to use (only needed in multisite environments or when running on an alternate port).', 'example-value' => 'http://example.com:8888');
  250. $options['verbose'] = array('short-form' => 'v', 'context' => 'DRUSH_VERBOSE', 'description' => 'Display extra information about the command.');
  251. $options['debug'] = array('short-form' => 'd', 'context' => 'DRUSH_DEBUG', 'description' => 'Display even more information, including internal messages.');
  252. $options['yes'] = array('short-form' => 'y', 'context' => 'DRUSH_AFFIRMATIVE', 'description' => "Assume 'yes' as answer to all prompts.");
  253. $options['no'] = array('short-form' => 'n', 'context' => 'DRUSH_NEGATIVE', 'description' => "Assume 'no' as answer to all prompts.");
  254. $options['simulate'] = array('short-form' => 's', 'context' => 'DRUSH_SIMULATE', 'never-propagate' => TRUE, 'description' => "Simulate all relevant actions (don't actually change the system).");
  255. $options['pipe'] = array('short-form' => 'p', 'hidden' => TRUE, 'description' => "Emit a compact representation of the command for scripting.");
  256. $options['help'] = array('short-form' => 'h', 'description' => "This help system.");
  257. if (!$brief) {
  258. $options['version'] = array('description' => "Show drush version.");
  259. $options['php'] = array('description' => "The absolute path to your PHP intepreter, if not 'php' in the path.", 'example-value' => '/path/to/file', 'never-propagate' => TRUE);
  260. $options['interactive'] = array('short-form' => 'ia', 'description' => "Force interactive mode for commands run on multiple targets (e.g. `drush @site1,@site2 cc --ia`).");
  261. $options['quiet'] = array('short-form' => 'q', 'description' => 'Suppress non-error messages.');
  262. $options['include'] = array('short-form' => 'i', 'short-has-arg' => TRUE, 'context' => 'DRUSH_INCLUDE', 'local-context-only' => TRUE, 'never-post' => TRUE, 'propagate-cli-value' => TRUE, 'merge-pathlist' => TRUE, 'description' => "A list of additional directory paths to search for drush commands.", 'example-value' => '/path/dir');
  263. $options['config'] = array('short-form' => 'c', 'short-has-arg' => TRUE, 'context' => 'DRUSH_CONFIG', 'local-context-only' => TRUE, 'merge-pathlist' => TRUE, 'description' => "Specify an additional config file to load. See example.drushrc.php.", 'example-value' => '/path/file');
  264. $options['user'] = array('short-form' => 'u', 'short-has-arg' => TRUE, 'propagate-cli-value' => TRUE, 'description' => "Specify a Drupal user to login with. May be a name or a number.", 'example-value' => 'name_or_number');
  265. $options['backend'] = array('short-form' => 'b', 'never-propagate' => TRUE, 'description' => "Hide all output and return structured data.");
  266. $options['choice'] = array('description' => "Provide an answer to a multiple-choice prompt.", 'example-value' => 'number');
  267. $options['variables'] = array('description' => "Comma delimited list of name=value pairs. These values take precedence even over settings.php variable overrides.", 'example-value' => 'foo=bar,baz=yaz');
  268. $options['search-depth'] = array('description' => "Control the depth that drush will search for alias files.", 'example-value' => 'number');
  269. $options['ignored-modules'] = array('description' => "Exclude some modules from consideration when searching for drush command files.", 'example-value' => 'token,views');
  270. $options['no-label'] = array('description' => "Remove the site label that drush includes in multi-site command output (e.g. `drush @site1,@site2 status`).");
  271. $options['label-separator'] = array('description' => "Specify the separator to use in multi-site command output (e.g. `drush @sites pm-list --label-separator=',' --format=csv`).");
  272. $options['nocolor'] = array('context' => 'DRUSH_NOCOLOR', 'propagate-cli-value' => TRUE, 'description' => "Suppress color highlighting on log messages.");
  273. $options['show-passwords'] = array('description' => "Show database passwords in commands that display connection information.");
  274. $options['show-invoke'] = array('description' => "Show all function names which could have been called for the current command. See drush_invoke().");
  275. $options['watchdog'] = array('description' => "Control logging of Drupal's watchdog() to drush log. Recognized values are 'log', 'print', 'disabled'. Defaults to log. 'print' shows calls to admin but does not add them to the log.", 'example-value' => 'print');
  276. $options['cache-default-class'] = array('description' => "A cache backend class that implements DrushCacheInterface. Defaults to DrushJSONCache.", 'example-value' => 'DrushJSONCache');
  277. $options['cache-class-<bin>'] = array('description' => "A cache backend class that implements DrushCacheInterface to use for a specific cache bin.", 'example-value' => 'className');
  278. $options['early'] = array('description' => "Include a file (with relative or full path) and call the drush_early_hook() function (where 'hook' is the filename). The function is called pre-bootstrap and offers an opportunity to alter the drush bootstrap environment or process (returning FALSE from the function will continue the bootstrap), or return output very rapidly (e.g. from caches). See includes/complete.inc for an example.");
  279. $options['alias-path'] = array('context' => 'ALIAS_PATH', 'local-context-only' => TRUE, 'merge-pathlist' => TRUE, 'propagate-cli-value' => TRUE, 'description' => "Specifies the list of paths where drush will search for alias files.", 'example-value' => '/path/alias1:/path/alias2');
  280. $options['backup-location'] = array('description' => "Specifies the directory where drush will store backups.", 'example-value' => '/path/to/dir');
  281. $options['confirm-rollback'] = array('description' => 'Wait for confirmation before doing a rollback when something goes wrong.');
  282. $options['complete-debug'] = array('hidden' => TRUE, 'description' => "Turn on debug mode forf completion code");
  283. $options['php-options'] = array('description' => "Options to pass to `php` when running drush. Only effective when using the `drush` script.", 'never-propagate' => TRUE, 'example-value' => '-d error_reporting="E_ALL"');
  284. $options['deferred-sanitization'] = array('hidden' => TRUE, 'description' => "Defer calculating the sanitization operations until after the database has been copied. This is done automatically if the source database is remote.");
  285. $options['remote-host'] = array('hidden' => TRUE, 'description' => 'Remote site to execute drush command on. Managed by site alias.');
  286. $options['remote-user'] = array('hidden' => TRUE, 'description' => 'User account to use with a remote drush command. Managed by site alias.');
  287. $options['remote-os'] = array('hidden' => TRUE, 'description' => 'The operating system used on the remote host. Managed by site alias.');
  288. $options['site-list'] = array('hidden' => TRUE, 'description' => 'List of sites to run commands on. Managed by site alias.');
  289. $options['reserve-margin'] = array('hidden' => TRUE, 'description' => 'Remove columns from formatted opions. Managed by multi-site command handling.');
  290. $options['strict'] = array('hidden' => TRUE, 'description' => 'Check requirements more strictly / remove backwards-compatibility features for unit tests.');
  291. $options['command-specific'] = array('hidden' => TRUE, 'merge-associative' => TRUE, 'description' => 'Command-specific options.');
  292. $options['site-aliases'] = array('hidden' => TRUE, 'merge-associative' => TRUE, 'description' => 'List of site aliases.');
  293. $options['shell-aliases'] = array('hidden' => TRUE, 'merge' => TRUE, 'never-propagate' => TRUE, 'description' => 'List of shell aliases.');
  294. $options['path-aliases'] = array('hidden' => TRUE, 'never-propagate' => TRUE, 'description' => 'Path aliases from site alias.');
  295. $options['ssh-options'] = array('never-propagate' => TRUE, 'description' => 'A string of extra options that will be passed to the ssh command', 'example-value' => '-p 100');
  296. $options['editor'] = array('never-propagate' => TRUE, 'description' => 'A string of bash which launches user\'s preferred text editor. Defaults to ${VISUAL-${EDITOR-vi}}.', 'example-value' => 'vi');
  297. $options['db-url'] = array('hidden' => TRUE, 'description' => 'A Drupal 6 style database URL. Used by various commands.', 'example-value' => 'mysql://root:pass@127.0.0.1/db');
  298. $command = array(
  299. 'options' => $options,
  300. '#brief' => FALSE,
  301. ) + drush_command_defaults('global-options', 'global_options', __FILE__);
  302. drush_command_invoke_all_ref('drush_help_alter', $command);
  303. $options = $command['options'];
  304. }
  305. return $options;
  306. }
  307. /**
  308. * Exits with a message. In general, you should use drush_set_error() instead of
  309. * this function. That lets drush proceed with other tasks.
  310. * TODO: Exit with a correct status code.
  311. */
  312. function drush_die($msg = NULL, $status = NULL) {
  313. die($msg ? "drush: $msg\n" : '');
  314. }
  315. /**
  316. * Check to see if the provided line is a "#!/usr/bin/env drush"
  317. * "shebang" script line.
  318. */
  319. function _drush_is_drush_shebang_line($line) {
  320. return ((substr($line,0,2) == '#!') && (strstr($line, 'drush') !== FALSE));
  321. }
  322. /**
  323. * Check to see if the provided script file is a "#!/usr/bin/env drush"
  324. * "shebang" script line.
  325. */
  326. function _drush_is_drush_shebang_script($script_filename) {
  327. $result = FALSE;
  328. if (file_exists($script_filename)) {
  329. $fp = fopen($script_filename, "r");
  330. if ($fp !== FALSE) {
  331. $line = fgets($fp);
  332. $result = _drush_is_drush_shebang_line($line);
  333. fclose($fp);
  334. }
  335. }
  336. return $result;
  337. }
  338. /**
  339. * @defgroup userinput Get input from the user.
  340. * @{
  341. */
  342. /**
  343. * Asks the user a basic yes/no question.
  344. *
  345. * @param string $msg
  346. * The question to ask.
  347. * @param int $indent
  348. * The number of spaces to indent the message.
  349. *
  350. * @return bool
  351. * TRUE if the user enters "y" or FALSE if "n".
  352. */
  353. function drush_confirm($msg, $indent = 0) {
  354. drush_print_prompt((string)$msg . " (y/n): ", $indent);
  355. // Automatically accept confirmations if the --yes argument was supplied.
  356. if (drush_get_context('DRUSH_AFFIRMATIVE')) {
  357. drush_print("y");
  358. return TRUE;
  359. }
  360. // Automatically cancel confirmations if the --no argument was supplied.
  361. elseif (drush_get_context('DRUSH_NEGATIVE')) {
  362. drush_print("n");
  363. return FALSE;
  364. }
  365. // See http://drupal.org/node/499758 before changing this.
  366. $stdin = fopen("php://stdin","r");
  367. while ($line = fgets($stdin)) {
  368. $line = trim($line);
  369. if ($line == 'y') {
  370. return TRUE;
  371. }
  372. if ($line == 'n') {
  373. return FALSE;
  374. }
  375. drush_print_prompt((string)$msg . " (y/n): ", $indent);
  376. }
  377. }
  378. /**
  379. * Ask the user to select an item from a list.
  380. * From a provided associative array, drush_choice will
  381. * display all of the questions, numbered from 1 to N,
  382. * and return the item the user selected. "0" is always
  383. * cancel; entering a blank line is also interpreted
  384. * as cancelling.
  385. *
  386. * @param $options
  387. * A list of questions to display to the user. The
  388. * KEYS of the array are the result codes to return to the
  389. * caller; the VALUES are the messages to display on
  390. * each line. Special keys of the form '-- something --' can be
  391. * provided as separator between choices groups. Separator keys
  392. * don't alter the numbering.
  393. * @param $prompt
  394. * The message to display to the user prompting for input.
  395. * @param $label
  396. * Controls the display of each line. Defaults to
  397. * '!value', which displays the value of each item
  398. * in the $options array to the user. Use '!key' to
  399. * display the key instead. In some instances, it may
  400. * be useful to display both the key and the value; for
  401. * example, if the key is a user id and the value is the
  402. * user name, use '!value (uid=!key)'.
  403. */
  404. function drush_choice($options, $prompt = 'Enter a number.', $label = '!value', $widths = array()) {
  405. drush_print(dt($prompt));
  406. // Preflight so that all rows will be padded out to the same number of columns
  407. $array_pad = 0;
  408. foreach ($options as $key => $option) {
  409. if (is_array($option) && (count($option) > $array_pad)) {
  410. $array_pad = count($option);
  411. }
  412. }
  413. $rows[] = array_pad(array('[0]', ':', 'Cancel'), $array_pad + 2, '');
  414. $selection_number = 0;
  415. foreach ($options as $key => $option) {
  416. if ((substr($key, 0, 3) == '-- ') && (substr($key, -3) == ' --')) {
  417. $rows[] = array_pad(array('', '', $option), $array_pad + 2, '');
  418. }
  419. else {
  420. $selection_number++;
  421. $row = array("[$selection_number]", ':');
  422. if (is_array($option)) {
  423. $row = array_merge($row, $option);
  424. }
  425. else {
  426. $row[] = dt($label, array('!number' => $selection_number, '!key' => $key, '!value' => $option));
  427. }
  428. $rows[] = $row;
  429. $selection_list[$selection_number] = $key;
  430. }
  431. }
  432. drush_print_table($rows, FALSE, $widths);
  433. drush_print_pipe(array_keys($options));
  434. // If the user specified --choice, then make an
  435. // automatic selection. Cancel if the choice is
  436. // not an available option.
  437. if (($choice = drush_get_option('choice', FALSE)) !== FALSE) {
  438. // First check to see if $choice is one of the symbolic options
  439. if (array_key_exists($choice, $options)) {
  440. return $choice;
  441. }
  442. // Next handle numeric selections
  443. elseif (array_key_exists($choice, $selection_list)) {
  444. return $selection_list[$choice];
  445. }
  446. return FALSE;
  447. }
  448. // If the user specified --no, then cancel; also avoid
  449. // getting hung up waiting for user input in --pipe and
  450. // backend modes. If none of these apply, then wait,
  451. // for user input and return the selected result.
  452. if (!drush_get_context('DRUSH_NEGATIVE') && !drush_get_context('DRUSH_AFFIRMATIVE') && !drush_get_context('DRUSH_PIPE')) {
  453. while ($line = trim(fgets(STDIN))) {
  454. if (array_key_exists($line, $selection_list)) {
  455. return $selection_list[$line];
  456. }
  457. }
  458. }
  459. // We will allow --yes to confirm input if there is only
  460. // one choice; otherwise, --yes will cancel to avoid ambiguity
  461. if (drush_get_context('DRUSH_AFFIRMATIVE') && (count($options) == 1)) {
  462. return $selection_list[1];
  463. }
  464. drush_print(dt('Cancelled'));
  465. return FALSE;
  466. }
  467. /**
  468. * Ask the user to select multiple items from a list.
  469. * This is a wrapper around drush_choice, that repeats the selection process,
  470. * allowing users to toggle a number of items in a list. The number of values
  471. * that can be constrained by both min and max: the user will only be allowed
  472. * finalize selection once the minimum number has been selected, and the oldest
  473. * selected value will "drop off" the list, if they exceed the maximum number.
  474. *
  475. * @param $options
  476. * Same as drush_choice() (see above).
  477. * @param $defaults
  478. * This can take 3 forms:
  479. * - FALSE: (Default) All options are unselected by default.
  480. * - TRUE: All options are selected by default.
  481. * - Array of $options keys to be selected by default.
  482. * @param $prompt
  483. * Same as drush_choice() (see above).
  484. * @param $label
  485. * Same as drush_choice() (see above).
  486. * @param $mark
  487. * Controls how selected values are marked. Defaults to '!value (selected)'.
  488. * @param $min
  489. * Constraint on minimum number of selections. Defaults to zero. When fewer
  490. * options than this are selected, no final options will be available.
  491. * @param $max
  492. * Constraint on minimum number of selections. Defaults to NULL (unlimited).
  493. * If the a new selection causes this value to be exceeded, the oldest
  494. * previously selected value is automatically unselected.
  495. * @param $final_options
  496. * An array of additional options in the same format as $options.
  497. * When the minimum number of selections is met, this array is merged into the
  498. * array of options. If the user selects one of these values and the
  499. * selection process will complete (the key for the final option is included
  500. * in the return value). If this is an empty array (default), then a built in
  501. * final option of "Done" will be added to the available options (in this case
  502. * no additional keys are added to the return value).
  503. */
  504. function drush_choice_multiple($options, $defaults = FALSE, $prompt = 'Select some numbers.', $label = '!value', $mark = '!value (selected)', $min = 0, $max = NULL, $final_options = array()) {
  505. $selections = array();
  506. // Load default selections.
  507. if (is_array($defaults)) {
  508. $selections = $defaults;
  509. }
  510. elseif ($defaults === TRUE) {
  511. $selections = array_keys($options);
  512. }
  513. $complete = FALSE;
  514. $final_builtin = array();
  515. if (empty($final_options)) {
  516. $final_builtin['done'] = dt('Done');
  517. }
  518. $final_options_keys = array_keys($final_options);
  519. while (TRUE) {
  520. $current_options = $options;
  521. // Mark selections.
  522. foreach ($selections as $selection) {
  523. $current_options[$selection] = dt($mark, array('!key' => $selection, '!value' => $options[$selection]));
  524. }
  525. // Add final options, if the minimum number of selections has been reached.
  526. if (count($selections) >= $min) {
  527. $current_options = array_merge($current_options, $final_options, $final_builtin);
  528. }
  529. $toggle = drush_choice($current_options, $prompt, $label);
  530. if ($toggle === FALSE) {
  531. return FALSE;
  532. }
  533. // Don't include the built in final option in the return value.
  534. if (count($selections) >= $min && empty($final_options) && $toggle == 'done') {
  535. return $selections;
  536. }
  537. // Toggle the selected value.
  538. $item = array_search($toggle, $selections);
  539. if ($item === FALSE) {
  540. array_unshift($selections, $toggle);
  541. }
  542. else {
  543. unset($selections[$item]);
  544. }
  545. // If the user selected one of the final options, return.
  546. if (count($selections) >= $min && in_array($toggle, $final_options_keys)) {
  547. return $selections;
  548. }
  549. // If the user selected too many options, drop the oldest selection.
  550. if (isset($max) && count($selections) > $max) {
  551. array_pop($selections);
  552. }
  553. }
  554. }
  555. /**
  556. * Prompt the user for input
  557. *
  558. * The input can be anything that fits on a single line (not only y/n),
  559. * so we can't use drush_confirm()
  560. *
  561. * @param $prompt
  562. * The text which is displayed to the user.
  563. * @param $default
  564. * The default value of the input.
  565. * @param $required
  566. * If TRUE, user may continue even when no value is in the input.
  567. * @param $password
  568. * If TRUE, surpress printing of the input.
  569. *
  570. * @see drush_confirm()
  571. */
  572. function drush_prompt($prompt, $default = NULL, $required = TRUE, $password = FALSE) {
  573. if (isset($default)) {
  574. $prompt .= " [" . $default . "]";
  575. }
  576. $prompt .= ": ";
  577. drush_print_prompt($prompt);
  578. if (drush_get_context('DRUSH_AFFIRMATIVE')) {
  579. return $default;
  580. }
  581. $stdin = fopen('php://stdin', 'r');
  582. if ($password) drush_shell_exec("stty -echo");
  583. stream_set_blocking($stdin, TRUE);
  584. while (($line = fgets($stdin)) !== FALSE) {
  585. $line = trim($line);
  586. if ($line === "") {
  587. $line = $default;
  588. }
  589. if ($line || !$required) {
  590. break;
  591. }
  592. drush_print_prompt($prompt);
  593. }
  594. fclose($stdin);
  595. if ($password) {
  596. drush_shell_exec("stty echo");
  597. print "\n";
  598. }
  599. return $line;
  600. }
  601. /**
  602. * @} End of "defgroup userinput".
  603. */
  604. /**
  605. * Calls a given function, passing through all arguments unchanged.
  606. *
  607. * This should be used when calling possibly mutative or destructive functions
  608. * (e.g. unlink() and other file system functions) so that can be suppressed
  609. * if the simulation mode is enabled.
  610. *
  611. * Important: Call @see drush_op_system() to execute a shell command,
  612. * or @see drush_shell_exec() to execute a shell command and capture the
  613. * shell output.
  614. *
  615. * @param $function
  616. * The name of the function. Any additional arguments are passed along.
  617. * @return
  618. * The return value of the function, or TRUE if simulation mode is enabled.
  619. *
  620. */
  621. function drush_op($function) {
  622. $args_printed = array();
  623. $args = func_get_args();
  624. array_shift($args); // Skip function name
  625. foreach ($args as $arg) {
  626. $args_printed[] = is_scalar($arg) ? $arg : (is_array($arg) ? 'Array' : 'Object');
  627. }
  628. // Special checking for drush_op('system')
  629. if ($function == 'system') {
  630. drush_log(dt("Do not call drush_op('system'); use drush_op_system instead"), 'debug');
  631. }
  632. if (drush_get_context('DRUSH_VERBOSE') || drush_get_context('DRUSH_SIMULATE')) {
  633. drush_log(sprintf("Calling %s(%s)", $function, implode(", ", $args_printed)), 'debug');
  634. }
  635. if (drush_get_context('DRUSH_SIMULATE')) {
  636. return TRUE;
  637. }
  638. return drush_call_user_func_array($function, $args);
  639. }
  640. /**
  641. * Mimic cufa but still call function directly. See http://drupal.org/node/329012#comment-1260752
  642. */
  643. function drush_call_user_func_array($function, $args = array() ) {
  644. switch (count($args)) {
  645. case 0: return $function(); break;
  646. case 1: return $function($args[0]); break;
  647. case 2: return $function($args[0], $args[1]); break;
  648. case 3: return $function($args[0], $args[1], $args[2]); break;
  649. case 4: return $function($args[0], $args[1], $args[2], $args[3]); break;
  650. case 5: return $function($args[0], $args[1], $args[2], $args[3], $args[4]); break;
  651. case 6: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]); break;
  652. case 7: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]); break;
  653. case 8: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]); break;
  654. case 9: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7], $args[8]); break;
  655. default: return call_user_func_array($function,$args);
  656. }
  657. }
  658. /**
  659. * Download a file using wget, curl or file_get_contents, or via download cache.
  660. *
  661. * @param string $url
  662. * The url of the file to download.
  663. * @param string $destination
  664. * The name of the file to be saved, which may include the full path.
  665. * Optional, if omitted the filename will be extracted from the url and the
  666. * file downloaded to the current working directory (Drupal root if
  667. * bootstrapped).
  668. * @param integer $cache_duration
  669. * The acceptable age of a cached file. If cached file is too old, a fetch
  670. * will occur and cache will be updated. Optional, if ommitted the file will
  671. * be fetched directly.
  672. *
  673. * @return string
  674. * The path to the downloaded file, or FALSE if the file could not be
  675. * downloaded.
  676. */
  677. function drush_download_file($url, $destination = FALSE, $cache_duration = 0) {
  678. // Generate destination if omitted.
  679. if (!$destination) {
  680. $file = basename(current(explode('?', $url, 2)));
  681. $destination = getcwd() . '/' . basename($file);
  682. }
  683. // Simply copy local files to the destination
  684. if (!_drush_is_url($url)) {
  685. return copy($url, $destination) ? $destination : FALSE;
  686. }
  687. if (drush_get_option('cache') && $cache_duration !== 0 && $cache_file = drush_download_file_name($url)) {
  688. // Check for cached, unexpired file.
  689. if (file_exists($cache_file) && filectime($cache_file) > ($_SERVER['REQUEST_TIME']-$cache_duration)) {
  690. drush_log(dt('!name retrieved from cache.', array('!name' => $cache_file)));
  691. }
  692. else {
  693. if (_drush_download_file($url, $cache_file, TRUE)) {
  694. // Cache was set just by downloading file to right location.
  695. }
  696. elseif (file_exists($cache_file)) {
  697. drush_log(dt('!name retrieved from an expired cache since refresh failed.', array('!name' => $cache_file)), 'warning');
  698. }
  699. else {
  700. $cache_file = FALSE;
  701. }
  702. }
  703. if ($cache_file && copy($cache_file, $destination)) {
  704. // Copy cached file to the destination
  705. return $destination;
  706. }
  707. }
  708. elseif ($return = _drush_download_file($url, $destination)) {
  709. drush_register_file_for_deletion($return);
  710. return $return;
  711. }
  712. // Unable to retrieve from cache nor download.
  713. return FALSE;
  714. }
  715. /**
  716. * Helper function to determine name of cached file.
  717. */
  718. function drush_download_file_name($url) {
  719. if ($cache_dir = drush_directory_cache('download')) {
  720. $cache_name = str_replace(array(':', '/', '?', '='), '-', $url);
  721. return $cache_dir . "/" . $cache_name;
  722. }
  723. else {
  724. return FALSE;
  725. }
  726. }
  727. /**
  728. * Check whether the given path is just a url or a local path
  729. * @param string $url
  730. * @return boolean
  731. * TRUE if the path does not contain a schema:// part.
  732. */
  733. function _drush_is_url($url) {
  734. return parse_url($url, PHP_URL_SCHEME) !== NULL;
  735. }
  736. /**
  737. * Download a file using wget, curl or file_get_contents. Does not use download
  738. * cache.
  739. *
  740. * @param string $url
  741. * The url of the file to download.
  742. * @param string $destination
  743. * The name of the file to be saved, which may include the full path.
  744. * @param boolean $overwrite
  745. * Overwrite any file thats already at the destination.
  746. * @return string
  747. * The path to the downloaded file, or FALSE if the file could not be
  748. * downloaded.
  749. */
  750. function _drush_download_file($url, $destination, $overwrite = TRUE) {
  751. static $use_wget;
  752. if ($use_wget === NULL) {
  753. $use_wget = drush_shell_exec('wget --version');
  754. }
  755. $destination_tmp = drush_tempnam('download_file');
  756. if ($use_wget) {
  757. drush_shell_exec("wget -q --timeout=30 -O %s %s", $destination_tmp, $url);
  758. }
  759. else {
  760. drush_shell_exec("curl --fail -s -L --connect-timeout 30 -o %s %s", $destination_tmp, $url);
  761. }
  762. if (!drush_file_not_empty($destination_tmp) && $file = @file_get_contents($url)) {
  763. @file_put_contents($destination_tmp, $file);
  764. }
  765. if (!drush_file_not_empty($destination_tmp)) {
  766. // Download failed.
  767. return FALSE;
  768. }
  769. drush_move_dir($destination_tmp, $destination, $overwrite);
  770. return $destination;
  771. }
  772. /**
  773. * Determines the MIME content type of the specified file.
  774. *
  775. * The power of this function depends on whether the PHP installation
  776. * has either mime_content_type() or finfo installed -- if not, only tar,
  777. * gz, zip and bzip2 types can be detected.
  778. *
  779. * If mime type can't be obtained, an error will be set.
  780. *
  781. * @return mixed
  782. * The MIME content type of the file or FALSE.
  783. */
  784. function drush_mime_content_type($filename) {
  785. $content_type = FALSE;
  786. if (class_exists('finfo')) {
  787. $finfo = new finfo(FILEINFO_MIME_TYPE);
  788. $content_type = $finfo->file($filename);
  789. if ($content_type == 'application/octet-stream') {
  790. drush_log(dt('Mime type for !file is application/octet-stream.', array('!file' => $filename)), 'debug');
  791. $content_type = FALSE;
  792. }
  793. }
  794. // If apache is configured in such a way that all files are considered
  795. // octet-stream (e.g with mod_mime_magic and an http conf that's serving all
  796. // archives as octet-stream for other reasons) we'll detect mime types on our
  797. // own by examing the file's magic header bytes.
  798. if (!$content_type) {
  799. drush_log(dt('Examining !file headers.', array('!file' => $filename)), 'debug');
  800. if ($file = fopen($filename, 'rb')) {
  801. $first = fread($file, 2);
  802. fclose($file);
  803. if ($first !== FALSE) {
  804. // Interpret the two bytes as a little endian 16-bit unsigned int.
  805. $data = unpack('v', $first);
  806. switch ($data[1]) {
  807. case 0x8b1f:
  808. // First two bytes of gzip files are 0x1f, 0x8b (little-endian).
  809. // See http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
  810. $content_type = 'application/x-gzip';
  811. break;
  812. case 0x4b50:
  813. // First two bytes of zip files are 0x50, 0x4b ('PK') (little-endian).
  814. // See http://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
  815. $content_type = 'application/zip';
  816. break;
  817. case 0x5a42:
  818. // First two bytes of bzip2 files are 0x5a, 0x42 ('BZ') (big-endian).
  819. // See http://en.wikipedia.org/wiki/Bzip2#File_format
  820. $content_type = 'application/x-bzip2';
  821. break;
  822. default:
  823. drush_log(dt('Unable to determine mime type from header bytes 0x!hex of !file.', array('!hex' => dechex($data[1]), '!file' => $filename,), 'debug'));
  824. }
  825. }
  826. else {
  827. drush_log(dt('Unable to read !file.', array('!file' => $filename)), 'warning');
  828. }
  829. }
  830. else {
  831. drush_log(dt('Unable to open !file.', array('!file' => $filename)), 'warning');
  832. }
  833. }
  834. // 3. Lastly if above methods didn't work, try to guess the mime type from
  835. // the file extension. This is useful if the file has no identificable magic
  836. // header bytes (for example tarballs).
  837. if (!$content_type) {
  838. drush_log(dt('Examining !file extension.', array('!file' => $filename)), 'debug');
  839. // Remove querystring from the filename, if present.
  840. $filename = basename(current(explode('?', $filename, 2)));
  841. $extension_mimetype = array(
  842. '.tar' => 'application/x-tar',
  843. '.sql' => 'application/octet-stream',
  844. );
  845. foreach ($extension_mimetype as $extension => $ct) {
  846. if (substr($filename, -strlen($extension)) === $extension) {
  847. $content_type = $ct;
  848. break;
  849. }
  850. }
  851. }
  852. if ($content_type) {
  853. drush_log(dt('Mime type for !file is !mt', array('!file' => $filename, '!mt' => $content_type)), 'notice');
  854. return $content_type;
  855. }
  856. return drush_set_error('MIME_CONTENT_TYPE_UNKNOWN', dt('Unable to determine mime type for !file.', array('!file' => $filename)));
  857. }
  858. /**
  859. * Check whether a file is a supported tarball.
  860. *
  861. * @return mixed
  862. * The file content type if it's a tarball. FALSE otherwise.
  863. */
  864. function drush_file_is_tarball($path) {
  865. $content_type = drush_mime_content_type($path);
  866. $supported = array(
  867. 'application/x-bzip2',
  868. 'application/x-gzip',
  869. 'application/x-tar',
  870. 'application/x-zip',
  871. 'application/zip',
  872. );
  873. if (in_array($content_type, $supported)) {
  874. return $content_type;
  875. }
  876. return FALSE;
  877. }
  878. /**
  879. * Extract a tarball.
  880. *
  881. * @param string $path
  882. * Path to the archive to be extracted.
  883. * @param string $destination
  884. * The destination directory the tarball should be extracted into.
  885. * Optional, if ommitted the tarball directory will be used as destination.
  886. * @param boolean $listing
  887. * If TRUE, a listing of the tar contents will be returned on success.
  888. * @param string $tar_extra_options
  889. * Extra options to be passed to the tar command.
  890. *
  891. * @return mixed
  892. * TRUE on success, FALSE on fail. If $listing is TRUE, a file listing of the
  893. * tarball is returned if the extraction reported success, instead of TRUE.
  894. */
  895. function drush_tarball_extract($path, $destination = FALSE, $listing = FALSE, $tar_extra_options = '') {
  896. // Check if tarball is supported.
  897. if (!($mimetype = drush_file_is_tarball($path))) {
  898. return drush_set_error('TARBALL_EXTRACT_UNKNOWN_FORMAT', dt('Unable to extract !path. Unknown archive format.', array('!path' => $path)));
  899. }
  900. // Check if destination is valid.
  901. if (!$destination) {
  902. $destination = dirname($path);
  903. }
  904. if (!drush_mkdir($destination)) {
  905. // drush_mkdir already set an error.
  906. return FALSE;
  907. }
  908. // Perform the extraction of a zip file.
  909. if (($mimetype == 'application/zip') || ($mimetype == 'application/x-zip')) {
  910. $return = drush_shell_cd_and_exec(dirname($path), "unzip %s -d %s", $path, $destination);
  911. if (!$return) {
  912. return drush_set_error('DRUSH_TARBALL_EXTRACT_ERROR', dt('Unable to unzip !filename.', array('!filename' => $path)));
  913. }
  914. if ($listing) {
  915. // unzip prefixes the file listing output with a header line,
  916. // and prefixes each line with a verb representing the compression type.
  917. $output = drush_shell_exec_output();
  918. // Remove the header line.
  919. array_shift($output);
  920. // Remove the prefix verb from each line.
  921. $output = array_map(create_function('$str', 'return substr($str, strpos($str, ":") + 3 + ' . strlen($destination) . ');'), $output);
  922. // Remove any remaining blank lines.
  923. $return = array_filter($output, create_function('$str', 'return $str != "";'));
  924. }
  925. }
  926. // Otherwise we have a possibly-compressed Tar file.
  927. // If we are not on Windows, then try to do "tar" in a single operation.
  928. elseif (!drush_is_windows()) {
  929. $tar = drush_get_tar_executable();
  930. $tar_compression_flag = '';
  931. if ($mimetype == 'application/x-gzip') {
  932. $tar_compression_flag = 'z';
  933. }
  934. elseif ($mimetype == 'application/x-bzip2') {
  935. $tar_compression_flag = 'j';
  936. }
  937. $return = drush_shell_cd_and_exec(dirname($path), "$tar {$tar_extra_options} -C %s -x%sf %s", $destination, $tar_compression_flag, basename($path));
  938. if (!$return) {
  939. return drush_set_error('DRUSH_TARBALL_EXTRACT_ERROR', dt('Unable to untar !filename.', array('!filename' => $path)));
  940. }
  941. if ($listing) {
  942. // We use a separate tar -tf instead of -xvf above because
  943. // the output is not the same in Mac.
  944. drush_shell_cd_and_exec(dirname($path), "$tar -t%sf %s", $tar_compression_flag, basename($path));
  945. $return = drush_shell_exec_output();
  946. }
  947. }
  948. // In windows, do the extraction by its primitive steps.
  949. else {
  950. // 1. copy the source tarball to the destination directory. Rename to a
  951. // temp name in case the destination directory == dirname($path)
  952. $tmpfile = drush_tempnam(basename($path), $destination);
  953. drush_copy_dir($path, $tmpfile, FILE_EXISTS_OVERWRITE);
  954. // 2. uncompress the tarball, if compressed.
  955. if (($mimetype == 'application/x-gzip') || ($mimetype == 'application/x-bzip2')) {
  956. if ($mimetype == 'application/x-gzip') {
  957. $compressed = $tmpfile . '.gz';
  958. // We used to use gzip --decompress in --stdout > out, but the output
  959. // redirection sometimes failed on Windows for some binary output.
  960. $command = 'gzip --decompress %s';
  961. }
  962. elseif ($mimetype == 'application/x-bzip2') {
  963. $compressed = $tmpfile . '.bz2';
  964. $command = 'bzip2 --decompress %s';
  965. }
  966. drush_op('rename', $tmpfile, $compressed);
  967. $return = drush_shell_cd_and_exec(dirname($compressed), $command, $compressed);
  968. if (!$return || !file_exists($tmpfile)) {
  969. return drush_set_error('DRUSH_TARBALL_EXTRACT_ERROR', dt('Unable to decompress !filename.', array('!filename' => $compressed)));
  970. }
  971. }
  972. // 3. Untar.
  973. $tar = drush_get_tar_executable();
  974. $return = drush_shell_cd_and_exec(dirname($tmpfile), "$tar {$tar_extra_options} -xvf %s", basename($tmpfile));
  975. if (!$return) {
  976. return drush_set_error('DRUSH_TARBALL_EXTRACT_ERROR', dt('Unable to untar !filename.', array('!filename' => $tmpfile)));
  977. }
  978. if ($listing) {
  979. $return = drush_shell_exec_output();
  980. // Cut off the 'x ' prefix for the each line of the tar output
  981. // See http://drupal.org/node/1775520
  982. foreach($return as &$line) {
  983. if(strpos($line, "x ") === 0)
  984. $line = substr($line, 2);
  985. }
  986. }
  987. // Remove the temporary file so the md5 hash is accurate.
  988. unlink($tmpfile);
  989. }
  990. return $return;
  991. }
  992. /**
  993. * Download and extract a tarball to the lib directory.
  994. *
  995. * Checks for reported success, but callers should normally check for existence
  996. * of specific expected file(s) in the library.
  997. *
  998. * @param string $url
  999. * The URL to the library tarball.
  1000. *
  1001. * @return boolean
  1002. * TRUE is the download and extraction reported success, FALSE otherwise.
  1003. */
  1004. function drush_lib_fetch($url) {
  1005. $lib = drush_get_option('lib', DRUSH_BASE_PATH . '/lib');
  1006. if (!is_writable($lib)) {
  1007. return drush_set_error('DRUSH_LIB_UNWRITABLE', dt("Drush needs to download a library from !url in order to function, and the attempt to download this file automatically failed because you do not have permission to write to the library directory !path. To continue you will need to manually download the package from !url, extract it, and copy the directory into your !path directory.", array('!path' => $lib, '!url' => $url)));
  1008. }
  1009. $destination = $lib . '/drush-library-' . mt_rand();
  1010. $path = drush_download_file($url, $destination);
  1011. if (!$path) {
  1012. return FALSE;
  1013. }
  1014. return drush_tarball_extract($path);
  1015. }
  1016. /**
  1017. * @defgroup commandprocessing Command processing functions.
  1018. * @{
  1019. *
  1020. * These functions manage command processing by the
  1021. * main function in drush.php.
  1022. */
  1023. /**
  1024. * Handle any command preprocessing that may need to be done, including
  1025. * potentially redispatching the command immediately (e.g. for remote
  1026. * commands).
  1027. *
  1028. * @return
  1029. * TRUE if the command was handled remotely.
  1030. */
  1031. function drush_preflight_command_dispatch() {
  1032. $interactive = drush_get_option('interactive', FALSE);
  1033. // The command will be executed remotely if the --remote-host flag
  1034. // is set; note that if a site alias is provided on the command line,
  1035. // and the site alias references a remote server, then the --remote-host
  1036. // option will be set when the site alias is processed.
  1037. // @see drush_sitealias_check_arg
  1038. $remote_host = drush_get_option('remote-host');
  1039. // Get the command early so that we can allow commands to directly handle remote aliases if they wish
  1040. $command = drush_parse_command();
  1041. drush_command_default_options($command);
  1042. // If the command sets the 'strict-option-handling' flag, then we will remove
  1043. // any cli options that appear after the command name form the 'cli' context.
  1044. // The cli options that appear before the command name are stored in the
  1045. // 'DRUSH_GLOBAL_CLI_OPTIONS' context, so we will just overwrite the cli context
  1046. // with this, after doing the neccessary fixup from short-form to long-form options.
  1047. // After we do that, we put back any local drush options identified by $command['options'].
  1048. if (is_array($command) && !empty($command['strict-option-handling'])) {
  1049. $cli_options = drush_get_context('DRUSH_GLOBAL_CLI_OPTIONS', array());
  1050. // Now we are going to sort out any options that exist in $command['options'];
  1051. // we will remove these from DRUSH_COMMAND_ARGS and put them back into the
  1052. // cli options.
  1053. $cli_context = drush_get_context('cli');
  1054. $remove_from_command_args = array();
  1055. foreach ($command['options'] as $option => $info) {
  1056. if (array_key_exists($option, $cli_context)) {
  1057. $cli_options[$option] = $cli_context[$option];
  1058. $remove_from_command_args[$option] = $option;
  1059. }
  1060. }
  1061. if (!empty($remove_from_command_args)) {
  1062. $drush_command_args = array();
  1063. foreach (drush_get_context('DRUSH_COMMAND_ARGS') as $arg) {
  1064. if (!_drush_should_remove_command_arg($arg, $remove_from_command_args)) {
  1065. $drush_command_args[] = $arg;
  1066. }
  1067. }
  1068. drush_set_context('DRUSH_COMMAND_ARGS', $drush_command_args);
  1069. }
  1070. drush_expand_short_form_options($cli_options);
  1071. drush_set_context('cli', $cli_options);
  1072. _drush_bootstrap_global_options();
  1073. }
  1074. // If the command sets the 'handle-remote-commands' flag, then we will short-circuit
  1075. // remote command dispatching and site-list command dispatching, and always let
  1076. // the command handler run on the local machine.
  1077. if (is_array($command) && !empty($command['handle-remote-commands'])) {
  1078. return FALSE;
  1079. }
  1080. if (isset($remote_host)) {
  1081. $args = drush_get_arguments();
  1082. $command_name = array_shift($args);
  1083. $remote_user = drush_get_option('remote-user');
  1084. // Force interactive mode if there is a single remote target. #interactive is added by drush_do_command_redispatch
  1085. drush_set_option('interactive', TRUE);
  1086. $values = drush_do_command_redispatch(is_array($command) ? $command : $command_name, $args, $remote_host, $remote_user);
  1087. // In 'interactive' mode, $values is the result code from drush_shell_proc_open.
  1088. // @todo: in _drush_backend_invoke, return array('error_status' => $ret) instead for uniformity.
  1089. if (!is_array($values) && ($values != 0)) {
  1090. // Force an error result code. Note that drush_shutdown() will still run.
  1091. drush_set_context('DRUSH_EXECUTION_COMPLETED', TRUE);
  1092. exit($values);
  1093. }
  1094. return TRUE;
  1095. }
  1096. // If the --site-list flag is set, then we will execute the specified
  1097. // command once for every site listed in the site list.
  1098. $site_list = drush_get_option('site-list');
  1099. if (isset($site_list)) {
  1100. if (!is_array($site_list)) {
  1101. $site_list = explode(',', $site_list);
  1102. }
  1103. $site_record = array('site-list' => $site_list);
  1104. $args = drush_get_arguments();
  1105. if (!drush_get_context('DRUSH_SIMULATE') && !$interactive) {
  1106. drush_print(dt("You are about to execute '!command' non-interactively (--yes forced) on all of the following targets:", array('!command' => implode(" ", $args))));
  1107. foreach ($site_list as $one_destination) {
  1108. drush_print(dt(' !target', array('!target' => $one_destination)));
  1109. }
  1110. if (drush_confirm('Continue? ') === FALSE) {
  1111. drush_user_abort();
  1112. return TRUE;
  1113. }
  1114. }
  1115. $command_name = array_shift($args);
  1116. $multi_options = drush_get_context('cli');
  1117. $backend_options = array();
  1118. if (drush_get_option('pipe') || drush_get_option('interactive')) {
  1119. $backend_options['interactive'] = TRUE;
  1120. }
  1121. if (drush_get_option('no-label', FALSE)) {
  1122. $backend_options['no-label'] = TRUE;
  1123. }
  1124. // If the user specified a format, try to look up the
  1125. // default list separator for the specified format.
  1126. // If the user did not specify a different label separator,
  1127. // then pass in the default as an option, so that the
  1128. // separator between the items in the list and the site
  1129. // name will be consistent.
  1130. $format = drush_get_option('format', FALSE);
  1131. if ($format && !array_key_exists('label-separator', $multi_options)) {
  1132. $formatter = drush_load_engine('outputformat', $format);
  1133. if ($formatter) {
  1134. $list_separator = $formatter->get_info('list-separator');
  1135. if ($list_separator) {
  1136. $multi_options['label-separator'] = $list_separator;
  1137. }
  1138. }
  1139. }
  1140. $values = drush_invoke_process($site_record, $command_name, $args, $multi_options, $backend_options);
  1141. return TRUE;
  1142. }
  1143. return FALSE;
  1144. }
  1145. /**
  1146. * Determine whether or not an argument should be removed from the
  1147. * DRUSH_COMMAND_ARGS context. This method is used when a Drush
  1148. * command has set the 'strict-option-handling' flag indicating
  1149. * that it will pass through all commandline arguments and any
  1150. * additional options (not known to Drush) to some shell command.
  1151. *
  1152. * Take as an example the following call to core-rsync:
  1153. *
  1154. * drush --yes core-rsync -v -az --exclude-paths='.git:.svn' local-files/ @site:%files
  1155. *
  1156. * In this instance:
  1157. *
  1158. * --yes is a global Drush option
  1159. *
  1160. * -v is an rsync option. It will make rsync run in verbose mode,
  1161. * but will not make Drush run in verbose mode due to the fact that
  1162. * core-rsync sets the 'strict-option-handling' flag.
  1163. *
  1164. * --exclude-paths is a local Drush option. It will be converted by
  1165. * Drush into --exclude='.git' and --exclude='.svn', and then passed
  1166. * on to the rsync command.
  1167. *
  1168. * The parameter $arg passed to this function is one of the elements
  1169. * of DRUSH_COMMAND_ARGS. It will have values such as:
  1170. * -v
  1171. * -az
  1172. * --exclude-paths='.git:.svn'
  1173. * local-files/
  1174. * @site:%files
  1175. *
  1176. * Our job in this function is to determine if $arg should be removed
  1177. * by virtue of appearing in $removal_list. $removal_list is an array
  1178. * that will contain values such as 'exclude-paths'. Both the key and
  1179. * the value of $removal_list is the same.
  1180. */
  1181. function _drush_should_remove_command_arg($arg, $removal_list) {
  1182. foreach ($removal_list as $candidate) {
  1183. if (($arg == "-$candidate") ||
  1184. ($arg == "--$candidate") ||
  1185. (substr($arg,0,strlen($candidate)+3) == "--$candidate=") ) {
  1186. return TRUE;
  1187. }
  1188. }
  1189. return FALSE;
  1190. }
  1191. /**
  1192. * Used by functions that operate on lists of sites, moving
  1193. * information from the source to the destination. Currenlty
  1194. * this includes 'drush rsync' and 'drush sql sync'.
  1195. */
  1196. function drush_do_multiple_command($command, $source_record, $destination_record, $allow_single_source = FALSE) {
  1197. $is_multiple_command = FALSE;
  1198. if ((($allow_single_source == TRUE) || array_key_exists('site-list', $source_record)) && array_key_exists('site-list', $destination_record)) {
  1199. $is_multiple_command = TRUE;
  1200. $source_path = array_key_exists('path-component', $source_record) ? $source_record['path-component'] : '';
  1201. $destination_path = array_key_exists('path-component', $destination_record) ? $destination_record['path-component'] : '';
  1202. $target_list = array_values(drush_sitealias_resolve_sitelist($destination_record));
  1203. if (array_key_exists('site-list', $source_record)) {
  1204. $source_list = array_values(drush_sitealias_resolve_sitelist($source_record));
  1205. if (drush_sitealias_check_lists_alignment($source_list, $target_list) === FALSE) {
  1206. if (array_key_exists('unordered-list', $source_record) || array_key_exists('unordered-list', $destination_record)) {
  1207. drush_sitelist_align_lists($source_list, $target_list, $aligned_source, $aligned_target);
  1208. $source_list = $aligned_source;
  1209. $target_list = $aligned_target;
  1210. }
  1211. }
  1212. }
  1213. else {
  1214. $source_list = array_fill(0, count($target_list), $source_record);
  1215. }
  1216. if (!drush_get_context('DRUSH_SIMULATE')) {
  1217. drush_print(dt('You are about to !command between all of the following targets:', array('!command' => $command)));
  1218. $i = 0;
  1219. foreach ($source_list as $one_source) {
  1220. $one_target = $target_list[$i];
  1221. ++$i;
  1222. drush_print(dt(' !source will overwrite !target', array('!source' => drush_sitealias_alias_record_to_spec($one_source) . $source_path, '!target' => drush_sitealias_alias_record_to_spec($one_target) . $destination_path)));
  1223. }
  1224. if (drush_confirm('Continue? ') === FALSE) {
  1225. return drush_user_abort();
  1226. }
  1227. }
  1228. $data = drush_redispatch_get_options();
  1229. $i = 0;
  1230. foreach ($source_list as $one_source) {
  1231. $one_target = $target_list[$i];
  1232. ++$i;
  1233. $source_spec = drush_sitealias_alias_record_to_spec($one_source);
  1234. $target_spec = drush_sitealias_alias_record_to_spec($one_target);
  1235. drush_log(dt('Begin do_multiple !command via backend invoke', array('!command' => $command)));
  1236. $values = drush_invoke_process('@self', $command, array($source_spec . $source_path, $target_spec . $destination_path), $data);
  1237. drush_log(dt('Backend invoke is complete'));
  1238. }
  1239. }
  1240. return $is_multiple_command;
  1241. }
  1242. /**
  1243. * Run a command on the site specified by the provided command record.
  1244. *
  1245. * The standard function that provides this service is called
  1246. * drush_invoke_process. Please call the standard function.
  1247. *
  1248. * @param backend_options
  1249. * TRUE - integrate errors
  1250. * FALSE - do not integrate errors
  1251. * array - @see drush_backend_invoke_concurrent
  1252. *
  1253. function drush_do_site_command($site_record, $command, $args = array(), $command_options = array(), $backend_options = FALSE) {
  1254. return drush_invoke_process($site_record, $command, $args, $command_options, $backend_options);
  1255. }
  1256. */
  1257. /**
  1258. * Redispatch the specified command using the same
  1259. * options that were passed to this invocation of drush.
  1260. */
  1261. function drush_do_command_redispatch($command, $args = array(), $remote_host = NULL, $remote_user = NULL, $drush_path = NULL) {
  1262. $additional_global_options = array();
  1263. $command_options = drush_redispatch_get_options();
  1264. if (is_array($command)) {
  1265. $command_name = $command['command'];
  1266. // If we are executing a remote command that uses strict option handling,
  1267. // then mark all of the options in the alias context as global, so that they
  1268. // will appear before the command name.
  1269. if (!empty($command['strict-option-handling'])) {
  1270. foreach(drush_get_context('alias') as $alias_key => $alias_value) {
  1271. if (array_key_exists($alias_key, $command_options) && !array_key_exists($alias_key, $command['options'])) {
  1272. $additional_global_options[$alias_key] = $alias_value;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. else {
  1278. $command_name = $command;
  1279. }
  1280. // If the path to drush was supplied, then use it to invoke the new command.
  1281. if ($drush_path == NULL) {
  1282. $drush_path = drush_get_option('drush-script');
  1283. if (!isset($drush_path)) {
  1284. $drush_folder = drush_get_option('drush');
  1285. if (isset($drush)) {
  1286. $drush_path = $drush_folder . '/drush';
  1287. }
  1288. }
  1289. }
  1290. $backend_options = array('drush-script' => $drush_path, 'remote-host' => $remote_host, 'remote-user' => $remote_user, 'integrate' => TRUE, 'additional-global-options' => $additional_global_options);
  1291. if (drush_get_option('interactive')) {
  1292. $backend_options['interactive'] = TRUE;
  1293. }
  1294. // Run the command in a new process.
  1295. drush_log(dt('Begin redispatch via drush_invoke_process().'));
  1296. $values = drush_invoke_process('@self', $command_name, $args, $command_options, $backend_options);
  1297. drush_log(dt('End redispatch via drush_invoke_process().'));
  1298. return $values;
  1299. }
  1300. /**
  1301. * @} End of "defgroup commandprocessing".
  1302. */
  1303. /**
  1304. * @defgroup logging Logging information to be provided as output.
  1305. * @{
  1306. *
  1307. * These functions are primarily for diagnostic purposes, but also provide an overview of tasks that were taken
  1308. * by drush.
  1309. */
  1310. /**
  1311. * Add a log message to the log history.
  1312. *
  1313. * This function calls the callback stored in the 'DRUSH_LOG_CALLBACK' context with
  1314. * the resulting entry at the end of execution.
  1315. *
  1316. * This allows you to replace it with custom logging implementations if needed,
  1317. * such as logging to a file or logging to a database (drupal or otherwise).
  1318. *
  1319. * The default callback is the _drush_print_log() function with prints the messages
  1320. * to the shell.
  1321. *
  1322. * @param message
  1323. * String containing the message to be logged.
  1324. * @param type
  1325. * The type of message to be logged. Common types are 'warning', 'error', 'success' and 'notice'.
  1326. * A type of 'failed' can also be supplied to flag as an 'error'.
  1327. * A type of 'ok' or 'completed' can also be supplied to flag as a 'success'.
  1328. * If you want your log messages to print to screen without the user entering
  1329. * a -v or --verbose flag, use type 'ok', this prints log messages out to
  1330. * STDERR, which prints to screen (unless you have redirected it). All other
  1331. * types of messages will be assumed to be notices.
  1332. */
  1333. function drush_log($message, $type = 'notice', $error = null) {
  1334. $log =& drush_get_context('DRUSH_LOG', array());
  1335. $callback = drush_get_context('DRUSH_LOG_CALLBACK', '_drush_print_log');
  1336. $entry = array(
  1337. 'type' => $type,
  1338. 'message' => $message,
  1339. 'timestamp' => microtime(TRUE),
  1340. 'memory' => memory_get_usage(),
  1341. );
  1342. $entry['error'] = $error;
  1343. $log[] = $entry;
  1344. drush_backend_packet('log', $entry);
  1345. return $callback($entry);
  1346. }
  1347. /**
  1348. * Backend command callback. Add a log message to the log history.
  1349. *
  1350. * @param entry
  1351. * The log entry.
  1352. */
  1353. function drush_backend_packet_log($entry, $backend_options) {
  1354. if (!$backend_options['log']) {
  1355. return;
  1356. }
  1357. if (!is_string($entry['message'])) {
  1358. $entry['message'] = implode("\n", (array)$entry['message']);
  1359. }
  1360. $entry['message'] = $entry['message'];
  1361. $log =& drush_get_context('DRUSH_LOG', array());
  1362. $log[] = $entry;
  1363. // Yes, this looks odd, but we might in fact be a backend command
  1364. // that ran another backend command.
  1365. drush_backend_packet('log', $entry);
  1366. if (array_key_exists('#output-label', $backend_options)) {
  1367. $entry['message'] = $backend_options['#output-label'] . $entry['message'];
  1368. }
  1369. // If integrate is FALSE, then log messages are stored in DRUSH_LOG,
  1370. // but are -not- printed to the console.
  1371. if ($backend_options['integrate']) {
  1372. $callback = drush_get_context('DRUSH_LOG_CALLBACK', '_drush_print_log');
  1373. return $callback($entry);
  1374. }
  1375. }
  1376. /**
  1377. * Retrieve the log messages from the log history
  1378. *
  1379. * @return
  1380. * Entire log history
  1381. */
  1382. function drush_get_log() {
  1383. return drush_get_context('DRUSH_LOG', array());
  1384. }
  1385. /**
  1386. * Run print_r on a variable and log the output.
  1387. */
  1388. function dlm($object) {
  1389. drush_log(print_r($object, TRUE));
  1390. }
  1391. /**
  1392. * Display the pipe output for the current request.
  1393. */
  1394. function drush_pipe_output() {
  1395. $pipe = drush_get_context('DRUSH_PIPE_BUFFER');
  1396. if (!empty($pipe)) {
  1397. drush_print_r($pipe, NULL, FALSE);
  1398. }
  1399. }
  1400. /**
  1401. * Display the log message
  1402. *
  1403. * By default, only warnings and errors will be displayed, if 'verbose' is specified, it will also display notices.
  1404. *
  1405. * @param
  1406. * The associative array for the entry.
  1407. *
  1408. * @return
  1409. * False in case of an error or failed type, True in all other cases.
  1410. */
  1411. function _drush_print_log($entry) {
  1412. if (drush_get_context('DRUSH_NOCOLOR')) {
  1413. $red = "[%s]";
  1414. $yellow = "[%s]";
  1415. $green = "[%s]";
  1416. }
  1417. else {
  1418. $red = "\033[31;40m\033[1m[%s]\033[0m";
  1419. $yellow = "\033[1;33;40m\033[1m[%s]\033[0m";
  1420. $green = "\033[1;32;40m\033[1m[%s]\033[0m";
  1421. }
  1422. $verbose = drush_get_context('DRUSH_VERBOSE');
  1423. $debug = drush_get_context('DRUSH_DEBUG');
  1424. $return = TRUE;
  1425. switch ($entry['type']) {
  1426. case 'warning' :
  1427. case 'cancel' :
  1428. $type_msg = sprintf($yellow, $entry['type']);
  1429. break;
  1430. case 'failed' :
  1431. case 'error' :
  1432. $type_msg = sprintf($red, $entry['type']);
  1433. $return = FALSE;
  1434. break;
  1435. case 'ok' :
  1436. case 'completed' :
  1437. case 'success' :
  1438. case 'status':
  1439. // In quiet mode, suppress progress messages
  1440. if (drush_get_context('DRUSH_QUIET')) {
  1441. return TRUE;
  1442. }
  1443. $type_msg = sprintf($green, $entry['type']);
  1444. break;
  1445. case 'notice' :
  1446. case 'message' :
  1447. case 'info' :
  1448. if (!$verbose) {
  1449. // print nothing. exit cleanly.
  1450. return TRUE;
  1451. }
  1452. $type_msg = sprintf("[%s]", $entry['type']);
  1453. break;
  1454. default :
  1455. if (!$debug) {
  1456. // print nothing. exit cleanly.
  1457. return TRUE;
  1458. }
  1459. $type_msg = sprintf("[%s]", $entry['type']);
  1460. break;
  1461. }
  1462. // When running in backend mode, log messages are not displayed, as they will
  1463. // be returned in the JSON encoded associative array.
  1464. if (drush_get_context('DRUSH_BACKEND')) {
  1465. return $return;
  1466. }
  1467. $columns = drush_get_context('DRUSH_COLUMNS', 80);
  1468. $width[1] = 11;
  1469. // Append timer and memory values.
  1470. if ($debug) {
  1471. $timer = sprintf('[%s sec, %s]', round($entry['timestamp']-DRUSH_REQUEST_TIME, 2), drush_format_size($entry['memory']));
  1472. $entry['message'] = $entry['message'] . ' ' . $timer;
  1473. }
  1474. $width[0] = ($columns - 11);
  1475. $format = sprintf("%%-%ds%%%ds", $width[0], $width[1]);
  1476. // Place the status message right aligned with the top line of the error message.
  1477. $message = wordwrap($entry['message'], $width[0]);
  1478. $lines = explode("\n", $message);
  1479. $lines[0] = sprintf($format, $lines[0], $type_msg);
  1480. $message = implode("\n", $lines);
  1481. drush_print($message, 0, STDERR);
  1482. return $return;
  1483. }
  1484. // Print all timers for the request.
  1485. function drush_print_timers() {
  1486. global $timers;
  1487. $temparray = array();
  1488. foreach ((array)$timers as $name => $timerec) {
  1489. // We have to use timer_read() for active timers, and check the record for others
  1490. if (isset($timerec['start'])) {
  1491. $temparray[$name] = timer_read($name);
  1492. }
  1493. else {
  1494. $temparray[$name] = $timerec['time'];
  1495. }
  1496. }
  1497. // Go no farther if there were no timers
  1498. if (count($temparray) > 0) {
  1499. // Put the highest cumulative times first
  1500. arsort($temparray);
  1501. $table = array();
  1502. $table[] = array('Timer', 'Cum (sec)', 'Count', 'Avg (msec)');
  1503. foreach ($temparray as $name => $time) {
  1504. $cum = round($time/1000, 3);
  1505. $count = $timers[$name]['count'];
  1506. if ($count > 0) {
  1507. $avg = round($time/$count, 3);
  1508. }
  1509. else {
  1510. $avg = 'N/A';
  1511. }
  1512. $table[] = array($name, $cum, $count, $avg);
  1513. }
  1514. drush_print_table($table, TRUE, array(), STDERR);
  1515. }
  1516. }
  1517. /**
  1518. * Turn drupal_set_message errors into drush_log errors
  1519. */
  1520. function _drush_log_drupal_messages() {
  1521. if (function_exists('drupal_get_messages')) {
  1522. $messages = drupal_get_messages(NULL, TRUE);
  1523. if (array_key_exists('error', $messages)) {
  1524. //Drupal message errors.
  1525. foreach ((array) $messages['error'] as $error) {
  1526. $error = strip_tags($error);
  1527. $header = preg_match('/^warning: Cannot modify header information - headers already sent by /i', $error);
  1528. $session = preg_match('/^warning: session_start\(\): Cannot send session /i', $error);
  1529. if ($header || $session) {
  1530. //These are special cases for an unavoidable warnings
  1531. //that are generated by generating output before Drupal is bootstrapped.
  1532. //or sending a session cookie (seems to affect d7 only?)
  1533. //Simply ignore them.
  1534. continue;
  1535. }
  1536. elseif (preg_match('/^warning:/i', $error)) {
  1537. drush_log(preg_replace('/^warning: /i', '', $error), 'warning');
  1538. }
  1539. elseif (preg_match('/^notice:/i', $error)) {
  1540. drush_log(preg_replace('/^notice: /i', '', $error), 'notice');
  1541. }
  1542. elseif (preg_match('/^user warning:/i', $error)) {
  1543. // This is a special case. PHP logs sql errors as 'User Warnings', not errors.
  1544. drush_set_error('DRUSH_DRUPAL_ERROR_MESSAGE', preg_replace('/^user warning: /i', '', $error));
  1545. }
  1546. else {
  1547. drush_set_error('DRUSH_DRUPAL_ERROR_MESSAGE', $error);
  1548. }
  1549. }
  1550. }
  1551. unset($messages['error']);
  1552. // Log non-error messages.
  1553. foreach ($messages as $type => $items) {
  1554. foreach ($items as $item) {
  1555. drush_log(strip_tags($item), $type);
  1556. }
  1557. }
  1558. }
  1559. }
  1560. // Copy of format_size() in Drupal.
  1561. function drush_format_size($size, $langcode = NULL) {
  1562. if ($size < DRUSH_DRUPAL_KILOBYTE) {
  1563. // format_plural() not always available.
  1564. return dt('@count bytes', array('@count' => $size));
  1565. }
  1566. else {
  1567. $size = $size / DRUSH_DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
  1568. $units = array(
  1569. dt('@size KB', array(), array('langcode' => $langcode)),
  1570. dt('@size MB', array(), array('langcode' => $langcode)),
  1571. dt('@size GB', array(), array('langcode' => $langcode)),
  1572. dt('@size TB', array(), array('langcode' => $langcode)),
  1573. dt('@size PB', array(), array('langcode' => $langcode)),
  1574. dt('@size EB', array(), array('langcode' => $langcode)),
  1575. dt('@size ZB', array(), array('langcode' => $langcode)),
  1576. dt('@size YB', array(), array('langcode' => $langcode)),
  1577. );
  1578. foreach ($units as $unit) {
  1579. if (round($size, 2) >= DRUSH_DRUPAL_KILOBYTE) {
  1580. $size = $size / DRUSH_DRUPAL_KILOBYTE;
  1581. }
  1582. else {
  1583. break;
  1584. }
  1585. }
  1586. return str_replace('@size', round($size, 2), $unit);
  1587. }
  1588. }
  1589. /**
  1590. * @} End of "defgroup logging".
  1591. */
  1592. /**
  1593. * @defgroup errorhandling Managing errors that occur in the Drush framework.
  1594. * @{
  1595. * Functions that manage the current error status of the Drush framework.
  1596. *
  1597. * These functions operate by maintaining a static variable that is a equal to the constant DRUSH_FRAMEWORK_ERROR if an
  1598. * error has occurred.
  1599. * This error code is returned at the end of program execution, and provide the shell or calling application with
  1600. * more information on how to diagnose any problems that may have occurred.
  1601. */
  1602. /**
  1603. * Set an error code for the error handling system.
  1604. *
  1605. * @param error
  1606. * A text string identifying the type of error.
  1607. *
  1608. * @param message
  1609. * Optional. Error message to be logged. If no message is specified, hook_drush_help will be consulted,
  1610. * using a key of 'error:MY_ERROR_STRING'.
  1611. *
  1612. * @param $output_label
  1613. * Optional. Label to prepend to the error message.
  1614. *
  1615. * @return
  1616. * Always returns FALSE, to allow you to return with false in the calling functions,
  1617. * such as <code>return drush_set_error('DRUSH_FRAMEWORK_ERROR')</code>
  1618. */
  1619. function drush_set_error($error, $message = null, $output_label = "") {
  1620. $error_code =& drush_get_context('DRUSH_ERROR_CODE', DRUSH_SUCCESS);
  1621. $error_code = DRUSH_FRAMEWORK_ERROR;
  1622. $error_log =& drush_get_context('DRUSH_ERROR_LOG', array());
  1623. if (is_numeric($error)) {
  1624. $error = 'DRUSH_FRAMEWORK_ERROR';
  1625. }
  1626. $message = ($message) ? $message : drush_command_invoke_all('drush_help', 'error:' . $error);
  1627. if (is_array($message)) {
  1628. $message = implode("\n", $message);
  1629. }
  1630. $error_log[$error][] = $message;
  1631. if (!drush_backend_packet('set_error', array('error' => $error, 'message' => $message))) {
  1632. drush_log(($message) ? $output_label . $message : $output_label . $error, 'error', $error);
  1633. }
  1634. return FALSE;
  1635. }
  1636. /**
  1637. * Return the current error handling status
  1638. *
  1639. * @return
  1640. * The current aggregate error status
  1641. */
  1642. function drush_get_error() {
  1643. return drush_get_context('DRUSH_ERROR_CODE', DRUSH_SUCCESS);
  1644. }
  1645. /**
  1646. * Return the current list of errors that have occurred.
  1647. *
  1648. * @return
  1649. * An associative array of error messages indexed by the type of message.
  1650. */
  1651. function drush_get_error_log() {
  1652. return drush_get_context('DRUSH_ERROR_LOG', array());
  1653. }
  1654. /**
  1655. * Check if a specific error status has been set.
  1656. *
  1657. * @param error
  1658. * A text string identifying the error that has occurred.
  1659. * @return
  1660. * TRUE if the specified error has been set, FALSE if not
  1661. */
  1662. function drush_cmp_error($error) {
  1663. $error_log = drush_get_error_log();
  1664. if (is_numeric($error)) {
  1665. $error = 'DRUSH_FRAMEWORK_ERROR';
  1666. }
  1667. return array_key_exists($error, $error_log);
  1668. }
  1669. /**
  1670. * Clear error context.
  1671. */
  1672. function drush_clear_error() {
  1673. drush_set_context('DRUSH_ERROR_CODE', DRUSH_SUCCESS);
  1674. }
  1675. /**
  1676. * Exit due to user declining a confirmation prompt.
  1677. *
  1678. * Usage: return drush_user_abort();
  1679. */
  1680. function drush_user_abort($msg = NULL) {
  1681. drush_set_context('DRUSH_USER_ABORT', TRUE);
  1682. drush_log($msg ? $msg : dt('Aborting.'), 'cancel');
  1683. return FALSE;
  1684. }
  1685. /**
  1686. * Turn PHP error handling off.
  1687. *
  1688. * This is commonly used while bootstrapping Drupal for install
  1689. * or updates.
  1690. *
  1691. * This also records the previous error_reporting setting, in
  1692. * case it wasn't recorded previously.
  1693. *
  1694. * @see drush_errors_off()
  1695. */
  1696. function drush_errors_off() {
  1697. drush_get_context('DRUSH_ERROR_REPORTING', error_reporting(0));
  1698. ini_set('display_errors', FALSE);
  1699. }
  1700. /**
  1701. * Turn PHP error handling on.
  1702. *
  1703. * We default to error_reporting() here just in
  1704. * case drush_errors_on() is called before drush_errors_off() and
  1705. * the context is not yet set.
  1706. *
  1707. * @arg $errors string
  1708. * The default error level to set in drush. This error level will be
  1709. * carried through further drush_errors_on()/off() calls even if not
  1710. * provided in later calls.
  1711. *
  1712. * @see error_reporting()
  1713. * @see drush_errors_off()
  1714. */
  1715. function drush_errors_on($errors = null) {
  1716. if (!isset($errors)) {
  1717. $errors = error_reporting();
  1718. }
  1719. else {
  1720. drush_set_context('DRUSH_ERROR_REPORTING', $errors);
  1721. }
  1722. error_reporting(drush_get_context('DRUSH_ERROR_REPORTING', $errors));
  1723. ini_set('display_errors', TRUE);
  1724. }
  1725. /**
  1726. * @} End of "defgroup errorhandling".
  1727. */
  1728. /**
  1729. * Get the PHP memory_limit value in bytes.
  1730. */
  1731. function drush_memory_limit() {
  1732. $value = trim(ini_get('memory_limit'));
  1733. $last = strtolower($value[strlen($value)-1]);
  1734. switch ($last) {
  1735. case 'g':
  1736. $value *= DRUSH_DRUPAL_KILOBYTE;
  1737. case 'm':
  1738. $value *= DRUSH_DRUPAL_KILOBYTE;
  1739. case 'k':
  1740. $value *= DRUSH_DRUPAL_KILOBYTE;
  1741. }
  1742. return $value;
  1743. }
  1744. /**
  1745. * Unset the named key anywhere in the provided
  1746. * data structure.
  1747. */
  1748. function drush_unset_recursive(&$data, $unset_key) {
  1749. if (!empty($data) && is_array($data)) {
  1750. unset($data[$unset_key]);
  1751. foreach ($data as $key => $value) {
  1752. if (is_array($value)) {
  1753. drush_unset_recursive($data[$key], $unset_key);
  1754. }
  1755. }
  1756. }
  1757. }
  1758. /**
  1759. * Return a list of VCSs reserved files and directories.
  1760. */
  1761. function drush_version_control_reserved_files() {
  1762. static $files = FALSE;
  1763. if (!$files) {
  1764. // Also support VCSs that are not drush vc engines.
  1765. $files = array('.git', '.gitignore', '.hg', '.hgignore', '.hgrags');
  1766. $engine_info = drush_get_engines('version_control');
  1767. $vcs = array_keys($engine_info['engines']);
  1768. foreach ($vcs as $name) {
  1769. $version_control = drush_include_engine('version_control', $name);
  1770. $files = array_merge($files, $version_control->reserved_files());
  1771. }
  1772. }
  1773. return $files;
  1774. }
  1775. /**
  1776. * Generate a random alphanumeric password. Copied from user.module.
  1777. */
  1778. function drush_generate_password($length = 10) {
  1779. // This variable contains the list of allowable characters for the
  1780. // password. Note that the number 0 and the letter 'O' have been
  1781. // removed to avoid confusion between the two. The same is true
  1782. // of 'I', 1, and 'l'.
  1783. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  1784. // Zero-based count of characters in the allowable list:
  1785. $len = strlen($allowable_characters) - 1;
  1786. // Declare the password as a blank string.
  1787. $pass = '';
  1788. // Loop the number of times specified by $length.
  1789. for ($i = 0; $i < $length; $i++) {
  1790. // Each iteration, pick a random character from the
  1791. // allowable string and append it to the password:
  1792. $pass .= $allowable_characters[mt_rand(0, $len)];
  1793. }
  1794. return $pass;
  1795. }
  1796. /**
  1797. * Form an associative array from a linear array.
  1798. *
  1799. * This function walks through the provided array and constructs an associative
  1800. * array out of it. The keys of the resulting array will be the values of the
  1801. * input array. The values will be the same as the keys unless a function is
  1802. * specified, in which case the output of the function is used for the values
  1803. * instead.
  1804. *
  1805. * @param $array
  1806. * A linear array.
  1807. * @param $function
  1808. * A name of a function to apply to all values before output.
  1809. *
  1810. * @return
  1811. * An associative array.
  1812. */
  1813. function drush_map_assoc($array, $function = NULL) {
  1814. // array_combine() fails with empty arrays:
  1815. // http://bugs.php.net/bug.php?id=34857.
  1816. $array = !empty($array) ? array_combine($array, $array) : array();
  1817. if (is_callable($function)) {
  1818. $array = array_map($function, $array);
  1819. }
  1820. return $array;
  1821. }
  1822. /**
  1823. * Clears completion caches.
  1824. *
  1825. * If called with no parameters the entire complete cache will be cleared.
  1826. * If called with just the $type parameter the global cache for that type will
  1827. * be cleared (in the site context, if any). If called with both $type and
  1828. * $command parameters the command cache of that type will be cleared (in the
  1829. * site context, if any).
  1830. *
  1831. * This is included in drush.inc as complete.inc is only loaded conditionally.
  1832. *
  1833. * @param $type
  1834. * The completion type (optional).
  1835. * @param $command
  1836. * The command name (optional), if command specific cache is to be cleared.
  1837. * If specifying a command, $type is not optional.
  1838. */
  1839. function drush_complete_cache_clear($type = NULL, $command = NULL) {
  1840. require_once DRUSH_BASE_PATH . '/includes/complete.inc';
  1841. if ($type) {
  1842. drush_cache_clear_all(drush_complete_cache_cid($type, $command), 'complete');
  1843. return;
  1844. }
  1845. // No type or command, so clear the entire complete cache.
  1846. drush_cache_clear_all('*', 'complete', TRUE);
  1847. }