provision_drupal.drush.inc 18.6 KB
Newer Older
1
<?php
2
// $Id$
3 4 5

include_once(dirname(__FILE__) . '/../provision.config.inc');

6 7 8 9 10 11 12 13
/**
 * @file
 * Drupal specific functions for the provisioning framework.
 *
 * This module is responsible for the creation and maintenance of the drupal settings.php file, the sites directory structure
 * and all the install api code. 
 */

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
function provision_drupal_drush_help($section) {
  switch ($section) {
    case 'error:PROVISION_CONFIG_NOT_VALID' : 
      return dt('Config file could not be loaded.');
    case 'error:PROVISION_DRUPAL_SITE_INSTALLED' : 
      return dt('Site has already been installed.');
    case 'error:PROVISION_DRUPAL_SITE_NOT_FOUND' : 
      return dt('Site was not found.');
    case 'error:PROVISION_DRUPAL_INSTALL_FAILED' : 
      return dt('Could not complete Drupal installation.');
    case 'error:PROVISION_DRUPAL_UPDATE_FAILED' : 
      return dt('Could not complete Drupal update.');
    case 'error:PROVISION_BACKUP_PATH_NOT_FOUND' :
      return dt("Backup directory does not exist.");
    case 'error:PROVISION_DRUPAL_INSTALL_MISSING_REQUIREMENTS' :
      return dt("Could not meet the requirements for installing the drupal profile");
    case 'error:PROVISION_REQUIRES_URL' : 
      return dt('You need to specify the URL argument for this command');
  }

}

36 37 38 39 40 41 42 43 44 45 46
function provision_drupal_drush_engine_drupal() {
  $engines = array();
  $engines['install'] = array();
  $engines['import'] = array();
  $engines['deploy'] = array();
  $engines['clear'] = array();
  $engines['packages'] = array();
  $engines['verify'] = array();
  return $engines;
}

47 48 49
/**
 * Initialize the platform / site
 *
50
 * This function is executed by drush_invoke, and is responsible
51 52
 * for populating the $data context array
 */
53
function provision_drupal_drush_init() {
54 55
  $command = drush_get_command();
  $command = explode(" ", $command['command']);
56

57
  if (preg_match("/^provision-/", $command[0])) {
58
    _provision_context_init();
59 60
  }
}
61

62
function _provision_context_init() {
63
  static $is_run = false;
64

65 66
  if ($is_run) {
    return TRUE;
67
  }
68

drumm's avatar
drumm committed
69
  if ((d()->type === 'platform' || d()->type === 'site') && drush_bootstrap_validate(DRUSH_BOOTSTRAP_DRUPAL_ROOT)) { 
70 71 72
    // i don't think i should be bootstrapping here yet ... but i have no choice yet.
    drush_bootstrap(DRUSH_BOOTSTRAP_DRUPAL_ROOT);
  }
73

drumm's avatar
drumm committed
74
  $is_run = TRUE;
75 76 77 78 79 80 81 82 83
}

/**
 * Finalize the platform / site
 *
 * This will run only if there were no errors in any of the previous hooks,
 * and will allow us to cache the successful settings to the site.php/ drushrc.php
 * files for future runs.
 */
84
function provision_drupal_drush_exit() {
85 86
  $command = drush_get_command();
  $command = explode(" ", $command['command']);
87 88

  if (preg_match("/^provision-/", $command[0])) {
drumm's avatar
drumm committed
89
    if (d()->type === 'site') {
90
      if (drush_get_option('installed')) {
Adrian Rossouw's avatar
Adrian Rossouw committed
91 92 93 94 95
        // dont generate the drushrc.php on provision-save commands.
        if (!preg_match("/^provision-save/", $command[0])) {
          drush_set_option('site_id', drush_get_option('site_id'), 'site');
          provision_save_site_data();
        }
96 97
      }
    }
drumm's avatar
drumm committed
98
    elseif (d()->type === 'platform') {
99 100
      // Generate a drushrc.php for the platform unless it's being deleted
      if (!preg_match("/^provision-delete/", $command[0])) {
101
        provision_save_platform_data();
102
      }
Adrian Rossouw's avatar
Adrian Rossouw committed
103
    }
104 105 106
  }
}

107 108 109 110 111 112 113 114
/**
 * Test to see if the site settings.php exists
 *
 * @param url
 *   The url of the site to check
 * @return
 *   If the file exists, return TRUE, else return FALSE.
 */
115
function _provision_drupal_site_exists() {
116
  return file_exists(d()->site_path . '/settings.php');
117 118
}

