sitealias.inc

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

The site alias API.

Run commands on remote server(s).

See also

example.aliases.drushrc.php

http://drupal.org/node/670460

Functions

Namesort descending Description
drush_convert_db_from_db_url Convert from an old-style database URL to an array of database settings
drush_get_special_keys Helper function to obtain the keys' names that need special handling in certain cases.
drush_sitealias_add_db_settings If the alias record does not contain a 'databases' or 'db-url' entry, then use backend invoke to look up the settings value from the remote or local site. The 'databases' form is preferred; 'db_url' will be…
drush_sitealias_add_db_url If the alias record does not contain a 'databases' or 'db-url' entry, then use backend invoke to look up the settings value from the remote or local site. The 'db_url' form is preferred; nothing is done if…
drush_sitealias_add_to_alias_path Add a path to the array of paths where alias files are searched for.
drush_sitealias_alias_path Return the array of paths where alias files are searched for.
drush_sitealias_alias_record_to_spec Convert from an alias record to a site specification
drush_sitealias_bootstrapped_site_name Get the name of the current bootstrapped site
drush_sitealias_build_record_from_settings_file
drush_sitealias_cache_alias_by_path Cache the specified alias in the alias path cache. The alias path cache creates a lookup from the site folder (/path/to/drupal/sites/default) to the provided alias record.
drush_sitealias_cache_db_settings
drush_sitealias_check_arg Check to see if the first command-line arg or the -l option is a site alias; if it is, copy its record values to the 'alias' context.
drush_sitealias_check_lists_alignment Check to see if the uri is the same in the source and target lists for all items in the array. This is a strong requirement in D6; in D7, it is still highly convenient for the uri to be the same, because the site folder name == the uri, and if the…
drush_sitealias_check_site_env
drush_sitealias_convert_db_from_db_url Convert from an old-style database URL to an array of database settings
drush_sitealias_create_self_alias Check to see if a '@self' record was created during bootstrap. If not, make one now.
drush_sitealias_create_sites_alias
drush_sitealias_evaluate_path Evaluate a path from its shorthand form to a literal path usable by rsync.
drush_sitealias_evaluate_paths_in_options Given a properly-escaped options string, replace any occurance of %files and so on embedded inside it with its corresponding path.
drush_sitealias_get_db_spec Return the $db_spec record for the database associated with the provided alias record. which will be used to first add the database information to the alias records, invoking sql-conf to look them up if necessary.
drush_sitealias_get_envar_filename Returns the filename for the file that stores the DRUPAL_SITE variable.
drush_sitealias_get_path_option First return an option set via drush_sitealias_overlay_options, if any, then fall back on "%" . $option from the path aliases.
drush_sitealias_get_record Get a site alias record given an alias name or site specification.
drush_sitealias_is_bootstrapped_site Check to see if we have already bootstrapped to a site.
drush_sitealias_is_remote_site Determines whether a given site alias is for a remote site.
drush_sitealias_load_all Load every alias file that can be found anywhere in the alias search path.
drush_sitealias_local_site_path Return the full path to the site directory of the given alias record.
drush_sitealias_lookup_alias_by_path Look for a defined alias that points to the specified site directory. The cache is tested first; if nothing is cached, then an exhaustive search is done for the specified site. If the exhaustive search returns a match, then it is cached.
drush_sitealias_overlay_options Given an alias record, overwrite its values with options from the command line and other drush contexts as specified by the provided prefix. For example, if the prefix is 'source-', then any option 'source-foo' will set the value…
drush_sitealias_quick_lookup_cached_alias_by_path Look for a cached alias that points to the specified site directory. Nothing is returned if there is no matching cached alias.
drush_sitealias_resolve_path_references If there are any path aliases (items beginning with "%") in the test string, then resolve them as path aliases and add them to the provided alias record.
drush_sitealias_resolve_sitelist Given an alias record that is a site list (contains a 'site-list' entry), resolve all of the members of the site list and return them is an array of alias records.
drush_sitealias_resolve_sitespecs Given an array of site specifications, resolve each one in turn and return an array of alias records. If you only want a single record, it is preferable to simply call drush_sitealias_get_record directly.
drush_sitealias_set_alias_context Given a site alias record, copy selected fields from it into the drush 'alias' context. The 'alias' context has lower precedence than the 'cli' context, so values set by an alias record can be overridden by…
drush_sitealias_simplify_names Given a list of alias records, shorten the name used if possible
drush_sitealias_site_dir_from_filename Pull the site directory from the path to settings.php
drush_sitealias_site_get Read the tmp file where the persistent site setting is stored.
drush_sitealias_site_selection_keys Option keys used for site selection.
drush_sitealias_uri_to_site_dir Convert from a URI to a site directory.
drush_sitealias_valid_alias_format Returns TRUE if $alias is a valid format for an alias name.
drush_sitelist_align_lists If the source and target lists contain alias records to the same sets of sites, but in different orders, this routine will re-order the lists so that they are in alignment.
sitealias_find_local_drupal_root
sitealias_get_databases_from_record Return the databases record from the alias record
_drush_find_local_sites_at_root Return a list of all of the local sites at the specified drupal root.
_drush_find_local_sites_in_sites_folder Return a list of all of the local sites at the specified 'sites' folder.
_drush_sitealias_add_inherited_values Check to see if there is a 'parent' item in the alias; if there is, then load the parent alias record and overlay the entries in the current alias record on top of the items from the parent record.
_drush_sitealias_add_inherited_values_to_record
_drush_sitealias_add_static_defaults Add "static" default values to the given alias record. The difference between a static default and a transient default is that static defaults -always- exist in the alias record, and they are cached, whereas transient defaults are only…
_drush_sitealias_add_transient_defaults Add "transient" default values to the given alias record. The difference between a static default and a transient default is that static defaults -always- exist in the alias record, whereas transient defaults are only added if the given…
_drush_sitealias_cache_alias Add an empty record for the specified alias name
_drush_sitealias_derive_record
_drush_sitealias_find_alias_files Function to find all alias files that might contain aliases that match the requested alias name.
_drush_sitealias_find_and_load_alias Traverses the alias search path and finds the specified alias record.
_drush_sitealias_find_and_load_alias_from_file
_drush_sitealias_find_and_load_all_aliases Worker function called by _drush_sitealias_load_alias and drush_sitealias_load_all. Traverses the alias search path and finds the specified alias record.
_drush_sitealias_find_local_alias_name Find the name of a local alias record that has the specified root and uri.
_drush_sitealias_find_local_sites Search for drupal installations in the search path.
_drush_sitealias_find_record_for_local_site If '$alias' is the name of a folder in the sites folder of the given drupal root, then build an alias record for it
_drush_sitealias_get_record This is a continuation of drush_sitealias_get_record, above. It is not intended to be called directly.
_drush_sitealias_initialize_alias_record Initialize an alias record; called as soon as the alias record is loaded from its alias file, before it is stored in the cache.
_drush_sitealias_load_alias Check and see if an alias definition for $alias is available. If it is, load it into the list of aliases cached in the 'site-aliases' context.
_drush_sitealias_preflight_path Call prior to drush_sitealias_evaluate_path to insure that any site-specific aliases associated with any local site in $path are defined.
_drush_sitealias_set_context_by_name Looks up the specified alias record and calls through to drush_sitealias_set_alias_context, below.
_drush_sitealias_set_record_element Utility function used by drush_get_alias; keys that start with '%' or '!' are path aliases, the rest are entries in the alias record.
_drush_sitelist_check_site_records
_drush_sitelist_find_in_list
_sitealias_array_merge Merges two site aliases.

File

