provision_drupal.drush.inc 19.7 KB
Newer Older
1
<?php
2
// $Id$
3 4 5 6 7 8 9 10
/**
 * @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. 
 */

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
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');
  }

}

33 34 35 36 37 38 39 40 41 42 43
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;
}

44 45 46
/**
 * Initialize the platform / site
 *
47
 * This function is executed by drush_invoke, and is responsible
48 49
 * for populating the $data context array
 */
50
function provision_drupal_drush_init($url = NULL) {
51 52
  $command = drush_get_command();
  $command = explode(" ", $command['command']);
53
  if (preg_match("/^provision-/", $command[0])) {
54

55 56 57 58 59 60 61
    if ($url) {
      drush_set_option('uri' , 'http://' . $url);
      drush_set_default('site_url', $url);
      drush_set_default('profile', 'default');
      drush_set_default('language', 'en');
      drush_set_default('aliases', array());
    }
62

63 64 65
    define('PROVISION_CONTEXT_SITE', ($url) ? TRUE : FALSE);
    define('PROVISION_CONTEXT_PLATFORM', !PROVISION_CONTEXT_SITE);
  }
66 67 68 69 70 71 72 73 74
}

/**
 * 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.
 */
75
function provision_drupal_drush_exit($url = NULL) {
76 77
  $command = drush_get_command();
  $command = explode(" ", $command['command']);
78 79

  if (preg_match("/^provision-/", $command[0])) {
80 81 82 83
    if (PROVISION_CONTEXT_SITE) {
      if (drush_get_option('installed')) {
        drush_set_option('site_url', drush_get_option('site_url'), 'site');
        drush_set_option('site_id', drush_get_option('site_id'), 'site');
84
        drush_set_option('client_email', drush_get_option('client_email'), 'site');
85 86 87 88
        provision_save_site_data($url);
      }
    }
    else {
89 90
      // Generate a drushrc.php for the platform unless it's being deleted
      if (!preg_match("/^provision-delete/", $command[0])) {
91
        provision_save_platform_data();
92
      }
Adrian Rossouw's avatar
Adrian Rossouw committed
93
    }
94 95 96 97 98 99 100 101 102
  }
}

/**
 * Some commands need to have a url to operate on.
 *  This prints out a message to that effect.
 */
function _provision_drupal_url_required() {
  if (PROVISION_CONTEXT_PLATFORM) {
103
    drush_set_error('PROVISION_REQUIRES_URL');
104 105 106 107 108 109 110 111 112 113
  }
}

/**
 * Validate a site exists, ie: has a settings.php file
 *
 * This will return an error for sites that haven't been created yet
 */
function _provision_drupal_valid_site() {
  if (PROVISION_CONTEXT_SITE) {
114
    if (!_provision_drupal_site_exists(drush_get_option('site_url'))) {
115
      drush_set_error('PROVISION_DRUPAL_SITE_NOT_FOUND');
116 117
    }
  }
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131
/**
 * 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.
 */
function _provision_drupal_site_exists($url) {
  return file_exists("sites/$url/settings.php");
}

132 133 134 135 136 137 138 139

/**
 * Validate a site has been installed, by checking it's site.php file. 
 *
 * This will return an error for sites that haven't been installed yet
 */
function _provision_drupal_valid_installed_site() {
  if (PROVISION_CONTEXT_SITE) {
140
    if (!_provision_drupal_site_installed(drush_get_option('site_url'))) {
141
      drush_set_error('PROVISION_DRUPAL_SITE_NOT_FOUND');
142 143 144 145 146 147
    }
  }
}

function _provision_drupal_valid_not_installed_site() {
  if (PROVISION_CONTEXT_SITE) {
148
    if (_provision_drupal_site_installed(drush_get_option('site_url'))) {
149
      drush_set_error('PROVISION_DRUPAL_SITE_INSTALLED');
150 151 152
    }
  }
}
153 154

/**
155
 * Test to see if the site has a site.php and has it set to 'installed'
156
 */
157 158
function _provision_drupal_site_installed($url) {
  if (_provision_drupal_site_exists($url)) {
159
    return drush_get_option('installed');
160
  }
161
  return FALSE;
162 163
}

164 165 166 167 168 169 170 171 172
/**
 * 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.
 */
173
function _provision_drupal_create_settings_file() {
174 175
  $config = new provisionConfig_drupal_settings(drush_get_merged_options());
  $config->write();
176 177
}

178 179 180
class provisionConfig_drupal_settings extends provisionConfig {
  public $template = 'provision_drupal_settings.tpl.php';
  public $description = 'Drupal settings.php file';
181
  protected $mode = 0440;
182 183 184 185 186 187 188 189 190 191 192 193

  function filename() {
    return $this->data['sites_path'] . '/' . $this->data['site_url'] . '/settings.php';
  }

  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";
    $this->data['extra_config'] .= join("\n", drush_command_invoke_all('provision_drupal_config', $this->data['site_url'], $this->data));
194 195

    $this->group = drush_get_option('web_group');
196 197 198
  }
}