drumm's avatar
drumm committed
119 120 121 122
/**
 * Sync the current Drupal platform and, if applicable, site. Call after
 * finishing operations that affect the filesystem.
 */
123 124 125
function provision_drupal_sync_site() {
  d()->service('file')->sync(d()->root, TRUE);
  if (d()->type === 'site') {
126
    d()->service('file')->sync(d()->site_path);
127 128 129
  }
}

130 131 132 133 134 135 136 137 138
/**
 * Generate a settings file for the site.
 *
 * @param url
 *   The url of the site being invoked.
 * @param data
 *   A reference to the associated array containing the data for the site. This needs to be a reference, 
 *   because the modules might provide additional information about the site.
 */
139
function _provision_drupal_create_settings_file() {
140
  $config = new provisionConfig_drupal_settings(d()->name);
141
  $config->write();
142
  provision_drupal_sync_site();
143 144
}

145 146 147
class provisionConfig_drupal_settings extends provisionConfig {
  public $template = 'provision_drupal_settings.tpl.php';
  public $description = 'Drupal settings.php file';
148
  protected $mode = 0440;
149 150

  function filename() {
151
    return $this->site_path . '/settings.php';
152 153 154 155 156 157 158 159
  }

  function process() {
    if (drush_drupal_major_version() >= 7) {
      $this->data['db_type'] = ($this->data['db_type'] == 'mysqli') ? 'mysql' : $this->data['db_type'];
    }

    $this->data['extra_config'] = "# Extra configuration from modules:\n";
drumm's avatar
drumm committed
160
    $this->data['extra_config'] .= join("\n", drush_command_invoke_all('provision_drupal_config', $this->data['uri'], $this->data));
161

Adrian Rossouw's avatar
Adrian Rossouw committed
162
    $this->group = $this->platform->server->web_group;
163 164 165
  }
}

166 167 168 169 170
/**
 * Create the directories needed to host a drupal site
 * 
 * Also maintains permissions on existing directories.
 */
171 172 173 174
function _provision_drupal_create_directories($url = NULL, $profile = NULL) {  
  if (is_null($url)) {
    $url = drush_get_option('uri');
  }
175 176
  # those directories will be created and their modes changed
  $mkdir = array(
177
    "sites/$url"                 => 0755,
178
    # those should be writable by the aegir primary group to ease development
179 180 181
    "sites/$url/themes"          => 02775,
    "sites/$url/modules"         => 02775,  
    "sites/$url/libraries"       => 02775, # http://drupal.org/node/496240
182 183 184 185
    // d7 support
    "sites/$url/private"         => 0755,
    "sites/$url/private/files"   => 02770,
    "sites/$url/private/temp"    => 02770,
186
  );
187 188
  $chown = array();
  $chgrp = array();
189
  // special case: platform. do not handle files dir
190
  if ($url != 'all') {
191
    $mkdir["sites/$url/files"]          = 02770;
192 193 194 195
    $mkdir["sites/$url/files/tmp"]          = 02770;
    $mkdir["sites/$url/files/images"]          = 02770;
    $mkdir["sites/$url/files/pictures"]          = 02770;
    # the owner/group of those directories will be changed recursively
Adrian Rossouw's avatar
Adrian Rossouw committed
196 197 198 199 200
    $chown["sites/$url/files"]          = d()->platform->server->script_user;
    $chgrp["sites/$url/files"]          = d()->platform->server->web_group;
    $chown["sites/$url/private"]        = d()->platform->server->script_user;
    $chgrp["sites/$url/private/files"]  = d()->platform->server->web_group;
    $chgrp["sites/$url/private/temp"]   = d()->platform->server->web_group;
201
  }
202

203
  foreach ($mkdir as $path => $perm) {
204
    if (!is_dir($path)) {
205
      d()->service('file')->mkdir($path) 
206 207
        ->succeed('Created <code>@path</code>')
        ->fail('Could not create <code>@path</code>', 'DRUSH_PERM_ERROR');
208
    }
209

210
    d()->service('file')->chmod($path, $perm, TRUE)
211 212
      ->succeed('Changed permissions of <code>@path</code> to @perm')
      ->fail('Could not change permissions <code>@path</code> to @perm');
213
  }
214
  foreach ($chown as $path => $owner) {
215
    d()->service('file')->chown($path, $owner, TRUE)
anarcat's avatar
anarcat committed
216
      ->succeed('Changed ownership of <code>@path</code> to @uid')
217
      ->fail('Could not change ownership <code>@path</code>', 'DRUSH_PERM_ERROR');
218 219
  }
  foreach ($chgrp as $path => $group) {
220
    d()->service('file')->chgrp($path, $group, TRUE)
anarcat's avatar
anarcat committed
221
      ->succeed('Changed group ownership of <code>@path</code> to @gid')
Adrian Rossouw's avatar
Adrian Rossouw committed
222
      ->fail('Could not change group ownership <code>@path</code> to @gid');
223 224 225
  }
}