includes/sitealias.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * The site alias API.
  5. *
  6. * Run commands on remote server(s).
  7. * @see example.aliases.drushrc.php
  8. * @see http://drupal.org/node/670460
  9. */
  10. /**
  11. * Check to see if the first command-line arg or the
  12. * -l option is a site alias; if it is, copy its record
  13. * values to the 'alias' context.
  14. *
  15. * @return boolean
  16. * TRUE if a site alias was found and processed.
  17. */
  18. function drush_sitealias_check_arg() {
  19. $args = drush_get_arguments();
  20. // Test to see if the first arg is a site specification
  21. if (!empty($args) && _drush_sitealias_set_context_by_name($args[0])) {
  22. drush_set_context('DRUSH_TARGET_SITE_ALIAS', $args[0]);
  23. array_shift($args);
  24. // We only need to expand the site specification
  25. // once, then we are done.
  26. drush_set_arguments($args);
  27. return TRUE;
  28. }
  29. // Return false to indicate that no site alias was specified.
  30. return FALSE;
  31. }
  32. function drush_sitealias_check_site_env() {
  33. $site = drush_get_context('DRUSH_TARGET_SITE_ALIAS');
  34. if (empty($site)) {
  35. $site_env = drush_sitealias_site_get();
  36. if (!empty($site_env) && (_drush_sitealias_set_context_by_name($site_env))) {
  37. drush_set_context('DRUSH_TARGET_SITE_ALIAS', $site_env);
  38. return TRUE;
  39. }
  40. }
  41. // Return false to indicate that no site alias was specified.
  42. return FALSE;
  43. }
  44. /**
  45. * Check to see if a '@self' record was created during bootstrap.
  46. * If not, make one now.
  47. */
  48. function drush_sitealias_create_self_alias() {
  49. $self_record = drush_sitealias_get_record('@self');
  50. if (!array_key_exists('root', $self_record) && !array_key_exists('remote-host', $self_record)) {
  51. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  52. $uri = drush_get_context('DRUSH_SELECTED_URI');
  53. if (!empty($drupal_root) && !empty($uri)) {
  54. // Create an alias '@self'
  55. _drush_sitealias_cache_alias('@self', array('root' => $drupal_root, 'uri' => $uri));
  56. }
  57. }
  58. }
  59. /**
  60. * Given a list of alias records, shorten the name used if possible
  61. */
  62. function drush_sitealias_simplify_names($site_list) {
  63. $result = array();
  64. foreach ($site_list as $original_name => $alias_record) {
  65. $adjusted_name = $alias_record['#name'];
  66. $hashpos = strpos($original_name, '#');
  67. if ($hashpos !== FALSE) {
  68. $adjusted_name = substr($original_name, $hashpos);
  69. if (array_key_exists('remote-host', $alias_record)) {
  70. $adjusted_name = $alias_record['remote-host'] . $adjusted_name;
  71. }
  72. }
  73. $result[$adjusted_name] = $alias_record;
  74. }
  75. return $result;
  76. }
  77. /**
  78. * Given an array of site specifications, resolve each one in turn and
  79. * return an array of alias records. If you only want a single record,
  80. * it is preferable to simply call drush_sitealias_get_record directly.
  81. *
  82. * @param $site_specifications
  83. * One of:
  84. * A comma-separated list of site specifications: '@site1,@site2'
  85. * An array of site specifications: array('@site1','@site2')
  86. * An array of alias records:
  87. * array(
  88. * 'site1' => array('root' => ...),
  89. * 'site2' => array('root' => ...)
  90. * )
  91. * An array of site specifications.
  92. * @see drush_sitealias_get_record() for the format of site specifications.
  93. * @return
  94. * An array of alias records
  95. */
  96. function drush_sitealias_resolve_sitespecs($site_specifications, $alias_path_context = NULL) {
  97. $result_list = array();
  98. $not_found = array();
  99. if (!is_array($site_specifications)) {
  100. $site_specifications = explode(',', $site_specifications);
  101. }
  102. if (!empty($site_specifications)) {
  103. foreach ($site_specifications as $site) {
  104. if (is_array($site)) {
  105. $result_list[] = $site;
  106. }
  107. else {
  108. $alias_record = drush_sitealias_get_record($site, $alias_path_context);
  109. if (!$alias_record) {
  110. $not_found[] = $site;
  111. }
  112. else {
  113. $result_list = array_merge($result_list, drush_sitealias_resolve_sitelist($alias_record));
  114. }
  115. }
  116. }
  117. }
  118. return array($result_list, $not_found);
  119. }
  120. /**
  121. * Returns TRUE if $alias is a valid format for an alias name.
  122. *
  123. * Mirrors the allowed formats shown below for drush_sitealias_get_record.
  124. */
  125. function drush_sitealias_valid_alias_format($alias) {
  126. return ( (strpos($alias, ',') !== false) ||
  127. ((strpos($alias, '@') === FALSE ? 0 : 1) + (strpos($alias, '/') === FALSE ? 0 : 1) + (strpos($alias, '#') === FALSE ? 0 : 1) >= 2) ||
  128. ($alias{0} == '#') ||
  129. ($alias{0} == '@')
  130. );
  131. return $alias{0} == '@';
  132. }
  133. /**
  134. * Get a site alias record given an alias name or site specification.
  135. *
  136. * If it is the name of a site alias, return the alias record from
  137. * the site aliases array.
  138. *
  139. * If it is the name of a folder in the 'sites' folder, construct
  140. * an alias record from values stored in settings.php.
  141. *
  142. * If it is a site specification, construct an alias record from the
  143. * values in the specification.
  144. *
  145. * Site specifications come in several forms:
  146. * - /path/to/drupal#sitename
  147. * - user@server/path/to/drupal#sitename
  148. * - user@server/path/to/drupal (sitename == server)
  149. * - user@server#sitename (only if $option['r'] set in some drushrc file on server)
  150. * - #sitename (only if $option['r'] already set, and 'sitename' is a folder in $option['r']/sites)
  151. * - sitename (only if $option['r'] already set, and 'sitename' is a folder in $option['r']/sites)
  152. *
  153. * Note that in the case of the first four forms, it is also possible
  154. * to add additional site variable to the specification using uri query
  155. * syntax. For example:
  156. *
  157. * user@server/path/to/drupal?db-url=...#sitename
  158. *
  159. * @param alias
  160. * An alias name or site specification
  161. * @return array
  162. * An alias record, or empty if none found.
  163. */
  164. function drush_sitealias_get_record($alias, $alias_context = NULL) {
  165. // Check to see if the alias contains commas. If it does, then
  166. // we will go ahead and make a site list record
  167. $alias_record = array();
  168. if (strpos($alias, ',') !== false) {
  169. // TODO: If the site list contains any site lists, or site
  170. // search paths, then we should expand those and merge them
  171. // into this list longhand.
  172. $alias_record['site-list'] = explode(',', $alias);
  173. }
  174. else {
  175. $alias_record = _drush_sitealias_get_record($alias, $alias_context);
  176. }
  177. if (!empty($alias_record)) {
  178. if (array_key_exists('#name', $alias_record)) {
  179. if ($alias_record['#name'] == 'self') {
  180. $path = drush_sitealias_local_site_path($alias_record);
  181. if ($path) {
  182. $cached_alias_record = drush_sitealias_lookup_alias_by_path($path);
  183. $alias_record = array_merge($alias_record, $cached_alias_record);
  184. }
  185. }
  186. }
  187. else {
  188. $alias_record['#name'] = drush_sitealias_uri_to_site_dir($alias);
  189. }
  190. }
  191. return $alias_record;
  192. }
  193. /**
  194. * This is a continuation of drush_sitealias_get_record, above. It is
  195. * not intended to be called directly.
  196. */
  197. function _drush_sitealias_get_record($alias, $alias_context = NULL) {
  198. $alias_record = array();
  199. // Before we do anything else, load $alias if it needs to be loaded
  200. _drush_sitealias_load_alias($alias, $alias_context);
  201. // Check to see if the provided parameter is in fact a defined alias.
  202. $all_site_aliases =& drush_get_context('site-aliases');
  203. if (array_key_exists($alias, $all_site_aliases)) {
  204. $alias_record = $all_site_aliases[$alias];
  205. }
  206. // If the parameter is not an alias, then it is some form of
  207. // site specification (or it is nothing at all)
  208. else {
  209. if (isset($alias)) {
  210. // Cases 1.) - 4.):
  211. // We will check for a site specification if the alias has at least
  212. // two characters from the set '@', '/', '#'.
  213. if ((strpos($alias, '@') === FALSE ? 0 : 1) + ((strpos($alias, '/') === FALSE && strpos($alias, '\\') === FALSE) ? 0 : 1) + (strpos($alias, '#') === FALSE ? 0 : 1) >= 2) {
  214. if ((substr($alias,0,7) != 'http://') && !drush_is_absolute_path($alias)) {
  215. // Add on a scheme so that "user:pass@server" will always parse correctly
  216. $parsed = parse_url('http://' . $alias);
  217. }
  218. else if (drush_is_windows() && drush_is_absolute_path($alias)) {
  219. // On windows if alias begins with a filesystem path we must add file:// scheme to make it parse correcly
  220. $parsed = parse_url('file:///' . $alias);
  221. }
  222. else {
  223. $parsed = parse_url($alias);
  224. }
  225. // Copy various parts of the parsed URL into the appropriate records of the alias record
  226. foreach (array('user' => 'remote-user', 'pass' => 'remote-pass', 'host' => 'remote-host', 'fragment' => 'uri', 'path' => 'root') as $url_key => $option_key) {
  227. if (array_key_exists($url_key, $parsed)) {
  228. _drush_sitealias_set_record_element($alias_record, $option_key, $parsed[$url_key]);
  229. }
  230. }
  231. // If the site specification has a query, also set the query items
  232. // in the alias record. This allows passing db_url as part of the
  233. // site specification, for example.
  234. if (array_key_exists('query', $parsed)) {
  235. foreach (explode('&', $parsed['query']) as $query_arg) {
  236. $query_components = explode('=', $query_arg);
  237. _drush_sitealias_set_record_element($alias_record, urldecode($query_components[0]), urldecode($query_components[1]));
  238. }
  239. }
  240. // Case 3.): If the URL contains a 'host' portion but no fragment, then set the uri to the host
  241. // Note: We presume that 'server' is the best default for case 3; without this code, the default would
  242. // be whatever is set in $options['l'] on the target machine's drushrc.php settings file.
  243. if (array_key_exists('host', $parsed) && !array_key_exists('fragment', $parsed)) {
  244. $alias_record['uri'] = $parsed['host'];
  245. }
  246. // Special checking: relative aliases embedded in a path
  247. $relative_alias_pos = strpos($alias_record['root'], '/@');
  248. if ($relative_alias_pos !== FALSE) {
  249. // Special checking: /path/@sites
  250. $base = substr($alias_record['root'], 0, $relative_alias_pos);
  251. $relative_alias = substr($alias_record['root'], $relative_alias_pos + 1);
  252. if (drush_valid_drupal_root($base) || ($relative_alias == '@sites')) {
  253. drush_sitealias_create_sites_alias($base);
  254. $alias_record = drush_sitealias_get_record($relative_alias);
  255. }
  256. else {
  257. $alias_record = array();
  258. }
  259. }
  260. }
  261. else {
  262. // Case 5.) and 6.):
  263. // If the alias is the name of a folder in the 'sites' directory,
  264. // then use it as a local site specification.
  265. $alias_record = _drush_sitealias_find_record_for_local_site($alias);
  266. }
  267. }
  268. }
  269. if (!empty($alias_record)) {
  270. if (!isset($alias_record['remote']) && !isset($alias_record['#loaded-config'])) {
  271. if (array_key_exists('root', $alias_record)) {
  272. drush_sitealias_add_to_alias_path($alias_record['root'] . '/drush');
  273. drush_sitealias_add_to_alias_path($alias_record['root'] . '/sites/all/drush');
  274. }
  275. $alias_site_dir = drush_sitealias_local_site_path($alias_record);
  276. if (isset($alias_site_dir)) {
  277. // Add the sites folder of this site to the alias search path list
  278. drush_sitealias_add_to_alias_path($alias_site_dir);
  279. }
  280. if (isset($alias_record['config']) && file_exists($alias_record['config'])) {
  281. drush_load_config_file('site', $alias_record['config']);
  282. $alias_record['#loaded-config'] = TRUE;
  283. }
  284. unset($alias_record['config']);
  285. }
  286. // Add the static defaults
  287. _drush_sitealias_add_static_defaults($alias_record);
  288. // Cache the result with all of its calculated values
  289. $all_site_aliases[$alias] = $alias_record;
  290. }
  291. return $alias_record;
  292. }
  293. /**
  294. * Add a path to the array of paths where alias files are searched for.
  295. *
  296. * @param $add_path
  297. * A path to add to the search path (or NULL to not add any).
  298. * Once added, the new path will remain available until drush
  299. * exits.
  300. * @return
  301. * An array of paths containing all values added so far
  302. */
  303. function drush_sitealias_add_to_alias_path($add_path) {
  304. static $site_paths = array();
  305. if ($add_path != NULL) {
  306. if (!is_array($add_path)) {
  307. $add_path = explode(PATH_SEPARATOR, $add_path);
  308. }
  309. // Normalize path to make sure we don't add the same path twice on
  310. // windows due to different spelling. e.g. c:\tmp and c:/tmp
  311. foreach($add_path as &$path) {
  312. $path = drush_normalize_path($path);
  313. }
  314. $site_paths = array_unique(array_merge($site_paths, $add_path));
  315. }
  316. return $site_paths;
  317. }
  318. /**
  319. * Return the array of paths where alias files are searched for.
  320. *
  321. * @param $alias_path_context
  322. * If the alias being looked up is part of a relative alias,
  323. * the alias path context specifies the context of the primary
  324. * alias the new alias is rooted from. Alias files stored in
  325. * the sites folder of this context, or inside the context itself
  326. * takes priority over any other search path that might define
  327. * a similarly-named alias. In this way, multiple sites can define
  328. * a '@peer' alias.
  329. * @return
  330. * An array of paths
  331. */
  332. function drush_sitealias_alias_path($alias_path_context = NULL) {
  333. $context_path = array();
  334. if (isset($alias_path_context)) {
  335. $context_path = array(drush_sitealias_local_site_path($alias_path_context));
  336. }
  337. // We get the current list of site paths by adding NULL
  338. // (nothing) to the path list, which is a no-op
  339. $site_paths = drush_sitealias_add_to_alias_path(NULL);
  340. // If the user defined the root of a drupal site, then also
  341. // look for alias files in /drush and /sites/all/drush.
  342. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  343. if (isset($drupal_root)) {
  344. $site_paths[] = $drupal_root . '/drush';
  345. $site_paths[] = $drupal_root . '/sites/all/drush';
  346. }
  347. $alias_path = (array) drush_get_context('ALIAS_PATH', array());
  348. return array_unique(array_merge($context_path, $alias_path, $site_paths));
  349. }
  350. /**
  351. * Return the full path to the site directory of the
  352. * given alias record.
  353. *
  354. * @param $alias_record
  355. * The alias record
  356. * @return
  357. * The path to the site directory of the associated
  358. * alias record, or NULL if the record is not a local site.
  359. */
  360. function drush_sitealias_local_site_path($alias_record) {
  361. $result = NULL;
  362. if (isset($alias_record['root']) && !isset($alias_record['remote-host'])) {
  363. if (isset($alias_record['uri'])) {
  364. $result = ($alias_record['root'] . '/sites/' . drush_sitealias_uri_to_site_dir($alias_record['uri']));
  365. $result = realpath($result);
  366. }
  367. if (!$result) {
  368. $result = realpath($alias_record['root'] . '/sites/default');
  369. }
  370. }
  371. return $result;
  372. }
  373. /**
  374. * Check and see if an alias definition for $alias is available.
  375. * If it is, load it into the list of aliases cached in the
  376. * 'site-aliases' context.
  377. *
  378. * @param $alias
  379. * The name of the alias to load in ordinary form ('@name')
  380. * @param $alias_path_context
  381. * When looking up a relative alias, the alias path context is
  382. * the primary alias that we will start our search from.
  383. */
  384. function _drush_sitealias_load_alias($alias, $alias_path_context = NULL) {
  385. $all_site_aliases = drush_get_context('site-aliases');
  386. $result = array();
  387. // Check to see if this is a relative alias ('@site/@peer')
  388. $relative_alias_pos = strpos($alias, '/@');
  389. if ($relative_alias_pos !== false) {
  390. $primary_alias = substr($alias,0,$relative_alias_pos);
  391. $relative_alias = substr($alias,$relative_alias_pos + 1);
  392. $primary_record = drush_sitealias_get_record($primary_alias);
  393. _drush_sitealias_find_and_load_alias(substr($relative_alias,1), $primary_record);
  394. $result = drush_sitealias_get_record($relative_alias);
  395. if (!empty($result)) {
  396. if (array_key_exists('inherited', $result)) {
  397. $result = array_merge($primary_record, $result);
  398. }
  399. $result['#name'] = $relative_alias;
  400. _drush_sitealias_add_inherited_values_to_record($result);
  401. _drush_sitealias_cache_alias($alias, $result);
  402. }
  403. }
  404. else {
  405. // Only aliases--those named entities that begin with '@'--can be loaded this way.
  406. // We also skip any alias that has already been loaded.
  407. if ((substr($alias,0,1) == '@') && !array_key_exists($alias,$all_site_aliases)) {
  408. $aliasname = substr($alias,1);
  409. $result = _drush_sitealias_find_and_load_alias($aliasname, $alias_path_context);
  410. if (!empty($result)) {
  411. $alias_options = array('site-aliases' => array($aliasname => $result));
  412. _drush_sitealias_add_inherited_values($alias_options['site-aliases']);
  413. drush_set_config_special_contexts($alias_options);
  414. if (array_key_exists('#file', $result)) {
  415. drush_log(dt('Loaded alias !alias from file !file', array('!alias' => $alias, '!file' => $result['#file'])));
  416. }
  417. }
  418. }
  419. }
  420. return $result;
  421. }
  422. /**
  423. * Load every alias file that can be found anywhere in the
  424. * alias search path.
  425. */
  426. function drush_sitealias_load_all($resolve_parent = TRUE) {
  427. $result = _drush_sitealias_find_and_load_all_aliases();
  428. if (!empty($result) && ($resolve_parent == TRUE)) {
  429. // If any aliases were returned, then check for
  430. // inheritance and then store the aliases into the
  431. // alias cache
  432. _drush_sitealias_add_inherited_values($result);
  433. $alias_options = array('site-aliases' => $result);
  434. drush_set_config_special_contexts($alias_options);
  435. }
  436. }
  437. /**
  438. * Worker function called by _drush_sitealias_load_alias and
  439. * drush_sitealias_load_all. Traverses the alias search path
  440. * and finds the specified alias record.
  441. *
  442. * @return
  443. * An array of $kay => $value pair of alias names and alias records
  444. * loaded.
  445. */
  446. function _drush_sitealias_find_and_load_all_aliases() {
  447. $result = array();
  448. $drush_alias_files = _drush_sitealias_find_alias_files();
  449. drush_set_context('drush-alias-files', $drush_alias_files);
  450. // For every file that matches, check inside it for
  451. // an alias with a matching name.
  452. foreach ($drush_alias_files as $filename) {
  453. if (file_exists($filename)) {
  454. $aliases = $options = array();
  455. // silently ignore files we can't include
  456. if ((@include $filename) === FALSE) {
  457. drush_log(dt('Cannot open alias file "!alias", ignoring.', array('!alias' => realpath($filename))), 'bootstrap');
  458. continue;
  459. }
  460. unset($options['site-aliases']); // maybe unnecessary
  461. // If $aliases are not set, but $options are, then define one alias named
  462. // after the first word of the file, before '.alias.drushrc.php.
  463. if (empty($aliases) && !empty($options)) {
  464. $this_alias_name = substr(basename($filename),0,strpos(basename($filename),'.'));
  465. $aliases[$this_alias_name] = $options;
  466. $options = array();
  467. }
  468. // If this is a group alias file, then make an
  469. // implicit alias from the group name that contains
  470. // a site-list of all of the aliases in the file
  471. $group_name = '';
  472. if (substr($filename, -20) == ".aliases.drushrc.php") {
  473. $group_name = basename($filename,".aliases.drushrc.php");
  474. if (!empty($aliases) && !array_key_exists($group_name, $aliases)) {
  475. $alias_names = array();
  476. foreach (array_keys($aliases) as $one_alias) {
  477. $alias_names[] = "@$group_name.$one_alias";
  478. $aliases["$group_name.$one_alias"] = $aliases[$one_alias];
  479. unset($aliases[$one_alias]);
  480. }
  481. $aliases[$group_name] = array('site-list' => implode(',', $alias_names));
  482. }
  483. }
  484. if (!empty($aliases)) {
  485. if (!empty($options)) {
  486. foreach ($aliases as $name => $value) {
  487. $aliases[$name] = array_merge($options, $value);
  488. }
  489. $options = array();
  490. }
  491. foreach ($aliases as $name => $value) {
  492. _drush_sitealias_initialize_alias_record($aliases[$name]);
  493. $aliases[$name]['#name'] = $name;
  494. $aliases[$name]['#file'] = $filename;
  495. }
  496. $result = _sitealias_array_merge($result, $aliases);
  497. // If we found at least one alias from this file
  498. // then record it in the drush-alias-files context.
  499. $drush_alias_files = drush_get_context('drush-alias-files');
  500. if (!in_array($filename, $drush_alias_files)) {
  501. $drush_alias_files[] = $filename;
  502. }
  503. drush_set_context('drush-alias-files', $drush_alias_files);
  504. }
  505. }
  506. }
  507. return $result;
  508. }
  509. /**
  510. * Function to find all alias files that might contain aliases
  511. * that match the requested alias name.
  512. */
  513. function _drush_sitealias_find_alias_files($aliasname = NULL, $alias_path_context = NULL) {
  514. $alias_files_to_consider = array();
  515. // The alias path is a list of folders to search for alias settings files
  516. $alias_path = drush_sitealias_alias_path($alias_path_context);
  517. // $alias_files contains a list of filename patterns
  518. // to search for. We will find any matching file in
  519. // any folder in the alias path. The directory scan
  520. // is not deep, though; only files immediately in the
  521. // search path are considered.
  522. $alias_files = array('/.*aliases\.drush(' . DRUSH_MAJOR_VERSION . '|)rc\.php$/');
  523. if ($aliasname == NULL) {
  524. $alias_files[] = '/.*\.alias\.drush(' . DRUSH_MAJOR_VERSION . '|)rc\.php$/';
  525. }
  526. else {
  527. $alias_files[] = '/' . preg_quote($aliasname, '/') . '\.alias\.drush(' . DRUSH_MAJOR_VERSION . '|)rc\.php$/';
  528. }
  529. // Search each path in turn
  530. foreach ($alias_path as $path) {
  531. // Find all of the matching files in this location
  532. foreach ($alias_files as $file_pattern_to_search_for) {
  533. $alias_files_to_consider = array_merge($alias_files_to_consider, array_keys(drush_scan_directory($path, $file_pattern_to_search_for, drush_filename_blacklist(), 0, FALSE)));
  534. }
  535. }
  536. return $alias_files_to_consider;
  537. }
  538. /**
  539. * Traverses the alias search path and finds the specified alias record.
  540. *
  541. * @param $aliasname
  542. * The name of the alias without the leading '@' (i.e. '#name')
  543. * or NULL to load every alias found in every alias file.
  544. * @param $alias_path_context
  545. * When looking up a relative alias, the alias path context is
  546. * the primary alias that we will start our search from.
  547. * @return
  548. * An empty array if nothing was loaded. If $aliasname is
  549. * not null, then the array returned is the alias record for
  550. * $aliasname. If $aliasname is NULL, then the array returned
  551. * is a $kay => $value pair of alias names and alias records
  552. * loaded.
  553. */
  554. function _drush_sitealias_find_and_load_alias($aliasname, $alias_path_context = NULL) {
  555. // Special checking for '@sites' alias
  556. if ($aliasname == 'sites') {
  557. $drupal_root = NULL;
  558. if ($alias_path_context != null) {
  559. if (array_key_exists('root', $alias_path_context) && !array_key_exists('remote-host', $alias_path_context)) {
  560. $drupal_root = $alias_path_context['root'];
  561. }
  562. }
  563. else {
  564. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  565. }
  566. if (isset($drupal_root) && !is_array($drupal_root)) {
  567. drush_sitealias_create_sites_alias($drupal_root);
  568. }
  569. }
  570. $alias_files_to_consider = _drush_sitealias_find_alias_files($aliasname, $alias_path_context);
  571. return _drush_sitealias_find_and_load_alias_from_file($aliasname, $alias_files_to_consider);
  572. }
  573. function _drush_sitealias_find_and_load_alias_from_file($aliasname, $alias_files_to_consider) {
  574. $result = array();
  575. $result_names = array();
  576. // For every file that matches, check inside it for
  577. // an alias with a matching name.
  578. $recorded_files = array();
  579. foreach ($alias_files_to_consider as $filename) {
  580. if (file_exists($filename)) {
  581. $aliases = $options = array();
  582. // silently ignore files we can't include
  583. if ((@include $filename) === FALSE) {
  584. drush_log(dt('Cannot open alias file "!alias", ignoring.', array('!alias' => realpath($filename))), 'bootstrap');
  585. continue;
  586. }
  587. unset($options['site-aliases']); // maybe unnecessary
  588. // If $aliases are not set, but $options are, then define one alias named
  589. // after the first word of the file, before '.alias.drushrc.php.
  590. if (empty($aliases) && !empty($options)) {
  591. $this_alias_name = substr(basename($filename),0,strpos(basename($filename),'.'));
  592. $aliases[$this_alias_name] = $options;
  593. $options = array();
  594. }
  595. // If this is a group alias file, then make an
  596. // implicit alias from the group name that contains
  597. // a site-list of all of the aliases in the file
  598. $group_prefix = '';
  599. if (substr($filename, -20) == ".aliases.drushrc.php") {
  600. $group_name = basename($filename,".aliases.drushrc.php");
  601. $group_prefix = $group_name . '.';
  602. if (!empty($aliases) && !array_key_exists($group_name, $aliases)) {
  603. $alias_names = array();
  604. foreach (array_keys($aliases) as $one_alias) {
  605. $alias_names[] = "@$group_name.$one_alias";
  606. $aliases[$one_alias]['#name'] = "$group_name.$one_alias";
  607. $aliases[$one_alias]['#group'] = $group_name;
  608. $aliases["$group_name.$one_alias"] = $aliases[$one_alias];
  609. $aliases[$one_alias]["#hidden"] = TRUE;
  610. }
  611. $aliases[$group_name] = array('site-list' => implode(',', $alias_names), '#group' => $group_name, '#name' => $group_name);
  612. }
  613. }
  614. // Store only the named alias into the alias cache
  615. if ((isset($aliases)) && !empty($aliasname) && array_key_exists($aliasname, $aliases)) {
  616. drush_set_config_special_contexts($options); // maybe unnecessary
  617. $one_result = array_merge($options, $aliases[$aliasname]);
  618. $one_result['#file'] = $filename;
  619. if (!array_key_exists('#name', $one_result)) {
  620. $one_result['#name'] = $aliasname;
  621. }
  622. _drush_sitealias_initialize_alias_record($one_result);
  623. // If the alias name is exactly the same as a previous match, then
  624. // merge the two records together
  625. if (!empty($result) && ($result['#name'] == $one_result['#name'])) {
  626. $result = _sitealias_array_merge($result, $one_result);
  627. }
  628. // Add the name of the found record to the list of results
  629. else {
  630. $result_names[] = "@" . $one_result['#name'];
  631. $result = $one_result;
  632. }
  633. }
  634. }
  635. }
  636. // If there are multiple matches, then return a list of results.
  637. if (count($result_names) > 1) {
  638. $result = array('site-list' => $result_names);
  639. }
  640. return $result;
  641. }
  642. /**
  643. * Merges two site aliases.
  644. *
  645. * array_merge_recursive is too much; we only want to run
  646. * array_merge on the common top-level keys of the array.
  647. *
  648. * @param array $site_alias_a
  649. * A site alias array.
  650. * @param array $site_alias_b
  651. * A site alias array.
  652. * @return
  653. * A site alias array where the keys from $site_alias_a are overwritten by the
  654. * keys from $site_alias_b.
  655. */
  656. function _sitealias_array_merge($site_alias_a, $site_alias_b) {
  657. $result = $site_alias_a;
  658. foreach($site_alias_b as $key => $value) {
  659. if (is_array($value) && array_key_exists($key, $result)) {
  660. $result[$key] = array_merge($result[$key], $value);
  661. }
  662. else {
  663. $result[$key] = $value;
  664. }
  665. }
  666. return $result;
  667. }
  668. /**
  669. * Check to see if there is a 'parent' item in the alias; if there is,
  670. * then load the parent alias record and overlay the entries in the
  671. * current alias record on top of the items from the parent record.
  672. *
  673. * @param $aliases
  674. * An array of alias records that are modified in-place.
  675. */
  676. function _drush_sitealias_add_inherited_values(&$aliases) {
  677. foreach ($aliases as $alias_name => $alias_value) {
  678. if (isset($alias_value['parent'])) {
  679. // Prevent circular references from causing an infinite loop
  680. _drush_sitealias_cache_alias("@$alias_name", array());
  681. _drush_sitealias_add_inherited_values_to_record($alias_value);
  682. $aliases[$alias_name] = $alias_value;
  683. }
  684. }
  685. }
  686. function _drush_sitealias_add_inherited_values_to_record(&$alias_value) {
  687. if (isset($alias_value['parent'])) {
  688. // Fetch and merge in each parent
  689. foreach (explode(',', $alias_value['parent']) as $parent) {
  690. $parent_record = drush_sitealias_get_record($parent);
  691. unset($parent_record['#name']);
  692. unset($parent_record['#file']);
  693. unset($parent_record['#hidden']);
  694. $array_based_keys = array_merge(drush_get_special_keys(), array('path-aliases'));
  695. foreach ($array_based_keys as $array_based_key) {
  696. if (isset($alias_value[$array_based_key]) && isset($parent_record[$array_based_key])) {
  697. $alias_value[$array_based_key] = array_merge($parent_record[$array_based_key], $alias_value[$array_based_key]);
  698. }
  699. }
  700. $alias_value = array_merge($parent_record, $alias_value);
  701. }
  702. unset($alias_value['parent']);
  703. }
  704. }
  705. /**
  706. * Add an empty record for the specified alias name
  707. *
  708. * @param $alias_name
  709. * The name of the alias, including the leading "@"
  710. */
  711. function _drush_sitealias_cache_alias($alias_name, $alias_record) {
  712. $cache =& drush_get_context('site-aliases');
  713. // If the alias already exists in the cache, then merge
  714. // the new alias with the existing alias
  715. if (array_key_exists($alias_name, $cache)) {
  716. $alias_record = array_merge($cache[$alias_name], $alias_record);
  717. }
  718. if (!isset($alias_record['#name'])) {
  719. $alias_record['#name'] = trim($alias_name, '@');
  720. }
  721. $cache[$alias_name] = $alias_record;
  722. // If the alias record points at a local site, make sure
  723. // that /drush, /sites/all/drush and the site folder for that site
  724. // are added to the alias path, so that other alias files
  725. // stored in those locations become searchable.
  726. if (!array_key_exists('remote-host', $alias_record) && !empty($alias_record['root'])) {
  727. drush_sitealias_add_to_alias_path($alias_record['root'] . '/drush');
  728. drush_sitealias_add_to_alias_path($alias_record['root'] . '/sites/all/drush');
  729. $site_dir = drush_sitealias_local_site_path($alias_record);
  730. if (isset($site_dir)) {
  731. drush_sitealias_add_to_alias_path($site_dir);
  732. }
  733. }
  734. }
  735. /**
  736. * If the alias record does not contain a 'databases' or 'db-url'
  737. * entry, then use backend invoke to look up the settings value
  738. * from the remote or local site. The 'db_url' form is preferred;
  739. * nothing is done if 'db_url' is not available (e.g. on a D7 site)
  740. *
  741. * @param $alias_record
  742. * The full alias record to populate with database settings
  743. */
  744. function drush_sitealias_add_db_url(&$alias_record) {
  745. if (!isset($alias_record['db-url']) && !isset($alias_record['databases']) && !isset($alias_record['site-list'])) {
  746. // We use sql-conf to fetch our database info. We set 'override-simulated' so that
  747. // we will fetch the database values even in --simulate mode.
  748. $values = drush_invoke_process($alias_record, "sql-conf", array(), array('db-url' => TRUE), array('integrate' => FALSE, 'override-simulated' => TRUE));
  749. if (isset($values['object']['db-url'])) {
  750. $alias_record['db-url'] = $values['object']['db-url'];
  751. }
  752. }
  753. }
  754. /**
  755. * Return the databases record from the alias record
  756. *
  757. * @param $alias_record
  758. * A record returned from drush_sitealias_get_record
  759. * @returns
  760. * A databases record (always in D7 format) or NULL
  761. * if the databases record could not be found.
  762. */
  763. function sitealias_get_databases_from_record(&$alias_record) {
  764. $altered_record = drush_sitealias_add_db_settings($alias_record);
  765. return array_key_exists('databases', $alias_record) ? $alias_record['databases'] : NULL;
  766. }
  767. /**
  768. * Return the $db_spec record for the database associated with
  769. * the provided alias record. @see drush_sitealias_add_db_settings(),
  770. * which will be used to first add the database information to the
  771. * alias records, invoking sql-conf to look them up if necessary.
  772. *
  773. * The options 'database' and 'target' are used to specify which
  774. * specific database should be fetched from the database record;
  775. * they may appear in the alias definition, or may be taken from the
  776. * command line options. The values 'default' and 'default' are
  777. * used if these options are not specified in either location.
  778. *
  779. * Note that in the context of sql-sync, the site alias record will
  780. * be taken from one of the source or target aliases
  781. * (e.g. `drush sql-sync @source @target`), which will be overlayed with
  782. * any options that begin with 'source-' or 'target-', respectively.
  783. * Therefore, the commandline options 'source-database' and 'source-target'
  784. * (or 'target-database' and 'source-target') may also affect the operation
  785. * of this function.
  786. */
  787. function drush_sitealias_get_db_spec(&$alias_record, $default_to_self = FALSE, $prefix = '') {
  788. $db_spec = NULL;
  789. $databases = sitealias_get_databases_from_record($alias_record);
  790. if (isset($databases) && !empty($databases)) {
  791. $database = drush_sitealias_get_option($alias_record, 'database', 'default', $prefix);
  792. $target = drush_sitealias_get_option($alias_record, 'target', 'default', $prefix);
  793. if (array_key_exists($database, $databases) && array_key_exists($target, $databases[$database])) {
  794. $db_spec = $databases[$database][$target];
  795. }
  796. }
  797. elseif ($default_to_self) {
  798. $db_spec = _drush_sql_get_db_spec();
  799. }
  800. if (isset($db_spec)) {
  801. $remote_host = drush_sitealias_get_option($alias_record, 'remote-host', NULL, $prefix);
  802. if (!drush_is_local_host($remote_host)) {
  803. $db_spec['remote-host'] = $remote_host;
  804. $db_spec['port'] = drush_sitealias_get_option($alias_record, 'remote-port', (isset($db_spec['port']) ? $db_spec['port'] : NULL), $prefix);
  805. }
  806. }
  807. return $db_spec;
  808. }
  809. /**
  810. * If the alias record does not contain a 'databases' or 'db-url'
  811. * entry, then use backend invoke to look up the settings value
  812. * from the remote or local site. The 'databases' form is
  813. * preferred; 'db_url' will be converted to 'databases' if necessary.
  814. *
  815. * @param $alias_record
  816. * The full alias record to populate with database settings
  817. */
  818. function drush_sitealias_add_db_settings(&$alias_record) {
  819. $altered_record = FALSE;
  820. if (isset($alias_record['root'])) {
  821. // If the alias record does not have a defined 'databases' entry,
  822. // then we'll need to look one up
  823. if (!isset($alias_record['db-url']) && !isset($alias_record['databases']) && !isset($alias_record['site-list'])) {
  824. $values = drush_invoke_process($alias_record, "sql-conf", array(), array('all' => TRUE), array('integrate' => FALSE, 'override-simulated' => TRUE));
  825. if (is_array($values) && ($values['error_status'] == 0)) {
  826. $altered_record = TRUE;
  827. // If there are any special settings in the '@self' record returned by drush_invoke_process,
  828. // then add those into our altered record as well
  829. if (array_key_exists('self', $values)) {
  830. $alias_record = array_merge($values['self'], $alias_record);
  831. }
  832. drush_sitealias_cache_db_settings($alias_record, $values['object']);
  833. }
  834. }
  835. }
  836. return $altered_record;
  837. }
  838. function drush_sitealias_cache_db_settings(&$alias_record, $databases) {
  839. if (!empty($databases)) {
  840. $alias_record['databases'] = $databases;
  841. }
  842. // If the name is set, then re-cache the record after we fetch the databases
  843. if (array_key_exists('#name', $alias_record)) {
  844. $all_site_aliases =& drush_get_context('site-aliases');
  845. $all_site_aliases['@' . $alias_record['#name']] = $alias_record;
  846. // Check and see if this record is a copy of 'self'
  847. if (($alias_record['#name'] != 'self') && array_key_exists('@self', $all_site_aliases) && array_key_exists('#name', $all_site_aliases['@self']) && ($all_site_aliases['@self']['#name'] == $alias_record['#name'])) {
  848. $all_site_aliases['@self'] = $alias_record;
  849. }
  850. }
  851. }
  852. /**
  853. * Check to see if we have already bootstrapped to a site.
  854. */
  855. function drush_sitealias_is_bootstrapped_site($alias_record) {
  856. if (!isset($alias_record['remote-host']) && array_key_exists('root', $alias_record)) {
  857. $self_record = drush_sitealias_get_record("@self");
  858. if (empty($self_record) || !array_key_exists('root', $self_record)) {
  859. // TODO: If we have not bootstrapped to a site yet, we could
  860. // perhaps bootstrap to $alias_record here.
  861. return FALSE;
  862. }
  863. elseif(($alias_record['root'] == $self_record['root']) && ($alias_record['uri'] == $self_record['uri'])) {
  864. return TRUE;
  865. }
  866. }
  867. return FALSE;
  868. }
  869. /**
  870. * Determines whether a given site alias is for a remote site.
  871. *
  872. * @param string $alias
  873. * An alias name or site specification.
  874. *
  875. * @return bool
  876. * Returns TRUE if the alias refer to a remote site, or FALSE if it does not.
  877. */
  878. function drush_sitealias_is_remote_site($alias) {
  879. if (!is_string($alias) || !strlen($alias)) {
  880. return FALSE;
  881. }
  882. $site_record = drush_sitealias_get_record($alias);
  883. if ($site_record) {
  884. if (!empty($site_record['remote-host'])) {
  885. return TRUE;
  886. }
  887. }
  888. else {
  889. drush_set_error('Unrecognized site alias.');
  890. }
  891. return FALSE;
  892. }
  893. /**
  894. * Get the name of the current bootstrapped site
  895. */
  896. function drush_sitealias_bootstrapped_site_name() {
  897. $site_name = NULL;
  898. $self_record = drush_sitealias_get_record('@self');
  899. if (array_key_exists('#name', $self_record)) {
  900. $site_name = $self_record['#name'];
  901. }
  902. if (!isset($site_name) || ($site_name == '@self')) {
  903. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  904. if (isset($drupal_root)) {
  905. $drupal_uri = drush_get_context('DRUSH_SELECTED_URI', 'default');
  906. $drupal_uri = str_replace('http://', '', $drupal_uri);
  907. // TODO: Maybe use _drush_sitealias_find_local_alias_name?
  908. $site_name = $drupal_root . '#' . $drupal_uri;
  909. }
  910. }
  911. return $site_name;
  912. }
  913. /**
  914. * If there are any path aliases (items beginning with "%") in the test
  915. * string, then resolve them as path aliases and add them to the provided
  916. * alias record.
  917. *
  918. * @param $alias_record
  919. * The full alias record to use in path alias expansion
  920. * @param $test_string
  921. * A slash-separated list of path aliases to resolve
  922. * e.g. "%files/%special".
  923. */
  924. function drush_sitealias_resolve_path_references(&$alias_record, $test_string = '') {
  925. $path_aliases = array_key_exists('path-aliases', $alias_record) ? $alias_record['path-aliases'] : array();
  926. // Convert the test string into an array of items, and
  927. // from this make a comma-separated list of projects
  928. // that we can pass to 'drush status'.
  929. $test_array = explode('/', $test_string);
  930. $project_array = array();
  931. foreach($test_array as $one_item) {
  932. if (!empty($one_item) && ($one_item[0] == '%') && (!array_key_exists($one_item,$path_aliases))) {
  933. $project_array[] = substr($one_item,1);
  934. }
  935. }
  936. $project_list = implode(',', $project_array);
  937. if (!empty($project_array)) {
  938. // Optimization: if we're already bootstrapped to the
  939. // site specified by $alias_record, then we can just
  940. // call _core_site_status_table() rather than use backend invoke.
  941. if (drush_sitealias_is_bootstrapped_site($alias_record) && drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL)) {
  942. $status_values = _core_site_status_table($project_list);
  943. }
  944. else {
  945. $values = drush_invoke_process($alias_record, "core-status", array(), empty($project_list) ? array() : array('project' => $project_list), array('integrate' => FALSE, 'override-simulated' => TRUE));
  946. $status_values = $values['object'];
  947. }
  948. if (isset($status_values['%paths'])) {
  949. foreach ($status_values['%paths'] as $key => $path) {
  950. $alias_record['path-aliases'][$key] = $path;
  951. }
  952. }
  953. // If 'root' is not set in the alias, then fill it in from the status values.
  954. if (!isset($alias_record['root']) && isset($status_values['root'])) {
  955. $alias_record['root'] = $status_values['root'];
  956. }
  957. }
  958. }
  959. /**
  960. * Given an alias record that is a site list (contains a 'site-list' entry),
  961. * resolve all of the members of the site list and return them
  962. * is an array of alias records.
  963. *
  964. * @param $alias_record
  965. * The site list alias record array
  966. * @return
  967. * An array of individual site alias records
  968. */
  969. function drush_sitealias_resolve_sitelist($alias_record) {
  970. $result_list = array();
  971. if (isset($alias_record)) {
  972. if (array_key_exists('site-list', $alias_record)) {
  973. foreach ($alias_record['site-list'] as $sitespec) {
  974. $one_result = drush_sitealias_get_record($sitespec);
  975. $result_list = array_merge($result_list, drush_sitealias_resolve_sitelist($one_result));
  976. }
  977. }
  978. elseif (array_key_exists('#name', $alias_record)) {
  979. $result_list[$alias_record['#name']] = $alias_record;
  980. }
  981. }
  982. return $result_list;
  983. }
  984. /**
  985. * Check to see if the uri is the same in the source and target
  986. * lists for all items in the array. This is a strong requirement
  987. * in D6; in D7, it is still highly convenient for the uri to
  988. * be the same, because the site folder name == the uri, and if
  989. * the uris match, then it is easier to rsync between remote machines.
  990. *
  991. * @param $source
  992. * Array of source alias records
  993. * @param $target
  994. * Array of target alias records to compare against source list
  995. * @return
  996. * TRUE iff the uris of the sources and targets are in alignment
  997. */
  998. function drush_sitealias_check_lists_alignment($source, $target) {
  999. $is_aligned = TRUE;
  1000. $i = 0;
  1001. foreach ($source as $one_source) {
  1002. if ((!isset($target[$i])) || (!_drush_sitelist_check_site_records($one_source, $target[$i]))) {
  1003. $is_aligned = FALSE;
  1004. break;
  1005. }
  1006. ++$i;
  1007. }
  1008. return $is_aligned;
  1009. }
  1010. /**
  1011. * If the source and target lists contain alias records to the same
  1012. * sets of sites, but in different orders, this routine will re-order
  1013. * the lists so that they are in alignment.
  1014. *
  1015. * TODO: Review the advisability of this operation.
  1016. */
  1017. function drush_sitelist_align_lists(&$source, &$target, &$source_result, &$target_result) {
  1018. $source_result = array();
  1019. $target_result = array();
  1020. foreach ($source as $key => $one_source) {
  1021. $one_target = _drush_sitelist_find_in_list($one_source, $target);
  1022. if ($one_target !== FALSE) {
  1023. $source_result[] = $one_source;
  1024. $target_result[] = $one_target;
  1025. unset($source[$key]);
  1026. }
  1027. }
  1028. $source = $source_result;
  1029. $target = $target_result;
  1030. }
  1031. function _drush_sitelist_find_in_list($one_source, &$target) {
  1032. $result = FALSE;
  1033. foreach ($target as $key => $one_target) {
  1034. if(_drush_sitelist_check_site_records($one_source, $one_target)) {
  1035. $result = $one_target;
  1036. unset($target[$key]);
  1037. }
  1038. }
  1039. return $result;
  1040. }
  1041. function _drush_sitelist_check_site_records($source, $target) {
  1042. if ((array_key_exists('uri', $source)) && (array_key_exists('uri', $target)) && ($source['uri'] == $target['uri'])) {
  1043. return TRUE;
  1044. }
  1045. return FALSE;
  1046. }
  1047. /**
  1048. * Initialize an alias record; called as soon as the alias
  1049. * record is loaded from its alias file, before it is stored
  1050. * in the cache.
  1051. *
  1052. * @param alias_record
  1053. * The alias record to be initialized; parameter is modified in place.
  1054. */
  1055. function _drush_sitealias_initialize_alias_record(&$alias_record) {
  1056. // If there is a 'from-list' entry, then build a derived
  1057. // list based on the site list with the given name.
  1058. if (array_key_exists('from-list', $alias_record)) {
  1059. // danger of infinite loops... move to transient defaults?
  1060. $from_record = drush_sitealias_get_record($alias_record['from-list']);
  1061. $from_list = drush_sitealias_resolve_sitelist($from_record);
  1062. $derived_list = array();
  1063. foreach ($from_list as $one_record) {
  1064. $derived_record = _drush_sitealias_derive_record($one_record, $alias_record);
  1065. $derived_list[] = drush_sitealias_alias_record_to_spec($derived_record);
  1066. }
  1067. $alias_record = array();
  1068. if (!empty($derived_list)) {
  1069. $alias_record['site-list'] = $derived_list;
  1070. }
  1071. }
  1072. // If there is a 'site-search-path' entry, then build
  1073. // a 'site-list' entry from all of the sites that can be
  1074. // found in the search path.
  1075. if (array_key_exists('site-search-path', $alias_record)) {
  1076. // TODO: Is there any point in merging the sites from
  1077. // the search path with any sites already listed in the
  1078. // 'site-list' entry? For now we'll just overwrite.
  1079. $search_path = $alias_record['site-search-path'];
  1080. if (!is_array($search_path)) {
  1081. $search_path = explode(',', $search_path);
  1082. }
  1083. $found_sites = _drush_sitealias_find_local_sites($search_path);
  1084. $alias_record['site-list'] = $found_sites;
  1085. // The 'unordered-list' flag indicates that the order of the items in the site list is not stable.
  1086. $alias_record['unordered-list'] = '1';
  1087. // DEBUG: var_export($alias_record, FALSE);
  1088. }
  1089. if (array_key_exists('site-list', $alias_record)) {
  1090. if (!is_array($alias_record['site-list'])) {
  1091. $alias_record['site-list'] = explode(',', $alias_record['site-list']);
  1092. }
  1093. }
  1094. else {
  1095. if (isset($alias_record['root']) && !isset($alias_recort['uri'])) {
  1096. $alias_recort['uri'] = 'default';
  1097. }
  1098. }
  1099. }
  1100. /**
  1101. * Add "static" default values to the given alias record. The
  1102. * difference between a static default and a transient default is
  1103. * that static defaults -always- exist in the alias record, and
  1104. * they are cached, whereas transient defaults are only added
  1105. * if the given drush command explicitly adds them.
  1106. *
  1107. * @param alias_record
  1108. * An alias record with most values already filled in
  1109. */
  1110. function _drush_sitealias_add_static_defaults(&$alias_record) {
  1111. // If there is a 'db-url' entry but not 'databases' entry, then we will
  1112. // build 'databases' from 'db-url' so that drush commands that use aliases
  1113. // can always count on using a uniform 'databases' array.
  1114. if (isset($alias_record['db-url']) && !isset($alias_record['databases'])) {
  1115. $alias_record['databases'] = drush_sitealias_convert_db_from_db_url($alias_record['db-url']);
  1116. }
  1117. // Adjustments for aliases to drupal instances (as opposed to aliases that are site lists)
  1118. if (array_key_exists('uri', $alias_record)) {
  1119. // Make sure that there is always a 'path-aliases' array
  1120. if (!array_key_exists('path-aliases', $alias_record)) {
  1121. $alias_record['path-aliases'] = array();
  1122. }
  1123. // If there is a 'root' entry, then copy it to the '%root' path alias
  1124. $alias_record['path-aliases']['%root'] = $alias_record['root'];
  1125. }
  1126. }
  1127. function _drush_sitealias_derive_record($from_record, $modifying_record) {
  1128. $result = $from_record;
  1129. // If there is a 'remote-user' in the modifying record, copy it.
  1130. if (array_key_exists('remote-user', $modifying_record)) {
  1131. $result['remote-user'] = $from_record['remote_user'];
  1132. }
  1133. // If there is a 'remote-host', then:
  1134. // If it is empty, clear the remote host in the result record
  1135. // If it ends in '.', then prepend it to the remote host in the result record
  1136. // Otherwise, copy it to the result record
  1137. if (array_key_exists('remote-host', $modifying_record)) {
  1138. $remote_host_modifier = $modifying_record['remote-host'];
  1139. if(empty($remote_host_modifier)) {
  1140. unset($result['remote-host']);
  1141. unset($result['remote-user']);
  1142. }
  1143. elseif ($remote_host_modifier[strlen($remote_host_modifier)-1] == '.') {
  1144. $result['remote-host'] = $remote_host_modifier . $result['remote-host'];
  1145. }
  1146. else {
  1147. $result['remote-host'] = $remote_host_modifier;
  1148. }
  1149. }
  1150. // If there is a 'root', then:
  1151. // If it begins with '/', copy it to the result record
  1152. // Otherwise, append it to the result record
  1153. if (array_key_exists('root', $modifying_record)) {
  1154. $root_modifier = $modifying_record['root'];
  1155. if($root_modifier[0] == '/') {
  1156. $result['root'] = $root_modifier;
  1157. }
  1158. else {
  1159. $result['root'] = $result['root'] . '/' . $root_modifier;
  1160. }
  1161. }
  1162. // Poor man's realpath: take out the /../ with preg_replace.
  1163. // (realpath fails if the files in the path do not exist)
  1164. while(strpos($result['root'], '/../') !== FALSE) {
  1165. $result['root'] = preg_replace('/\w+\/\.\.\//', '', $result['root']);
  1166. }
  1167. // TODO: Should we allow the uri to be transformed?
  1168. // I think that if the uri does not match, then you should
  1169. // always build the list by hand, and not rely on '_drush_sitealias_derive_record'.
  1170. return $result;
  1171. }
  1172. /**
  1173. * Convert from an alias record to a site specification
  1174. *
  1175. * @param alias_record
  1176. * The full alias record to convert
  1177. *
  1178. * @param with_db
  1179. * True if the site specification should include a ?db-url term
  1180. *
  1181. * @return string
  1182. * The site specification
  1183. */
  1184. function drush_sitealias_alias_record_to_spec($alias_record, $with_db = false) {
  1185. $result = '';
  1186. // TODO: we should handle 'site-list' records too.
  1187. if (array_key_exists('site-list', $alias_record)) {
  1188. // TODO: we should actually expand the site list and recompose it
  1189. $result = implode(',', $alias_record['site-list']);
  1190. }
  1191. else {
  1192. // There should always be a uri
  1193. if (array_key_exists('uri', $alias_record)) {
  1194. $result = '#' . drush_sitealias_uri_to_site_dir($alias_record['uri']);
  1195. }
  1196. // There should always be a root
  1197. if (array_key_exists('root', $alias_record)) {
  1198. $result = $alias_record['root'] . $result;
  1199. }
  1200. if (array_key_exists('remote-host', $alias_record)) {
  1201. $result = drush_remote_host($alias_record) . $result;
  1202. }
  1203. // Add the database info to the specification if desired
  1204. if ($with_db) {
  1205. // If db-url is not supplied, look it up from the remote
  1206. // or local site and add it to the site alias
  1207. if (!isset($alias_record['db-url'])) {
  1208. drush_sitealias_add_db_url($alias_record);
  1209. }
  1210. $result = $result . '?db-url=' . urlencode(is_array($alias_record['db-url']) ? $alias_record['db-url']['default'] : $alias_record['db-url']);
  1211. }
  1212. }
  1213. return $result;
  1214. }
  1215. /**
  1216. * Search for drupal installations in the search path.
  1217. *
  1218. * @param search_path
  1219. * An array of drupal root folders
  1220. *
  1221. * @return
  1222. * An array of site specifications (/path/to/root#sitename.com)
  1223. */
  1224. function _drush_sitealias_find_local_sites($search_path) {
  1225. $result = array();
  1226. foreach ($search_path as $a_drupal_root) {
  1227. $result = array_merge($result, _drush_find_local_sites_at_root($a_drupal_root));
  1228. }
  1229. return $result;
  1230. }
  1231. /**
  1232. * Return a list of all of the local sites at the specified drupal root.
  1233. */
  1234. function _drush_find_local_sites_at_root($a_drupal_root = '', $search_depth = 1) {
  1235. $site_list = array();
  1236. $base_path = (empty($a_drupal_root) ? drush_get_context('DRUSH_DRUPAL_ROOT') : $a_drupal_root );
  1237. if (!empty($base_path)) {
  1238. if (drush_valid_drupal_root($base_path)) {
  1239. // If $a_drupal_root is in fact a valid drupal root, then return
  1240. // all of the sites found inside the 'sites' folder of this drupal instance.
  1241. $site_list = _drush_find_local_sites_in_sites_folder($base_path);
  1242. }
  1243. else {
  1244. $bootstrap_files = drush_scan_directory($base_path, '/' . basename(DRUSH_DRUPAL_SIGNATURE) . '/' , array('.', '..', 'CVS', 'examples'), 0, drush_get_option('search-depth', $search_depth) + 1, 'filename', 1);
  1245. foreach ($bootstrap_files as $one_bootstrap => $info) {
  1246. $includes_dir = dirname($one_bootstrap);
  1247. if (basename($includes_dir) == basename(dirname(DRUSH_DRUPAL_SIGNATURE))) {
  1248. $drupal_root = dirname($includes_dir);
  1249. $site_list = array_merge(_drush_find_local_sites_in_sites_folder($drupal_root), $site_list);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return $site_list;
  1255. }
  1256. /**
  1257. * Return a list of all of the local sites at the specified 'sites' folder.
  1258. */
  1259. function _drush_find_local_sites_in_sites_folder($a_drupal_root) {
  1260. $site_list = array();
  1261. // If anyone searches for sites at a given root, then
  1262. // make sure that alias files stored at this root
  1263. // directory are included in the alias search path
  1264. drush_sitealias_add_to_alias_path($a_drupal_root);
  1265. $base_path = $a_drupal_root . '/sites';
  1266. // TODO: build a cache keyed off of $base_path (realpath($base_path)?),
  1267. // so that it is guarenteed that the lists returned will definitely be
  1268. // exactly the same should this routine be called twice with the same path.
  1269. $files = drush_scan_directory($base_path, '/settings\.php/', array('.', '..', 'CVS', 'all'), 0, 1, 'filename', 1);
  1270. foreach ($files as $filename => $info) {
  1271. if ($info->basename == 'settings.php') {
  1272. // First we'll resolve the realpath of the settings.php file,
  1273. // so that we get the correct drupal root when symlinks are in use.
  1274. $real_sitedir = dirname(realpath($filename));
  1275. $real_root = drush_locate_root($filename);
  1276. if ($real_root !== FALSE) {
  1277. $a_drupal_site = $real_root . '#' . basename($real_sitedir);
  1278. }
  1279. // If the symlink points to some folder outside of any drupal
  1280. // root, then we'll use the
  1281. else {
  1282. $uri = drush_sitealias_site_dir_from_filename($filename);
  1283. $a_drupal_site = $a_drupal_root . '#' . $uri;
  1284. }
  1285. // Add the site if it isn't already in the array
  1286. if (!in_array($a_drupal_site, $site_list)) {
  1287. $site_list[] = $a_drupal_site;
  1288. }
  1289. }
  1290. }
  1291. return $site_list;
  1292. }
  1293. function drush_sitealias_create_sites_alias($a_drupal_root = '') {
  1294. $sites_list = _drush_find_local_sites_at_root($a_drupal_root);
  1295. _drush_sitealias_cache_alias('@sites', array('site-list' => $sites_list));
  1296. }
  1297. /**
  1298. * Add "transient" default values to the given alias record. The
  1299. * difference between a static default and a transient default is
  1300. * that static defaults -always- exist in the alias record,
  1301. * whereas transient defaults are only added if the given drush
  1302. * command explicitly calls this function. The other advantage
  1303. * of transient defaults is that it is possible to differentiate
  1304. * between a default value and an unspecified value, since the
  1305. * transient defaults are not added until requested.
  1306. *
  1307. * Since transient defaults are not cached, you should avoid doing
  1308. * expensive operations here. To be safe, drush commands should
  1309. * avoid calling this function more than once.
  1310. *
  1311. * @param alias_record
  1312. * An alias record with most values already filled in
  1313. */
  1314. function _drush_sitealias_add_transient_defaults(&$alias_record) {
  1315. if (isset($alias_record['path-aliases'])) {
  1316. // Add the path to the drush folder to the path aliases as !drush
  1317. if (!array_key_exists('%drush', $alias_record['path-aliases'])) {
  1318. if (array_key_exists('%drush-script', $alias_record['path-aliases'])) {
  1319. $alias_record['path-aliases']['%drush'] = dirname($alias_record['path-aliases']['%drush-script']);
  1320. }
  1321. else {
  1322. $alias_record['path-aliases']['%drush'] = dirname($GLOBALS['argv'][0]);
  1323. }
  1324. }
  1325. // Add the path to the site folder to the path aliases as !site
  1326. if (!array_key_exists('%site', $alias_record['path-aliases']) && array_key_exists('uri', $alias_record)) {
  1327. $alias_record['path-aliases']['%site'] = 'sites/' . drush_sitealias_uri_to_site_dir($alias_record['uri']) . '/';
  1328. }
  1329. }
  1330. }
  1331. /**
  1332. * Find the name of a local alias record that has the specified
  1333. * root and uri.
  1334. */
  1335. function _drush_sitealias_find_local_alias_name($root, $uri) {
  1336. $result = '';
  1337. $all_site_aliases =& drush_get_context('site-aliases');
  1338. foreach ($all_site_aliases as $alias_name => $alias_values) {
  1339. if (!array_key_exists('remote-host', $alias_values) && array_key_exists('root', $alias_values) && array_key_exists('uri', $alias_values) && ($alias_name != '@self')) {
  1340. if (($root == $alias_values['root']) && ($uri == $alias_values['uri'])) {
  1341. $result = $alias_name;
  1342. }
  1343. }
  1344. }
  1345. return $result;
  1346. }
  1347. /**
  1348. * If '$alias' is the name of a folder in the sites folder of the given drupal
  1349. * root, then build an alias record for it
  1350. *
  1351. * @param alias
  1352. * The name of the site in the 'sites' folder to convert
  1353. * @return array
  1354. * An alias record, or empty if none found.
  1355. */
  1356. function _drush_sitealias_find_record_for_local_site($alias, $drupal_root = null) {
  1357. $alias_record = array();
  1358. // Clip off the leading '#' if it is there
  1359. if (substr($alias,0,1) == '#') {
  1360. $alias = substr($alias,1);
  1361. }
  1362. if (!isset($drupal_root)) {
  1363. $drupal_root = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT');
  1364. }
  1365. if (isset($drupal_root)) {
  1366. $alias_dir = drush_sitealias_uri_to_site_dir($alias);
  1367. $site_settings_file = $drupal_root . '/sites/' . $alias_dir . '/settings.php';
  1368. $alias_record = drush_sitealias_build_record_from_settings_file($site_settings_file, $alias, $drupal_root);
  1369. }
  1370. return $alias_record;
  1371. }
  1372. function drush_sitealias_build_record_from_settings_file($site_settings_file, $alias = null, $drupal_root = null) {
  1373. $alias_record = array();
  1374. if (file_exists($site_settings_file)) {
  1375. if (!isset($drupal_root)) {
  1376. $drupal_root = drush_locate_root($site_settings_file);
  1377. }
  1378. $alias_record['root'] = $drupal_root;
  1379. if (isset($alias)) {
  1380. $alias_record['uri'] = $alias;
  1381. }
  1382. else {
  1383. $alias_record['uri'] = _drush_sitealias_site_dir_to_uri(drush_sitealias_site_dir_from_filename($site_settings_file));
  1384. }
  1385. }
  1386. return $alias_record;
  1387. }
  1388. /**
  1389. * Pull the site directory from the path to settings.php
  1390. *
  1391. * @param site_settings_file
  1392. * path to settings.php
  1393. *
  1394. * @return string
  1395. * the site directory component of the path to settings.php
  1396. */
  1397. function drush_sitealias_site_dir_from_filename($site_settings_file) {
  1398. return basename(dirname($site_settings_file));
  1399. }
  1400. /**
  1401. * Convert from a URI to a site directory.
  1402. *
  1403. * @param uri
  1404. * A uri, such as http://domain.com:8080/drupal
  1405. * @return string
  1406. * A directory, such as domain.com.8080.drupal
  1407. */
  1408. function drush_sitealias_uri_to_site_dir($uri) {
  1409. $uri = str_replace('http://', '', $uri);
  1410. if (drush_is_windows()) {
  1411. // Handle absolute paths on windows
  1412. $uri = str_replace(array(':/', ':\\'), array('.', '.'), $uri);
  1413. }
  1414. $hostname = str_replace(array('/', ':', '\\'), array('.', '.', '.'), $uri);
  1415. // Check sites.php mappings
  1416. $site_dir = drush_site_dir_lookup_from_hostname($hostname);
  1417. return $site_dir ? $site_dir : $hostname;
  1418. }
  1419. /**
  1420. * Convert from an old-style database URL to an array of database settings
  1421. *
  1422. * @param db_url
  1423. * A Drupal 6 db-url string to convert, or an array with a 'default' element.
  1424. * @return array
  1425. * An array of database values containing only the 'default' element of
  1426. * the db_url.
  1427. */
  1428. function drush_convert_db_from_db_url($db_url) {
  1429. if (is_array($db_url)) {
  1430. $url = parse_url($db_url['default']);
  1431. }
  1432. else {
  1433. $url = parse_url($db_url);
  1434. }
  1435. // Fill in defaults to prevent notices.
  1436. $url += array(
  1437. 'driver' => NULL,
  1438. 'user' => NULL,
  1439. 'pass' => NULL,
  1440. 'host' => NULL,
  1441. 'port' => NULL,
  1442. 'path' => NULL,
  1443. 'database' => NULL,
  1444. );
  1445. $url = (object)array_map('urldecode', $url);
  1446. return array(
  1447. 'driver' => $url->scheme == 'mysqli' ? 'mysql' : $url->scheme,
  1448. 'username' => $url->user,
  1449. 'password' => $url->pass,
  1450. 'port' => $url->port,
  1451. 'host' => $url->scheme == 'sqlite' ? '' : $url->host,
  1452. // Remove leading / character from database names, unless we're installing
  1453. // to SQLite (which won't have a slash there unless it's part of a path).
  1454. 'database' => $url->scheme == 'sqlite' ? $url->host . $url->path : substr($url->path, 1),
  1455. );
  1456. }
  1457. /**
  1458. * Convert from an old-style database URL to an array of database settings
  1459. *
  1460. * @param db_url
  1461. * A Drupal 6 db-url string to convert, or an array with multiple db-urls.
  1462. * @return array
  1463. * An array of database values.
  1464. */
  1465. function drush_sitealias_convert_db_from_db_url($db_url) {
  1466. $result = array();
  1467. if (!is_array($db_url)) {
  1468. $result = array('default' => array('default' => drush_convert_db_from_db_url($db_url)));
  1469. }
  1470. else {
  1471. foreach ($db_url as $one_name => $one_db_url) {
  1472. $result[$one_name] = array('default' => drush_convert_db_from_db_url($one_db_url));
  1473. }
  1474. }
  1475. return $result;
  1476. }
  1477. /**
  1478. * Utility function used by drush_get_alias; keys that start with
  1479. * '%' or '!' are path aliases, the rest are entries in the alias record.
  1480. */
  1481. function _drush_sitealias_set_record_element(&$alias_record, $key, $value) {
  1482. if ((substr($key,0,1) == '%') || (substr($key,0,1) == '!')) {
  1483. $alias_record['path-aliases'][$key] = $value;
  1484. }
  1485. elseif (!empty($key)) {
  1486. $alias_record[$key] = $value;
  1487. }
  1488. }
  1489. /**
  1490. * Looks up the specified alias record and calls through to
  1491. * drush_sitealias_set_alias_context, below.
  1492. *
  1493. * @param alias
  1494. * The name of the alias record
  1495. * @param prefix
  1496. * The prefix value to afix to the beginning of every
  1497. * key set.
  1498. * @return boolean
  1499. * TRUE is an alias was found and processed.
  1500. */
  1501. function _drush_sitealias_set_context_by_name($alias, $prefix = '') {
  1502. $site_alias_settings = drush_sitealias_get_record($alias);
  1503. if (!empty($site_alias_settings)) {
  1504. drush_sitealias_set_alias_context($site_alias_settings, $prefix);
  1505. drush_sitealias_cache_alias_by_path($site_alias_settings);
  1506. if (empty($prefix)) {
  1507. // Create an alias '@self'
  1508. _drush_sitealias_cache_alias('@self', $site_alias_settings);
  1509. // change the selected site to match the new --root and --uri, if any were set
  1510. _drush_bootstrap_select_drupal_site();
  1511. }
  1512. return TRUE;
  1513. }
  1514. return FALSE;
  1515. }
  1516. /**
  1517. * Given an alias record, overwrite its values with options
  1518. * from the command line and other drush contexts as specified
  1519. * by the provided prefix. For example, if the prefix is 'source-',
  1520. * then any option 'source-foo' will set the value 'foo' in the
  1521. * alias record.
  1522. */
  1523. function drush_sitealias_overlay_options($site_alias_record, $prefix) {
  1524. return array_merge($site_alias_record, drush_get_merged_prefixed_options($prefix));
  1525. }
  1526. /**
  1527. * First return an option set via drush_sitealias_overlay_options, if
  1528. * any, then fall back on "%" . $option from the path aliases.
  1529. */
  1530. function drush_sitealias_get_path_option($site_alias_record, $option, $default = NULL) {
  1531. if (isset($site_alias_record) && array_key_exists($option, $site_alias_record)) {
  1532. return $site_alias_record[$option];
  1533. }
  1534. if (isset($site_alias_record) && array_key_exists('path-aliases', $site_alias_record) && array_key_exists("%$option", $site_alias_record['path-aliases'])) {
  1535. return $site_alias_record['path-aliases']["%$option"];
  1536. }
  1537. else {
  1538. return drush_get_option($option, $default);
  1539. }
  1540. }
  1541. /**
  1542. * Given a site alias record, copy selected fields from it
  1543. * into the drush 'alias' context. The 'alias' context has
  1544. * lower precedence than the 'cli' context, so values
  1545. * set by an alias record can be overridden by command-line
  1546. * parameters.
  1547. *
  1548. * @param site_alias_settings
  1549. * An alias record
  1550. * @param prefix
  1551. * The prefix value to afix to the beginning of every
  1552. * key set. For example, if this function is called once with
  1553. * 'source-' and again with 'destination-' prefixes, then the
  1554. * source database records will be stored in 'source-databases',
  1555. * and the destination database records will be in
  1556. * 'destination-databases'.
  1557. */
  1558. function drush_sitealias_set_alias_context($site_alias_settings, $prefix = '') {
  1559. $options = drush_get_context('alias');
  1560. // There are some items that we should just skip
  1561. $skip_list = drush_get_special_keys();
  1562. // If 'php-options' are set in the alias, then we will force drush
  1563. // to redispatch via the remote dispatch mechanism even if the target is localhost.
  1564. if (array_key_exists('php-options', $site_alias_settings) || drush_get_context('DRUSH_BACKEND', FALSE)) {
  1565. if (!array_key_exists('remote-host', $site_alias_settings)) {
  1566. $site_alias_settings['remote-host'] = 'localhost';
  1567. }
  1568. }
  1569. // If 'php-options' are not set in the alias, then skip 'remote-host'
  1570. // and 'remote-user' if 'remote-host' is actually the local machine.
  1571. // This prevents drush from using the remote dispatch mechanism (the command
  1572. // is just run directly on the local machine, bootstrapping to the specified alias)
  1573. elseif (array_key_exists('remote-host', $site_alias_settings) && drush_is_local_host($site_alias_settings['remote-host'])) {
  1574. $skip_list[] = 'remote-host';
  1575. $skip_list[] = 'remote-user';
  1576. }
  1577. // If prefix is set, then copy from the 'prefix-' version
  1578. // of the drush special keys ('command-specific', 'path-aliases')
  1579. // into the ordinary version. This will allow us to set
  1580. // 'source-command-specific' options that will only apply when
  1581. // the alias is used as the source option for rsync or sql-sync.
  1582. if (!empty($prefix)) {
  1583. $special_contexts = drush_get_special_keys();
  1584. foreach ($special_contexts as $option_name) {
  1585. if (array_key_exists($prefix . $option_name, $site_alias_settings)) {
  1586. $site_alias_settings[$option_name] = array_key_exists($option_name, $site_alias_settings) ? array_merge($site_alias_settings[$option_name], $site_alias_settings[$prefix . $option_name]) : $site_alias_settings[$prefix . $option_name];
  1587. }
  1588. }
  1589. }
  1590. // Transfer all options from the site alias to the drush options
  1591. // in the 'alias' context.
  1592. foreach ($site_alias_settings as $key => $value) {
  1593. // Special handling for path aliases:
  1594. if ($key == "path-aliases") {
  1595. $path_aliases = $value;
  1596. foreach (array('%drush-script', '%dump', '%dump-dir', '%include') as $path_key) {
  1597. if (array_key_exists($path_key, $path_aliases)) {
  1598. // Evaluate the path value, and substitute any path references found.
  1599. // ex: '%dump-dir' => '%root/dumps' will store sql-dumps in the folder
  1600. // 'dumps' in the Drupal root folder for the site.
  1601. $evaluated_path = str_replace(array_keys($path_aliases), array_values($path_aliases), $path_aliases[$path_key]);
  1602. $options[$prefix . substr($path_key, 1)] = $evaluated_path;
  1603. }
  1604. }
  1605. }
  1606. // Special handling for command-specific
  1607. elseif ($key == "command-specific") {
  1608. $options[$key] = $value;
  1609. }
  1610. elseif (!in_array($key, $skip_list)) {
  1611. $options[$prefix . $key] = $value;
  1612. }
  1613. }
  1614. drush_set_config_options('alias', $options);
  1615. }
  1616. /**
  1617. * Call prior to drush_sitealias_evaluate_path to insure
  1618. * that any site-specific aliases associated with any
  1619. * local site in $path are defined.
  1620. */
  1621. function _drush_sitealias_preflight_path($path) {
  1622. $alias = NULL;
  1623. // Parse site aliases if there is a colon in the path
  1624. // We allow:
  1625. // @alias:/path
  1626. // machine.domain.com:/path
  1627. // machine:/path
  1628. // Note that paths in the form "c:/path" are converted to
  1629. // "/cygdrive/c/path" later; we do not want them to confuse
  1630. // us here, so we skip paths that start with a single character
  1631. // before the colon if we are running on Windows. Single-character
  1632. // machine names are allowed in Linux only.
  1633. $colon_pos = strpos($path, ':');
  1634. if ($colon_pos > (drush_is_windows("LOCAL") ? 1 : 0)) {
  1635. $alias = substr($path, 0, $colon_pos);
  1636. $path = substr($path, $colon_pos + 1);
  1637. $site_alias_settings = drush_sitealias_get_record($alias);
  1638. if (empty($site_alias_settings) && (substr($path,0,1) == '@')) {
  1639. return NULL;
  1640. }
  1641. $machine = $alias;
  1642. }
  1643. else {
  1644. $machine = '';
  1645. // if the path is a site alias or a local site...
  1646. $site_alias_settings = drush_sitealias_get_record($path);
  1647. if (empty($site_alias_settings) && (substr($path,0,1) == '@')) {
  1648. return NULL;
  1649. }
  1650. if (!empty($site_alias_settings) || drush_is_local_host($path)) {
  1651. $alias = $path;
  1652. $path = '';
  1653. }
  1654. }
  1655. return array('alias' => $alias, 'path' => $path, 'machine' => $machine);
  1656. }
  1657. /**
  1658. * Given a properly-escaped options string, replace any occurance of
  1659. * %files and so on embedded inside it with its corresponding path.
  1660. */
  1661. function drush_sitealias_evaluate_paths_in_options($option_string) {
  1662. $path_aliases = _core_path_aliases();
  1663. return str_replace(array_keys($path_aliases), array_values($path_aliases), $option_string);
  1664. }
  1665. /**
  1666. * Evaluate a path from its shorthand form to a literal path
  1667. * usable by rsync.
  1668. *
  1669. * A path is "machine:/path" or "machine:path" or "/path" or "path".
  1670. * 'machine' might instead be an alias record, or the name
  1671. * of a site in the 'sites' folder. 'path' might be (or contain)
  1672. * '%root' or some other path alias. This function will examine
  1673. * all components of the path and evaluate them as necessary to
  1674. * come to the final path.
  1675. *
  1676. * @param path
  1677. * The path to evaluate
  1678. * @param additional_options
  1679. * An array of options that overrides whatever was passed in on
  1680. * the command line (like the 'process' context, but only for
  1681. * the scope of this one call).
  1682. * @param local_only
  1683. * If TRUE, force an error if the provided path points to a remote
  1684. * machine. This is used in core-cli, for example, to insure that you
  1685. * do not 'cd' to a remote machine.
  1686. * @param os
  1687. * This should be the local system os, unless evaluate path is
  1688. * being called for rsync, in which case it should be "CWRSYNC"
  1689. * if cwrsync is being used, or "rsync" to automatically select
  1690. * between "LOCAL" and "CWRSYNC" based on the platform.
  1691. * @return
  1692. * The site record for the machine specified in the path, if any,
  1693. * with the path to pass to rsync (including the machine specifier)
  1694. * in the 'evaluated-path' item.
  1695. */
  1696. function drush_sitealias_evaluate_path($path, &$additional_options, $local_only = FALSE, $os = NULL, $command_specific_prefix = '') {
  1697. $site_alias_settings = array();
  1698. $path_aliases = array();
  1699. $remote_user = '';
  1700. $preflight = _drush_sitealias_preflight_path($path);
  1701. if (!isset($preflight)) {
  1702. return NULL;
  1703. }
  1704. $alias = $preflight['alias'];
  1705. $path = $preflight['path'];
  1706. $machine = $preflight['machine'];
  1707. if (isset($alias)) {
  1708. // Note that the alias settings may have an 'os' component, but we do
  1709. // not want to use it here. The paths passed to rsync should always be
  1710. // escaped per the LOCAL rules, without regard to the remote platform type.
  1711. $site_alias_settings = drush_sitealias_get_record($alias);
  1712. if (!empty($command_specific_prefix)) {
  1713. drush_command_set_command_specific_options($command_specific_prefix);
  1714. drush_sitealias_command_default_options($site_alias_settings, $command_specific_prefix);
  1715. }
  1716. }
  1717. if (!empty($site_alias_settings)) {
  1718. if ($local_only && array_key_exists('remote-host', $site_alias_settings)) {
  1719. return drush_set_error('DRUSH_REMOTE_SITE_IN_LOCAL_CONTEXT', dt("A remote site alias was used in a context where only a local alias is appropriate."));
  1720. }
  1721. // Apply any options from this alias that might affect our rsync
  1722. drush_sitealias_set_alias_context($site_alias_settings);
  1723. // Use 'remote-host' from settings if available; otherwise site is local
  1724. if (array_key_exists('remote-host', $site_alias_settings) && !drush_is_local_host($site_alias_settings['remote-host'])) {
  1725. $machine = drush_remote_host($site_alias_settings);
  1726. }
  1727. else {
  1728. $machine = '';
  1729. }
  1730. }
  1731. else {
  1732. // Strip the machine portion of the path if the
  1733. // alias points to the local machine.
  1734. if (drush_is_local_host($machine)) {
  1735. $machine = '';
  1736. }
  1737. else {
  1738. $machine = "$remote_user$machine";
  1739. }
  1740. }
  1741. // TOD: The code below is a little rube-goldberg-ish, and needs to be
  1742. // reworked. core-rsync will call this function twice: once to
  1743. // evaluate the destination, and then again to evaluate the source. Things
  1744. // get odd with --exclude-paths, especially in conjunction with command-specific
  1745. // and the --exclude-files option. @see testCommandSpecific()
  1746. // If the --exclude-other-sites option is specified, then
  1747. // convert that into --include-paths='%site' and --exclude-sites.
  1748. if (drush_get_option_override($additional_options, 'exclude-other-sites', FALSE) && !drush_get_context('exclude-other-sites-processed', FALSE)) {
  1749. $include_path_option = drush_get_option_override($additional_options, 'include-paths', '');
  1750. $additional_options['include-paths'] = '%site';
  1751. if (!empty($include_path_option)) {
  1752. // We use PATH_SEPARATOR here because we are later going to explicitly explode() this variable using PATH_SEPARATOR.
  1753. $additional_options['include-paths'] .= PATH_SEPARATOR . $include_path_option;
  1754. }
  1755. $additional_options['exclude-sites'] = TRUE;
  1756. drush_set_context('exclude-other-sites-processed', TRUE);
  1757. }
  1758. else {
  1759. unset($additional_options['include-paths']);
  1760. }
  1761. // If the --exclude-files option is specified, then
  1762. // convert that into --exclude-paths='%files'.
  1763. if (drush_get_option_override($additional_options, 'exclude-files', FALSE) && !drush_get_option_override($additional_options, 'exclude-files-processed', FALSE, 'process')) {
  1764. $exclude_path_option = drush_get_option_override($additional_options, 'exclude-paths', '');
  1765. $additional_options['exclude-paths'] = '%files';
  1766. if (!empty($exclude_path_option)) {
  1767. // We use PATH_SEPARATOR here because we are later going to explicitly explode() this variable using PATH_SEPARATOR.
  1768. $additional_options['exclude-paths'] .= PATH_SEPARATOR . $exclude_path_option;
  1769. }
  1770. $additional_options['exclude-files-processed'] = TRUE;
  1771. }
  1772. else {
  1773. unset($additional_options['exclude-paths']);
  1774. }
  1775. // If there was no site specification given, and the
  1776. // machine is local, then try to look
  1777. // up an alias record for the default drush site.
  1778. if (empty($site_alias_settings) && empty($machine)) {
  1779. $drush_uri = drush_get_context('DRUSH_SELECTED_URI', 'default');
  1780. $site_alias_settings = drush_sitealias_get_record($drush_uri);
  1781. }
  1782. // Always add transient defaults
  1783. _drush_sitealias_add_transient_defaults($site_alias_settings);
  1784. // The $resolve_path variable is used by drush_sitealias_resolve_path_references
  1785. // to test to see if there are any path references such as %site or %files
  1786. // in it, so that resolution is only done if the path alias is referenced.
  1787. // Therefore, we can concatenate without worrying too much about the structure of
  1788. // this variable's contents.
  1789. $include_path = drush_get_option_override($additional_options, 'include-paths', '');
  1790. $exclude_path = drush_get_option_override($additional_options, 'exclude-paths', '');
  1791. $resolve_path = $path . $include_path . $exclude_path;
  1792. // Resolve path aliases such as %files, if any exist in the path
  1793. if (!empty($resolve_path)) {
  1794. drush_sitealias_resolve_path_references($site_alias_settings, $resolve_path);
  1795. }
  1796. if (array_key_exists('path-aliases', $site_alias_settings)) {
  1797. $path_aliases = $site_alias_settings['path-aliases'];
  1798. }
  1799. // Get the 'root' setting from the alias; if it does not
  1800. // exist, then get the root from the bootstrapped site.
  1801. if (array_key_exists('root', $site_alias_settings)) {
  1802. $drupal_root = $site_alias_settings['root'];
  1803. }
  1804. else {
  1805. drush_bootstrap_max(DRUSH_BOOTSTRAP_DRUPAL_SITE);
  1806. $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  1807. }
  1808. if (empty($drupal_root)) {
  1809. $drupal_root = '';
  1810. }
  1811. else {
  1812. // Add a slash to the end of the drupal root, as below.
  1813. $drupal_root = drush_trim_path($drupal_root) . "/";
  1814. }
  1815. $full_path_aliases = $path_aliases;
  1816. foreach ($full_path_aliases as $key => $value) {
  1817. // Expand all relative path aliases to be based off of the Drupal root
  1818. if (!drush_is_absolute_path($value, "LOCAL") && ($key != '%root')) {
  1819. $full_path_aliases[$key] = $drupal_root . $value;
  1820. }
  1821. // We do not want slashes on the end of our path aliases.
  1822. $full_path_aliases[$key] = drush_trim_path($full_path_aliases[$key]);
  1823. }
  1824. // Fill in path aliases in the path, the include path and the exclude path.
  1825. $path = str_replace(array_keys($full_path_aliases), array_values($full_path_aliases), $path);
  1826. if (!empty($include_path)) {
  1827. drush_set_option('include-paths', str_replace(array_keys($path_aliases), array_values($path_aliases), $include_path));
  1828. }
  1829. if (!empty($exclude_path)) {
  1830. drush_set_option('exclude-paths', str_replace(array_keys($path_aliases), array_values($path_aliases), $exclude_path));
  1831. }
  1832. // Next make the rsync path, which includes the machine
  1833. // and path components together.
  1834. // First make empty paths or relative paths start from the drupal root.
  1835. if (empty($path) || (!drush_is_absolute_path($path, "LOCAL"))) {
  1836. $path = $drupal_root . $path;
  1837. }
  1838. // When calculating a path for use with rsync, we must correct
  1839. // absolute paths in the form c:\path when cwrsync is in use.
  1840. $path = drush_correct_absolute_path_for_exec($path, $os);
  1841. // If there is a $machine component, to the path, then
  1842. // add it to the beginning
  1843. $evaluated_path = drush_escapeshellarg($path, $os);
  1844. if (!empty($machine)) {
  1845. $evaluated_path = $machine . ':' . $evaluated_path;
  1846. }
  1847. //
  1848. // Add our result paths:
  1849. //
  1850. // evaluated-path: machine:/path
  1851. // server-component: machine
  1852. // path-component: :/path
  1853. // path: /path
  1854. // user-path: path (as specified in input parameter)
  1855. //
  1856. $site_alias_settings['evaluated-path'] = $evaluated_path;
  1857. if (!empty($machine)) {
  1858. $site_alias_settings['server-component'] = $machine;
  1859. }
  1860. $site_alias_settings['path-component'] = (!empty($path) ? ':' . $path : '');
  1861. $site_alias_settings['path'] = $path;
  1862. $site_alias_settings['user-path'] = $preflight['path'];
  1863. return $site_alias_settings;
  1864. }
  1865. /**
  1866. * Option keys used for site selection.
  1867. */
  1868. function drush_sitealias_site_selection_keys() {
  1869. return array('remote-host', 'remote-user', 'winrs-password', 'ssh-options', '#name', 'os');
  1870. }
  1871. function sitealias_find_local_drupal_root($site_list) {
  1872. $drupal_root = NULL;
  1873. foreach ($site_list as $site) {
  1874. if (($drupal_root == NULL) && (array_key_exists('root', $site) && !array_key_exists('remote-host', $site))) {
  1875. $drupal_root = $site['root'];
  1876. }
  1877. }
  1878. return $drupal_root;
  1879. }
  1880. /**
  1881. * Helper function to obtain the keys' names that need special handling in certain
  1882. * cases.
  1883. * @return
  1884. * A non-associative array containing the needed keys' names.
  1885. */
  1886. function drush_get_special_keys() {
  1887. $special_keys = array(
  1888. 'command-specific',
  1889. 'site-aliases',
  1890. );
  1891. return $special_keys;
  1892. }
  1893. /**
  1894. * Read the tmp file where the persistent site setting is stored.
  1895. *
  1896. * @return string
  1897. * A valid site specification.
  1898. */
  1899. function drush_sitealias_site_get() {
  1900. if (($filename = drush_sitealias_get_envar_filename()) && file_exists($filename)) {
  1901. $site = file_get_contents($filename);
  1902. return $site;
  1903. }
  1904. else {
  1905. return FALSE;
  1906. }
  1907. }
  1908. /**
  1909. * Returns the filename for the file that stores the DRUPAL_SITE variable.
  1910. *
  1911. * @param string $filename_prefix
  1912. * An arbitrary string to prefix the filename with.
  1913. *
  1914. * @return string|false
  1915. * Returns the full path to temp file if possible, or FALSE if not.
  1916. */
  1917. function drush_sitealias_get_envar_filename($filename_prefix = 'drush-drupal-site-') {
  1918. $shell_pid = getenv('DRUSH_SHELL_PID');
  1919. if (!$shell_pid && function_exists('posix_getppid')) {
  1920. $shell_pid = posix_getppid();
  1921. }
  1922. if (!$shell_pid) {
  1923. return FALSE;
  1924. }
  1925. $tmp = getenv('TMPDIR') ? getenv('TMPDIR') : '/tmp';
  1926. $username = drush_get_username();
  1927. return "{$tmp}/drush-env-{$username}/{$filename_prefix}" . $shell_pid;
  1928. }
  1929. /**
  1930. * Cache the specified alias in the alias path cache. The
  1931. * alias path cache creates a lookup from the site folder
  1932. * (/path/to/drupal/sites/default) to the provided alias record.
  1933. *
  1934. * Only the name of the alias and the path to the file it
  1935. * is stored in is cached; when it is retrieved, it is
  1936. * loaded directly from the correct file.
  1937. */
  1938. function drush_sitealias_cache_alias_by_path($alias_record) {
  1939. if (!isset($alias_record['remote-host']) && isset($alias_record['root']) && isset($alias_record['uri']) && isset($alias_record['#name']) && isset($alias_record['#file'])) {
  1940. $path = drush_sitealias_local_site_path($alias_record);
  1941. if ($path) {
  1942. $cid = drush_get_cid('alias-path-', array(), array($path));
  1943. $alias_path_data = array(
  1944. '#name' => $alias_record['#name'],
  1945. '#file' => $alias_record['#file'],
  1946. );
  1947. drush_cache_set($cid, $alias_path_data);
  1948. }
  1949. }
  1950. }
  1951. /**
  1952. * Look for a defined alias that points to the specified
  1953. * site directory. The cache is tested first; if nothing
  1954. * is cached, then an exhaustive search is done for the
  1955. * specified site. If the exhaustive search returns a
  1956. * match, then it is cached.
  1957. *
  1958. * @param $path
  1959. * /path/to/drupal/sites/default
  1960. * @return
  1961. * An alias record for the provided path
  1962. */
  1963. function drush_sitealias_lookup_alias_by_path($path) {
  1964. $result = drush_sitealias_quick_lookup_cached_alias_by_path($path);
  1965. if (empty($result)) {
  1966. $aliases = _drush_sitealias_find_and_load_all_aliases();
  1967. foreach ($aliases as $name => $alias_record) {
  1968. if (!isset($alias_record['remote-host']) && isset($alias_record['root']) && isset($alias_record['uri']) && isset($alias_record['#name']) && isset($alias_record['#file'])) {
  1969. if ($path == drush_sitealias_local_site_path($alias_record)) {
  1970. $result = $alias_record;
  1971. _drush_sitealias_add_inherited_values_to_record($result);
  1972. drush_sitealias_cache_alias_by_path($result);
  1973. return $result;
  1974. }
  1975. }
  1976. }
  1977. }
  1978. return $result;
  1979. }
  1980. /**
  1981. * Look for a cached alias that points to the specified
  1982. * site directory. Nothing is returned if there is no
  1983. * matching cached alias.
  1984. *
  1985. * @param $path
  1986. * /path/to/drupal/sites/default
  1987. * @return
  1988. * An alias record for the provided path
  1989. */
  1990. function drush_sitealias_quick_lookup_cached_alias_by_path($path) {
  1991. $alias_record = array();
  1992. $cid = drush_get_cid('alias-path-', array(), array($path));
  1993. $alias_path_cache = drush_cache_get($cid);
  1994. if (isset($alias_path_cache->data)) {
  1995. $alias_name = $alias_path_cache->data['#name'];
  1996. $alias_file = $alias_path_cache->data['#file'];
  1997. $alias_record = _drush_sitealias_find_and_load_alias_from_file($alias_name, array($alias_file));
  1998. _drush_sitealias_add_inherited_values_to_record($alias_record);
  1999. $alias_record['#name'] = $alias_name;
  2000. }
  2001. return $alias_record;
  2002. }