199 200 201 202 203
/**
 * Create the directories needed to host a drupal site
 * 
 * Also maintains permissions on existing directories.
 */
204
function _provision_drupal_create_directories($url, $profile = NULL) {  
205 206
  # those directories will be created and their modes changed
  $mkdir = array(
207
    "sites/$url"                 => 0755,
208
    # those should be writable by the aegir primary group to ease development
209 210 211
    "sites/$url/themes"          => 02775,
    "sites/$url/modules"         => 02775,  
    "sites/$url/libraries"       => 02775, # http://drupal.org/node/496240
212 213 214 215
    // d7 support
    "sites/$url/private"         => 0755,
    "sites/$url/private/files"   => 02770,
    "sites/$url/private/temp"    => 02770,
216
  );
217 218
  $chown = array();
  $chgrp = array();
219
  // special case: platform. do not handle files dir
220
  if ($url != 'all') {
221
    $mkdir["sites/$url/files"]          = 02770;
222 223 224 225
    $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
226 227
    $chown["sites/$url/files"]          = drush_get_option('script_user');
    $chgrp["sites/$url/files"]          = drush_get_option('web_group');
228
    $chown["sites/$url/private"]        = drush_get_option('script_user');
229
    $chgrp["sites/$url/private/files"]  = drush_get_option('web_group');
230
    $chgrp["sites/$url/private/temp"]   = drush_get_option('web_group');
231
  }
232

233
  foreach ($mkdir as $path => $perm) {
234
    if (!is_dir($path)) {
235 236 237
      provision_service('file')->mkdir($path) 
        ->succeed('Created <code>@path</code>')
        ->fail('Could not create <code>@path</code>', 'DRUSH_PERM_ERROR');
238
    }
239

240 241 242
    provision_service('file')->chmod($path, $perm, TRUE)
      ->succeed('Changed permissions of <code>@path</code> to @perm')
      ->fail('Could not change permissions <code>@path</code> to @perm');
243
  }
244
  foreach ($chown as $path => $owner) {
245 246 247
    provision_service('file')->chown($path, $owner, TRUE)
      ->succeed('Changed ownership of <code>@path</code>')
      ->fail('Could not change ownership <code>@path</code>', 'DRUSH_PERM_ERROR');
248 249
  }
  foreach ($chgrp as $path => $group) {
250 251 252
    provision_service('file')->chgrp($path, $group, TRUE)
      ->succeed('Changed group ownership of <code>@path</code>')
      ->fail('Could not change group ownership <code>@path</code>');
253 254 255
  }
}

256 257 258
/**
 * Runs an external script to reload all the various drupal caches
 */
259
function _provision_drupal_rebuild_caches($url = NULL) {
260
  if (PROVISION_CONTEXT_SITE) {
261
    drush_include_engine('drupal', 'clear');
262
  }
263 264
}

265

266 267 268 269 270 271
/**
 * Find available profiles on this platform.
 */