226 227 228
/**
 * Runs an external script to reload all the various drupal caches
 */
229
function _provision_drupal_rebuild_caches() {
drumm's avatar
drumm committed
230
  if (d()->type === 'site') {
231
    drush_include_engine('drupal', 'clear');
232
  }
233 234
}

235

236 237 238 239 240 241
/**
 * Find available profiles on this platform.
 */
function _provision_find_profiles() {
  include_once('includes/install.inc');

242
  if (!$dir = opendir("./profiles")) {
243
    drush_log(dt("Cannot find profiles directory"), 'error');
244 245 246
    return FALSE;
  }
  while (FALSE !== ($name = readdir($dir))) {
247
    $languages = array();
248 249 250 251 252 253 254 255
    $file = "./profiles/$name/$name.profile";
    if ($name == '..' || $name == '.' || !file_exists($file)) {
      continue;
    }
    $profile = new stdClass();
    $profile->name = $name;
    $profile->filename = $file;

256
    _provision_cvs_deploy($profile);
257 258 259 260 261
    require_once($profile->filename);
    $func = $profile->name . "_profile_details";
    if (function_exists($func)) {
      $profile->info =  $func();
    }
262

263
    $languages['en'] = 1;
264
    // Find languages available
265 266
    $files = array_keys(drush_scan_directory('./profiles/' . $name . '/translations', '/\.po$/', array('.', '..', 'CVS'), 0, FALSE, 'filepath'));
    $files = array_merge($files, array_keys(drush_scan_directory('./profiles/' . $name , '/\.po$/', array('.', '..', 'CVS'), 0, FALSE, 'filepath')));
267 268 269 270 271
    if (is_array($files)) {
      foreach ($files as $file) {
        if (preg_match('!(/|\.)([^\./]+)\.po$!', $file, $langcode)) {
          $languages[$langcode[2]] = 1; // use the language name as an index to weed out duplicates
        }
272 273
      }
    }
Adrian Rossouw's avatar
Adrian Rossouw committed
274
    $profile->info['languages'] = array_keys($languages);
275 276 277 278 279 280 281

    // Drupal 7 renamed the default install profile to 'standard'
    // Aegir now allows projects to specify an "old short name" to provide an upgrade path when projects get renamed. 
    if ($profile->name == 'standard') {
      $profile->info['old_short_name'] = 'default';
    }

anarcat's avatar
anarcat committed
282
    $return[$name] = $profile;
283
    drush_log(dt('Found install profile %name', array('%name' => $name)));
284
  }
285

286 287 288 289
  return $return;

}

290
function provision_drupal_find_sites() {
291 292
  if ($dir = opendir("./sites")) {
    while (FALSE !== ($subdir = readdir($dir))) {
293
      // skip internal directory pointers
294
      if ($subdir != '.' && $subdir != '..') {
295 296 297 298
        $file = "./sites/$subdir/settings.php";
        if (file_exists("$file") && ($subdir != 'default') && !is_link("./sites/$subdir")) {
          $sites[$subdir] = $file;
        }
299 300
      }
    }
301
    closedir($dir);
302
  } else {
303
    drush_log(dt("Cannot find sites directory"), 'error');
304
    $sites = FALSE;
305 306
  }
  return $sites;
307 308
}

309 310
function _provision_drupal_get_cvs_versions($files) {
  foreach ($files as $modulename => $file) {
311 312 313
      $project = array();
      $project['filename'] = $file->filename;
      $project['name'] = $file->name;
314
      $file->info['description'] = str_replace("\n", "", $file->info['description']);
315
      if (!isset($project['project'])) {
316 317 318
        $project['project'] = cvs_deploy_get_project_name($project);
      }
      _cvs_deploy_version_alter($file->info['version'], $project);
319
      $name = !empty($project['project']) ? $project['project'] : $modulename;
320
      $files[$name] = $file; 
321
  }
322

323
  return $files;
324
}
325

326 327 328
/**
 * Create and remove symlinks for each of the possible domain aliases of an existing site
 */
