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