bootstrap.inc

  1. 8.0.x tests/bootstrap.inc
  2. 8.0.x includes/bootstrap.inc
  3. 6.x includes/bootstrap.inc
  4. 7.x tests/bootstrap.inc
  5. 7.x includes/bootstrap.inc
  6. 5.x includes/bootstrap.inc
  7. master includes/bootstrap.inc
  8. master tests/bootstrap.inc

Drush bootstrapping code.

Functions here are used to bootstrap drush and then maybe Drupal to a level sufficient so that we can run commands. This is also where third party extensions can bootstrap drush without going through drush.php (this is used in the unit tests for example).

Functions

Namesort descending Description
drush_autoload Used by a Drush extension to request that its Composer autoload files be loaded by Drush, if they have not already been.
drush_bootstrap Bootstrap Drush to the desired phase.
drush_bootstrap_error Helper function to collect any errors that occur during the bootstrap process. Always returns FALSE, for convenience.
drush_bootstrap_finish Cleanup our bootstrap.
drush_bootstrap_max Bootstrap to the highest level possible, without triggering any errors.
drush_bootstrap_max_to_sitealias Bootstrap the specified site alias. The site alias must be a valid alias to a local site.
drush_bootstrap_prepare Prepare drush for bootstrap
drush_bootstrap_to_phase Bootstrap to the specified phase.
drush_bootstrap_validate Validate whether a bootstrap phase can be reached.
drush_bootstrap_value Helper function to store any context settings that are being validated.
drush_has_boostrapped Determine whether a given bootstrap phase has been completed
drush_return_status
drush_shutdown Shutdown function for use while Drupal is bootstrapping and to return any registered errors.
_drush_bootstrap_base_environment Sets up basic environment that controls where Drush looks for files on a system-wide basis. Important to call for "early" functions that need to work with unit tests.
_drush_bootstrap_do_drupal_site Called by _drush_bootstrap_drupal_site to do the main work of the drush drupal site bootstrap.
_drush_bootstrap_drupal_configuration Initialize and load the Drupal configuration files.
_drush_bootstrap_drupal_database Boostrap the Drupal database.
_drush_bootstrap_drupal_database_validate Validate the DRUSH_BOOTSTRAP_DRUPAL_DATABASE phase
_drush_bootstrap_drupal_full Attempt to load the full Drupal system.
_drush_bootstrap_drupal_login Log into the bootstrapped Drupal site with a specific username or user id.
_drush_bootstrap_drupal_root Bootstrap Drush with a valid Drupal Directory.
_drush_bootstrap_drupal_root_validate Validate the DRUSH_BOOTSTRAP_DRUPAL_ROOT phase.
_drush_bootstrap_drupal_site Initialize a site on the Drupal root.
_drush_bootstrap_drupal_site_validate VALIDATE the DRUSH_BOOTSTRAP_DRUPAL_SITE phase.
_drush_bootstrap_drush Initial Drush bootstrap phase.
_drush_bootstrap_drush_validate Validate that Drush is running in a suitable environment.
_drush_bootstrap_global_options
_drush_bootstrap_output_prepare
_drush_bootstrap_phases Helper function listing phases.
_drush_bootstrap_selected_uri Find the URI that has been selected by the --uri / -l option or the cwd.
_drush_bootstrap_select_drupal_site Determine which Drupal site will be selected.

Constants

Namesort descending Description
DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION Load the settings from the Drupal sites directory.
DRUSH_BOOTSTRAP_DRUPAL_DATABASE Connect to the Drupal database using the database credentials loaded during the previous bootstrap phase.
DRUSH_BOOTSTRAP_DRUPAL_FULL Fully initialize Drupal.
DRUSH_BOOTSTRAP_DRUPAL_LOGIN Log in to the initialiased Drupal site.
DRUSH_BOOTSTRAP_DRUPAL_ROOT Set up and test for a valid drupal root, either through the -r/--root options, or evaluated based on the current working directory.
DRUSH_BOOTSTRAP_DRUPAL_SITE Set up a Drupal site directory and the correct environment variables to allow Drupal to find the configuration file.
DRUSH_BOOTSTRAP_DRUSH Only bootstrap Drush, without any Drupal specific code.
DRUSH_BOOTSTRAP_MAX Use drush_bootstrap_max instead of drush_bootstrap_to_phase
DRUSH_BOOTSTRAP_NONE No bootstrap.

File