329
function _provision_drupal_maintain_aliases() {
drumm's avatar
drumm committed
330
  if (d()->type === 'site') {
331
    // First we delete all the old aliases
mig5's avatar
mig5 committed
332
    drush_set_option('aliases', drush_get_option('aliases'), 'site');
333
    _provision_drupal_delete_aliases(drush_get_option('aliases', array(), 'site'), false);
334

335 336 337 338 339 340 341
    if (!drush_get_option('redirection')) {
      $aliases = drush_get_option('aliases');
      if (!is_array($aliases)) {
        $aliases = explode(",", $aliases);
      }
      foreach($aliases as $alias) {
        if (trim($alias)) {
342
          d()->service('file')->symlink(d()->uri, d()->root . '/sites/' . $alias)
343 344
            ->succeed('Created symlink for alias @target')
            ->fail('Could not create symlink for alias @target');
345
        }
346 347 348 349 350 351 352 353
      }
    }
  }
}

/**
 * Delete a list of aliases
 */
354
function _provision_drupal_delete_aliases($aliases, $silent = false) {
355 356 357
  if (!is_array($aliases)) {
    $aliases = explode(",", $aliases);
  }
358 359
  if ($silent) {
    $error = NULL;
360 361 362
  }
  else {
    $error = 'Could not remove symlink for alias @path';
363
  }
364
  foreach ($aliases as $alias) {
365
    if ($alias = trim($alias)) {
366
      d()->service('file')->unlink(d()->root . '/sites/' . $alias)
367 368
        ->succeed('Removed symlink for alias @path')
        ->fail($error);
369
    }
370 371
  }
}
372

373 374 375
require_once('cvs_deploy.inc');

function provision_find_packages() {
376
  // Load the version specific include files.
377
  drush_include_engine('drupal', 'packages', drush_drupal_major_version());
378 379 380 381 382 383 384 385 386 387 388

  $packages['base'] = _provision_find_packages('base');

  // Create a package for the Drupal release
  $packages['base']['platforms'] = _provision_find_platforms();

  // Find install profiles.
  $profiles = _provision_find_profiles();
  drush_set_option('profiles', array_keys((array) $profiles), 'drupal'); 

  // Iterate through the install profiles, finding the profile specific packages
389
  foreach ($profiles as $profile => $info) {
390 391 392 393 394
    _provision_cvs_deploy($info);
    if (!$info->version) {
      $info->version = drush_drupal_version();
    }
    $packages['base']['profiles'][$profile] = $info;
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    $packages['profiles'][$profile] =  _provision_find_packages('profiles', $profile);
  }

  return $packages;
}

function _provision_find_platforms() {
  return array(
    'drupal' => array(
    'short_name' => 'drupal', 'version' => drush_drupal_version(), 
    'description' => dt("This platform is running @short_name @version", array('@short_name' => 'Drupal', '@version' => VERSION))));
}

/**
 * A small helper function to reduce code duplication
 */
function _provision_find_packages($scope, $key = '') {
412
  $packages = array();
413 414
  $scope_text = ($key) ? "$scope/$key" : $scope;
  foreach (array('modules', 'themes') as $type) {
415
    $packages[$type] = array();
416 417 418 419 420 421 422 423
    $func = "_provision_drupal_find_$type";
    $result = $func($scope, $key);
    if (sizeof($result)) {
      $packages[$type] = $result;
      drush_log(dt("Found !count !type in !scope", 
        array('!count' => sizeof($result), 
        '!scope' => $scope_text, '!type' => $type)));
    }
424 425 426 427
  }
  return $packages;
}

428 429 430 431
/**
 * Map the system table to a packages multi-dimensional array component
 */
function provision_drupal_system_map() {
432
  // Load the version specific include files.
433
  drush_include_engine('drupal', 'packages');
434

435
  $profiles = _provision_find_profiles();
436 437 438 439 440 441 442
  foreach ($profiles as $profile => $info) {
    _provision_cvs_deploy($info);
    if (!$info->version) {
      $info->version = drush_drupal_version();
    }
    $profiles[$profile] = $info;
  }
443
  $packages['platforms'] = _provision_find_platforms();
444 445

  $profile = drush_get_option('profile');
446 447
  $packages['profiles'][$profile] = $profiles[$profile];
  $packages['profiles'][$profile]->status = 1;
448 449

  foreach (_provision_system_query("module") as $module) { 
450 451 452 453 454
    $frags = explode("/", $module->filename);
    // ignore site-specific modules
    if ($frags[0] == 'sites' && $frags[1] != 'all') {
      continue;
    }
455 456 457
    $info_file = sprintf("%s/%s.info", dirname($module->filename), $module->name);
    $module->info = provision_parse_info_file($info_file);

458 459
    _provision_cvs_deploy($module);
    $module->filename = realpath($module->filename);
460 461 462
    if ($module->schema_version == -1) {
      $module->schema_version = 0;
    }
463 464 465 466 467
    $packages['modules'][$module->name] = $module;
  }

  drush_log(dt("Found !count modules", array('!count' => sizeof($packages['modules']))));

468
  // XXX: mostly a copy-paste from above
Adrian Rossouw's avatar
Adrian Rossouw committed
469
  foreach (_provision_system_query("theme") as $theme) {
470 471 472 473 474
    $frags = explode("/", $theme->filename);
    // ignore site-specific themes
    if ($frags[0] == 'sites' && $frags[1] != 'all') {
      continue;
    }
475 476
    $info_file = sprintf("%s/%s.info", dirname($theme->filename), $theme->name);
    $theme->info = provision_parse_info_file($info_file);
477 478
    _provision_cvs_deploy($theme);
    $theme->filename = realpath($theme->filename);
479 480 481 482 483

    if ($theme->schema_version == -1) {
      $theme->schema_version = 0;
    }

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    $packages['themes'][$theme->name] = $theme;
  }
  drush_log(dt("Found !count themes", array('!count' => sizeof($packages['themes']))));
  return $packages;
}

