drush.inc 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848
  1. <?php
  2. /**
  3. * @file
  4. * The drush API implementation and helpers.
  5. */
  6. /**
  7. * The number of bytes in a kilobyte. Copied from Drupal.
  8. */
  9. define('DRUSH_DRUPAL_KILOBYTE', 1024);
  10. /**
  11. * Include a file, selecting a version specific file if available.
  12. *
  13. * For example, if you pass the path "/var/drush" and the name
  14. * "update" when bootstrapped on a Drupal 6 site it will first check for
  15. * the presence of "/var/drush/update_6.inc" in include it if exists. If this
  16. * file does NOT exist it will proceed and check for "/var/drush/update.inc".
  17. * If neither file exists, it will return FALSE.
  18. *
  19. * @param $path
  20. * The path you want to search.
  21. * @param $name
  22. * The file base name you want to include (not including a version suffix
  23. * or extension).
  24. * @param $version
  25. * The version suffix you want to include (could be specific to the software
  26. * or platform your are connecting to) - defaults to the current Drupal core
  27. * major version.
  28. * @param $extension
  29. * The extension - defaults to ".inc".
  30. *
  31. * @return
  32. * TRUE if the file was found and included.
  33. */
  34. function drush_include($path, $name, $version = NULL, $extension = 'inc') {
  35. $version = ($version) ? $version : drush_drupal_major_version();
  36. $file = sprintf("%s/%s_%s.%s", $path, $name, $version, $extension);
  37. if (file_exists($file)) {
  38. // drush_log(dt('Including version specific file : @file', array('@file' => $file)));
  39. include_once($file);
  40. return TRUE;
  41. }
  42. $file = sprintf("%s/%s.%s", $path, $name, $extension);
  43. if (file_exists($file)) {
  44. // drush_log(dt('Including non-version specific file : @file', array('@file' => $file)));
  45. include_once($file);
  46. return TRUE;
  47. }
  48. }
  49. /**
  50. * Return a structured array of engines of a specific type from commandfiles
  51. * implementing hook_drush_engine_$type.
  52. *
  53. * Engines are pluggable subsystems. Each engine of a specific type will
  54. * implement the same set of API functions and perform the same high-level
  55. * task using a different backend or approach.
  56. *
  57. * This function/hook is useful when you have a selection of several mutually
  58. * exclusive options to present to a user to select from.
  59. *
  60. * Other commands are able to extend this list and provide their own engines.
  61. * The hook can return useful information to help users decide which engine
  62. * they need, such as description or list of available engine options.
  63. *
  64. * The engine path element will automatically default to a subdirectory (within
  65. * the directory of the commandfile that implemented the hook) with the name of
  66. * the type of engine - e.g. an engine "wget" of type "handler" provided by
  67. * the "pm" commandfile would automatically be found if the file
  68. * "pm/handler/wget.inc" exists and a specific path is not provided.
  69. *
  70. * @param $type
  71. * The type of engine.
  72. *
  73. * @return
  74. * A structured array of engines.
  75. */
  76. function drush_get_engines($type) {
  77. $engines = array();
  78. $list = drush_commandfile_list();
  79. foreach ($list as $commandfile => $path) {
  80. if (drush_command_hook($commandfile, 'drush_engine_' . $type)) {
  81. $function = $commandfile . '_drush_engine_' . $type;
  82. $result = $function();
  83. foreach ((array)$result as $key => $engine) {
  84. // Add some defaults
  85. $engine += array(
  86. 'commandfile' => $commandfile,
  87. // Engines by default live in a subdirectory of the commandfile that
  88. // declared them, named as per the type of engine they are.
  89. 'path' => sprintf("%s/%s", dirname($path), $type),
  90. );
  91. $engines[$key] = $engine;
  92. }
  93. }
  94. }
  95. return $engines;
  96. }
  97. /**
  98. * Include the engine code for a specific named engine of a certain type.
  99. *
  100. * If the engine type has implemented hook_drush_engine_$type the path to the
  101. * engine specified in the array will be used.
  102. *
  103. * If you don't need to present any user options for selecting the engine
  104. * (which is common if the selection is implied by the running environment)
  105. * and you don't need to allow other modules to define their own engines you can
  106. * simply pass the $path to the directory where the engines are, and the
  107. * appropriate one will be included.
  108. *
  109. * Unlike drush_include this function will set errors if the requested engine
  110. * cannot be found.
  111. *
  112. * @param $type
  113. * The type of engine.
  114. * @param $engine
  115. * The key for the engine to be included.
  116. * @param $version
  117. * The version of the engine to be included - defaults to the current Drupal core
  118. * major version.
  119. * @param $path
  120. * A path to include from, if the engine has no corresponding
  121. * hook_drush_engine_$type item path.
  122. * @return unknown_type
  123. */
  124. function drush_include_engine($type, $engine, $version = NULL, $path = NULL) {
  125. $engines = drush_get_engines($type);
  126. if (!$path && isset($engines[$engine])) {
  127. $path = $engines[$engine]['path'];
  128. }
  129. if (!$path) {
  130. return drush_set_error('DRUSH_ENGINE INCLUDE_NO_PATH', dt('No path was set for including the !type engine !engine.', array('!type' => $type, '!engine' => $engine)));
  131. }
  132. if (drush_include($path, $engine, $version)) {
  133. return TRUE;
  134. }
  135. return drush_set_error('DRUSH_ENGINE INCLUDE_FAILED', dt('Unable to include the !type engine !engine from !path.' , array('!path' => $path, '!type' => $type, '!engine' => $engine)));
  136. }
  137. /**
  138. * Detects the version number of the current Drupal installation,
  139. * if any. Returns FALSE if there is no current Drupal installation,
  140. * or it is somehow broken.
  141. *
  142. * @return
  143. * A string containing the version number of the current
  144. * Drupal installation, if any. Otherwise, return FALSE.
  145. */
  146. function drush_drupal_version($drupal_root = NULL) {
  147. static $version = FALSE;
  148. if (!$version) {
  149. if (($drupal_root != NULL) || ($drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT'))) {
  150. // D7 stores VERSION in bootstrap.inc
  151. $version_constant_paths = array('/modules/system/system.module', '/includes/bootstrap.inc');
  152. foreach ($version_constant_paths as $path) {
  153. if (file_exists($drupal_root . $path)) {
  154. require_once $drupal_root . $path;
  155. }
  156. }
  157. // We just might be dealing with an early Drupal version (pre 4.7)
  158. if (defined('VERSION')) {
  159. $version = VERSION;
  160. }
  161. }
  162. }
  163. return $version;
  164. }
  165. /**
  166. * Check to see if a newer version of drush is available
  167. *
  168. * @return
  169. * TRUE - A new version is available.
  170. * FALSE - Error.
  171. * NULL - No release available.
  172. */
  173. function drush_check_self_update() {
  174. $error = "";
  175. // Don't check unless we have a datestamp in drush.info
  176. $drush_info = drush_read_drush_info();
  177. if (($drush_info === FALSE) || (!array_key_exists('datestamp', $drush_info))) {
  178. drush_log(dt('Cannot determine release date for drush'), 'notice');
  179. return FALSE;
  180. }
  181. // Allow updates to the latest HEAD release if --self-update=head is specified.
  182. // If we are called from `drush self-update`, then --dev will set --self-update=head.
  183. $dev_ok = (drush_get_option('self-update') == 'head');
  184. $is_dev = FALSE;
  185. // Get release info for drush
  186. $info = _drush_pm_get_releases(array('drush'));
  187. // Check for newer releases based on the datestamp.
  188. // We add 60 seconds to the drush.info date because of a drupal.org WTF. See http://drupal.org/node/1019356.
  189. $version_date = $drush_info['datestamp'] + 60;
  190. $newer_version = FALSE;
  191. foreach ($info['drush']['releases'] as $version => $release_info) {
  192. // We deliberately skip any dev releases unless the current release is a dev release.
  193. if ($dev_ok || ((!array_key_exists('version_extra', $release_info) || ($release_info['version_extra'] != 'dev')))) {
  194. if ($release_info['date'] > $version_date) {
  195. $newer_version = $release_info['version'];
  196. $version_date = $release_info['date'];
  197. $is_dev = isset($release_info['version_extra']) && $release_info['version_extra'] == 'dev';
  198. if ($is_dev) {
  199. $newer_version .= " (" . date('Y-M-d', $version_date) . ")";
  200. }
  201. }
  202. }
  203. }
  204. if ($newer_version) {
  205. drush_print(dt('A newer version of drush, !version, is available. You are currently running drush version !currentversion; to update, run `drush self-update`. To disable this check, put "$options[\'self-update\'] = FALSE;" in your drushrc.php configuration file.' . "\n", array('!version' => $newer_version, '!currentversion' => DRUSH_VERSION)));
  206. return TRUE;
  207. }
  208. else {
  209. drush_log(dt("drush self-update check: drush !version is up-to-date.", array('!version' => DRUSH_VERSION)), 'notice');
  210. }
  211. return NULL;
  212. }
  213. /**
  214. * Generate an .ini file. used by archive-dump."
  215. *
  216. * @param array $ini
  217. * A two dimensional associative array where top level are sections and
  218. * second level are key => value pairs.
  219. *
  220. * @return string
  221. * .ini formatted text.
  222. */
  223. function drush_export_ini($ini) {
  224. $output = '';
  225. foreach ($ini as $section => $pairs) {
  226. if ($section) {
  227. $output .= "[$section]\n";
  228. }
  229. foreach ($pairs as $k => $v) {
  230. if ($v) {
  231. $output .= "$k = \"$v\"\n";
  232. }
  233. }
  234. }
  235. return $output;
  236. }
  237. /**
  238. * Generate code friendly to the Drupal .info format from a structured array.
  239. * Mostly copied from http://drupalcode.org/viewvc/drupal/contributions/modules/features/features.export.inc.
  240. *
  241. * @param $info
  242. * An array or single value to put in a module's .info file.
  243. *
  244. * @param boolean $integer_keys
  245. * Use integer in keys.
  246. *
  247. * @param $parents
  248. * Array of parent keys (internal use only).
  249. *
  250. * @return
  251. * A code string ready to be written to a module's .info file.
  252. */
  253. function drush_export_info($info, $integer_keys = FALSE, $parents = array()) {
  254. $output = '';
  255. if (is_array($info)) {
  256. foreach ($info as $k => $v) {
  257. $child = $parents;
  258. $child[] = $k;
  259. $output .= drush_export_info($v, $integer_keys, $child);
  260. }
  261. }
  262. else if (!empty($info) && count($parents)) {
  263. $line = array_shift($parents);
  264. foreach ($parents as $key) {
  265. $line .= (!$integer_keys && is_numeric($key)) ? "[]" : "[{$key}]";
  266. }
  267. $line .= " = \"{$info}\"\n";
  268. return $line;
  269. }
  270. return $output;
  271. }
  272. function drush_drupal_cache_clear_all() {
  273. $prior = drush_get_context('DRUSH_AFFIRMATIVE');
  274. drush_set_context('DRUSH_AFFIRMATIVE', TRUE);
  275. drush_invoke('cache-clear', 'all');
  276. drush_set_context('DRUSH_AFFIRMATIVE', $prior);
  277. }
  278. /**
  279. * Returns the Drupal major version number (5, 6, 7 ...)
  280. */
  281. function drush_drupal_major_version($drupal_root = NULL) {
  282. $major_version = FALSE;
  283. if ($version = drush_drupal_version($drupal_root)) {
  284. $version_parts = explode('.', $version);
  285. if (is_numeric($version_parts[0])) {
  286. $major_version = (integer)$version_parts[0];
  287. }
  288. }
  289. return $major_version;
  290. }
  291. /**
  292. * Convert a csv string, or an array of items which
  293. * may contain csv strings, into an array of items.
  294. *
  295. * @param $args
  296. * A simple csv string; e.g. 'a,b,c'
  297. * or a simple list of items; e.g. array('a','b','c')
  298. * or some combination; e.g. array('a,b','c') or array('a,','b,','c,')
  299. *
  300. * @returns array
  301. * A simple list of items (e.g. array('a','b','c')
  302. */
  303. function _convert_csv_to_array($args) {
  304. //
  305. // Step 1: implode(',',$args) converts from, say, array('a,','b,','c,') to 'a,,b,,c,'
  306. // Step 2: explode(',', ...) converts to array('a','','b','','c','')
  307. // Step 3: array_filter(...) removes the empty items
  308. //
  309. return array_filter(explode(',', is_array($args) ? implode(',',$args) : $args));
  310. }
  311. /**
  312. * Get the available global options. Used by help command. Command files may
  313. * modify this list using hook_drush_help_alter().
  314. *
  315. * @param boolean $brief
  316. * Return a reduced set of important options. Used by help command.
  317. *
  318. * @return
  319. * An associative array containing the option definition as the key, and the description as the value,
  320. * for each of the available options.
  321. */
  322. function drush_get_global_options($brief = FALSE) {
  323. $options['root'] = array('short-form' => 'r', 'description' => dt("Drupal root directory to use (default: current directory)"), 'example-value' => '<path>');
  324. $options['uri'] = array('short-form' => 'l', 'description' => dt('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');
  325. $options['verbose'] = array('short-form' => 'v', 'description' => dt('Display extra information about the command.'));
  326. $options['debug'] = array('short-form' => 'd', 'description' => dt('Display even more information, including internal messages.'));
  327. $options['yes'] = array('short-form' => 'y', 'description' => dt("Assume 'yes' as answer to all prompts"));
  328. $options['no'] = array('short-form' => 'n', 'description' => dt("Assume 'no' as answer to all prompts"));
  329. $options['simulate'] = array('short-form' => 's', 'description' => dt("Simulate all relevant actions (don't actually change the system)"));
  330. $options['pipe'] = array('short-form' => 'p', 'description' => dt("Emit a compact representation of the command for scripting."));
  331. $options['help'] = array('short-form' => 'h', 'description' => dt("This help system."));
  332. $options['version'] = dt("Show drush version.");
  333. $options['php'] = dt("The absolute path to your PHP intepreter, if not 'php' in the path.");
  334. if (!$brief) {
  335. $options['quiet'] = array('short-form' => 'q', 'description' => dt('Hide all output'));
  336. $options['include'] = array('short-form' => 'i', 'description' => dt("A list of paths to search for drush commands"));
  337. $options['config'] = array('short-form' => 'c', 'description' => dt("Specify a config file to use. See example.drushrc.php"));
  338. $options['user'] = array('short-form' => 'u', 'description' => dt("Specify a user to login with. May be a name or a number."));
  339. $options['backend'] = array('short-form' => 'b', 'description' => dt("Hide all output and return structured data (internal use only)."));
  340. $options['choice'] = dt("Provide an answer to a multiple-choice prompt.");
  341. $options['no-label'] = dt("Remove the site label that drush includes in multi-site command output(e.g. `drush @site1,@site2 status`).");
  342. $options['nocolor'] = dt("Suppress color highlighting on log messages.");
  343. $options['show-passwords'] = dt("Show database passwords in commands that display connection information.");
  344. $options['show-invoke'] = dt("Show all function names which could have been called for the current command. See drush_invoke().");
  345. $options['watchdog'] = dt("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.");
  346. }
  347. return $options;
  348. }
  349. /**
  350. * Prints out help for a given command.
  351. */
  352. function drush_show_help($commandstring) {
  353. // First check and see if the command can already be found.
  354. $commands = drush_get_commands();
  355. if (!array_key_exists($commandstring, $commands)) {
  356. // If the command cannot be found, then bootstrap so that
  357. // additional commands will be brought in.
  358. // For speed, only bootstrap up to DRUSH_BOOTSTRAP_DRUPAL_SITE.
  359. drush_bootstrap_max(DRUSH_BOOTSTRAP_DRUPAL_SITE);
  360. $commands = drush_get_commands();
  361. }
  362. if (array_key_exists($commandstring, $commands)) {
  363. $command = $commands[$commandstring];
  364. drush_print_help($command);
  365. return TRUE;
  366. }
  367. return drush_set_error('DRUSH_COMMAND_NOT_FOUND', dt('Invalid command !command.', array('!command' => $commandstring)));
  368. }
  369. /**
  370. * Print the help for a single command to the screen.
  371. *
  372. * @param array $command
  373. * A fully loaded $command array.
  374. */
  375. function drush_print_help($command) {
  376. // Merge in engine specific help.
  377. foreach ($command['engines'] as $type => $description) {
  378. $all_engines = drush_get_engines($type);
  379. foreach ($all_engines as $name => $engine) {
  380. $command = array_merge_recursive($command, $engine);
  381. }
  382. }
  383. if (!$help = drush_command_invoke_all('drush_help', 'drush:'. $command['command'])) {
  384. $help = array($command['description']);
  385. }
  386. // Give commandfiles an opportunity to add examples and options to the command.
  387. drush_bootstrap_max(DRUSH_BOOTSTRAP_DRUPAL_SITE);
  388. drush_command_invoke_all_ref('drush_help_alter', $command);
  389. drush_print(wordwrap(implode("\n", $help), drush_get_context('DRUSH_COLUMNS', 80)));
  390. drush_print();
  391. foreach ($command['sections'] as $key => $value) {
  392. if (!empty($command[$key])) {
  393. drush_print(dt($value) . ':');
  394. $rows = drush_format_help_section($command, $key);
  395. drush_print_table($rows, FALSE, array(40));
  396. unset($rows);
  397. drush_print();
  398. }
  399. }
  400. // Append aliases if any.
  401. if ($command['aliases']) {
  402. drush_print(dt("Aliases: ") . implode(', ', $command['aliases']));
  403. }
  404. }
  405. /**
  406. * Format one named help section from a command record
  407. *
  408. * @param $command
  409. * A command record with help information
  410. * @param $section
  411. * The name of the section to format ('options', 'topic', etc.)
  412. * @returns array
  413. * Formatted rows, suitable for printing via drush_print_table.
  414. */
  415. function drush_format_help_section($command, $section) {
  416. $formatter = (function_exists('drush_help_section_formatter_' . $section)) ? 'drush_help_section_formatter_' . $section : 'drush_help_section_default_formatter';
  417. foreach ($command[$section] as $name => $help_attributes) {
  418. if (!is_array($help_attributes)) {
  419. $help_attributes = array('description' => $help_attributes);
  420. }
  421. $help_attributes['label'] = $name;
  422. call_user_func_array($formatter, array($command, &$help_attributes));
  423. $rows[] = array($help_attributes['label'], $help_attributes['description']);
  424. // Process the subsections too, if any
  425. if (!empty($command['sub-' . $section]) && array_key_exists($name, $command['sub-' . $section])) {
  426. $rows = array_merge($rows, _drush_format_help_subsection($command, $section, $name, $formatter));
  427. }
  428. }
  429. return $rows;
  430. }
  431. /**
  432. * Format one named portion of a subsection from a command record.
  433. * Subsections allow related parts of a help record to be grouped
  434. * together. For example, in the 'options' section, sub-options that
  435. * are related to a particular primary option are stored in a 'sub-options'
  436. * section whose name == the name of the primary option.
  437. *
  438. * @param $command
  439. * A command record with help information
  440. * @param $section
  441. * The name of the section to format ('options', 'topic', etc.)
  442. * @param $subsection
  443. * The name of the subsection (e.g. the name of the primary option)
  444. * @param $formatter
  445. * The name of a function to use to format the rows of the subsection
  446. * @param $prefix
  447. * Characters to prefix to the front of the label (for indentation)
  448. * @returns array
  449. * Formatted rows, suitable for printing via drush_print_table.
  450. */
  451. function _drush_format_help_subsection($command, $section, $subsection, $formatter, $prefix = ' ') {
  452. foreach ($command['sub-' . $section][$subsection] as $name => $help_attributes) {
  453. if (!is_array($help_attributes)) {
  454. $help_attributes = array('description' => $help_attributes);
  455. }
  456. $help_attributes['label'] = $name;
  457. call_user_func_array($formatter, array($command, &$help_attributes));
  458. $rows[] = array($prefix . $help_attributes['label'], $help_attributes['description']);
  459. // Process the subsections too, if any
  460. if (!empty($command['sub-' . $section]) && array_key_exists($name, $command['sub-' . $section])) {
  461. $rows = array_merge($rows, _drush_format_help_subsection($command, $section, $name, $formatter, $prefix . ' '));
  462. }
  463. }
  464. return $rows;
  465. }
  466. /**
  467. * The options section formatter. Adds a "--" in front of each
  468. * item label. Also handles short-form and example-value
  469. * components in the help attributes.
  470. */
  471. function drush_help_section_formatter_options($command, &$help_attributes) {
  472. if ($help_attributes['label'][0] == '-') {
  473. drush_log(dt("Option '%option' of command %command should instead be declared as '%fixed'", array('%option' => $help_attributes['label'], '%command' => $command['command'], '%fixed' => preg_replace('/^--*/', '', $help_attributes['label']))), 'debug');
  474. }
  475. else {
  476. $help_attributes['label'] = '--' . $help_attributes['label'];
  477. }
  478. if (array_key_exists('example-value', $help_attributes)) {
  479. $help_attributes['label'] .= '=' . $help_attributes['example-value'];
  480. if (array_key_exists('short-form', $help_attributes)) {
  481. $help_attributes['short-form'] .= ' ' . $help_attributes['example-value'];
  482. }
  483. }
  484. if (array_key_exists('short-form', $help_attributes)) {
  485. $help_attributes['label'] = '-' . $help_attributes['short-form'] . ', ' . $help_attributes['label'];
  486. }
  487. drush_help_section_default_formatter($command, $help_attributes);
  488. }
  489. /**
  490. * The default section formatter. Replaces '[command]' with the
  491. * command name.
  492. */
  493. function drush_help_section_default_formatter($command, &$help_attributes) {
  494. // '[command]' is a token representing the current command. @see pm_drush_engine_version_control().
  495. $help_attributes['label'] = str_replace('[command]', $command['command'], $help_attributes['label']);
  496. }
  497. /**
  498. * Exits with a message. In general, you should use drush_set_error() instead of
  499. * this function. That lets drush proceed with other tasks.
  500. * TODO: Exit with a correct status code.
  501. */
  502. function drush_die($msg = NULL, $status = NULL) {
  503. die($msg ? "drush: $msg\n" : '');
  504. }
  505. /*
  506. * Check to see if the provided line is a "#!/usr/bin/env drush"
  507. * "shebang" script line.
  508. */
  509. function _drush_is_drush_shebang_line($line) {
  510. return ((substr($line,0,2) == '#!') && (strstr($line, 'drush') !== FALSE));
  511. }
  512. /*
  513. * Check to see if the provided script file is a "#!/usr/bin/env drush"
  514. * "shebang" script line.
  515. */
  516. function _drush_is_drush_shebang_script($script_filename) {
  517. $result = FALSE;
  518. if (file_exists($script_filename)) {
  519. $fp = fopen($script_filename, "r");
  520. if ($fp !== FALSE) {
  521. $line = fgets($fp);
  522. $result = _drush_is_drush_shebang_line($line);
  523. fclose($fp);
  524. }
  525. }
  526. return $result;
  527. }
  528. /**
  529. * @defgroup outputfunctions Process output text.
  530. * @{
  531. /**
  532. * Prints a message with optional indentation. In general,
  533. * drush_log($message, 'ok') is often a better choice than this function.
  534. * That gets your confirmation message (for example) into the logs for this
  535. * drush request. Consider that drush requests may be executed remotely and
  536. * non interactively.
  537. *
  538. * @param $message
  539. * The message to print.
  540. * @param $indent
  541. * The indentation (space chars)
  542. * @param $handle
  543. * File handle to write to. NULL will write
  544. * to standard output, STDERR will write to the standard
  545. * error. See http://php.net/manual/en/features.commandline.io-streams.php
  546. */
  547. function drush_print($message = '', $indent = 0, $handle = NULL) {
  548. $msg = str_repeat(' ', $indent) . (string)$message . "\n";
  549. if (($charset = drush_get_option('output_charset')) && function_exists('iconv')) {
  550. $msg = iconv('UTF-8', $charset, $msg);
  551. }
  552. if (isset($handle)) {
  553. fwrite($handle, $msg);
  554. }
  555. else {
  556. print $msg;
  557. }
  558. }
  559. /**
  560. * Stores a message which is printed during drush_shutdown() if in compact mode.
  561. * @param $message
  562. * The message to print. If $message is an array,
  563. * then each element of the array is printed on a
  564. * separate line.
  565. */
  566. function drush_print_pipe($message = '') {
  567. $buffer = &drush_get_context('DRUSH_PIPE_BUFFER' , '');
  568. if (is_array($message)) {
  569. $message = implode("\n", $message) . "\n";
  570. }
  571. $buffer .= $message;
  572. }
  573. /**
  574. * Prints an array or string.
  575. * @param $array
  576. * The array to print.
  577. */
  578. function drush_print_r($array, $handle = NULL) {
  579. drush_print(print_r($array, TRUE), 0, $handle);
  580. }
  581. /**
  582. * Rudimentary replacement for Drupal API t() function.
  583. *
  584. * @param string
  585. * String to process, possibly with replacement item.
  586. * @param array
  587. * An associative array of replacement items.
  588. *
  589. * @return
  590. * The processed string.
  591. *
  592. * @see t()
  593. */
  594. function dt($string, $args = array()) {
  595. if (function_exists('t')) {
  596. return t($string, $args);
  597. }
  598. else {
  599. if (!empty($args)) {
  600. return strtr($string, $args);
  601. }
  602. else {
  603. return $string;
  604. }
  605. }
  606. }
  607. /**
  608. * Convert html to readable text. Compatible API to
  609. * drupal_html_to_text, but less functional. Caller
  610. * might prefer to call drupal_html_to_text if there
  611. * is a bootstrapped Drupal site available.
  612. *
  613. * @param string $html
  614. * The html text to convert.
  615. *
  616. * @return string
  617. * The plain-text representation of the input.
  618. */
  619. function drush_html_to_text($html, $allowed_tags = NULL) {
  620. $replacements = array(
  621. '<hr>' => '------------------------------------------------------------------------------',
  622. '<li>' => ' * ',
  623. '<h1>' => '===== ',
  624. '</h1>' => ' =====',
  625. '<h2>' => '---- ',
  626. '</h2>' => ' ----',
  627. '<h3>' => '::: ',
  628. '</h3>' => ' :::',
  629. '<br/>' => "\n",
  630. );
  631. $text = str_replace(array_keys($replacements), array_values($replacements), $html);
  632. return html_entity_decode(preg_replace('/ *<[^>]*> */', ' ', $text));
  633. }
  634. /**
  635. * Print a formatted table.
  636. *
  637. * @param $rows
  638. * The rows to print.
  639. * @param $header
  640. * If TRUE, the first line will be treated as table header.
  641. * @param $widths
  642. * The widths of each column (in characters) to use - if not specified this
  643. * will be determined automatically, based on a "best fit" algorithm.
  644. * @param $handle
  645. * File handle to write to. NULL will write
  646. * to standard output, STDERR will write to the standard
  647. * error. See http://php.net/manual/en/features.commandline.io-streams.php
  648. * @return $tbl
  649. * Use $tbl->getTable() to get the output from the return value.
  650. */
  651. function drush_print_table($rows, $header = FALSE, $widths = array(), $handle = NULL) {
  652. $tbl = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT , '');
  653. $auto_widths = drush_table_column_autowidth($rows, $widths);
  654. // Do wordwrap on all cells.
  655. $newrows = array();
  656. foreach ($rows as $rowkey => $row) {
  657. foreach ($row as $col_num => $cell) {
  658. $newrows[$rowkey][$col_num] = wordwrap($cell, $auto_widths[$col_num], "\n", TRUE);
  659. if (isset($widths[$col_num])) {
  660. $newrows[$rowkey][$col_num] = str_pad($newrows[$rowkey][$col_num], $widths[$col_num]);
  661. }
  662. }
  663. }
  664. if ($header) {
  665. $headers = array_shift($newrows);
  666. $tbl->setHeaders($headers);
  667. }
  668. $tbl->addData($newrows);
  669. $output = $tbl->getTable();
  670. if (!stristr(PHP_OS, 'WIN')) {
  671. $output = str_replace("\r\n", PHP_EOL, $output);
  672. }
  673. // Check if the handle argument is a string to preserve compatability with
  674. // previous versions that accepted a filename instead.
  675. if (is_string($handle)) {
  676. file_put_contents($handle, $output, FILE_APPEND);
  677. }
  678. else {
  679. drush_print($output, 0, $handle);
  680. }
  681. return $tbl;
  682. }
  683. /**
  684. * Convert an associative array of key : value pairs into
  685. * a table suitable for processing by drush_print_table.
  686. *
  687. * @param $keyvalue_table
  688. * An associative array of key : value pairs.
  689. * @return
  690. * An array of arrays, where the keys from the input
  691. * array are stored in the first column, and the values
  692. * are stored in the third. A second colum is created
  693. * specifically to hold the ':' separator.
  694. */
  695. function drush_key_value_to_array_table($keyvalue_table) {
  696. $table = array();
  697. foreach ($keyvalue_table as $key => $value) {
  698. if (isset($value)) {
  699. $table[] = array($key, ' :', $value);
  700. }
  701. else {
  702. $table[] = array($key . ':', '', '');
  703. }
  704. }
  705. return $table;
  706. }
  707. /**
  708. * Determine the best fit for column widths.
  709. *
  710. * @param $rows
  711. * The rows to use for calculations.
  712. * @param $widths
  713. * Manually specified widths of each column (in characters) - these will be
  714. * left as is.
  715. */
  716. function drush_table_column_autowidth($rows, $widths) {
  717. $auto_widths = $widths;
  718. // First we determine the distribution of row lengths in each column.
  719. // This is an array of descending character length keys (i.e. starting at
  720. // the rightmost character column), with the value indicating the number
  721. // of rows where that character column is present.
  722. $col_dist = array();
  723. foreach ($rows as $rowkey => $row) {
  724. foreach ($row as $col_num => $cell) {
  725. if (empty($widths[$col_num])) {
  726. $length = strlen($cell);
  727. while ($length > 0) {
  728. if (!isset($col_dist[$col_num][$length])) {
  729. $col_dist[$col_num][$length] = 0;
  730. }
  731. $col_dist[$col_num][$length]++;
  732. $length--;
  733. }
  734. }
  735. }
  736. }
  737. foreach ($col_dist as $col_num => $count) {
  738. // Sort the distribution in decending key order.
  739. krsort($col_dist[$col_num]);
  740. // Initially we set all columns to their "ideal" longest width
  741. // - i.e. the width of their longest column.
  742. $auto_widths[$col_num] = max(array_keys($col_dist[$col_num]));
  743. }
  744. // We determine what width we have available to use, and what width the
  745. // above "ideal" columns take up.
  746. $available_width = drush_get_context('DRUSH_COLUMNS', 80) - (count($auto_widths) * 2);
  747. $auto_width_current = array_sum($auto_widths);
  748. // If we need to reduce a column so that we can fit the space we use this
  749. // loop to figure out which column will cause the "least wrapping",
  750. // (relative to the other columns) and reduce the width of that column.
  751. while ($auto_width_current > $available_width) {
  752. $count = 0;
  753. $width = 0;
  754. foreach ($col_dist as $col_num => $counts) {
  755. // If we are just starting out, select the first column.
  756. if ($count == 0 ||
  757. // OR: if this column would cause less wrapping than the currently
  758. // selected column, then select it.
  759. (current($counts) < $count) ||
  760. // OR: if this column would cause the same amount of wrapping, but is
  761. // longer, then we choose to wrap the longer column (proportionally
  762. // less wrapping, and helps avoid triple line wraps).
  763. (current($counts) == $count && key($counts) > $width)) {
  764. // Select the column number, and record the count and current width
  765. // for later comparisons.
  766. $column = $col_num;
  767. $count = current($counts);
  768. $width = key($counts);
  769. }
  770. }
  771. if ($width <= 1) {
  772. // If we have reached a width of 1 then give up, so wordwrap can still progress.
  773. break;
  774. }
  775. // Reduce the width of the selected column.
  776. $auto_widths[$column]--;
  777. // Reduce our overall table width counter.
  778. $auto_width_current--;
  779. // Remove the corresponding data from the disctribution, so next time
  780. // around we use the data for the row to the left.
  781. unset($col_dist[$column][$width]);
  782. }
  783. return $auto_widths;
  784. }
  785. /**
  786. * Print the contents of a file.
  787. *
  788. * @param string $file
  789. * Full path to a file.
  790. */
  791. function drush_print_file($file) {
  792. // Don't even bother to print the file in --no mode
  793. if (drush_get_context('DRUSH_NEGATIVE')) {
  794. return;
  795. }
  796. if ((substr($file,-4) == ".htm") || (substr($file,-5) == ".html")) {
  797. $tmp_file = drush_tempnam(basename($file));
  798. file_put_contents($tmp_file, drush_html_to_text(file_get_contents($file)));
  799. $file = $tmp_file;
  800. }
  801. // Do not wait for user input in --yes or --pipe modes
  802. if (drush_get_context('DRUSH_PIPE')) {
  803. drush_print_pipe(file_get_contents($file));
  804. }
  805. elseif (drush_get_context('DRUSH_AFFIRMATIVE')) {
  806. drush_print(file_get_contents($file));
  807. }
  808. elseif (drush_shell_exec_interactive("less %s", $file)) {
  809. return;
  810. }
  811. elseif (drush_shell_exec_interactive("more %s", $file)) {
  812. return;
  813. }
  814. else {
  815. drush_print(file_get_contents($file));
  816. }
  817. }
  818. /**
  819. * Converts a PHP variable into its Javascript equivalent.
  820. *
  821. * We provide a copy of D7's drupal_json_encode since this function is
  822. * unavailable on earlier versions of Drupal.
  823. *
  824. * @see drupal_json_decode()
  825. * @ingroup php_wrappers
  826. */
  827. function drush_json_encode($var) {
  828. // json_encode() does not escape <, > and &, so we do it with str_replace().
  829. return str_replace(array('<', '>', '&'), array('\u003c', '\u003e', '\u0026'), json_encode($var));
  830. }
  831. /**
  832. * Converts an HTML-safe JSON string into its PHP equivalent.
  833. *
  834. * We provide a copy of D7's drupal_json_decode since this function is
  835. * unavailable on earlier versions of Drupal.
  836. *
  837. * @see drupal_json_encode()
  838. * @ingroup php_wrappers
  839. */
  840. function drush_json_decode($var) {
  841. return json_decode($var, TRUE);
  842. }
  843. /**
  844. * @} End of "defgroup outputfunctions".
  845. */
  846. /**
  847. * @defgroup userinput Get input from the user.
  848. * @{
  849. /**
  850. * Ask the user a basic yes/no question.
  851. *
  852. * @param $msg The question to ask
  853. * @return TRUE if the user entered 'y', FALSE if he entered 'n'
  854. */
  855. function drush_confirm($msg, $indent = 0) {
  856. print str_repeat(' ', $indent) . (string)$msg . " (y/n): ";
  857. // Automatically accept confirmations if the --yes argument was supplied.
  858. if (drush_get_context('DRUSH_AFFIRMATIVE')) {
  859. print "y\n";
  860. return TRUE;
  861. }
  862. // Automatically cancel confirmations if the --no argument was supplied.
  863. elseif (drush_get_context('DRUSH_NEGATIVE')) {
  864. print "n\n";
  865. return FALSE;
  866. }
  867. // See http://drupal.org/node/499758 before changing this.
  868. $stdin = fopen("php://stdin","r");
  869. while ($line = fgets($stdin)) {
  870. $line = trim($line);
  871. if ($line == 'y') {
  872. return TRUE;
  873. }
  874. if ($line == 'n') {
  875. return FALSE;
  876. }
  877. print str_repeat(' ', $indent) . (string)$msg . " (y/n): ";
  878. }
  879. }
  880. /**
  881. * Ask the user to select an item from a list.
  882. * From a provided associative array, drush_choice will
  883. * display all of the questions, numbered from 1 to N,
  884. * and return the item the user selected. "0" is always
  885. * cancel; entering a blank line is also interpreted
  886. * as cancelling.
  887. *
  888. * @param $options
  889. * A list of questions to display to the user. The
  890. * KEYS of the array are the result codes to return to the
  891. * caller; the VALUES are the messages to display on
  892. * each line. Special keys of the form '-- something --' can be
  893. * provided as separator between choices groups. Separator keys
  894. * don't alter the numbering.
  895. * @param $prompt
  896. * The message to display to the user prompting for input.
  897. * @param $label
  898. * Controls the display of each line. Defaults to
  899. * '!value', which displays the value of each item
  900. * in the $options array to the user. Use '!key' to
  901. * display the key instead. In some instances, it may
  902. * be useful to display both the key and the value; for
  903. * example, if the key is a user id and the value is the
  904. * user name, use '!value (uid=!key)'.
  905. */
  906. function drush_choice($options, $prompt = 'Enter a number.', $label = '!value') {
  907. print dt($prompt) . "\n";
  908. // Preflight so that all rows will be padded out to the same number of columns
  909. $array_pad = 0;
  910. foreach ($options as $key => $option) {
  911. if (is_array($option) && (count($option) > $array_pad)) {
  912. $array_pad = count($option);
  913. }
  914. }
  915. $rows[] = array_pad(array('[0]', ':', 'Cancel'), $array_pad + 2, '');
  916. $selection_number = 0;
  917. foreach ($options as $key => $option) {
  918. if ((substr($key, 0, 3) == '-- ') && (substr($key, -3) == ' --')) {
  919. $rows[] = array_pad(array('', '', $option), $array_pad + 2, '');
  920. }
  921. else {
  922. $selection_number++;
  923. $row = array("[$selection_number]", ':');
  924. if (is_array($option)) {
  925. $row = array_merge($row, $option);
  926. }
  927. else {
  928. $row[] = dt($label, array('!number' => $selection_number, '!key' => $key, '!value' => $option));
  929. }
  930. $rows[] = $row;
  931. $selection_list[$selection_number] = $key;
  932. }
  933. }
  934. drush_print_table($rows);
  935. drush_print_pipe(array_keys($options));
  936. // If the user specified --choice, then make an
  937. // automatic selection. Cancel if the choice is
  938. // not an available option.
  939. if (($choice = drush_get_option('choice', FALSE)) !== FALSE) {
  940. // First check to see if $choice is one of the symbolic options
  941. if (array_key_exists($choice, $options)) {
  942. return $choice;
  943. }
  944. // Next handle numeric selections
  945. elseif (array_key_exists($choice, $selection_list)) {
  946. return $selection_list[$choice];
  947. }
  948. return FALSE;
  949. }
  950. // If the user specified --no, then cancel; also avoid
  951. // getting hung up waiting for user input in --pipe and
  952. // backend modes. If none of these apply, then wait,
  953. // for user input and return the selected result.
  954. if (!drush_get_context('DRUSH_NEGATIVE') && !drush_get_context('DRUSH_AFFIRMATIVE') && !drush_get_context('DRUSH_PIPE')) {
  955. while ($line = trim(fgets(STDIN))) {
  956. if (array_key_exists($line, $selection_list)) {
  957. return $selection_list[$line];
  958. }
  959. }
  960. }
  961. // We will allow --yes to confirm input if there is only
  962. // one choice; otherwise, --yes will cancel to avoid ambiguity
  963. if (drush_get_context('DRUSH_AFFIRMATIVE') && (count($options) == 1)) {
  964. return $selection_list[1];
  965. }
  966. drush_print(dt('Cancelled'));
  967. return FALSE;
  968. }
  969. /**
  970. * Ask the user to select multiple items from a list.
  971. * This is a wrapper around drush_choice, that repeats the selection process,
  972. * allowing users to toggle a number of items in a list. The number of values
  973. * that can be constrained by both min and max: the user will only be allowed
  974. * finalize selection once the minimum number has been selected, and the oldest
  975. * selected value will "drop off" the list, if they exceed the maximum number.
  976. *
  977. * @param $options
  978. * Same as drush_choice() (see above).
  979. * @param $defaults
  980. * This can take 3 forms:
  981. * - FALSE: (Default) All options are unselected by default.
  982. * - TRUE: All options are selected by default.
  983. * - Array of $options keys to be selected by default.
  984. * @param $prompt
  985. * Same as drush_choice() (see above).
  986. * @param $label
  987. * Same as drush_choice() (see above).
  988. * @param $mark
  989. * Controls how selected values are marked. Defaults to '!value (selected)'.
  990. * @param $min
  991. * Constraint on minimum number of selections. Defaults to zero. When fewer
  992. * options than this are selected, no final options will be available.
  993. * @param $max
  994. * Constraint on minimum number of selections. Defaults to NULL (unlimited).
  995. * If the a new selection causes this value to be exceeded, the oldest
  996. * previously selected value is automatically unselected.
  997. * @param $final_options
  998. * An array of additional options in the same format as $options.
  999. * When the minimum number of selections is met, this array is merged into the
  1000. * array of options. If the user selects one of these values and the
  1001. * selection process will complete (the key for the final option is included
  1002. * in the return value). If this is an empty array (default), then a built in
  1003. * final option of "Done" will be added to the available options (in this case
  1004. * no additional keys are added to the return value).
  1005. */
  1006. function drush_choice_multiple($options, $defaults = FALSE, $prompt = 'Select some numbers.', $label = '!value', $mark = '!value (selected)', $min = 0, $max = NULL, $final_options = array()) {
  1007. $selections = array();
  1008. // Load default selections.
  1009. if (is_array($defaults)) {
  1010. $selections = $defaults;
  1011. }
  1012. elseif ($defaults === TRUE) {
  1013. $selections = array_keys($options);
  1014. }
  1015. $complete = FALSE;
  1016. $final_builtin = array();
  1017. if (empty($final_options)) {
  1018. $final_builtin['done'] = dt('Done');
  1019. }
  1020. $final_options_keys = array_keys($final_options);
  1021. while (TRUE) {
  1022. $current_options = $options;
  1023. // Mark selections.
  1024. foreach ($selections as $selection) {
  1025. $current_options[$selection] = dt($mark, array('!key' => $selection, '!value' => $options[$selection]));
  1026. }
  1027. // Add final options, if the minimum number of selections has been reached.
  1028. if (count($selections) >= $min) {
  1029. $current_options = array_merge($current_options, $final_options, $final_builtin);
  1030. }
  1031. $toggle = drush_choice($current_options, $prompt, $label);
  1032. if ($toggle === FALSE) {
  1033. return FALSE;
  1034. }
  1035. // Don't include the built in final option in the return value.
  1036. if (count($selections) >= $min && empty($final_options) && $toggle == 'done') {
  1037. return $selections;
  1038. }
  1039. // Toggle the selected value.
  1040. $item = array_search($toggle, $selections);
  1041. if ($item === FALSE) {
  1042. array_unshift($selections, $toggle);
  1043. }
  1044. else {
  1045. unset($selections[$item]);
  1046. }
  1047. // If the user selected one of the final options, return.
  1048. if (count($selections) >= $min && in_array($toggle, $final_options_keys)) {
  1049. return $selections;
  1050. }
  1051. // If the user selected too many options, drop the oldest selection.
  1052. if (count($selections) > $max) {
  1053. array_pop($selections);
  1054. }
  1055. }
  1056. }
  1057. /**
  1058. * Prompt the user for input
  1059. *
  1060. * The input can be anything that fits on a single line (not only y/n),
  1061. * so we can't use drush_confirm()
  1062. *
  1063. * @param $prompt
  1064. * The text which is displayed to the user.
  1065. * @param $default
  1066. * The default value of the input.
  1067. * @param $required
  1068. * If TRUE, user may continue even when no value is in the input.
  1069. *
  1070. * @see drush_confirm()
  1071. */
  1072. function drush_prompt($prompt, $default = NULL, $required = TRUE) {
  1073. if (!is_null($default)) {
  1074. $prompt .= " [" . $default . "]";
  1075. }
  1076. $prompt .= ": ";
  1077. print $prompt;
  1078. if (drush_get_context('DRUSH_AFFIRMATIVE')) {
  1079. return $default;
  1080. }
  1081. $stdin = fopen('php://stdin', 'r');
  1082. stream_set_blocking($stdin, TRUE);
  1083. while (($line = fgets($stdin)) !== FALSE) {
  1084. $line = trim($line);
  1085. if ($line === "") {
  1086. $line = $default;
  1087. }
  1088. if ($line || !$required) {
  1089. break;
  1090. }
  1091. print $prompt;
  1092. }
  1093. fclose($stdin);
  1094. return $line;
  1095. }
  1096. /**
  1097. * @} End of "defgroup userinput".
  1098. */
  1099. /**
  1100. * @defgroup commandwrappers Functions to execute commands.
  1101. * @{
  1102. */
  1103. /**
  1104. * Calls a given function, passing through all arguments unchanged.
  1105. *
  1106. * This should be used when calling possibly mutative or destructive functions
  1107. * (e.g. unlink() and other file system functions) so that can be suppressed
  1108. * if the simulation mode is enabled.
  1109. *
  1110. * Important: Call @see drush_op_system() to execute a shell command,
  1111. * or @see drush_shell_exec() to execute a shell command and capture the
  1112. * shell output.
  1113. *
  1114. * @param $function
  1115. * The name of the function. Any additional arguments are passed along.
  1116. * @return
  1117. * The return value of the function, or TRUE if simulation mode is enabled.
  1118. *
  1119. */
  1120. function drush_op($function) {
  1121. $args = func_get_args();
  1122. array_shift($args); // Skip function name
  1123. foreach ($args as $arg) {
  1124. $args_printed[] = is_scalar($arg) ? $arg : (is_array($arg) ? 'Array' : 'Object');
  1125. }
  1126. // Special checking for drush_op('system')
  1127. if ($function == 'system') {
  1128. drush_log(dt("Do not call drush_op('system'); use drush_op_system instead"), 'debug');
  1129. }
  1130. if (drush_get_context('DRUSH_VERBOSE') || drush_get_context('DRUSH_SIMULATE')) {
  1131. drush_log(sprintf("Calling %s(%s)", $function, implode(", ", $args_printed)), 'debug');
  1132. }
  1133. if (drush_get_context('DRUSH_SIMULATE')) {
  1134. return TRUE;
  1135. }
  1136. return call_user_func_array($function, $args);
  1137. }
  1138. /**
  1139. * Calls 'system()' function, passing through all arguments unchanged.
  1140. *
  1141. * This should be used when calling possibly mutative or destructive functions
  1142. * (e.g. unlink() and other file system functions) so that can be suppressed
  1143. * if the simulation mode is enabled.
  1144. *
  1145. * @param $exec
  1146. * The shell command to execute. Parameters should already be escaped.
  1147. * @return
  1148. * The result code from system(): 0 == success.
  1149. *
  1150. * @see drush_shell_exec()
  1151. */
  1152. function drush_op_system($exec) {
  1153. if (drush_get_context('DRUSH_VERBOSE') || drush_get_context('DRUSH_SIMULATE')) {
  1154. drush_print("Calling system($exec);");
  1155. }
  1156. if (drush_get_context('DRUSH_SIMULATE')) {
  1157. return 0;
  1158. }
  1159. // Throw away output. Use drush_shell_exec() to capture output.
  1160. system($exec, $result_code);
  1161. return $result_code;
  1162. }
  1163. /**
  1164. * Executes a shell command at a new working directory.
  1165. * The old cwd is restored on exit.
  1166. *
  1167. * @param $effective_wd
  1168. * The new working directory to execute the shell command at.
  1169. * @param $cmd
  1170. * The command to execute. May include placeholders used for sprintf.
  1171. * @param ...
  1172. * Values for the placeholders specified in $cmd. Each of these will be passed through escapeshellarg() to ensure they are safe to use on the command line.
  1173. * @return
  1174. * TRUE on success, FALSE on failure
  1175. */
  1176. function drush_shell_cd_and_exec($effective_wd, $cmd) {
  1177. $args = func_get_args();
  1178. $effective_wd = array_shift($args);
  1179. $cwd = getcwd();
  1180. drush_op('chdir', $effective_wd);
  1181. $result = call_user_func_array('drush_shell_exec', $args);
  1182. drush_op('chdir', $cwd);
  1183. return $result;
  1184. }
  1185. /**
  1186. * Executes a shell command.
  1187. * Output is only printed if in verbose mode.
  1188. * Output is stored and can be retrieved using drush_shell_exec_output().
  1189. * If in simulation mode, no action is taken.
  1190. *
  1191. * @param $cmd
  1192. * The command to execute. May include placeholders used for sprintf.
  1193. * @param ...
  1194. * Values for the placeholders specified in $cmd. Each of these will be passed through escapeshellarg() to ensure they are safe to use on the command line.
  1195. * @return
  1196. * TRUE on success, FALSE on failure
  1197. */
  1198. function drush_shell_exec($cmd) {
  1199. return _drush_shell_exec(func_get_args());
  1200. }
  1201. /**
  1202. * Executes a command in interactive mode.
  1203. *
  1204. * @see drush_shell_exec.
  1205. */
  1206. function drush_shell_exec_interactive($cmd) {
  1207. return _drush_shell_exec(func_get_args(), TRUE);
  1208. }
  1209. /**
  1210. * Internal function: executes a shell command on the
  1211. * local machine. This function should not be used
  1212. * in instances where ssh is utilized to execute a
  1213. * command remotely; otherwise, remote operations would
  1214. * fail if executed from a Windows machine to a remote
  1215. * Linux server.
  1216. *
  1217. * @param $args
  1218. * The command and its arguments.
  1219. * @param $interactive
  1220. * Whether to run in
  1221. *
  1222. * @return
  1223. * TRUE on success, FALSE on failure
  1224. *
  1225. * @see drush_shell_exec.
  1226. */
  1227. function _drush_shell_exec($args, $interactive = FALSE) {
  1228. //do not change the command itself, just the parameters.
  1229. for ($x = 1; $x < sizeof($args); $x++) {
  1230. $args[$x] = drush_escapeshellarg($args[$x]);
  1231. }
  1232. $command = call_user_func_array('sprintf', $args);
  1233. if (drush_get_context('DRUSH_VERBOSE') || drush_get_context('DRUSH_SIMULATE')) {
  1234. drush_print('Executing: ' . $command);
  1235. }
  1236. if (!drush_get_context('DRUSH_SIMULATE')) {
  1237. if ($interactive) {
  1238. $result = proc_open($command, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
  1239. proc_close($result);
  1240. // proc_open returns FALSE on failure, or a resource on success.
  1241. return ($result === FALSE) ? FALSE : TRUE;
  1242. }
  1243. else {
  1244. exec($command . ' 2>&1', $output, $result);
  1245. _drush_shell_exec_output_set($output);
  1246. if (drush_get_context('DRUSH_DEBUG')) {
  1247. foreach ($output as $line) {
  1248. drush_print($line, 2);
  1249. }
  1250. }
  1251. // Exit code 0 means success.
  1252. return ($result == 0);
  1253. }
  1254. }
  1255. else {
  1256. return TRUE;
  1257. }
  1258. }
  1259. /**
  1260. * Determine the appropriate os value for the
  1261. * specified site record
  1262. *
  1263. * @returns
  1264. * NULL for 'same as local machine', 'Windows' or 'Linux'.
  1265. */
  1266. function drush_os($site_record = NULL) {
  1267. // Default to $os = NULL, meaning 'same as local machine'
  1268. $os = NULL;
  1269. // If the site record has an 'os' element, use it
  1270. if (isset($site_record) && array_key_exists('os', $site_record)) {
  1271. $os = $site_record['os'];
  1272. }
  1273. // Otherwise, we will assume that all remote machines are Linux
  1274. // (or whatever value 'remote-os' is set to in drushrc.php).
  1275. elseif (isset($site_record) && array_key_exists('remote-host', $site_record) && !empty($site_record['remote-host'])) {
  1276. $os = drush_get_option('remote-os', 'Linux');
  1277. }
  1278. return $os;
  1279. }
  1280. /**
  1281. * Platform-independent version of escapeshellarg().
  1282. * This only works for local commands.
  1283. * TODO: Make a unified drush_escapeshellarg
  1284. * that works on Linux and Windows.
  1285. */
  1286. function drush_escapeshellarg($arg) {
  1287. if (drush_is_windows()) {
  1288. return _drush_escapeshellarg_windows($arg);
  1289. }
  1290. else {
  1291. return escapeshellarg($arg);
  1292. }
  1293. }
  1294. /**
  1295. * Check if the operating system is Windows.
  1296. */
  1297. function drush_is_windows() {
  1298. if (substr(php_uname(), 0, 7) == 'Windows') {
  1299. return TRUE;
  1300. }
  1301. else {
  1302. return FALSE;
  1303. }
  1304. }
  1305. /**
  1306. * Windows version of escapeshellarg().
  1307. *
  1308. * @deprecated escapeshellarg needs to be cross-platform,
  1309. * because drush does not always know in advance whether an
  1310. * escaped arg will be used locally or on a remote system.
  1311. * See http://drupal.org/node/766080
  1312. */
  1313. function _drush_escapeshellarg_windows($arg) {
  1314. // Double the backslashes before any double quotes. Escape the double quotes.
  1315. // (\" => \\\") && (" => \") =
  1316. // (\" => \\") +
  1317. $arg = preg_replace('/\\\"/', '\\\\\\"', $arg);
  1318. // + (" => \")
  1319. $arg = preg_replace('/"/', '\\"', $arg);
  1320. // The same with single quotes.
  1321. // (\' => \\\') && (' => \') =
  1322. // (\' => \\') +
  1323. $arg = preg_replace('/\\\'/', '\\\\\\\'', $arg);
  1324. // + (' => \')
  1325. $arg = preg_replace('/\'/', '\\\'', $arg);
  1326. // Replace "\t", "\n", "\r", "\0", "\x0B" with a whitespace.
  1327. $arg = str_replace(array("\t", "\n", "\r", "\0", "\x0B"), ' ', $arg);
  1328. // Add surrounding quotes.
  1329. $arg = '"' . $arg . '"';
  1330. return $arg;
  1331. }
  1332. /**
  1333. * Stores output for the most recent shell command.
  1334. * This should only be run from drush_shell_exec().
  1335. *
  1336. * @param $output
  1337. * The output of the most recent shell command.
  1338. * If this is not set the stored value will be returned.
  1339. */
  1340. function _drush_shell_exec_output_set($output = FALSE) {
  1341. static $stored_output;
  1342. if ($output === FALSE) return $stored_output;
  1343. $stored_output = $output;
  1344. }
  1345. /**
  1346. * Returns the output of the most recent shell command as an array of lines.
  1347. */
  1348. function drush_shell_exec_output() {
  1349. return _drush_shell_exec_output_set();
  1350. }
  1351. /**
  1352. * Download a file using wget or curl.
  1353. *
  1354. * @param string $url
  1355. * The path to the file to download
  1356. *
  1357. * @return string
  1358. * The filename that was downloaded,
  1359. * or NULL if the file could not be
  1360. * downloaded.
  1361. */
  1362. function _drush_download_file($url) {
  1363. $filename = explode('/', $url);
  1364. $filename = array_pop($filename);
  1365. if (!drush_shell_exec("wget %s", $url)) {
  1366. if(!drush_shell_exec("curl -O %s", $url)) {
  1367. return NULL;
  1368. }
  1369. }
  1370. return $filename;
  1371. }
  1372. /**
  1373. * Extract a tarball.
  1374. *
  1375. * @param string $path
  1376. * The name of the .tar.gz or .tgz file to be extracted.
  1377. * @param string $destination
  1378. * The destination directory the tarball should be extracted into.
  1379. * Optional, if ommitted the tarball directory will be used as destination.
  1380. * @param boolean $listing
  1381. * If TRUE, a listing of the tar contents will be returned on success.
  1382. *
  1383. * @return string
  1384. * TRUE on success, FALSE on fail. If $listing is TRUE, a file listing of the
  1385. * tarball is returned if the extraction reported success, instead of TRUE.
  1386. */
  1387. function drush_tarball_extract($path, $destination = FALSE, $listing = FALSE) {
  1388. if (!file_exists($path)) {
  1389. return drush_set_error('TARBALL_EXTRACT_NOT_FOUND', dt('Tarball !path could not be found.', array('!path' => $path)));
  1390. }
  1391. $olddir = getcwd();
  1392. if (!$destination) {
  1393. $destination = dirname($path);
  1394. }
  1395. if (!is_writeable($destination)) {
  1396. return drush_set_error('TARBALL_EXTRACT_DESTINATION', dt('Extracting !path failed, as the destination directory !dest was not found or could not be written to.', array('!path' => $path, '!dest' => $dest)));
  1397. }
  1398. // If we are not on Windows, then try to do "tar" in a single operation.
  1399. if ((!drush_is_windows()) && (drush_shell_cd_and_exec(dirname($path), "tar -C %s -xzf %s", $destination, basename($path)))) {
  1400. if ($listing) {
  1401. // We use a separate tar -tf instead of -xvf above because
  1402. // the output is not the same in Mac.
  1403. drush_shell_cd_and_exec(dirname($path), "tar -tf %s", basename($path));
  1404. return drush_shell_exec_output();
  1405. }
  1406. return TRUE;
  1407. }
  1408. // If we could not get the single-op tar to work, do it in three steps.
  1409. // Copy the source tarball to the destination directory. Rename to a temp name in case the destination directory == dirname($path)
  1410. $paths_basename = basename(basename($path, '.tar.gz'), '.tgz');
  1411. $tarball = drush_tempnam($paths_basename, $destination) . ".tar.gz";
  1412. drush_register_file_for_deletion($tarball);
  1413. drush_copy_dir($path, $tarball);
  1414. $unzipped = $destination . '/' . basename($tarball, ".tar.gz") . ".tar";
  1415. // We used to use gzip --decompress in --stdout > out, but the output redirection sometimes failed on Windows for some binary output
  1416. drush_shell_cd_and_exec(dirname($tarball), "gzip --decompress %s", $tarball);
  1417. if (file_exists($unzipped)) {
  1418. drush_register_file_for_deletion($unzipped);
  1419. if (drush_shell_cd_and_exec(dirname($unzipped), "tar -xf %s", basename($unzipped))) {
  1420. if ($listing) {
  1421. // We use a separate tar -tf instead of -xf above because
  1422. // the output is not the same in Mac.
  1423. drush_shell_cd_and_exec(dirname($unzipped), "tar -tf %s", basename($unzipped));
  1424. return drush_shell_exec_output();
  1425. }
  1426. return TRUE;
  1427. }
  1428. return drush_set_error('TARBALL_EXTRACT_TAR_FAIL', dt('Extracting !path using the tar command failed.', array('!path' => $path)));
  1429. }
  1430. else {
  1431. return drush_set_error('TARBALL_EXTRACT_GZIP_FAIL', dt('Uncompressing !path using the gzip command failed.', array('!path' => $path)));
  1432. }
  1433. }
  1434. /**
  1435. * @} End of "defgroup commandwrappers".
  1436. */
  1437. /**
  1438. * @defgroup filesystemfunctions Filesystem convenience functions.
  1439. * @{
  1440. */
  1441. /**
  1442. * Deletes the provided file or folder and everything inside it.
  1443. *
  1444. * @param $dir
  1445. * The directory to delete
  1446. * @return
  1447. * FALSE on failure, TRUE if everything was deleted
  1448. */
  1449. function drush_delete_dir($dir) {
  1450. if (!file_exists($dir)) {
  1451. return TRUE;
  1452. }
  1453. if (!is_dir($dir)) {
  1454. return unlink($dir);
  1455. }
  1456. foreach (scandir($dir) as $item) {
  1457. if ($item == '.' || $item == '..') {
  1458. continue;
  1459. }
  1460. if (!drush_delete_dir($dir.'/'.$item)) {
  1461. return FALSE;
  1462. }
  1463. }
  1464. return rmdir($dir);
  1465. }
  1466. /**
  1467. * Copy $src to $dest.
  1468. *
  1469. * @param $src
  1470. * The directory to copy.
  1471. * @param $dest
  1472. * The destination to copy the source to, including the new name of
  1473. * the directory. To copy directory "a" from "/b" to "/c", then
  1474. * $src = "/b/a" and $dest = "/c/a". To copy "a" to "/c" and rename
  1475. * it to "d", then $dest = "/c/d".
  1476. * @param $overwrite
  1477. * If TRUE, the destination will be deleted if it exists.
  1478. * @return
  1479. * TRUE on success, FALSE on failure.
  1480. */
  1481. function drush_copy_dir($src, $dest, $overwrite = FALSE) {
  1482. // Preflight based on $overwrite if $dest exists.
  1483. if (file_exists($dest)) {
  1484. if ($overwrite) {
  1485. drush_op('drush_delete_dir', $dest);
  1486. }
  1487. else {
  1488. return drush_set_error('DRUSH_DESTINATION_EXISTS', dt('Destination directory !dest already exists.', array('!dest' => $dest)));
  1489. }
  1490. }
  1491. // $src readable?
  1492. if (!drush_op('is_readable', $src)) {
  1493. return drush_set_error('DRUSH_SOURCE_NOT_EXISTS', dt('Source directory !src is not readable or does not exist.', array('!src' => $src)));
  1494. }
  1495. // $dest writable?
  1496. if (!drush_op('is_writable', dirname($dest))) {
  1497. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Destination directory !dest is not writable.', array('!dest' => dirname($dest))));
  1498. }
  1499. // Try to do a recursive copy.
  1500. if (@drush_op('_drush_recursive_copy', $src, $dest)) {
  1501. return TRUE;
  1502. }
  1503. return drush_set_error('DRUSH_COPY_DIR_FAILURE', dt('Unable to copy !src to !dest.', array('src' => $src, 'dest' => $dest)));
  1504. }
  1505. /**
  1506. * Internal function called by drush_copy_dir; do not use directly.
  1507. */
  1508. function _drush_recursive_copy($src, $dest) {
  1509. // all subdirectories and contents:
  1510. if(is_dir($src)) {
  1511. drush_mkdir($dest);
  1512. $dir_handle = opendir($src);
  1513. while($file = readdir($dir_handle)) {
  1514. if ($file != "." && $file != "..") {
  1515. if (_drush_recursive_copy("$src/$file", "$dest/$file") !== TRUE) {
  1516. return FALSE;
  1517. }
  1518. }
  1519. }
  1520. closedir($dir_handle);
  1521. }
  1522. elseif (drush_op('copy', $src, $dest) !== TRUE) {
  1523. return FALSE;
  1524. }
  1525. // Preserve permissions
  1526. if (!drush_is_windows()) {
  1527. chmod($dest, intval(fileperms($src), 8));
  1528. }
  1529. return TRUE;
  1530. }
  1531. /**
  1532. * Move $src to $dest.
  1533. *
  1534. * If the php 'rename' function doesn't work, then we'll do copy & delete.
  1535. *
  1536. * @param $src
  1537. * The directory to move.
  1538. * @param $dest
  1539. * The destination to move the source to, including the new name of
  1540. * the directory. To move directory "a" from "/b" to "/c", then
  1541. * $src = "/b/a" and $dest = "/c/a". To move "a" to "/c" and rename
  1542. * it to "d", then $dest = "/c/d" (just like php rename function).
  1543. * @param $overwrite
  1544. * If TRUE, the destination will be deleted if it exists.
  1545. * @return
  1546. * TRUE on success, FALSE on failure.
  1547. */
  1548. function drush_move_dir($src, $dest, $overwrite = FALSE) {
  1549. // Preflight based on $overwrite if $dest exists.
  1550. if (file_exists($dest)) {
  1551. if ($overwrite) {
  1552. drush_op('drush_delete_dir', $dest);
  1553. }
  1554. else {
  1555. return drush_set_error('DRUSH_DESTINATION_EXISTS', dt('Destination directory !dest already exists.', array('!dest' => $dest)));
  1556. }
  1557. }
  1558. // $src readable?
  1559. if (!drush_op('is_readable', $src)) {
  1560. return drush_set_error('DRUSH_SOURCE_NOT_EXISTS', dt('Source directory !src is not readable or does not exist.', array('!src' => $src)));
  1561. }
  1562. // $dest writable?
  1563. if (!drush_op('is_writable', dirname($dest))) {
  1564. return drush_set_error('DRUSH_DESTINATION_NOT_WRITABLE', dt('Destination directory !dest is not writable.', array('!dest' => dirname($dest))));
  1565. }
  1566. // Try rename. It will fail if $src and $dest are not in the same partition.
  1567. if (@drush_op('rename', $src, $dest)) {
  1568. return TRUE;
  1569. }
  1570. // Eventually it will create an empty file in $dest. See
  1571. // http://www.php.net/manual/es/function.rename.php#90025
  1572. elseif (is_file($dest)) {
  1573. drush_op('unlink', $dest);
  1574. }
  1575. // If 'rename' fails, then we will use copy followed
  1576. // by a delete of the source.
  1577. if (drush_copy_dir($src, $dest)) {
  1578. drush_op('drush_delete_dir', $src);
  1579. return TRUE;
  1580. }
  1581. return drush_set_error('DRUSH_MOVE_DIR_FAILURE', dt('Unable to move !src to !dest.', array('!src' => $src, '!dest' => $dest)));
  1582. }
  1583. /**
  1584. * Cross-platform compatible helper function to recursively create a directory tree.
  1585. * @see http://theserverpages.com/php/manual/en/function.mkdir.php#50383
  1586. */
  1587. function drush_mkdir($path) {
  1588. return is_dir($path) || (drush_mkdir(dirname($path)) && drush_shell_exec('mkdir %s', $path));
  1589. }
  1590. /**
  1591. * Save a string to a temporary file. Does not depend on Drupal's API.
  1592. * The temporary file will be automatically deleted when drush exits.
  1593. *
  1594. * @param string $data
  1595. * @return string
  1596. * A path to the file.
  1597. */
  1598. function drush_save_data_to_temp_file($data) {
  1599. static $fp;
  1600. $fp = tmpfile();
  1601. fwrite($fp, $data);
  1602. $meta_data = stream_get_meta_data($fp);
  1603. $file = $meta_data['uri'];
  1604. drush_register_file_for_deletion($file);
  1605. return $file;
  1606. }
  1607. /**
  1608. * Returns the path to a temporary directory.
  1609. *
  1610. * This is a custom version of file_directory_path().
  1611. * We can't directly rely on sys_get_temp_dir() as this
  1612. * path is not valid in some setups for Mac.
  1613. */
  1614. function drush_find_tmp() {
  1615. static $temporary_directory = NULL;
  1616. if (is_null($temporary_directory)) {
  1617. $directories = array();
  1618. // Operating system specific dirs.
  1619. if (substr(PHP_OS, 0, 3) == 'WIN') {
  1620. $directories[] = 'c:\\windows\\temp';
  1621. $directories[] = 'c:\\winnt\\temp';
  1622. }
  1623. else {
  1624. $directories[] = '/tmp';
  1625. }
  1626. // This function exists in PHP 5 >= 5.2.1, but drush
  1627. // requires PHP 5 >= 5.2.0, so we check for it.
  1628. if (function_exists('sys_get_temp_dir')) {
  1629. $directories[] = sys_get_temp_dir();
  1630. }
  1631. foreach ($directories as $directory) {
  1632. if (is_dir($directory) && is_writable($directory)) {
  1633. $temporary_directory = $directory;
  1634. break;
  1635. }
  1636. }
  1637. if (empty($temporary_directory)) {
  1638. // If no directory has been found, create one in cwd.
  1639. $temporary_directory = drush_cwd() . '/tmp';
  1640. drush_mkdir($temporary_directory);
  1641. if (!is_dir($directory)) {
  1642. return drush_set_error('DRUSH_UNABLE_TO_CREATE_TMP_DIR', dt("Unable to create a temporary directory."));
  1643. }
  1644. drush_register_file_for_deletion($temporary_directory);
  1645. }
  1646. }
  1647. return $temporary_directory;
  1648. }
  1649. /**
  1650. * Creates a temporary file, and registers it so that
  1651. * it will be deleted when drush exits. Whenever possible,
  1652. * drush_save_data_to_temp_file() should be used instead
  1653. * of this function.
  1654. */
  1655. function drush_tempnam($pattern, $tmp_dir = NULL) {
  1656. if ($tmp_dir == NULL) {
  1657. $tmp_dir = drush_find_tmp();
  1658. }
  1659. $tmp_file = tempnam($tmp_dir, $pattern);
  1660. drush_register_file_for_deletion($tmp_file);
  1661. return $tmp_file;
  1662. }
  1663. /**
  1664. * Creates a temporary directory and return its path.
  1665. */
  1666. function drush_tempdir() {
  1667. $tmp_dir = rtrim(drush_find_tmp(), DIRECTORY_SEPARATOR);
  1668. $tmp_dir .= '/' . 'drush_tmp_' . time();
  1669. drush_mkdir($tmp_dir);
  1670. drush_register_file_for_deletion($tmp_dir);
  1671. return $tmp_dir;
  1672. }
  1673. /**
  1674. * Any file passed in to this function will be deleted
  1675. * when drush exits.
  1676. */
  1677. function drush_register_file_for_deletion($file = NULL) {
  1678. static $registered_files = array();
  1679. if (isset($file)) {
  1680. if (empty($registered_files)) {
  1681. register_shutdown_function('_drush_delete_registered_files');
  1682. }
  1683. $registered_files[] = $file;
  1684. }
  1685. return $registered_files;
  1686. }
  1687. /**
  1688. * Delete all of the registered temporary files.
  1689. */
  1690. function _drush_delete_registered_files() {
  1691. $files_to_delete = drush_register_file_for_deletion();
  1692. foreach ($files_to_delete as $file) {
  1693. // We'll make sure that the file still exists, just
  1694. // in case someone came along and deleted it, even
  1695. // though they did not need to.
  1696. if (file_exists($file)) {
  1697. if (is_dir($file)) {
  1698. drush_delete_dir($file);
  1699. }
  1700. else {
  1701. unlink($file);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. /**
  1707. * Decide where our backup directory should go
  1708. *
  1709. * @param string $subdir
  1710. * The name of the desired subdirectory(s) under drush-backups.
  1711. * Usually a database name.
  1712. */
  1713. function drush_preflight_backup_dir($subdir = NULL) {
  1714. $backup_dir = drush_get_context('DRUSH_BACKUP_DIR', drush_get_option('backup-location'));
  1715. if (empty($backup_dir)) {
  1716. // Try to use db name as subdir if none was provided.
  1717. if (empty($subdir)) {
  1718. $subdir = 'unknown';
  1719. if ($creds = drush_get_context('DRUSH_DB_CREDENTIALS')) {
  1720. $subdir = $creds['name'];
  1721. }
  1722. }
  1723. // Save the date to be used in the backup directory's path name.
  1724. $date = gmdate('YmdHis', $_SERVER['REQUEST_TIME']);
  1725. $backup_dir = drush_get_option('backup-dir', drush_server_home() . '/' . 'drush-backups');
  1726. $backup_dir = rtrim($backup_dir, DIRECTORY_SEPARATOR) . '/' . $subdir . '/' . $date;
  1727. drush_set_context('DRUSH_BACKUP_DIR', $backup_dir);
  1728. }
  1729. return $backup_dir;
  1730. }
  1731. /**
  1732. * Prepare a backup directory
  1733. */
  1734. function drush_prepare_backup_dir($subdir = NULL) {
  1735. $backup_dir = drush_preflight_backup_dir($subdir);
  1736. $backup_parent = dirname($backup_dir);
  1737. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  1738. if ((!empty($drupal_root)) && (strpos($backup_parent, $drupal_root) === 0)) {
  1739. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('It\'s not allowed to store backups inside the Drupal root directory.'));
  1740. }
  1741. if (!file_exists($backup_parent)) {
  1742. if (!drush_mkdir($backup_parent)) {
  1743. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Unable to create backup directory !dir.', array('!dir' => $backup_parent)));
  1744. }
  1745. }
  1746. if (!is_writable($backup_parent)) {
  1747. return drush_set_error('DRUSH_PM_BACKUP_FAILED', dt('Backup directory !dir is not writable.', array('!dir' => $backup_parent)));
  1748. }
  1749. drush_mkdir($backup_dir);
  1750. return $backup_dir;
  1751. }
  1752. /**
  1753. * @} End of "defgroup filesystemfunctions".
  1754. */
  1755. /**
  1756. * @defgroup dbfunctions Database convenience functions.
  1757. * @{
  1758. */
  1759. /**
  1760. * Replace named placeholders in a WHERE snippet.
  1761. *
  1762. * Helper function to allow the usage of Drupal 7 WHERE snippets
  1763. * with named placeholders in code for Drupal 5 and 6.
  1764. *
  1765. * @param $where
  1766. * String with a WHERE snippet using named placeholders.
  1767. * @param $args
  1768. * Array of placeholder values.
  1769. * @return
  1770. * String. $where filled with literals from $args.
  1771. */
  1772. function _drush_replace_query_placeholders($where, $args) {
  1773. foreach ($args as $key => $data) {
  1774. if (is_array($data)) {
  1775. $new_keys = array();
  1776. // $data can't have keys that are a prefix of other keys to
  1777. // prevent a corrupted result in the below calls to str_replace().
  1778. // To avoid this we will use a zero padded indexed array of the values of $data.
  1779. $pad_length = strlen((string)count(array_values($data)));
  1780. foreach (array_values($data) as $i => $value) {
  1781. if (!is_numeric($value)) {
  1782. $value = "'".$value."'";
  1783. }
  1784. $new_keys[$key . '_' . str_pad($i, $pad_length, '0', STR_PAD_LEFT)] = $value;
  1785. }
  1786. $where = preg_replace('#' . $key . '\b#', implode(', ', array_keys($new_keys)), $where);
  1787. unset($args[$key]);
  1788. $args += $new_keys;
  1789. }
  1790. else if (!is_numeric($data)) {
  1791. $args[$key] = "'".$data."'";
  1792. }
  1793. }
  1794. foreach ($args as $key => $data) {
  1795. $where = str_replace($key, $data, $where);
  1796. }
  1797. return $where;
  1798. }
  1799. /**
  1800. * A db_select() that works for any version of Drupal.
  1801. *
  1802. * @param $table
  1803. * String. The table to operate on.
  1804. * @param $fields
  1805. * Array or string. Fields affected in this operation. Valid string values are '*' or a single column name.
  1806. * @param $where
  1807. * String. WHERE snippet for the operation. It uses named placeholders. see @_drush_replace_query_placeholders()
  1808. * @param $args
  1809. * Array. Arguments for the WHERE snippet.
  1810. * @param $start
  1811. * Int. Value for OFFSET.
  1812. * @param $length
  1813. * Int. Value for LIMIT.
  1814. * @param $order_by_field
  1815. * String. Database column to order by.
  1816. * @param $order_by_direction
  1817. * ('ASC', 'DESC'). Ordering direction.
  1818. * @return
  1819. * A database resource.
  1820. */
  1821. function drush_db_select($table, $fields = '*', $where = NULL, $args = NULL, $start = NULL, $length = NULL, $order_by_field = NULL, $order_by_direction = 'ASC') {
  1822. if (drush_drupal_major_version() >= 7) {
  1823. if (!is_array($fields)) {
  1824. if ($fields == '*') {
  1825. $fields = array();
  1826. }
  1827. else {
  1828. $fields = array($fields);
  1829. }
  1830. }
  1831. $query = db_select($table, $table)
  1832. ->fields($table, $fields);
  1833. if (!empty($where)) {
  1834. $query = $query->where($where, $args);
  1835. }
  1836. if (!is_null($order_by_field)) {
  1837. $query = $query->orderBy($order_by_field, $order_by_direction);
  1838. }
  1839. if (!is_null($length)) {
  1840. $query = $query->range($start, $length);
  1841. }
  1842. return $query->execute();
  1843. }
  1844. else {
  1845. if (is_array($fields)) {
  1846. $fields = implode(', ', $fields);
  1847. }
  1848. $query = "SELECT $fields FROM {{$table}}";
  1849. if (!empty($where)) {
  1850. $where = _drush_replace_query_placeholders($where, $args);
  1851. $query .= " WHERE ".$where;
  1852. }
  1853. if (!is_null($order_by_field)) {
  1854. $query .= " ORDER BY $order_by_field $order_by_direction";
  1855. }
  1856. if (!is_null($length)) {
  1857. $limit = " LIMIT $length";
  1858. if (!is_null($start)) {
  1859. $limit .= " OFFSET $start";
  1860. }
  1861. $query .= $limit;
  1862. }
  1863. return db_query($query, $args);
  1864. }
  1865. }
  1866. /**
  1867. * A db_delete() that works for any version of Drupal.
  1868. *
  1869. * @param $table
  1870. * String. The table to operate on.
  1871. * @param $where
  1872. * String. WHERE snippet for the operation. It uses named placeholders. see @_drush_replace_query_placeholders()
  1873. * @param $args
  1874. * Array. Arguments for the WHERE snippet.
  1875. * @return
  1876. * Affected rows (except on D7+mysql without a WHERE clause - returns TRUE) or FALSE.
  1877. */
  1878. function drush_db_delete($table, $where = NULL, $args = NULL) {
  1879. if (drush_drupal_major_version() >= 7) {
  1880. if (!empty($where)) {
  1881. $query = db_delete($table)->where($where, $args);
  1882. return $query->execute();
  1883. }
  1884. else {
  1885. return db_truncate($table)->execute();
  1886. }
  1887. }
  1888. else {
  1889. $query = "DELETE FROM {{$table}}";
  1890. if (!empty($where)) {
  1891. $where = _drush_replace_query_placeholders($where, $args);
  1892. $query .= ' WHERE '.$where;
  1893. }
  1894. if (!db_query($query, $args)) {
  1895. return FALSE;
  1896. }
  1897. return db_affected_rows();
  1898. }
  1899. }
  1900. /**
  1901. * A db_result() that works consistently for any version of Drupal.
  1902. *
  1903. * @param
  1904. * A Database result object.
  1905. */
  1906. function drush_db_result($result) {
  1907. switch (drush_drupal_major_version()) {
  1908. case 5:
  1909. // In versions of Drupal <= 5, db_result only returns the first row no matter how
  1910. // many times you call it. So instead of calling it here, we use db_fetch_array which
  1911. // does increment the pointer to the next row (as db_result does on Drupal 6)
  1912. if ($array = db_fetch_array($result)) {
  1913. return array_shift($array); // return first element in array.
  1914. }
  1915. return FALSE;
  1916. case 6:
  1917. return db_result($result);
  1918. case 7:
  1919. default:
  1920. return $result->fetchField();
  1921. }
  1922. }
  1923. /**
  1924. * A db_fetch_object() that works for any version of Drupal.
  1925. *
  1926. * @param
  1927. * A Database result object.
  1928. */
  1929. function drush_db_fetch_object($result) {
  1930. return drush_drupal_major_version() >= 7 ? $result->fetchObject() : db_fetch_object($result);
  1931. }
  1932. /**
  1933. * @} End of "defgroup dbfunctions".
  1934. */
  1935. /**
  1936. * @defgroup commandprocessing Command processing functions.
  1937. * @{
  1938. *
  1939. * These functions manage command processing by the
  1940. * main function in drush.php.
  1941. */
  1942. /**
  1943. * Process commands that are executed on a remote drush instance.
  1944. *
  1945. * @return
  1946. * TRUE if the command was handled remotely.
  1947. */
  1948. function drush_remote_command() {
  1949. // The command will be executed remotely if the --remote-host flag
  1950. // is set; note that if a site alias is provided on the command line,
  1951. // and the site alias references a remote server, then the --remote-host
  1952. // option will be set when the site alias is processed.
  1953. // @see _drush_process_site_alias
  1954. $remote_host = drush_get_option('remote-host');
  1955. if (isset($remote_host)) {
  1956. $args = drush_get_arguments();
  1957. $command = array_shift($args);
  1958. $remote_user = drush_get_option('remote-user');
  1959. drush_do_command_redispatch($command, $args, $remote_host, $remote_user);
  1960. return TRUE;
  1961. }
  1962. // If the --site-list flag is set, then we will execute the specified
  1963. // command once for every site listed in the site list.
  1964. $site_list = drush_get_option('site-list');
  1965. if (isset($site_list)) {
  1966. if (!is_array($site_list)) {
  1967. $site_list = explode(',', $site_list);
  1968. }
  1969. $site_list = drush_sitealias_resolve_sitespecs($site_list);
  1970. $site_list = drush_sitealias_simplify_names($site_list);
  1971. $args = drush_get_arguments();
  1972. if (!drush_get_context('DRUSH_SIMULATE')) {
  1973. drush_print(dt("You are about to execute '!command' on all of the following targets:", array('!command' => implode(" ", $args))));
  1974. foreach ($site_list as $one_destination => $one_record) {
  1975. drush_print(dt(' !target', array('!target' => $one_destination)));
  1976. }
  1977. if (drush_confirm('Continue? ') === FALSE) {
  1978. drush_user_abort();
  1979. return TRUE;
  1980. }
  1981. }
  1982. $command = array_shift($args);
  1983. $multi_options = drush_get_context('cli');
  1984. if (!drush_get_option('no-label', FALSE)) {
  1985. $label_separator = ' >> ';
  1986. $max_name_length = 0;
  1987. foreach ($site_list as $alias_name => $alias_record) {
  1988. if (strlen($alias_name) > $max_name_length) {
  1989. $max_name_length = strlen($alias_name);
  1990. }
  1991. }
  1992. $multi_options['reserve-margin'] = $max_name_length + strlen($label_separator);
  1993. foreach ($site_list as $alias_name => $alias_record) {
  1994. $values = drush_do_site_command($alias_record, $command, $args, $multi_options);
  1995. foreach (explode("\n", $values['output']) as $line) {
  1996. if (empty($line)) {
  1997. drush_print();
  1998. }
  1999. else {
  2000. drush_print(str_pad($alias_name, $max_name_length, " ") . $label_separator . $line);
  2001. }
  2002. }
  2003. }
  2004. }
  2005. else {
  2006. foreach ($site_list as $alias_name => $alias_record) {
  2007. $values = drush_do_site_command($alias_record, $command, $args, $multi_options);
  2008. drush_print($values['output']);
  2009. }
  2010. }
  2011. return TRUE;
  2012. }
  2013. return FALSE;
  2014. }
  2015. /**
  2016. * Used by functions that operate on lists of sites, moving
  2017. * information from the source to the destination. Currenlty
  2018. * this includes 'drush rsync' and 'drush sql sync'.
  2019. */
  2020. function drush_do_multiple_command($command, $source_record, $destination_record, $allow_single_source = FALSE) {
  2021. $is_multiple_command = FALSE;
  2022. if ((($allow_single_source == TRUE) || array_key_exists('site-list', $source_record)) && array_key_exists('site-list', $destination_record)) {
  2023. $is_multiple_command = TRUE;
  2024. $source_path = array_key_exists('path-component', $source_record) ? $source_record['path-component'] : '';
  2025. $destination_path = array_key_exists('path-component', $destination_record) ? $destination_record['path-component'] : '';
  2026. $target_list = array_values(drush_sitealias_resolve_sitelist($destination_record));
  2027. if (array_key_exists('site-list', $source_record)) {
  2028. $source_list = array_values(drush_sitealias_resolve_sitelist($source_record));
  2029. if (drush_sitealias_check_lists_alignment($source_list, $target_list) === FALSE) {
  2030. if (array_key_exists('unordered-list', $source_record) || array_key_exists('unordered-list', $destination_record)) {
  2031. drush_sitelist_align_lists($source_list, $target_list, $aligned_source, $aligned_target);
  2032. $source_list = $aligned_source;
  2033. $target_list = $aligned_target;
  2034. }
  2035. }
  2036. }
  2037. else {
  2038. $source_list = array_fill(0, count($target_list), $source_record);
  2039. }
  2040. if (!drush_get_context('DRUSH_SIMULATE')) {
  2041. drush_print(dt('You are about to !command between all of the following targets:', array('!command' => $command)));
  2042. $i = 0;
  2043. foreach ($source_list as $one_source) {
  2044. $one_target = $target_list[$i];
  2045. ++$i;
  2046. 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)));
  2047. }
  2048. if (drush_confirm('Continue? ') === FALSE) {
  2049. return drush_user_abort();
  2050. }
  2051. }
  2052. $data = drush_redispatch_get_options();
  2053. $i = 0;
  2054. foreach ($source_list as $one_source) {
  2055. $one_target = $target_list[$i];
  2056. ++$i;
  2057. $source_spec = drush_sitealias_alias_record_to_spec($one_source);
  2058. $target_spec = drush_sitealias_alias_record_to_spec($one_target);
  2059. drush_log(dt('Begin do_multiple !command via backend invoke', array('!command' => $command)));
  2060. $values = drush_backend_invoke_args($command, array($source_spec . $source_path, $target_spec . $destination_path), $data, 'GET', TRUE);
  2061. drush_log(dt('Backend invoke is complete'));
  2062. }
  2063. }
  2064. return $is_multiple_command;
  2065. }
  2066. /**
  2067. * Run a command on the site specified by the provided command record.
  2068. *
  2069. * The standard function that provides this service is called
  2070. * drush_invoke_sitealias_args. Please call the standard function
  2071. * unless you need to set $integrate = TRUE.
  2072. */
  2073. function drush_do_site_command($site_record, $command, $args = array(), $data = array(), $integrate = FALSE) {
  2074. $values = NULL;
  2075. if (!empty($site_record)) {
  2076. foreach ($site_record as $key => $value) {
  2077. if (!isset($data[$key]) && !in_array($key, drush_sitealias_site_selection_keys())) {
  2078. $data[$key] = $site_record[$key];
  2079. }
  2080. }
  2081. $values = drush_backend_invoke_sitealias($site_record, $command, $args, $data, 'GET', $integrate);
  2082. }
  2083. return $values;
  2084. }
  2085. /**
  2086. * Redispatch the specified command using the same
  2087. * options that were passed to this invocation of drush.
  2088. */
  2089. function drush_do_command_redispatch($command, $args = array(), $remote_host = NULL, $remote_user = NULL, $drush_path = NULL) {
  2090. $data = drush_redispatch_get_options();
  2091. // If the path to drush was supplied, then pass it to backend invoke.
  2092. if ($drush_path == NULL) {
  2093. $drush_path = drush_get_option('drush-script');
  2094. if (!isset($drush_path)) {
  2095. $drush_folder = drush_get_option('drush');
  2096. if (isset($drush)) {
  2097. $drush_path = $drush_folder . '/drush';
  2098. }
  2099. }
  2100. }
  2101. // Call through to backend invoke.
  2102. drush_log(dt('Begin redispatch via backend invoke'));
  2103. $values = drush_backend_invoke_args($command, $args, $data, 'GET', TRUE, $drush_path, $remote_host, $remote_user);
  2104. drush_log(dt('Backend invoke is complete'));
  2105. return $values;
  2106. }
  2107. /**
  2108. * @} End of "defgroup commandprocessing".
  2109. */
  2110. /**
  2111. * @defgroup logging Logging information to be provided as output.
  2112. * @{
  2113. *
  2114. * These functions are primarily for diagnostic purposes, but also provide an overview of tasks that were taken
  2115. * by drush.
  2116. */
  2117. /**
  2118. * Add a log message to the log history.
  2119. *
  2120. * This function calls the callback stored in the 'DRUSH_LOG_CALLBACK' context with
  2121. * the resulting entry at the end of execution.
  2122. *
  2123. * This allows you to replace it with custom logging implementations if needed,
  2124. * such as logging to a file or logging to a database (drupal or otherwise).
  2125. *
  2126. * The default callback is the _drush_print_log() function with prints the messages
  2127. * to the shell.
  2128. *
  2129. * @param message
  2130. * String containing the message to be logged.
  2131. * @param type
  2132. * The type of message to be logged. Common types are 'warning', 'error', 'success' and 'notice'.
  2133. * A type of 'failed' can also be supplied to flag as an 'error'.
  2134. * A type of 'ok' or 'completed' can also be supplied to flag as a 'success'
  2135. * All other types of messages will be assumed to be notices.
  2136. */
  2137. function drush_log($message, $type = 'notice', $error = null) {
  2138. $log =& drush_get_context('DRUSH_LOG', array());
  2139. $callback = drush_get_context('DRUSH_LOG_CALLBACK', '_drush_print_log');
  2140. $entry = array(
  2141. 'type' => $type,
  2142. 'message' => $message,
  2143. 'timestamp' => microtime(TRUE),
  2144. 'memory' => memory_get_usage(),
  2145. );
  2146. $entry['error'] = $error;
  2147. $log[] = $entry;
  2148. return $callback($entry);
  2149. }
  2150. /**
  2151. * Retrieve the log messages from the log history
  2152. *
  2153. * @return
  2154. * Entire log history
  2155. */
  2156. function drush_get_log() {
  2157. return drush_get_context('DRUSH_LOG', array());
  2158. }
  2159. /**
  2160. * Run print_r on a variable and log the output.
  2161. */
  2162. function dlm($object) {
  2163. ob_start();
  2164. print_r($object);
  2165. $contents = ob_get_contents();
  2166. ob_end_clean();
  2167. drush_log($contents);
  2168. }
  2169. /**
  2170. * Display the pipe output for the current request.
  2171. */
  2172. function drush_pipe_output() {
  2173. $pipe = drush_get_context('DRUSH_PIPE_BUFFER');
  2174. if (!empty($pipe)) {
  2175. drush_print_r($pipe);
  2176. }
  2177. }
  2178. /**
  2179. * Display the log message
  2180. *
  2181. * By default, only warnings and errors will be displayed, if 'verbose' is specified, it will also display notices.
  2182. *
  2183. * @param
  2184. * The associative array for the entry.
  2185. *
  2186. * @return
  2187. * False in case of an error or failed type, True in all other cases.
  2188. */
  2189. function _drush_print_log($entry) {
  2190. if (drush_get_context('DRUSH_NOCOLOR')) {
  2191. $red = "[%s]";
  2192. $yellow = "[%s]";
  2193. $green = "[%s]";
  2194. }
  2195. else {
  2196. $red = "\033[31;40m\033[1m[%s]\033[0m";
  2197. $yellow = "\033[1;33;40m\033[1m[%s]\033[0m";
  2198. $green = "\033[1;32;40m\033[1m[%s]\033[0m";
  2199. }
  2200. $verbose = drush_get_context('DRUSH_VERBOSE');
  2201. $debug = drush_get_context('DRUSH_DEBUG');
  2202. $return = TRUE;
  2203. switch ($entry['type']) {
  2204. case 'warning' :
  2205. case 'cancel' :
  2206. $type_msg = sprintf($yellow, $entry['type']);
  2207. break;
  2208. case 'failed' :
  2209. case 'error' :
  2210. $type_msg = sprintf($red, $entry['type']);
  2211. $return = FALSE;
  2212. break;
  2213. case 'ok' :
  2214. case 'completed' :
  2215. case 'success' :
  2216. case 'status':
  2217. $type_msg = sprintf($green, $entry['type']);
  2218. break;
  2219. case 'notice' :
  2220. case 'message' :
  2221. case 'info' :
  2222. if (!$verbose) {
  2223. // print nothing. exit cleanly.
  2224. return TRUE;
  2225. }
  2226. $type_msg = sprintf("[%s]", $entry['type']);
  2227. break;
  2228. default :
  2229. if (!$debug) {
  2230. // print nothing. exit cleanly.
  2231. return TRUE;
  2232. }
  2233. $type_msg = sprintf("[%s]", $entry['type']);
  2234. break;
  2235. }
  2236. // When running in backend mode, log messages are not displayed, as they will
  2237. // be returned in the JSON encoded associative array. In quiet mode, we
  2238. // just drop log messages.
  2239. if (drush_get_context('DRUSH_BACKEND') || drush_get_context('DRUSH_QUIET')) {
  2240. return $return;
  2241. }
  2242. $columns = drush_get_context('DRUSH_COLUMNS', 80);
  2243. $width[1] = 11;
  2244. // Append timer and memory values.
  2245. if ($debug) {
  2246. $timer = sprintf('[%s sec, %s]', round($entry['timestamp']-DRUSH_REQUEST_TIME, 2), drush_format_size($entry['memory']));
  2247. $entry['message'] = $entry['message'] . ' ' . $timer;
  2248. }
  2249. $width[0] = ($columns - 11);
  2250. $format = sprintf("%%-%ds%%%ds", $width[0], $width[1]);
  2251. // Place the status message right aligned with the top line of the error message.
  2252. $message = wordwrap($entry['message'], $width[0]);
  2253. $lines = explode("\n", $message);
  2254. $lines[0] = sprintf($format, $lines[0], $type_msg);
  2255. $message = implode("\n", $lines);
  2256. drush_print($message, 0, STDERR);
  2257. return $return;
  2258. }
  2259. // Print all timers for the request.
  2260. function drush_print_timers() {
  2261. global $timers;
  2262. $temparray = array();
  2263. foreach ((array)$timers as $name => $timerec) {
  2264. // We have to use timer_read() for active timers, and check the record for others
  2265. if (isset($timerec['start'])) {
  2266. $temparray[$name] = timer_read($name);
  2267. }
  2268. else {
  2269. $temparray[$name] = $timerec['time'];
  2270. }
  2271. }
  2272. // Go no farther if there were no timers
  2273. if (count($temparray) > 0) {
  2274. // Put the highest cumulative times first
  2275. arsort($temparray);
  2276. $table = array();
  2277. $table[] = array('Timer', 'Cum (sec)', 'Count', 'Avg (msec)');
  2278. foreach ($temparray as $name => $time) {
  2279. $cum = round($time/1000, 3);
  2280. $count = $timers[$name]['count'];
  2281. if ($count > 0) {
  2282. $avg = round($time/$count, 3);
  2283. }
  2284. else {
  2285. $avg = 'N/A';
  2286. }
  2287. $table[] = array($name, $cum, $count, $avg);
  2288. }
  2289. drush_print_table($table, TRUE, array(), STDERR);
  2290. }
  2291. }
  2292. /**
  2293. * Turn drupal_set_message errors into drush_log errors
  2294. */
  2295. function _drush_log_drupal_messages() {
  2296. if (function_exists('drupal_get_messages')) {
  2297. $messages = drupal_get_messages(NULL, TRUE);
  2298. if (array_key_exists('error', $messages)) {
  2299. //Drupal message errors.
  2300. foreach ((array) $messages['error'] as $error) {
  2301. $error = strip_tags($error);
  2302. $header = preg_match('/^warning: Cannot modify header information - headers already sent by /i', $error);
  2303. $session = preg_match('/^warning: session_start\(\): Cannot send session /i', $error);
  2304. if ($header || $session) {
  2305. //These are special cases for an unavoidable warnings
  2306. //that are generated by generating output before Drupal is bootstrapped.
  2307. //or sending a session cookie (seems to affect d7 only?)
  2308. //Simply ignore them.
  2309. continue;
  2310. }
  2311. elseif (preg_match('/^warning:/i', $error)) {
  2312. drush_log(preg_replace('/^warning: /i', '', $error), 'warning');
  2313. }
  2314. elseif (preg_match('/^notice:/i', $error)) {
  2315. drush_log(preg_replace('/^notice: /i', '', $error), 'notice');
  2316. }
  2317. elseif (preg_match('/^user warning:/i', $error)) {
  2318. // This is a special case. PHP logs sql errors as 'User Warnings', not errors.
  2319. drush_set_error('DRUSH_DRUPAL_ERROR_MESSAGE', preg_replace('/^user warning: /i', '', $error));
  2320. }
  2321. else {
  2322. drush_set_error('DRUSH_DRUPAL_ERROR_MESSAGE', $error);
  2323. }
  2324. }
  2325. }
  2326. unset($messages['error']);
  2327. // Log non-error messages.
  2328. foreach ($messages as $type => $items) {
  2329. foreach ($items as $item) {
  2330. drush_log(strip_tags($item), $type);
  2331. }
  2332. }
  2333. }
  2334. }
  2335. // Copy of format_size() in Drupal.
  2336. function drush_format_size($size, $langcode = NULL) {
  2337. if ($size < DRUSH_DRUPAL_KILOBYTE) {
  2338. // format_plural() not always available.
  2339. return dt('@count bytes', array('@count' => $size));
  2340. }
  2341. else {
  2342. $size = $size / DRUSH_DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
  2343. $units = array(
  2344. dt('@size KB', array(), array('langcode' => $langcode)),
  2345. dt('@size MB', array(), array('langcode' => $langcode)),
  2346. dt('@size GB', array(), array('langcode' => $langcode)),
  2347. dt('@size TB', array(), array('langcode' => $langcode)),
  2348. dt('@size PB', array(), array('langcode' => $langcode)),
  2349. dt('@size EB', array(), array('langcode' => $langcode)),
  2350. dt('@size ZB', array(), array('langcode' => $langcode)),
  2351. dt('@size YB', array(), array('langcode' => $langcode)),
  2352. );
  2353. foreach ($units as $unit) {
  2354. if (round($size, 2) >= DRUSH_DRUPAL_KILOBYTE) {
  2355. $size = $size / DRUSH_DRUPAL_KILOBYTE;
  2356. }
  2357. else {
  2358. break;
  2359. }
  2360. }
  2361. return str_replace('@size', round($size, 2), $unit);
  2362. }
  2363. }
  2364. /**
  2365. * Log Drupal watchdog() calls.
  2366. *
  2367. * A sneaky implementation of hook_watchdog().
  2368. */
  2369. function system_watchdog($log_entry) {
  2370. // Transform non informative severity levels to 'error' for compatibility with _drush_print_log.
  2371. // Other severity levels are coincident with the ones we use in drush.
  2372. if (drush_drupal_major_version() >= 6 && $log_entry['severity'] <= 2) {
  2373. $severity = 'error';
  2374. }
  2375. else {
  2376. drush_include_engine('drupal', 'environment');
  2377. $levels = core_watchdog_severity_levels();
  2378. $severity = $levels[$log_entry['severity']];
  2379. }
  2380. // Format the message.
  2381. if (is_array($log_entry['variables'])) {
  2382. $message = strtr($log_entry['message'], $log_entry['variables']);
  2383. }
  2384. else {
  2385. $message = $log_entry['message'];
  2386. }
  2387. // decode_entities() only loaded after FULL bootstrap.
  2388. if (function_exists('decode_entities')) {
  2389. $message = decode_entities($message);
  2390. }
  2391. $message = strip_tags($message);
  2392. // Log or print or ignore. Just printing saves memory but thats rarely needed.
  2393. switch (drush_get_option('watchdog', 'log')) {
  2394. case 'log':
  2395. drush_log('WD '. $log_entry['type'] . ': ' . $message, $severity);
  2396. break;
  2397. case 'print':
  2398. // Disable in backend mode since it logs output and the goal is to conserve memory.
  2399. // @see _drush_bootstrap_drush().
  2400. if (ob_get_length() === FALSE) {
  2401. drush_print('WD '. $severity . ' ' . $log_entry['type'] . ': ' . $message);
  2402. }
  2403. break;
  2404. default:
  2405. // Do nothing.
  2406. }
  2407. }
  2408. /**
  2409. * Log the return value of Drupal hook_update_n functions.
  2410. *
  2411. * This is used during install and update to log the output
  2412. * of the update process to the logging system.
  2413. */
  2414. function _drush_log_update_sql($ret) {
  2415. if (sizeof($ret)) {
  2416. foreach ($ret as $info) {
  2417. if (is_array($info)) {
  2418. if (!$info['success']) {
  2419. drush_set_error('DRUPAL_UPDATE_FAILED', $info['query']);
  2420. }
  2421. else {
  2422. drush_log($info['query'], ($info['success']) ? 'success' : 'error');
  2423. }
  2424. }
  2425. }
  2426. }
  2427. }
  2428. /**
  2429. * @} End of "defgroup logging".
  2430. */
  2431. /**
  2432. * @name Error status definitions
  2433. * @{
  2434. * Error code definitions for interpreting the current error status.
  2435. * @see drush_set_error(), drush_get_error(), drush_get_error_log(), drush_cmp_error()
  2436. */
  2437. /** The command completed successfully. */
  2438. define('DRUSH_SUCCESS', 0);
  2439. /** The command could not be completed because the framework has specified errors that have occured. */
  2440. define('DRUSH_FRAMEWORK_ERROR', 1);
  2441. /** The command that was executed resulted in an application error,
  2442. The most commom causes for this is invalid PHP or a broken SSH
  2443. pipe when using drush_backend_invoke in a distributed manner. */
  2444. define('DRUSH_APPLICATION_ERROR', 255);
  2445. /**
  2446. * @} End of "name Error status defintions".
  2447. */
  2448. /**
  2449. * @defgroup errorhandling Managing errors that occur in the Drush framework.
  2450. * @{
  2451. * Functions that manage the current error status of the Drush framework.
  2452. *
  2453. * These functions operate by maintaining a static variable that is a equal to the constant DRUSH_FRAMEWORK_ERROR if an
  2454. * error has occurred.
  2455. * This error code is returned at the end of program execution, and provide the shell or calling application with
  2456. * more information on how to diagnose any problems that may have occurred.
  2457. */
  2458. /**
  2459. * Set an error code for the error handling system.
  2460. *
  2461. * @param error
  2462. * A text string identifying the type of error.
  2463. *
  2464. * @param message
  2465. * Optional. Error message to be logged. If no message is specified, hook_drush_help will be consulted,
  2466. * using a key of 'error:MY_ERROR_STRING'.
  2467. *
  2468. * @return
  2469. * Always returns FALSE, to allow you to return with false in the calling functions,
  2470. * such as <code>return drush_set_error('DRUSH_FRAMEWORK_ERROR')</code>
  2471. */
  2472. function drush_set_error($error, $message = null) {
  2473. $error_code =& drush_get_context('DRUSH_ERROR_CODE', DRUSH_SUCCESS);
  2474. $error_code = DRUSH_FRAMEWORK_ERROR;
  2475. $error_log =& drush_get_context('DRUSH_ERROR_LOG', array());
  2476. if (is_numeric($error)) {
  2477. $error = 'DRUSH_FRAMEWORK_ERROR';
  2478. }
  2479. $message = ($message) ? $message : drush_command_invoke_all('drush_help', 'error:' . $error);
  2480. if (is_array($message)) {
  2481. $message = implode("\n", $message);
  2482. }
  2483. $error_log[$error][] = $message;
  2484. drush_log(($message) ? $message : $error, 'error', $error);
  2485. return FALSE;
  2486. }
  2487. /**
  2488. * Return the current error handling status
  2489. *
  2490. * @return
  2491. * The current aggregate error status
  2492. */
  2493. function drush_get_error() {
  2494. return drush_get_context('DRUSH_ERROR_CODE', DRUSH_SUCCESS);
  2495. }
  2496. /**
  2497. * Return the current list of errors that have occurred.
  2498. *
  2499. * @return
  2500. * An associative array of error messages indexed by the type of message.
  2501. */
  2502. function drush_get_error_log() {
  2503. return drush_get_context('DRUSH_ERROR_LOG', array());
  2504. }
  2505. /**
  2506. * Check if a specific error status has been set.
  2507. *
  2508. * @param error
  2509. * A text string identifying the error that has occurred.
  2510. * @return
  2511. * TRUE if the specified error has been set, FALSE if not
  2512. */
  2513. function drush_cmp_error($error) {
  2514. $error_log = drush_get_error_log();
  2515. if (is_numeric($error)) {
  2516. $error = 'DRUSH_FRAMEWORK_ERROR';
  2517. }
  2518. return array_key_exists($error, $error_log);
  2519. }
  2520. /**
  2521. * Exit due to user declining a confirmation prompt.
  2522. *
  2523. * Usage: return drush_user_abort();
  2524. */
  2525. function drush_user_abort($msg = NULL) {
  2526. drush_set_context('DRUSH_USER_ABORT', TRUE);
  2527. drush_log($msg ? $msg : dt('Aborting.'), 'cancel');
  2528. return FALSE;
  2529. }
  2530. /**
  2531. * Turn PHP error handling off.
  2532. *
  2533. * This is commonly used while bootstrapping Drupal for install
  2534. * or updates.
  2535. */
  2536. function drush_errors_off() {
  2537. $errors =& drush_get_context('DRUSH_ERROR_REPORTING', 0);
  2538. $errors = error_reporting(0);
  2539. ini_set('display_errors', FALSE);
  2540. }
  2541. /**
  2542. * Turn PHP error handling on.
  2543. */
  2544. function drush_errors_on() {
  2545. $errors =& drush_get_context('DRUSH_ERROR_REPORTING', E_ALL ^ E_NOTICE);
  2546. $errors = error_reporting($errors);
  2547. ini_set('display_errors', TRUE);
  2548. }
  2549. /**
  2550. * @} End of "defgroup errorhandling".
  2551. */
  2552. /**
  2553. * Test to see if a file exists and is not empty
  2554. */
  2555. function drush_file_not_empty($file_to_test) {
  2556. if (file_exists($file_to_test)) {
  2557. $stat = stat($file_to_test);
  2558. if ($stat['size'] > 0) {
  2559. return TRUE;
  2560. }
  2561. }
  2562. return FALSE;
  2563. }
  2564. /**
  2565. * Get the PHP memory_limit value in bytes.
  2566. */
  2567. function drush_memory_limit() {
  2568. $value = trim(ini_get('memory_limit'));
  2569. $last = strtolower($value[strlen($value)-1]);
  2570. switch ($last) {
  2571. case 'g':
  2572. $value *= DRUSH_DRUPAL_KILOBYTE;
  2573. case 'm':
  2574. $value *= DRUSH_DRUPAL_KILOBYTE;
  2575. case 'k':
  2576. $value *= DRUSH_DRUPAL_KILOBYTE;
  2577. }
  2578. return $value;
  2579. }
  2580. /**
  2581. * Unset the named key anywhere in the provided
  2582. * data structure.
  2583. */
  2584. function drush_unset_recursive(&$data, $unset_key) {
  2585. if (!empty($data) && is_array($data)) {
  2586. unset($data[$unset_key]);
  2587. foreach ($data as $key => $value) {
  2588. if (is_array($value)) {
  2589. drush_unset_recursive($data[$key], $unset_key);
  2590. }
  2591. }
  2592. }
  2593. }
  2594. /**
  2595. * Return a list of VCSs reserved files and directories.
  2596. */
  2597. function drush_version_control_reserved_files() {
  2598. static $files = FALSE;
  2599. if (!$files) {
  2600. // Also support VCSs that are not drush vc engines.
  2601. $files = array('.git', '.gitignore', '.hg', '.hgignore', '.hgrags');
  2602. $vcs = array_keys(drush_get_engines('version_control'));
  2603. foreach ($vcs as $name) {
  2604. drush_include_engine('version_control', $name);
  2605. $class = 'drush_pm_version_control_' . $name;
  2606. // For php < 5.3 we can't access a static method by referencing the class
  2607. // using a variable.
  2608. $version_control = new $class();
  2609. $files = array_merge($files, $version_control->reserved_files());
  2610. }
  2611. }
  2612. return $files;
  2613. }