function _provision_find_profiles() {
  include_once('includes/install.inc');

272
  if (!$dir = opendir("./profiles")) {
273
    drush_log(dt("Cannot find profiles directory"), 'error');
274 275 276
    return FALSE;
  }
  while (FALSE !== ($name = readdir($dir))) {
277
    $languages = array();
278 279 280 281 282 283 284 285
    $file = "./profiles/$name/$name.profile";
    if ($name == '..' || $name == '.' || !file_exists($file)) {
      continue;
    }
    $profile = new stdClass();
    $profile->name = $name;
    $profile->filename = $file;

286
    _provision_cvs_deploy($profile);
287 288 289 290 291
    require_once($profile->filename);
    $func = $profile->name . "_profile_details";
    if (function_exists($func)) {
      $profile->info =  $func();
    }
292

293
    $languages['en'] = 1;
294
    // Find languages available
295 296
    $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')));
297 298 299 300 301
    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
        }
302 303
      }
    }
Adrian Rossouw's avatar
Adrian Rossouw committed
304
    $profile->info['languages'] = array_keys($languages);
305 306 307 308 309 310 311

    // 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
312
    $return[$name] = $profile;
313
    drush_log(dt('Found install profile %name', array('%name' => $name)));
314
  }
315

316 317 318 319
  return $return;

}

320
function provision_drupal_find_sites() {
321 322
  if ($dir = opendir("./sites")) {
    while (FALSE !== ($subdir = readdir($dir))) {
323
      // skip internal directory pointers
324
      if ($subdir != '.' && $subdir != '..') {
325 326 327 328
        $file = "./sites/$subdir/settings.php";
        if (file_exists("$file") && ($subdir != 'default') && !is_link("./sites/$subdir")) {
          $sites[$subdir] = $file;
        }
329 330
      }
    }
331
    closedir($dir);
332
  } else {
333
    drush_log(dt("Cannot find sites directory"), 'error');
334
    $sites = FALSE;
335 336
  }
  return $sites;
337 338
}

339 340
function _provision_drupal_get_cvs_versions($files) {
  foreach ($files as $modulename => $file) {
341 342 343
      $project = array();
      $project['filename'] = $file->filename;
      $project['name'] = $file->name;
344
      $file->info['description'] = str_replace("\n", "", $file->info['description']);
345
      if (!isset($project['project'])) {
346 347 348
        $project['project'] = cvs_deploy_get_project_name($project);
      }
      _cvs_deploy_version_alter($file->info['version'], $project);
349
      $name = !empty($project['project']) ? $project['project'] : $modulename;
350
      $files[$name] = $file; 
351
  }
352

353
  return $files;
354
}
355

356 357 358
/**
 * Create and remove symlinks for each of the possible domain aliases of an existing site
 */
359
function _provision_drupal_maintain_aliases($url) {
360
  if (PROVISION_CONTEXT_SITE) {
361
    // First we delete all the old aliases
mig5's avatar
mig5 committed
362
    drush_set_option('aliases', drush_get_option('aliases'), 'site');
363
    _provision_drupal_delete_aliases(drush_get_option('aliases', array(), 'site'), false);
364

365 366 367 368 369 370 371
    if (!drush_get_option('redirection')) {
      $aliases = drush_get_option('aliases');
      if (!is_array($aliases)) {
        $aliases = explode(",", $aliases);
      }
      foreach($aliases as $alias) {
        if (trim($alias)) {
372 373 374
          provision_service('file')->symlink($url, drush_get_option('docroot_path') . '/sites/' . $alias)
            ->succeed('Created symlink for alias @target')
            ->fail('Could not create symlink for alias @target');
375
        }
376 377 378 379 380 381 382 383
      }
    }
  }
}

/**
 * Delete a list of aliases
 */
384
function _provision_drupal_delete_aliases($aliases, $silent = false) {
385 386 387
  if (!is_array($aliases)) {
    $aliases = explode(",", $aliases);
  }
388 389
  if ($silent) {
    $error = NULL;
390 391 392
  }
  else {
    $error = 'Could not remove symlink for alias @path';
393
  }
394
  foreach ($aliases as $alias) {
395
    if ($alias = trim($alias)) {
396 397 398
      provision_service('file')->unlink(drush_get_option('docroot_path') . '/sites/' . $alias)
        ->succeed('Removed symlink for alias @path')
        ->fail($error);
399
    }
400 401
  }
}
402

403 404 405
require_once('cvs_deploy.inc');