includes/bootstrap.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * Drush bootstrapping code.
  6. *
  7. * Functions here are used to bootstrap drush and then maybe Drupal to
  8. * a level sufficient so that we can run commands. This is also where
  9. * third party extensions can bootstrap drush without going through
  10. * drush.php (this is used in the unit tests for example).
  11. */
  12. /**
  13. * @name Drush bootstrap phases
  14. * @{
  15. * Sequential Drush bootstrapping phases.
  16. */
  17. /**
  18. * No bootstrap.
  19. *
  20. * This constant is only used to indicate that the bootstrap process has
  21. * not started yet. It is not possible to have no bootstrap.
  22. */
  23. define('DRUSH_BOOTSTRAP_NONE', -1);
  24. /**
  25. * Use drush_bootstrap_max instead of drush_bootstrap_to_phase
  26. *
  27. * This constant is only usable as the value of the 'bootstrap'
  28. * item of a command object, or as the parameter to
  29. * drush_bootstrap_to_phase. It is not a real bootstrap state.
  30. */
  31. define('DRUSH_BOOTSTRAP_MAX', -2);
  32. /**
  33. * Only bootstrap Drush, without any Drupal specific code.
  34. *
  35. * Any code that operates on the Drush installation, and not specifically
  36. * any Drupal directory, should bootstrap to this phase.
  37. */
  38. define('DRUSH_BOOTSTRAP_DRUSH', 0);
  39. /**
  40. * Set up and test for a valid drupal root, either through the -r/--root options,
  41. * or evaluated based on the current working directory.
  42. *
  43. * Any code that interacts with an entire Drupal installation, and not a specific
  44. * site on the Drupal installation should use this bootstrap phase.
  45. */
  46. define('DRUSH_BOOTSTRAP_DRUPAL_ROOT', 1);
  47. /**
  48. * Set up a Drupal site directory and the correct environment variables to
  49. * allow Drupal to find the configuration file.
  50. *
  51. * If no site is specified with the -l / --uri options, Drush will assume the
  52. * site is 'default', which mimics Drupal's behaviour.
  53. *
  54. * If you want to avoid this behaviour, it is recommended that you use the
  55. * DRUSH_BOOTSTRAP_DRUPAL_ROOT bootstrap phase instead.
  56. *
  57. * Any code that needs to modify or interact with a specific Drupal site's
  58. * settings.php file should bootstrap to this phase.
  59. */
  60. define('DRUSH_BOOTSTRAP_DRUPAL_SITE', 2);
  61. /**
  62. * Load the settings from the Drupal sites directory.
  63. *
  64. * This phase is analagous to the DRUPAL_BOOTSTRAP_CONFIGURATION bootstrap phase in Drupal
  65. * itself, and this is also the first step where Drupal specific code is included.
  66. *
  67. * This phase is commonly used for code that interacts with the Drupal install API,
  68. * as both install.php and update.php start at this phase.
  69. */
  70. define('DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION', 3);
  71. /**
  72. * Connect to the Drupal database using the database credentials loaded
  73. * during the previous bootstrap phase.
  74. *
  75. * This phase is analogous to the DRUPAL_BOOTSTRAP_DATABASE bootstrap phase in
  76. * Drupal.
  77. *
  78. * Any code that needs to interact with the Drupal database API needs to
  79. * be bootstrapped to at least this phase.
  80. */
  81. define('DRUSH_BOOTSTRAP_DRUPAL_DATABASE', 4);
  82. /**
  83. * Fully initialize Drupal.
  84. *
  85. * This is analogous to the DRUPAL_BOOTSTRAP_FULL bootstrap phase in
  86. * Drupal.
  87. *
  88. * Any code that interacts with the general Drupal API should be
  89. * bootstrapped to this phase.
  90. */
  91. define('DRUSH_BOOTSTRAP_DRUPAL_FULL', 5);
  92. /**
  93. * Log in to the initialiased Drupal site.
  94. *
  95. * This is the default bootstrap phase all commands will try to reach,
  96. * unless otherwise specified.
  97. *
  98. * This bootstrap phase is used after the site has been
  99. * fully bootstrapped.
  100. *
  101. * This phase will log you in to the drupal site with the username
  102. * or user ID specified by the --user/ -u option.
  103. *
  104. * Use this bootstrap phase for your command if you need to have access
  105. * to information for a specific user, such as listing nodes that might
  106. * be different based on who is logged in.
  107. */
  108. define('DRUSH_BOOTSTRAP_DRUPAL_LOGIN', 6);
  109. /**
  110. * Helper function listing phases.
  111. *
  112. * For commands that need to iterate through the phases, such as help
  113. */
  114. function _drush_bootstrap_phases($function_names = FALSE, $init_phases_only = FALSE) {
  115. static $functions = array(
  116. DRUSH_BOOTSTRAP_DRUSH => '_drush_bootstrap_drush',
  117. DRUSH_BOOTSTRAP_DRUPAL_ROOT => '_drush_bootstrap_drupal_root',
  118. DRUSH_BOOTSTRAP_DRUPAL_SITE => '_drush_bootstrap_drupal_site',
  119. DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION => '_drush_bootstrap_drupal_configuration',
  120. DRUSH_BOOTSTRAP_DRUPAL_DATABASE => '_drush_bootstrap_drupal_database',
  121. DRUSH_BOOTSTRAP_DRUPAL_FULL => '_drush_bootstrap_drupal_full',
  122. DRUSH_BOOTSTRAP_DRUPAL_LOGIN => '_drush_bootstrap_drupal_login');
  123. $result = array();
  124. if ($init_phases_only) {
  125. foreach (array(DRUSH_BOOTSTRAP_DRUSH, DRUSH_BOOTSTRAP_DRUPAL_FULL) as $phase) {
  126. $result[$phase] = $functions[$phase];
  127. }
  128. }
  129. else {
  130. $result = $functions;
  131. }
  132. if (!$function_names) {
  133. $result = array_keys($result);
  134. }
  135. return $result;
  136. }
  137. /**
  138. * @} End of Drush bootstrap phases.
  139. */
  140. /**
  141. * Bootstrap Drush to the desired phase.
  142. *
  143. * This function will sequentially bootstrap each
  144. * lower phase up to the phase that has been requested.
  145. *
  146. * @param phase
  147. * The bootstrap phase to bootstrap to.
  148. * Any of the following constants :
  149. * DRUSH_BOOTSTRAP_DRUSH = Only Drush.
  150. * DRUSH_BOOTSTRAP_DRUPAL_ROOT = Find a valid Drupal root.
  151. * DRUSH_BOOTSTRAP_DRUPAL_SITE = Find a valid Drupal site.
  152. * DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION = Load the site's settings.
  153. * DRUSH_BOOTSTRAP_DRUPAL_DATABASE = Initialize the database.
  154. * DRUSH_BOOTSTRAP_DRUPAL_FULL = Initialize Drupal fully.
  155. * DRUSH_BOOTSTRAP_DRUPAL_LOGIN = Log into Drupal with a valid user.
  156. */
  157. function drush_bootstrap($phase, $phase_max = FALSE) {
  158. static $phases;
  159. if (!$phases) {
  160. $phases = _drush_bootstrap_phases(TRUE);
  161. }
  162. static $phase_index = 0;
  163. drush_set_context('DRUSH_BOOTSTRAPPING', TRUE);
  164. while ($phase >= $phase_index && isset($phases[$phase_index])) {
  165. if (drush_bootstrap_validate($phase_index)) {
  166. $current_phase = $phases[$phase_index];
  167. if (function_exists($current_phase) && !drush_get_error()) {
  168. drush_log(dt("Drush bootstrap phase : !function()", array('!function' => $current_phase)), 'bootstrap');
  169. $current_phase();
  170. // Find any command files that are available during this bootstrap phase.
  171. _drush_find_commandfiles($phase_index, $phase_max);
  172. }
  173. drush_set_context('DRUSH_BOOTSTRAP_PHASE', $phase_index);
  174. }
  175. else {
  176. $errors = drush_get_context('DRUSH_BOOTSTRAP_ERRORS', array());
  177. foreach ($errors as $code => $message) {
  178. drush_set_error($code, $message);
  179. }
  180. break;
  181. }
  182. unset($phases[$phase_index++]);
  183. }
  184. drush_set_context('DRUSH_BOOTSTRAPPING', FALSE);
  185. return !drush_get_error();
  186. }
  187. /**
  188. * Determine whether a given bootstrap phase has been completed
  189. *
  190. * This function name has a typo which makes me laugh so we choose not to
  191. * fix it. Take a deep breath, and smile. See
  192. * http://en.wikipedia.org/wiki/HTTP_referer
  193. *
  194. *
  195. * @param phase
  196. * The bootstrap phase to test
  197. *
  198. * @returns
  199. * TRUE if the specified bootstrap phase has completed.
  200. */
  201. function drush_has_boostrapped($phase) {
  202. $phase_index = drush_get_context('DRUSH_BOOTSTRAP_PHASE');
  203. return isset($phase_index) && ($phase_index >= $phase);
  204. }
  205. /**
  206. * Validate whether a bootstrap phase can be reached.
  207. *
  208. * This function will validate the settings that will be used
  209. * during the actual bootstrap process, and allow commands to
  210. * progressively bootstrap to the highest level that can be reached.
  211. *
  212. * This function will only run the validation function once, and
  213. * store the result from that execution in a local static. This avoids
  214. * validating phases multiple times.
  215. *
  216. * @param phase
  217. * The bootstrap phase to validate to.
  218. * Any of the following constants :
  219. * DRUSH_BOOTSTRAP_DRUSH = Only Drush.
  220. * DRUSH_BOOTSTRAP_DRUPAL_ROOT = Find a valid Drupal root.
  221. * DRUSH_BOOTSTRAP_DRUPAL_SITE = Find a valid Drupal site.
  222. * DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION = Load the site's settings.
  223. * DRUSH_BOOTSTRAP_DRUPAL_DATABASE = Initialize the database.
  224. * DRUSH_BOOTSTRAP_DRUPAL_FULL = Initialize Drupal fully.
  225. * DRUSH_BOOTSTRAP_DRUPAL_LOGIN = Log into Drupal with a valid user.
  226. *
  227. * @return
  228. * True if bootstrap is possible, False if the validation failed.
  229. *
  230. */
  231. function drush_bootstrap_validate($phase) {
  232. static $phases;
  233. static $result_cache = array();
  234. if (!$phases) {
  235. $phases = _drush_bootstrap_phases(TRUE);
  236. }
  237. static $phase_index = 0;
  238. // Check to see if anyone has changed --root or --uri
  239. _drush_bootstrap_select_drupal_site();
  240. if (!array_key_exists($phase, $result_cache)) {
  241. drush_set_context('DRUSH_BOOTSTRAP_ERRORS', array());
  242. drush_set_context('DRUSH_BOOTSTRAP_VALUES', array());
  243. while ($phase >= $phase_index && isset($phases[$phase_index])) {
  244. $current_phase = $phases[$phase_index] . '_validate';
  245. if (function_exists($current_phase)) {
  246. $result_cache[$phase_index] = $current_phase();
  247. }
  248. else {
  249. $result_cache[$phase_index] = TRUE;
  250. }
  251. drush_set_context('DRUSH_BOOTSTRAP_VALIDATION_PHASE', $phase_index);
  252. unset($phases[$phase_index++]);
  253. }
  254. }
  255. return $result_cache[$phase];
  256. }
  257. /**
  258. * Bootstrap to the specified phase.
  259. *
  260. * @param $max_phase_index
  261. * Only attempt bootstrap to the specified level.
  262. */
  263. function drush_bootstrap_to_phase($max_phase_index) {
  264. // If $max_phase_index is DRUSH_BOOTSTRAP_MAX, then
  265. // we will bootstrap as far as we can. drush_bootstrap_max
  266. // is different than drush_bootstrap_to_phase in that
  267. // it is not an error if DRUSH_BOOTSTRAP_LOGIN is not reached.
  268. if ($max_phase_index == DRUSH_BOOTSTRAP_MAX) {
  269. drush_bootstrap_max();
  270. return TRUE;
  271. }
  272. drush_log(dt("Bootstrap to phase !phase.", array('!phase' => $max_phase_index)), 'bootstrap');
  273. $phases = _drush_bootstrap_phases();
  274. $result = TRUE;
  275. // Try to bootstrap to the maximum possible level, without generating errors
  276. foreach ($phases as $phase_index) {
  277. if ($phase_index > $max_phase_index) {
  278. // Stop trying, since we achieved what was specified.
  279. break;
  280. }
  281. if (drush_bootstrap_validate($phase_index)) {
  282. if ($phase_index > drush_get_context('DRUSH_BOOTSTRAP_PHASE')) {
  283. $result = drush_bootstrap($phase_index, $max_phase_index);
  284. }
  285. }
  286. else {
  287. $result = FALSE;
  288. break;
  289. }
  290. }
  291. return $result;
  292. }
  293. /**
  294. * Bootstrap to the highest level possible, without triggering any errors.
  295. *
  296. * @param $max_phase_index
  297. * Only attempt bootstrap to the specified level.
  298. *
  299. * @return int
  300. * The maximum phase to which we bootstrapped.
  301. */
  302. function drush_bootstrap_max($max_phase_index = FALSE) {
  303. $phases = _drush_bootstrap_phases();
  304. $phase_index = DRUSH_BOOTSTRAP_DRUSH;
  305. if (!$max_phase_index) {
  306. $max_phase_index = count($phases);
  307. }
  308. // Try to bootstrap to the maximum possible level, without generating errors
  309. foreach ($phases as $phase_index) {
  310. if ($phase_index > $max_phase_index) {
  311. // Stop trying, since we achieved what was specified.
  312. break;
  313. }
  314. if (drush_bootstrap_validate($phase_index)) {
  315. if ($phase_index > drush_get_context('DRUSH_BOOTSTRAP_PHASE')) {
  316. drush_bootstrap($phase_index, $max_phase_index);
  317. }
  318. }
  319. else {
  320. break;
  321. }
  322. }
  323. return drush_get_context('DRUSH_BOOTSTRAP_PHASE');
  324. }
  325. /**
  326. * Bootstrap the specified site alias. The site alias must
  327. * be a valid alias to a local site.
  328. *
  329. * @param $site_record
  330. * The alias record for the given site alias.
  331. * @see drush_sitealias_get_record().
  332. * @param $max_phase_index
  333. * Only attempt bootstrap to the specified level.
  334. * @returns TRUE if attempted to bootstrap, or FALSE
  335. * if no bootstrap attempt was made.
  336. */
  337. function drush_bootstrap_max_to_sitealias($site_record, $max_phase_index = NULL) {
  338. if ((array_key_exists('root', $site_record) && !array_key_exists('remote-host', $site_record))) {
  339. drush_sitealias_set_alias_context($site_record);
  340. drush_bootstrap_max($max_phase_index);
  341. return TRUE;
  342. }
  343. return FALSE;
  344. }
  345. /**
  346. * Helper function to collect any errors that occur during the bootstrap process.
  347. * Always returns FALSE, for convenience.
  348. */
  349. function drush_bootstrap_error($code, $message = null) {
  350. $errors = drush_get_context('DRUSH_BOOTSTRAP_ERRORS');
  351. $errors[$code] = $message;
  352. drush_set_context('DRUSH_BOOTSTRAP_ERRORS', $errors);
  353. return FALSE;
  354. }
  355. /**
  356. * Validate that Drush is running in a suitable environment.
  357. */
  358. function _drush_bootstrap_drush_validate() {
  359. // @todo _drush_environment_php_ini_checks() always returns TRUE.
  360. $return = _drush_environment_check_php_ini();
  361. if ($return !== TRUE) {
  362. return $return;
  363. }
  364. if (drush_environment_lib() === FALSE) {
  365. return FALSE;
  366. }
  367. if (drush_environment_table_lib() === FALSE) {
  368. return FALSE;
  369. }
  370. return TRUE;
  371. }
  372. /**
  373. * Initial Drush bootstrap phase.
  374. *
  375. * During the initialization of Drush,
  376. * this is the first step where all we are
  377. * aware of is Drush itself.
  378. *
  379. * In this step we will register the shutdown function,
  380. * parse the command line arguments and store them in their
  381. * related contexts.
  382. *
  383. * Configuration files (drushrc.php) that are
  384. * a) Specified on the command line
  385. * b) Stored in the root directory of drush.php
  386. * c) Stored in the home directory of the system user.
  387. *
  388. * Additionally the DRUSH_QUIET and DRUSH_BACKEND contexts,
  389. * will be evaluated now, as they need to be set very early in
  390. * the execution flow to be able to take affect/
  391. */
  392. function _drush_bootstrap_drush() {
  393. // Create an alias '@none' to represent no Drupal site
  394. _drush_sitealias_cache_alias('@none', array('root' => '', 'uri' => ''));
  395. // Set the terminal width, used for wrapping table output.
  396. // Normally this is exported using tput in the drush script.
  397. // If this is not present we do an additional check using stty here.
  398. // On Windows in CMD and PowerShell is this exported using mode con.
  399. if (!($columns = getenv('COLUMNS'))) {
  400. // Trying to export the columns using stty.
  401. exec('stty size 2>&1', $columns_output, $columns_status);
  402. if (!$columns_status) $columns = preg_replace('/\d+\s(\d+)/', '$1', $columns_output[0], -1, $columns_count);
  403. // If stty fails and Drush us running on Windows are we trying with mode con.
  404. if (($columns_status || !$columns_count) && drush_is_windows()) {
  405. $columns_output = array();
  406. exec('mode con', $columns_output, $columns_status);
  407. if (!$columns_status && is_array($columns_output)) {
  408. $columns = (int)preg_replace('/\D/', '', $columns_output[4], -1, $columns_count);
  409. }
  410. else {
  411. drush_log(dt('Drush could not detect the console window width. Set a Windows Environment Variable of COLUMNS to the desired width.'), 'warning');
  412. }
  413. }
  414. // Failling back to default columns value
  415. if (empty($columns)) {
  416. $columns = 80;
  417. }
  418. }
  419. // If a caller wants to reserve some room to add additional
  420. // information to the drush output via post-processing, the
  421. // --reserve-margin flag can be used to declare how much
  422. // space to leave out. This only affects drush functions
  423. // such as drush_print_table() that wrap the output.
  424. $columns -= drush_get_option('reserve-margin', 0);
  425. drush_set_context('DRUSH_COLUMNS', $columns);
  426. // Statically define a way to call drush again.
  427. define('DRUSH_COMMAND', drush_find_drush());
  428. // prime the CWD cache
  429. drush_cwd();
  430. // Set up base environment for system-wide file locations.
  431. _drush_bootstrap_base_environment();
  432. // Load a drushrc.php file in the drush.php's directory.
  433. drush_load_config('drush');
  434. // Load a drushrc.php file in the $ETC_PREFIX/etc/drush directory.
  435. drush_load_config('system');
  436. // Load a drushrc.php file at ~/.drushrc.php.
  437. drush_load_config('user');
  438. // Load a drushrc.php file in the ~/.drush directory.
  439. drush_load_config('home.drush');
  440. // Load a custom config specified with the --config option.
  441. drush_load_config('custom');
  442. // Process the site alias that specifies which instance
  443. // of drush (local or remote) this command will operate on.
  444. // We must do this after we load our config files (so that
  445. // site aliases are available), but before the rest
  446. // of the drush and drupal root bootstrap phases are
  447. // done, since site aliases may set option values that
  448. // affect these phases.
  449. drush_sitealias_check_arg();
  450. // Check to see if we 'use'd a site alias with site-set
  451. drush_sitealias_check_site_env();
  452. // If an alias was not created by drush_sitealias_check_arg()
  453. // or drush_sitealias_check_site_env(), make one now.
  454. drush_sitealias_create_self_alias();
  455. // Load the config options from Drupal's /drush and sites/all/drush directories,
  456. // even prior to bootstrapping the root.
  457. drush_load_config('drupal');
  458. // Similarly, load the Drupal site configuration options upfront.
  459. drush_load_config('site');
  460. // If applicable swaps in shell alias value (or executes it).
  461. drush_shell_alias_replace();
  462. // If drush_load_config defined a site alias that did not
  463. // exist before, then sitealias check arg might now match
  464. // against one of those aliases. This is also the place
  465. // where we will find @self, if it was created via
  466. // drush_sitealias_create_self_alias().
  467. if ((drush_sitealias_check_arg() === TRUE) || (drush_sitealias_check_site_env() === TRUE)) {
  468. $remote_host = drush_get_option('remote-host');
  469. if (!isset($remote_host)) {
  470. // Load the config files for the "new" site.
  471. drush_load_config('drupal');
  472. drush_load_config('site');
  473. }
  474. }
  475. _drush_bootstrap_global_options();
  476. }
  477. function _drush_bootstrap_output_prepare() {
  478. $backend = drush_set_context('DRUSH_BACKEND', drush_get_option('backend'));
  479. // Pipe implies quiet.
  480. $quiet = drush_set_context('DRUSH_QUIET', drush_get_option(array('quiet', 'pipe')));
  481. drush_set_context('DRUSH_PIPE', drush_get_option('pipe'));
  482. if ($backend) {
  483. // Load options passed as a JSON encoded string through STDIN.
  484. $stdin_options = _drush_backend_get_stdin();
  485. if (is_array($stdin_options)) {
  486. drush_set_context('stdin', $stdin_options);
  487. }
  488. // Add an output buffer handler to collect output/pass through backend
  489. // packets. Using a chunksize of 2 ensures that each line is flushed
  490. // straight away.
  491. if ($quiet) {
  492. // Pass through of backend packets, discard regular output.
  493. ob_start('drush_backend_output_discard', 2);
  494. }
  495. else {
  496. // Collect output.
  497. ob_start('drush_backend_output_collect', 2);
  498. }
  499. }
  500. // In non-backend quiet mode we start buffering and discards it on command
  501. // completion.
  502. if ($quiet && !$backend) {
  503. ob_start();
  504. }
  505. }
  506. /**
  507. * Determine which Drupal site will be selected.
  508. *
  509. * The Drupal site itself will be bootstrapped at a later
  510. * phase; at this time, we set context variables to
  511. * point to the drupal root, site URI and site configuration
  512. * path that will be used when needed.
  513. *
  514. * These early context variables are used to find
  515. * drush configuration and alias files stored with the
  516. * site to be bootstrapped.
  517. */
  518. function _drush_bootstrap_select_drupal_site() {
  519. $drupal_root = drush_get_option('root');
  520. if (!isset($drupal_root)) {
  521. $drupal_root = drush_locate_root();
  522. }
  523. drush_set_context('DRUSH_SELECTED_DRUPAL_ROOT', $drupal_root);
  524. $uri = _drush_bootstrap_selected_uri();
  525. drush_set_context('DRUSH_SELECTED_URI', $uri);
  526. drush_set_context('DRUSH_SELECTED_DRUPAL_SITE_CONF_PATH', drush_conf_path($uri));
  527. if (!empty($drupal_root) && !empty($uri)) {
  528. // Create an alias '@self'
  529. _drush_sitealias_cache_alias('@self', array('root' => $drupal_root, 'uri' => $uri));
  530. }
  531. }
  532. /**
  533. * Sets up basic environment that controls where Drush looks for files on a
  534. * system-wide basis. Important to call for "early" functions that need to
  535. * work with unit tests.
  536. */
  537. function _drush_bootstrap_base_environment() {
  538. // Copy ETC_PREFIX and SHARE_PREFIX from environment variables if available.
  539. // This alters where we check for server-wide config and alias files.
  540. // Used by unit test suite to provide a clean environment.
  541. if (getenv('ETC_PREFIX')) drush_set_context('ETC_PREFIX', getenv('ETC_PREFIX'));
  542. if (getenv('SHARE_PREFIX')) drush_set_context('SHARE_PREFIX', getenv('SHARE_PREFIX'));
  543. drush_set_context('DOC_PREFIX', DRUSH_BASE_PATH);
  544. if (!file_exists(DRUSH_BASE_PATH . '/README.md') && file_exists(drush_get_context('SHARE_PREFIX', '/usr') . '/share/doc/drush' . '/README.md')) {
  545. drush_set_context('DOC_PREFIX', drush_get_context('SHARE_PREFIX', '/usr') . '/share/doc/drush');
  546. }
  547. $alias_path =& drush_get_context('ALIAS_PATH');
  548. $default_prefix_configuration = drush_is_windows() ? getenv('ALLUSERSPROFILE') . '/Drush' : '';
  549. $default_prefix_commandfile = drush_is_windows() ? getenv('ALLUSERSPROFILE') . '/Drush' : '/usr';
  550. $site_wide_configuration_dir = drush_get_context('ETC_PREFIX', $default_prefix_configuration) . '/etc/drush';
  551. $site_wide_commandfile_dir = drush_get_context('SHARE_PREFIX', $default_prefix_commandfile) . '/share/drush/commands';
  552. $alias_path[] = $site_wide_configuration_dir;
  553. drush_set_context('DRUSH_SITE_WIDE_CONFIGURATION', $site_wide_configuration_dir);
  554. drush_set_context('DRUSH_SITE_WIDE_COMMANDFILES', $site_wide_commandfile_dir);
  555. $alias_path[] = dirname(__FILE__) . '/..';
  556. $server_home = drush_server_home();
  557. if (isset($server_home)) {
  558. $alias_path[] = $server_home . '/.drush';
  559. drush_set_context('DRUSH_PER_USER_CONFIGURATION', $server_home . '/.drush');
  560. }
  561. }
  562. function _drush_bootstrap_global_options() {
  563. // Debug implies verbose
  564. drush_set_context('DRUSH_VERBOSE', drush_get_option(array('verbose', 'debug'), FALSE));
  565. drush_set_context('DRUSH_DEBUG', drush_get_option('debug'));
  566. // Backend implies affirmative unless negative is explicitly specified
  567. drush_set_context('DRUSH_NEGATIVE', drush_get_option('no', FALSE));
  568. drush_set_context('DRUSH_AFFIRMATIVE', drush_get_option(array('yes', 'pipe'), FALSE) || (drush_get_context('DRUSH_BACKEND') && !drush_get_context('DRUSH_NEGATIVE')));
  569. drush_set_context('DRUSH_SIMULATE', drush_get_option('simulate', FALSE));
  570. // Suppress colored logging if --nocolor option is explicitly given or if
  571. // terminal does not support it.
  572. $nocolor = (drush_get_option('nocolor', FALSE));
  573. if (!$nocolor) {
  574. // Check for colorless terminal. If there is no terminal, then
  575. // 'tput colors 2>&1' will return "tput: No value for $TERM and no -T specified",
  576. // which is not numeric and therefore will put us in no-color mode.
  577. $colors = exec('tput colors 2>&1');
  578. $nocolor = !($colors === FALSE || (is_numeric($colors) && $colors >= 3));
  579. }
  580. drush_set_context('DRUSH_NOCOLOR', $nocolor);
  581. }
  582. /**
  583. * Validate the DRUSH_BOOTSTRAP_DRUPAL_ROOT phase.
  584. *
  585. * In this function, we will check if a valid Drupal directory is available.
  586. * We also determine the value that will be stored in the DRUSH_DRUPAL_ROOT
  587. * context and DRUPAL_ROOT constant if it is considered a valid option.
  588. */
  589. function _drush_bootstrap_drupal_root_validate() {
  590. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  591. if (empty($drupal_root)) {
  592. return drush_bootstrap_error('DRUSH_NO_DRUPAL_ROOT', dt("A Drupal installation directory could not be found"));
  593. }
  594. if (!$signature = drush_valid_drupal_root($drupal_root)) {
  595. return drush_bootstrap_error('DRUSH_INVALID_DRUPAL_ROOT', dt("The directory !drupal_root does not contain a valid Drupal installation", array('!drupal_root' => $drupal_root)));
  596. }
  597. drush_bootstrap_value('drupal_root', $drupal_root);
  598. drush_set_context('DRUSH_DRUPAL_ROOT', $drupal_root);
  599. $version = drush_drupal_version();
  600. $major_version = drush_drupal_major_version();
  601. // For Drupal 8, use the master branch of Drush.
  602. if ($major_version <= 5 || $major_version >= 8) {
  603. return drush_set_error('DRUSH_DRUPAL_VERSION_UNSUPPORTED', dt('Drush !drush_version does not support Drupal !major_version. See http://drupal.org/project/drush for more information.', array('!drush_version' => DRUSH_VERSION, '!major_version' => $major_version)));
  604. }
  605. define('DRUSH_DRUPAL_SIGNATURE', $signature);
  606. return TRUE;
  607. }
  608. /**
  609. * Bootstrap Drush with a valid Drupal Directory.
  610. *
  611. * In this function, the pwd will be moved to the root
  612. * of the Drupal installation.
  613. *
  614. * The DRUSH_DRUPAL_ROOT context, DRUSH_DRUPAL_CORE context, DRUPAL_ROOT, and the
  615. * DRUSH_DRUPAL_CORE constants are populated from the value that we determined during
  616. * the validation phase.
  617. *
  618. * We also now load the drushrc.php for this specific platform.
  619. * We can now include files from the Drupal Tree, and figure
  620. * out more context about the platform, such as the version of Drupal.
  621. */
  622. function _drush_bootstrap_drupal_root() {
  623. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  624. chdir($drupal_root);
  625. $version = drush_drupal_version();
  626. $major_version = drush_drupal_major_version();
  627. define('DRUPAL_ROOT', $drupal_root);
  628. // DRUSH_DRUPAL_CORE should point to the /core folder in Drupal 8+ or to DRUPAL_ROOT
  629. // in prior versions.
  630. $core = $major_version >= 8 ? DRUPAL_ROOT . '/core' : DRUPAL_ROOT;
  631. drush_set_context('DRUSH_DRUPAL_CORE', $core);
  632. define('DRUSH_DRUPAL_CORE', $core);
  633. _drush_bootstrap_global_options();
  634. drush_log(dt("Initialized Drupal !version root directory at !drupal_root", array("!version" => $version, '!drupal_root' => $drupal_root)));
  635. }
  636. /**
  637. * Find the URI that has been selected by the --uri / -l option
  638. * or the cwd.
  639. */
  640. function _drush_bootstrap_selected_uri() {
  641. $uri = drush_get_option('uri');
  642. if (!isset($uri)) {
  643. $site_path = drush_site_path();
  644. $elements = explode('/', $site_path);
  645. $current = array_pop($elements);
  646. if (!$current) {
  647. $current = 'default';
  648. }
  649. $uri = 'http://'. $current;
  650. }
  651. return $uri;
  652. }
  653. /**
  654. * VALIDATE the DRUSH_BOOTSTRAP_DRUPAL_SITE phase.
  655. *
  656. * In this function we determine the URL used for the command,
  657. * and check for a valid settings.php file.
  658. *
  659. * To do this, we need to set up the $_SERVER environment variable,
  660. * to allow us to use conf_path to determine what Drupal will load
  661. * as a configuration file.
  662. */
  663. function _drush_bootstrap_drupal_site_validate() {
  664. $drush_uri = drush_get_context('DRUSH_SELECTED_URI');
  665. // Fake the necessary HTTP headers that Drupal needs:
  666. if ($drush_uri) {
  667. $drupal_base_url = parse_url($drush_uri);
  668. // If there's no url scheme set, add http:// and re-parse the url
  669. // so the host and path values are set accurately.
  670. if (!array_key_exists('scheme', $drupal_base_url)) {
  671. $drush_uri = 'http://' . $drush_uri;
  672. $drupal_base_url = parse_url($drush_uri);
  673. }
  674. // Fill in defaults.
  675. $drupal_base_url += array(
  676. 'path' => NULL,
  677. 'host' => NULL,
  678. 'port' => NULL,
  679. );
  680. $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
  681. if ($drupal_base_url['scheme'] == 'https') {
  682. $_SERVER['HTTPS'] = 'on';
  683. }
  684. if ($drupal_base_url['port']) {
  685. $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
  686. }
  687. $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
  688. if (array_key_exists('path', $drupal_base_url)) {
  689. $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
  690. }
  691. else {
  692. $_SERVER['PHP_SELF'] = '/index.php';
  693. }
  694. }
  695. else {
  696. $_SERVER['HTTP_HOST'] = 'default';
  697. $_SERVER['PHP_SELF'] = '/index.php';
  698. }
  699. $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
  700. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  701. $_SERVER['REQUEST_METHOD'] = NULL;
  702. $_SERVER['SERVER_SOFTWARE'] = NULL;
  703. $_SERVER['HTTP_USER_AGENT'] = NULL;
  704. $site = drush_bootstrap_value('site', $_SERVER['HTTP_HOST']);
  705. $conf_path = drush_bootstrap_value('conf_path', conf_path(TRUE, TRUE));
  706. $conf_file = "$conf_path/settings.php";
  707. if (!file_exists($conf_file)) {
  708. return drush_bootstrap_error('DRUPAL_SITE_SETTINGS_NOT_FOUND', dt("Could not find a Drupal settings.php file at !file.",
  709. array('!file' => $conf_file)));
  710. }
  711. return TRUE;
  712. }
  713. /**
  714. * Called by _drush_bootstrap_drupal_site to do the main work
  715. * of the drush drupal site bootstrap.
  716. */
  717. function _drush_bootstrap_do_drupal_site() {
  718. $drush_uri = drush_get_context('DRUSH_SELECTED_URI');
  719. drush_set_context('DRUSH_URI', $drush_uri);
  720. $site = drush_set_context('DRUSH_DRUPAL_SITE', drush_bootstrap_value('site'));
  721. $conf_path = drush_set_context('DRUSH_DRUPAL_SITE_ROOT', drush_bootstrap_value('conf_path'));
  722. drush_log(dt("Initialized Drupal site !site at !site_root", array('!site' => $site, '!site_root' => $conf_path)));
  723. _drush_bootstrap_global_options();
  724. }
  725. /**
  726. * Initialize a site on the Drupal root.
  727. *
  728. * We now set various contexts that we determined and confirmed to be valid.
  729. * Additionally we load an optional drushrc.php file in the site directory.
  730. */
  731. function _drush_bootstrap_drupal_site() {
  732. _drush_bootstrap_do_drupal_site();
  733. }
  734. /**
  735. * Initialize and load the Drupal configuration files.
  736. *
  737. * We process and store a normalized set of database credentials
  738. * from the loaded configuration file, so we can validate them
  739. * and access them easily in the future.
  740. *
  741. * Also override Drupal variables as per --variables option.
  742. */
  743. function _drush_bootstrap_drupal_configuration() {
  744. global $conf;
  745. drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
  746. // Unset drupal error handler and restore drush's one.
  747. if (drush_drupal_major_version() >= 7) {
  748. restore_error_handler();
  749. }
  750. $override = array(
  751. 'dev_query' => FALSE, // Force Drupal6 not to store queries since we are not outputting them.
  752. 'cron_safe_threshold' => 0, // Don't run poormanscron during Drush request (D7+).
  753. );
  754. // Avoid MTimeProtected grief in D8+. See http://drupal.org/node/1899842. If you really don't
  755. // want this override, set different values using a drushrc.php by passing different values.
  756. $override['php_storage']['default'] = array(
  757. 'class' => 'Drupal\Component\PhpStorage\FileReadOnlyStorage',
  758. // 'directory' => drush_directory_cache('php_storage'),
  759. );
  760. $current_override = drush_get_option_list('variables');
  761. foreach ($current_override as $name => $value) {
  762. if (is_numeric($name) && (strpos($value, '=') !== FALSE)) {
  763. list($name, $value) = explode('=', $value, 2);
  764. }
  765. $override[$name] = $value;
  766. }
  767. $conf = is_array($conf) ? array_merge($conf, $override) : $conf;
  768. // Populate the DRUSH_DB_CREDENTIALS with the fields loaded from the configuration.
  769. $creds = array();
  770. switch (drush_drupal_major_version()) {
  771. case 6:
  772. if (!empty($GLOBALS['db_url'])) {
  773. $url = $GLOBALS['db_url'];
  774. if (is_array($url)) {
  775. $url = $url['default'];
  776. }
  777. $parts = parse_url($url);
  778. $parts += array('pass' => '', 'port' => '');
  779. $creds['driver'] = $parts['scheme'];
  780. $creds['user'] = urldecode($parts['user']);
  781. $creds['host'] = $parts['host'];
  782. $creds['port'] = $parts['port'];
  783. $creds['pass'] = urldecode($parts['pass']);
  784. $creds['name'] = trim($parts['path'], '/');
  785. }
  786. break;
  787. case 7:
  788. default:
  789. if (!empty($GLOBALS['databases']['default']['default'])) {
  790. $conn = $GLOBALS['databases']['default']['default'];
  791. // Fill in defaults to prevent notices.
  792. $conn += array(
  793. 'username' => NULL,
  794. 'host' => NULL,
  795. 'port' => NULL,
  796. 'password' => NULL,
  797. 'database' => NULL,
  798. 'unix_socket' => NULL,
  799. );
  800. $creds['driver'] = $conn['driver'];
  801. $creds['user'] = $conn['username'];
  802. $creds['unix_socket'] = $conn['unix_socket'];
  803. $creds['host'] = $conn['host'];
  804. $creds['port'] = $conn['port'];
  805. $creds['name'] = $conn['database'];
  806. $creds['pass'] = $conn['password'];
  807. if(isset($conn['pdo'])) {
  808. $creds['pdo'] = $conn['pdo'];
  809. } else { $creds['pdo'] = null; }
  810. }
  811. break;
  812. }
  813. drush_set_context('DRUSH_DB_CREDENTIALS', $creds);
  814. }
  815. /**
  816. * Validate the DRUSH_BOOTSTRAP_DRUPAL_DATABASE phase
  817. *
  818. * Attempt to making a working database connection using the
  819. * database credentials that were loaded during the previous
  820. * phase.
  821. */
  822. function _drush_bootstrap_drupal_database_validate() {
  823. if (!drush_valid_db_credentials()) {
  824. return drush_bootstrap_error('DRUSH_DRUPAL_DB_ERROR');
  825. }
  826. return TRUE;
  827. }
  828. /**
  829. * Boostrap the Drupal database.
  830. */
  831. function _drush_bootstrap_drupal_database() {
  832. drush_log(dt("Successfully connected to the Drupal database."), 'bootstrap');
  833. drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  834. }
  835. /**
  836. * Attempt to load the full Drupal system.
  837. */
  838. function _drush_bootstrap_drupal_full() {
  839. if (!drush_get_context('DRUSH_QUIET', FALSE)) {
  840. ob_start();
  841. }
  842. drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  843. if (!drush_get_context('DRUSH_QUIET', FALSE)) {
  844. ob_end_clean();
  845. }
  846. // Unset drupal error handler and restore drush's one.
  847. if (drush_drupal_major_version() == 6) {
  848. restore_error_handler();
  849. }
  850. // If needed, prod module_implements() to recognize our system_watchdog() implementation.
  851. $dogs = module_implements('watchdog');
  852. if (!in_array('system', $dogs)) {
  853. // Note that this resets module_implements cache.
  854. module_implements('watchdog', FALSE, TRUE);
  855. }
  856. // Write correct install_profile to cache as needed. Used by _drush_find_commandfiles().
  857. $cid = drush_cid_install_profile();
  858. if ($cached_install_profile = drush_cache_get($cid)) {
  859. // We have a cached profile. Check it for correctness and save new value if needed.
  860. $install_profile = drush_drupal_major_version() >= 7 ? drupal_get_profile() : variable_get('install_profile', 'standard');
  861. if ($cached_install_profile->data != $install_profile) {
  862. drush_cache_set($cid, $install_profile);
  863. }
  864. }
  865. else {
  866. // No cached entry so write to cache.
  867. $install_profile = drush_drupal_major_version() >= 7 ? drupal_get_profile() : variable_get('install_profile', 'standard');
  868. drush_cache_set($cid, $install_profile);
  869. }
  870. _drush_log_drupal_messages();
  871. }
  872. /**
  873. * Log into the bootstrapped Drupal site with a specific
  874. * username or user id.
  875. */
  876. function _drush_bootstrap_drupal_login() {
  877. $drush_user = drush_set_context('DRUSH_USER', drush_get_option('user', 0));
  878. drush_drupal_login($drush_user);
  879. _drush_log_drupal_messages();
  880. }
  881. /**
  882. * Helper function to store any context settings that are being validated.
  883. */
  884. function drush_bootstrap_value($context, $value = null) {
  885. $values =& drush_get_context('DRUSH_BOOTSTRAP_VALUES', array());
  886. if (isset($value)) {
  887. $values[$context] = $value;
  888. }
  889. if (array_key_exists($context, $values)) {
  890. return $values[$context];
  891. }
  892. return null;
  893. }
  894. /**
  895. * Prepare drush for bootstrap
  896. *
  897. * All pre-flight checks and includes necessary to begin the bootstrap
  898. * process.
  899. *
  900. * Ran before drush_main().
  901. *
  902. * @see drush_main()
  903. * @see drush.php
  904. */
  905. function drush_bootstrap_prepare() {
  906. define('DRUSH_BASE_PATH', dirname(dirname(__FILE__)));
  907. require_once DRUSH_BASE_PATH . '/includes/environment.inc';
  908. require_once DRUSH_BASE_PATH . '/includes/command.inc';
  909. require_once DRUSH_BASE_PATH . '/includes/drush.inc';
  910. require_once DRUSH_BASE_PATH . '/includes/engines.inc';
  911. require_once DRUSH_BASE_PATH . '/includes/backend.inc';
  912. require_once DRUSH_BASE_PATH . '/includes/batch.inc';
  913. require_once DRUSH_BASE_PATH . '/includes/context.inc';
  914. require_once DRUSH_BASE_PATH . '/includes/sitealias.inc';
  915. require_once DRUSH_BASE_PATH . '/includes/exec.inc';
  916. require_once DRUSH_BASE_PATH . '/includes/drupal.inc';
  917. require_once DRUSH_BASE_PATH . '/includes/output.inc';
  918. require_once DRUSH_BASE_PATH . '/includes/cache.inc';
  919. require_once DRUSH_BASE_PATH . '/includes/filesystem.inc';
  920. require_once DRUSH_BASE_PATH . '/includes/dbtng.inc';
  921. // Terminate immediately unless invoked as a command line script
  922. if (!drush_verify_cli()) {
  923. return drush_set_error('DRUSH_REQUIREMENTS_ERROR', dt('Drush is designed to run via the command line.'));
  924. }
  925. // Check supported version of PHP.
  926. // Note: If this is adjusted, check other code that compares
  927. // PHP_VERSION, such as runserver/runserver.drush.inc, and also
  928. // adjust _drush_environment_check_php_ini() and the php_prohibited_options
  929. // list in the drush script. See http://drupal.org/node/1748228
  930. define('DRUSH_MINIMUM_PHP', '5.3.0');
  931. if (version_compare(phpversion(), DRUSH_MINIMUM_PHP) < 0 && !getenv('DRUSH_NO_MIN_PHP')) {
  932. return drush_set_error('DRUSH_REQUIREMENTS_ERROR', dt('Your command line PHP installation is too old. Drush requires at least PHP !version. To suppress this check, set the environment variable DRUSH_NO_MIN_PHP=1', array('!version' => DRUSH_MINIMUM_PHP)));
  933. }
  934. $drush_info = drush_read_drush_info();
  935. define('DRUSH_VERSION', $drush_info['drush_version']);
  936. $version_parts = explode('.', DRUSH_VERSION);
  937. define('DRUSH_MAJOR_VERSION', $version_parts[0]);
  938. define('DRUSH_MINOR_VERSION', $version_parts[1]);
  939. define('DRUSH_REQUEST_TIME', microtime(TRUE));
  940. drush_set_context('argc', $GLOBALS['argc']);
  941. drush_set_context('argv', $GLOBALS['argv']);
  942. // Set an error handler and a shutdown function
  943. set_error_handler('drush_error_handler');
  944. register_shutdown_function('drush_shutdown');
  945. drush_set_context('DRUSH_BOOTSTRAP_PHASE', DRUSH_BOOTSTRAP_NONE);
  946. // We need some global options/arguments processed at this early stage.
  947. drush_parse_args();
  948. }
  949. /**
  950. * Cleanup our bootstrap.
  951. *
  952. * This is ran after we have bootstrapped and dispatched properly in
  953. * drush_main().
  954. *
  955. * @see drush_main()
  956. */
  957. function drush_bootstrap_finish() {
  958. // We set this context to let the shutdown function know we reached the end of drush_main();
  959. drush_set_context("DRUSH_EXECUTION_COMPLETED", TRUE);
  960. }
  961. /**
  962. * Shutdown function for use while Drupal is bootstrapping and to return any
  963. * registered errors.
  964. *
  965. * The shutdown command checks whether certain options are set to reliably
  966. * detect and log some common Drupal initialization errors.
  967. *
  968. * If the command is being executed with the --backend option, the script
  969. * will return a json string containing the options and log information
  970. * used by the script.
  971. *
  972. * The command will exit with '1' if it was successfully executed, and the
  973. * result of drush_get_error() if it wasn't.
  974. */
  975. function drush_shutdown() {
  976. // Mysteriously make $user available during sess_write(). Avoids a NOTICE.
  977. global $user;
  978. if (!drush_get_context('DRUSH_EXECUTION_COMPLETED', FALSE) && !drush_get_context('DRUSH_USER_ABORT', FALSE)) {
  979. $php_error_message = '';
  980. if ($error = error_get_last()) {
  981. $php_error_message = "\n" . dt('Error: !message in !file, line !line', array('!message' => $error['message'], '!file' => $error['file'], '!line' => $error['line']));
  982. }
  983. // We did not reach the end of the drush_main function,
  984. // this generally means somewhere in the code a call to exit(),
  985. // was made. We catch this, so that we can trigger an error in
  986. // those cases.
  987. drush_set_error("DRUSH_NOT_COMPLETED", dt("Drush command terminated abnormally due to an unrecoverable error.!message", array('!message' => $php_error_message)));
  988. // Attempt to give the user some advice about how to fix the problem
  989. _drush_postmortem();
  990. }
  991. $phase = drush_get_context('DRUSH_BOOTSTRAP_PHASE');
  992. if (drush_get_context('DRUSH_BOOTSTRAPPING')) {
  993. switch ($phase) {
  994. case DRUSH_BOOTSTRAP_DRUPAL_FULL :
  995. ob_end_clean();
  996. _drush_log_drupal_messages();
  997. drush_set_error('DRUSH_DRUPAL_BOOTSTRAP_ERROR');
  998. break;
  999. }
  1000. }
  1001. if (drush_get_context('DRUSH_BACKEND', FALSE)) {
  1002. drush_backend_output();
  1003. }
  1004. elseif (drush_get_context('DRUSH_QUIET', FALSE)) {
  1005. ob_end_clean();
  1006. // If we are in pipe mode, emit the compact representation of the command, if available.
  1007. if (drush_get_context('DRUSH_PIPE')) {
  1008. drush_pipe_output();
  1009. }
  1010. }
  1011. /**
  1012. * For now, drush skips end of page processing on D7. Doing so could write
  1013. * cache entries to module_implements and lookup_cache that don't match web requests.
  1014. */
  1015. // if (drush_drupal_major_version() >= 7 && function_exists('drupal_page_footer')) {
  1016. // drupal_page_footer();
  1017. // }
  1018. // this way drush_return_status will always be the last shutdown function (unless other shutdown functions register shutdown functions...)
  1019. // and won't prevent other registered shutdown functions (IE from numerous cron methods) from running by calling exit() before they get a chance.
  1020. register_shutdown_function('drush_return_status');
  1021. }
  1022. function drush_return_status() {
  1023. exit((drush_get_error()) ? DRUSH_FRAMEWORK_ERROR : DRUSH_SUCCESS);
  1024. }
  1025. /**
  1026. * Used by a Drush extension to request that its Composer autoload
  1027. * files be loaded by Drush, if they have not already been.
  1028. *
  1029. * Usage:
  1030. *
  1031. * function mycommandfile_drush_init() {
  1032. * drush_autoload(__FILE__)
  1033. * }
  1034. *
  1035. */
  1036. function drush_autoload($commandfile) {
  1037. $dir = dirname($commandfile);
  1038. $candidates = array("vendor/autoload.php", "../../../vendor/autoload.php");
  1039. foreach ($candidates as $candidate) {
  1040. $autoload = $dir . '/' . $candidate;
  1041. if (file_exists($autoload)) {
  1042. include $autoload;
  1043. }
  1044. }
  1045. }