/**
 * Retrieve a list of paths to search in a certain scope
 */
function _provision_drupal_search_paths($scope, $key = '', $type = 'modules') {
  $searchpaths = array();
  $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
  switch ($scope) {
    case 'base' : 
      $searchpaths[] = sprintf("%s/%s", $drupal_root, $type);
      $searchpaths[] = sprintf("%s/sites/all/%s", $drupal_root, $type);
      break;
    default : 
      if ($key) { 
        $searchpaths[] = sprintf("%s/%s/%s/%s", $drupal_root, $scope, $key, $type);
      }
      break;
     
  }
  return $searchpaths;
}
510

511 512 513 514 515 516 517 518
/**
 * Find modules in a certain scope.
 *
 * This function is general enough that it works for all supported
 * versions of Drupal.
 */
function _provision_drupal_find_modules($scope, $key = '') {
  $paths = _provision_drupal_search_paths($scope, $key, 'modules');
519 520
  $files = array();
  foreach ($paths as $path) {
521
    $files = array_merge($files, drush_scan_directory($path, "/\.module$/", array('.', '..', 'CVS', '.svn'), 0, true, 'name'));
522 523 524
  }
  foreach ($files as $name => $info) {
    $install_file = sprintf("%s/%s.install", dirname($info->filename), $name);
525
    $schema_version = 0;
526 527 528 529 530
    if (file_exists($install_file)) {
      $source = file_get_contents(trim($install_file));
      $source = str_replace("\r\n", "\n", $source);
      $source = str_replace("\r", "\n", $source);
      $function_matches = array();
531
        preg_match_all('!function\s*&?([a-zA-Z0-9_]+)_update_([0-9]+)\s*\(.*?\s*\{!', $source, $function_matches);
532 533
      
      if (sizeof($function_matches[0])) {
534
        $schema_version = max($function_matches[2]);
535 536 537 538 539 540 541 542 543 544 545 546 547
      }
    }
    $info_file = sprintf("%s/%s.info", dirname($info->filename), $name);
    $files[$name]->info = provision_parse_info_file($info_file);
    $files[$name]->schema_version = $schema_version;
    _provision_cvs_deploy($files[$name]);
  }
  return $files;
}

function provision_parse_info_file($filename) {
  $info = array();

548
  $defaults = array(
549 550 551 552 553 554 555
    'dependencies' => array(),
    'description' => '',
    'version' => NULL,
    'php' => DRUPAL_MINIMUM_PHP,
  );
  
  if (file_exists($filename)) {
556
    $info = _provision_drupal_parse_info_file($filename);
557 558 559 560 561 562
  }

  // Merge in defaults and return
  return $info + $defaults;
}

563
/**
564 565 566 567
 * Set up the $_SERVER environment variable so that drupal can correctly parse the settings.php file.
 * The real credentials are stored in the Apache vhost of the relevant site, to prevent leaking of 
 * sensitive data to site administrators with PHP access who might otherwise access such credentials 
 * potentially of other sites' settings.php in a multisite set-up.
568 569 570 571 572 573
 */
function provision_prepare_environment() {
  $fields = array('db_type', 'db_host', 'db_user', 'db_passwd', 'db_name');
  foreach ($fields as $key) {
    $_SERVER[$key] = drush_get_option($key, null, 'site');
  }
Adrian Rossouw's avatar
Adrian Rossouw committed
574 575 576 577 578

  // As of Drupal 7 there is no more mysqli type
  if (drush_drupal_major_version() >= 7) {
    $_SERVER['db_type'] = ($_SERVER['db_type'] == 'mysqli') ? 'mysql' : $_SERVER['db_type'];
  }
579
}