function provision_find_packages() {
406
  // Load the version specific include files.
407
  drush_include_engine('drupal', 'packages', drush_drupal_major_version());
408 409 410 411 412 413 414 415 416 417 418

  $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
419
  foreach ($profiles as $profile => $info) {
420 421 422 423 424
    _provision_cvs_deploy($info);
    if (!$info->version) {
      $info->version = drush_drupal_version();
    }
    $packages['base']['profiles'][$profile] = $info;
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    $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 = '') {
442
  $packages = array();
443 444
  $scope_text = ($key) ? "$scope/$key" : $scope;
  foreach (array('modules', 'themes') as $type) {
445
    $packages[$type] = array();
446 447 448 449 450 451 452 453
    $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)));
    }
454 455 456 457
  }
  return $packages;
}

458 459 460 461
/**
 * Map the system table to a packages multi-dimensional array component
 */
function provision_drupal_system_map() {
462
  // Load the version specific include files.
463
  drush_include_engine('drupal', 'packages');
464

465
  $profiles = _provision_find_profiles();
466 467 468 469 470 471 472
  foreach ($profiles as $profile => $info) {
    _provision_cvs_deploy($info);
    if (!$info->version) {
      $info->version = drush_drupal_version();
    }
    $profiles[$profile] = $info;
  }
473
  $packages['platforms'] = _provision_find_platforms();
474 475

  $profile = drush_get_option('profile');
476 477
  $packages['profiles'][$profile] = $profiles[$profile];
  $packages['profiles'][$profile]->status = 1;
478 479

  foreach (_provision_system_query("module") as $module) { 
480 481 482 483 484
    $frags = explode("/", $module->filename);
    // ignore site-specific modules
    if ($frags[0] == 'sites' && $frags[1] != 'all') {
      continue;
    }
485 486 487
    $info_file = sprintf("%s/%s.info", dirname($module->filename), $module->name);
    $module->info = provision_parse_info_file($info_file);

488 489
    _provision_cvs_deploy($module);
    $module->filename = realpath($module->filename);
490 491 492
    if ($module->schema_version == -1) {
      $module->schema_version = 0;
    }
493 494 495 496 497
    $packages['modules'][$module->name] = $module;
  }

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

498
  // XXX: mostly a copy-paste from above
499
  foreach (_provision_system_query("theme") as $theme) { 
500 501 502 503 504
    $frags = explode("/", $theme->filename);
    // ignore site-specific themes
    if ($frags[0] == 'sites' && $frags[1] != 'all') {
      continue;
    }
505 506
    $info_file = sprintf("%s/%s.info", dirname($theme->filename), $theme->name);
    $theme->info = provision_parse_info_file($info_file);
507 508
    _provision_cvs_deploy($theme);
    $theme->filename = realpath($theme->filename);
509 510 511 512 513

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

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    $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;
}
540

541 542 543 544 545 546 547 548
/**
 * 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');
549 550
  $files = array();
  foreach ($paths as $path) {
551
    $files = array_merge($files, drush_scan_directory($path, "/\.module$/", array('.', '..', 'CVS', '.svn'), 0, true, 'name'));
552 553 554
  }
  foreach ($files as $name => $info) {
    $install_file = sprintf("%s/%s.install", dirname($info->filename), $name);
555
    $schema_version = 0;
556 557 558 559 560
    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();
561
        preg_match_all('!function\s*&?([a-zA-Z0-9_]+)_update_([0-9]+)\s*\(.*?\s*\{!', $source, $function_matches);
562 563
      
      if (sizeof($function_matches[0])) {
564
        $schema_version = max($function_matches[2]);
565 566 567 568 569 570 571 572 573 574 575 576 577
      }
    }
    $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();

578
  $defaults = array(
579 580 581 582 583 584 585
    'dependencies' => array(),
    'description' => '',
    'version' => NULL,
    'php' => DRUPAL_MINIMUM_PHP,
  );
  
  if (file_exists($filename)) {
586
    $info = _provision_drupal_parse_info_file($filename);
587 588 589 590 591 592
  }

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

593
/**
594 595 596 597
 * 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.
598 599 600 601 602 603
 */
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
604 605 606 607 608

  // 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'];
  }
609
}