install.core.inc 110 KB
Newer Older
1 2
<?php

3
use Drupal\Component\Utility\UserAgent;
4 5
use Drupal\Component\Utility\Crypt;

6
use Drupal\Component\Utility\Settings;
7
use Drupal\Core\Config\FileStorage;
katbailey's avatar
katbailey committed
8
use Drupal\Core\DrupalKernel;
9
use Drupal\Core\CoreServiceProvider;
10
use Drupal\Core\Database\Database;
11
use Drupal\Core\Database\DatabaseExceptionWrapper;
12
use Drupal\Core\Database\Install\TaskException;
13
use Drupal\Core\Language\Language;
14
use Drupal\Core\Language\LanguageManager;
15
use Drupal\Core\StringTranslation\Translator\FileTranslation;
16

17
use Drupal\Core\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
use Symfony\Component\DependencyInjection\Reference;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22

23 24
use Guzzle\Http\Exception\RequestException;

25 26 27 28 29 30
/**
 * @file
 * API functions for installing Drupal.
 */

/**
31
 * Do not run the task during the current installation request.
32 33 34 35 36 37 38 39 40
 *
 * This can be used to skip running an installation task when certain
 * conditions are met, even though the task may still show on the list of
 * installation tasks presented to the user. For example, the Drupal installer
 * uses this flag to skip over the database configuration form when valid
 * database connection information is already available from settings.php. It
 * also uses this flag to skip language import tasks when the installation is
 * being performed in English.
 */
41
const INSTALL_TASK_SKIP = 1;
42 43

/**
44
 * Run the task on each installation request that reaches it.
45 46 47
 *
 * This is primarily used by the Drupal installer for bootstrap-related tasks.
 */
48
const INSTALL_TASK_RUN_IF_REACHED = 2;
49 50

/**
51
 * Run the task on each installation request until the database is set up.
52 53 54 55 56 57 58 59
 *
 * This is the default method for running tasks and should be used for most
 * tasks that occur after the database is set up; these tasks will then run
 * once and be marked complete once they are successfully finished. For
 * example, the Drupal installer uses this flag for the batch installation of
 * modules on the new site, and also for the configuration form that collects
 * basic site information and sets up the site maintenance account.
 */
60
const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
61 62

/**
63
 * Installs Drupal either interactively or via an array of passed-in settings.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
 *
 * The Drupal installation happens in a series of steps, which may be spread
 * out over multiple page requests. Each request begins by trying to determine
 * the last completed installation step (also known as a "task"), if one is
 * available from a previous request. Control is then passed to the task
 * handler, which processes the remaining tasks that need to be run until (a)
 * an error is thrown, (b) a new page needs to be displayed, or (c) the
 * installation finishes (whichever happens first).
 *
 * @param $settings
 *   An optional array of installation settings. Leave this empty for a normal,
 *   interactive, browser-based installation intended to occur over multiple
 *   page requests. Alternatively, if an array of settings is passed in, the
 *   installer will attempt to use it to perform the installation in a single
 *   page request (optimized for the command line) and not send any output
 *   intended for the web browser. See install_state_defaults() for a list of
 *   elements that are allowed to appear in this array.
 *
 * @see install_state_defaults()
 */
function install_drupal($settings = array()) {
  global $install_state;
  // Initialize the installation state with the settings that were passed in,
  // as well as a boolean indicating whether or not this is an interactive
  // installation.
  $interactive = empty($settings);
  $install_state = $settings + array('interactive' => $interactive) + install_state_defaults();
  try {
    // Begin the page request. This adds information about the current state of
    // the Drupal installation to the passed-in array.
    install_begin_request($install_state);
    // Based on the installation state, run the remaining tasks for this page
    // request, and collect any output.
    $output = install_run_tasks($install_state);
  }
  catch (Exception $e) {
    // When an installation error occurs, either send the error to the web
    // browser or pass on the exception so the calling script can use it.
    if ($install_state['interactive']) {
      install_display_output($e->getMessage(), $install_state);
    }
    else {
      throw $e;
    }
  }
109 110 111 112 113 114 115
  // After execution, all tasks might be complete, in which case
  // $install_state['installation_finished'] is TRUE. In case the last task
  // has been processed, remove the global $install_state, so other code can
  // reliably check whether it is running during the installer.
  // @see drupal_installation_attempted()
  $state = $install_state;
  if (!empty($install_state['installation_finished'])) {
116
    unset($GLOBALS['install_state']);
117 118
  }

119 120 121
  // All available tasks for this page request are now complete. Interactive
  // installations can send output to the browser or redirect the user to the
  // next page.
122 123
  if ($state['interactive']) {
    if ($state['parameters_changed']) {
124
      // Redirect to the correct page if the URL parameters have changed.
125
      install_goto(install_redirect_url($state));
126 127 128 129 130
    }
    elseif (isset($output)) {
      // Display a page only if some output is available. Otherwise it is
      // possible that we are printing a JSON page and theme output should
      // not be shown.
131
      install_display_output($output, $state);
132 133 134 135 136
    }
  }
}

/**
137
 * Returns an array of default settings for the global installation state.
138 139 140 141 142 143 144 145
 *
 * The installation state is initialized with these settings at the beginning
 * of each page request. They may evolve during the page request, but they are
 * initialized again once the next request begins.
 *
 * Non-interactive Drupal installations can override some of these default
 * settings by passing in an array to the installation script, most notably
 * 'parameters' (which contains one-time parameters such as 'profile' and
146
 * 'langcode' that are normally passed in via the URL) and 'forms' (which can
147 148 149 150 151 152 153 154 155 156 157 158 159 160
 * be used to programmatically submit forms during the installation; the keys
 * of each element indicate the name of the installation task that the form
 * submission is for, and the values are used as the $form_state['values']
 * array that is passed on to the form submission via drupal_form_submit()).
 *
 * @see drupal_form_submit()
 */
function install_state_defaults() {
  $defaults = array(
    // The current task being processed.
    'active_task' => NULL,
    // The last task that was completed during the previous installation
    // request.
    'completed_task' => NULL,
161
    // TRUE when there are valid config directories.
162
    'config_verified' => FALSE,
163
    // TRUE when there is a valid database connection.
164
    'database_verified' => FALSE,
165 166 167 168 169
    // TRUE when a valid settings.php exists (containing both database
    // connection information and config directory names).
    'settings_verified' => FALSE,
    // TRUE when the base system has been installed and is ready to operate.
    'base_system_verified' => FALSE,
170 171 172
    // Whether a translation file for the selected language will be downloaded
    // from the translation server.
    'download_translation' => FALSE,
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    // An array of forms to be programmatically submitted during the
    // installation. The keys of each element indicate the name of the
    // installation task that the form submission is for, and the values are
    // used as the $form_state['values'] array that is passed on to the form
    // submission via drupal_form_submit().
    'forms' => array(),
    // This becomes TRUE only at the end of the installation process, after
    // all available tasks have been completed and Drupal is fully installed.
    // It is used by the installer to store correct information in the database
    // about the completed installation, as well as to inform theme functions
    // that all tasks are finished (so that the task list can be displayed
    // correctly).
    'installation_finished' => FALSE,
    // Whether or not this installation is interactive. By default this will
    // be set to FALSE if settings are passed in to install_drupal().
    'interactive' => TRUE,
    // An array of parameters for the installation, pre-populated by the URL
    // or by the settings passed in to install_drupal(). This is primarily
    // used to store 'profile' (the name of the chosen installation profile)
192
    // and 'langcode' (the code of the chosen installation language), since
193 194 195 196 197 198 199 200
    // these settings need to persist from page request to page request before
    // the database is available for storage.
    'parameters' => array(),
    // Whether or not the parameters have changed during the current page
    // request. For interactive installations, this will trigger a page
    // redirect.
    'parameters_changed' => FALSE,
    // An array of information about the chosen installation profile. This will
201
    // be filled in based on the profile's .info.yml file.
202 203 204 205 206 207 208
    'profile_info' => array(),
    // An array of available installation profiles.
    'profiles' => array(),
    // An array of server variables that will be substituted into the global
    // $_SERVER array via drupal_override_server_variables(). Used by
    // non-interactive installations only.
    'server' => array(),
209 210 211 212
    // The server URL where the interface translation files can be downloaded.
    // Tokens in the pattern will be replaced by appropriate values for the
    // required translation file.
    'server_pattern' => 'http://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po',
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    // Installation tasks can set this to TRUE to force the page request to
    // end (even if there is no themable output), in the case of an interactive
    // installation. This is needed only rarely; for example, it would be used
    // by an installation task that prints JSON output rather than returning a
    // themed page. The most common example of this is during batch processing,
    // but the Drupal installer automatically takes care of setting this
    // parameter properly in that case, so that individual installation tasks
    // which implement the batch API do not need to set it themselves.
    'stop_page_request' => FALSE,
    // Installation tasks can set this to TRUE to indicate that the task should
    // be run again, even if it normally wouldn't be. This can be used, for
    // example, if a single task needs to be spread out over multiple page
    // requests, or if it needs to perform some validation before allowing
    // itself to be marked complete. The most common examples of this are batch
    // processing and form submissions, but the Drupal installer automatically
    // takes care of setting this parameter properly in those cases, so that
    // individual installation tasks which implement the batch API or form API
    // do not need to set it themselves.
    'task_not_complete' => FALSE,
    // A list of installation tasks which have already been performed during
    // the current page request.
    'tasks_performed' => array(),
235 236 237
    // An array of translation files URIs available for the installation. Keyed
    // by the translation language code.
    'translations' => array(),
238 239 240 241 242
  );
  return $defaults;
}

/**
243
 * Begins an installation request, modifying the installation state as needed.
244 245 246 247 248 249 250 251 252
 *
 * This function performs commands that must run at the beginning of every page
 * request. It throws an exception if the installation should not proceed.
 *
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   modified with information gleaned from the beginning of the page request.
 */
function install_begin_request(&$install_state) {
253 254 255 256 257 258 259 260 261 262
  // A request object from the HTTPFoundation to tell us about the request.
  $request = Request::createFromGlobals();

  // Create a minimal container so that t() and $request will work. This
  // container will be overriden but it's needed for the very early installation
  // process when database tasks run.
  $container = new ContainerBuilder();
  $container->set('request', $request);
  \Drupal::setContainer($container);

263
  // Add any installation parameters passed in via the URL.
264
  if ($install_state['interactive']) {
265
    $install_state['parameters'] += $request->query->all();
266
  }
267 268 269 270 271

  // Validate certain core settings that are used throughout the installation.
  if (!empty($install_state['parameters']['profile'])) {
    $install_state['parameters']['profile'] = preg_replace('/[^a-zA-Z_0-9]/', '', $install_state['parameters']['profile']);
  }
272 273
  if (!empty($install_state['parameters']['langcode'])) {
    $install_state['parameters']['langcode'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['langcode']);
274 275
  }

276
  // Allow command line scripts to override server variables used by Drupal.
277
  require_once __DIR__ . '/bootstrap.inc';
278

279 280 281 282
  if (!$install_state['interactive']) {
    drupal_override_server_variables($install_state['server']);
  }

283 284 285 286 287 288
  // Initialize conf_path().
  // This primes the site path to be used during installation. By not requiring
  // settings.php, a bare site folder can be prepared in the /sites directory,
  // which will be used for installing Drupal.
  conf_path(FALSE);

289 290
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);

291 292 293 294 295 296 297
  // If the hash salt leaks, it becomes possible to forge a valid testing user
  // agent, install a new copy of Drupal, and take over the original site. To
  // avoid this yet allow for automated testing of the installer, make sure
  // there is also a special test-specific settings.php overriding conf_path().
  // _drupal_load_test_overrides() sets the simpletest_conf_path in-memory
  // setting in this case.
  if ($install_state['interactive'] && drupal_valid_test_ua() && !settings()->get('simpletest_conf_path')) {
298
    header($request->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
299 300 301
    exit;
  }

302 303 304
  // Register the 'language_manager' service.
  $container->register('language_manager', 'Drupal\Core\Language\LanguageManager');

305 306 307 308
  // If we have a language selected and it is not yet saved in the system
  // (eg. pre-database data screens we are unable to persistently store
  // the default language), we should set language_default so the proper
  // language is used to display installer pages as early as possible.
309 310 311 312 313 314 315 316
  // The language list is stored in configuration and cannot be saved either
  // until later in the process. Language negotiation bootstrapping needs
  // the new default language to be in the list though, so inject it in.
  if (!empty($install_state['parameters']['langcode']) && language_default()->id != $install_state['parameters']['langcode']) {
    $GLOBALS['conf']['language_default'] = array('id' => $install_state['parameters']['langcode']);

    $languages = &drupal_static('language_list');
    $languages[$install_state['parameters']['langcode']] = new Language($GLOBALS['conf']['language_default']);
317 318
  }

319 320 321 322 323 324
  require_once __DIR__ . '/../modules/system/system.install';
  require_once __DIR__ . '/common.inc';
  require_once __DIR__ . '/file.inc';
  require_once __DIR__ . '/install.inc';
  require_once __DIR__ . '/schema.inc';
  require_once __DIR__ . '/../../' . settings()->get('path_inc', 'core/includes/path.inc');
325 326 327 328 329
  require_once __DIR__ . '/cache.inc';
  require_once __DIR__ . '/database.inc';
  require_once __DIR__ . '/form.inc';
  require_once __DIR__ . '/batch.inc';
  require_once __DIR__ . '/ajax.inc';
330 331

  // Load module basics (needed for hook invokes).
332 333 334
  include_once __DIR__ . '/module.inc';
  include_once __DIR__ . '/session.inc';
  require_once __DIR__ . '/entity.inc';
335

336 337
  // Register the translation services.
  install_register_translation_service($container);
338
  \Drupal::setContainer($container);
339

340 341
  // Determine whether base system services are ready to operate.
  $install_state['config_verified'] = install_verify_config_directory(CONFIG_ACTIVE_DIRECTORY) && install_verify_config_directory(CONFIG_STAGING_DIRECTORY);
342 343
  $install_state['database_verified'] = install_verify_database_settings();
  $install_state['settings_verified'] = $install_state['config_verified'] && $install_state['database_verified'];
344

345
  if ($install_state['settings_verified']) {
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    try {
      $system_schema = system_schema();
      end($system_schema);
      $table = key($system_schema);
      $install_state['base_system_verified'] = Database::getConnection()->schema()->tableExists($table);
    }
    catch (DatabaseExceptionWrapper $e) {
      // The last defined table of the base system_schema() does not exist yet.
      // $install_state['base_system_verified'] defaults to FALSE, so the code
      // following below will use the minimal installer service container.
      // As soon as the base system is verified here, the installer operates in
      // a full and regular Drupal environment, without any kind of exceptions.
    }
  }

  if ($install_state['base_system_verified']) {
362
    $kernel = new DrupalKernel('install', drupal_classloader(), FALSE);
363
    $kernel->boot();
364 365 366 367
    $container = $kernel->getContainer();
    // Add the file translation service to the container.
    $container->set('string_translator.file_translation', install_file_translation_service());
    $container->get('string_translation')->addTranslator($container->get('string_translator.file_translation'));
368
  }
369 370 371
  // Replace services with in-memory implementations and specialized installer
  // implementations. This service container is reverted to a regular
  // DrupalKernel in install_bootstrap_full().
372
  else {
373 374
    // @todo Move into a proper Drupal\Core\DependencyInjection\InstallContainerBuilder.
    $container = new ContainerBuilder();
375
    $container->register('event_dispatcher', 'Symfony\Component\EventDispatcher\EventDispatcher');
376 377

    $container->register('config.storage', 'Drupal\Core\Config\InstallStorage');
378

379 380 381 382
    $container->register('config.storage.schema', 'Drupal\Core\Config\Schema\SchemaStorage');

    $container->register('config.typed', 'Drupal\Core\Config\TypedConfigManager')
      ->addArgument(new Reference('config.storage'))
383 384
      ->addArgument(new Reference('config.storage.schema'))
      ->addArgument(new Reference('cache.config'));
385

386 387
    $container->register('config.factory', 'Drupal\Core\Config\ConfigFactory')
      ->addArgument(new Reference('config.storage'))
388
      ->addArgument(new Reference('event_dispatcher'))
389
      ->addArgument(new Reference('config.typed'));
390

391
    // Register the 'language_manager' service.
392
    $container->register('language_manager', 'Drupal\Core\Language\LanguageManager');
393 394

    // Register the translation services.
395
    install_register_translation_service($container);
396

397
    foreach (array('bootstrap', 'config', 'cache', 'menu', 'page', 'path') as $bin) {
398 399 400 401
      $container
        ->register("cache.$bin", 'Drupal\Core\Cache\MemoryBackend')
        ->addArgument($bin);
    }
402

403 404 405 406 407 408 409 410
    // The install process cannot use the database lock backend since the database
    // is not fully up, so we use a null backend implementation during the
    // installation process. This will also speed up the installation process.
    // The site being installed will use the real lock backend when doing AJAX
    // requests but, except for a WSOD, there is no chance for a a lock to stall
    // (as opposed to the cache backend) so we can afford having a null
    // implementation here.
    $container->register('lock', 'Drupal\Core\Lock\NullLockBackend');
411

412 413 414 415 416 417 418
    $container
      ->register('theme.registry', 'Drupal\Core\Theme\Registry')
      ->addArgument(new Reference('cache.cache'))
      ->addArgument(new Reference('lock'))
      ->addArgument(new Reference('module_handler'))
      ->addTag('needs_destruction');

419 420 421
    // Register a module handler for managing enabled modules.
    $container
      ->register('module_handler', 'Drupal\Core\Extension\ModuleHandler');
422 423 424 425 426 427 428 429 430 431 432

    // Register the Guzzle HTTP client for fetching translation files from a
    // remote translation server such as localization.drupal.org.
    $container->register('http_default_client', 'Guzzle\Http\Client')
      ->addArgument(NULL)
      ->addArgument(array(
        'curl.CURLOPT_TIMEOUT' => 30.0,
        'curl.CURLOPT_MAXREDIRS' => 3,
      ))
      ->addMethodCall('setUserAgent', array('Drupal (+http://drupal.org/)'));

433 434 435
    $container->register('settings', 'Drupal\Component\Utility\Settings')
      ->setFactoryClass('Drupal\Component\Utility\Settings')
      ->setFactoryMethod('getSingleton');
436

437
    $container
438
      ->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueMemoryFactory');
439
    $container
440
      ->register('keyvalue.expirable', 'Drupal\Core\KeyValueStore\KeyValueNullExpirableFactory');
441

442 443
    $container->register('state', 'Drupal\Core\KeyValueStore\State')
      ->addArgument(new Reference('keyvalue'));
444

445
    // Register Twig template engine for use during install.
446
    CoreServiceProvider::registerTwig($container);
447

448 449
    $container->register('url_generator', 'Drupal\Core\Routing\NullGenerator');

450 451 452 453 454 455 456 457 458 459
    $container->register('form_builder', 'Drupal\Core\Form\FormBuilder')
      ->addArgument(new Reference('module_handler'))
      ->addArgument(new Reference('keyvalue.expirable'))
      ->addArgument(new Reference('event_dispatcher'))
      ->addArgument(new Reference('url_generator'))
      ->addArgument(new Reference('string_translation'))
      ->addArgument(new Reference('csrf_token', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))
      ->addArgument(new Reference('http_kernel', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))
      ->addMethodCall('setRequest', array(new Reference('request')));

460 461 462
    // Register UUID.
    CoreServiceProvider::registerUuid($container);

463
    // Register the CSS and JavaScript asset collection renderers.
464 465 466 467
    $container->register('asset.css.collection_renderer', 'Drupal\Core\Asset\CssCollectionRenderer')
      ->addArgument(new Reference('state'));
    $container->register('asset.js.collection_renderer', 'Drupal\Core\Asset\JsCollectionRenderer')
      ->addArgument(new Reference('state'));
468

469 470
    // Register the info parser.
    $container->register('info_parser', 'Drupal\Core\Extension\InfoParser');
471 472 473 474 475 476

    $container->register('theme_handler', 'Drupal\Core\Extension\ThemeHandler')
      ->addArgument(new Reference('config.factory'))
      ->addArgument(new Reference('module_handler'))
      ->addArgument(new Reference('cache.cache'))
      ->addArgument(new Reference('info_parser'));
477
  }
478

479 480 481 482
  // Set the request in the kernel to the new created Request above
  // so it is available to the rest of the installation process.
  $container->set('request', $request);

483
  \Drupal::setContainer($container);
484

485
  // Set up $language, so t() caller functions will still work.
katbailey's avatar
katbailey committed
486
  drupal_language_initialize();
487 488
  // Add in installation language if present.
  if (isset($install_state['parameters']['langcode'])) {
489
    \Drupal::translation()->setDefaultLangcode($install_state['parameters']['langcode']);
490
  }
491

492
  $module_handler = \Drupal::moduleHandler();
493 494 495 496 497
  if (!$module_handler->moduleExists('system')) {
    // Override the module list with a minimal set of modules.
    $module_handler->setModuleList(array('system' => 'core/modules/system/system.module'));
  }
  $module_handler->load('system');
498

499 500 501 502 503 504
  // Prepare for themed output. We need to run this at the beginning of the
  // page request to avoid a different theme accidentally getting set. (We also
  // need to run it even in the case of command-line installations, to prevent
  // any code in the installer that happens to initialize the theme system from
  // accessing the database before it is set up yet.)
  drupal_maintenance_theme();
505

506
  if ($install_state['database_verified']) {
507 508 509 510 511 512
    // Verify the last completed task in the database, if there is one.
    $task = install_verify_completed_task();
  }
  else {
    $task = NULL;

513 514
    // Do not install over a configured settings.php.
    if (!empty($GLOBALS['databases'])) {
515 516 517 518
      throw new Exception(install_already_done_error());
    }
  }

519 520 521 522 523 524 525 526 527 528
  // Ensure that the active configuration directory is empty before installation
  // starts.
  if ($install_state['config_verified'] && empty($task)) {
    $config = glob(config_get_config_directory(CONFIG_ACTIVE_DIRECTORY) . '/*.' . FileStorage::getFileExtension());
    if (!empty($config)) {
      $task = NULL;
      throw new Exception(install_already_done_error());
    }
  }

529 530
  // Modify the installation state as appropriate.
  $install_state['completed_task'] = $task;
531 532

  // Add the list of available profiles to the installation state.
533
  $install_state['profiles'] += drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.profile$/', 'profiles');
534 535 536
}

/**
537
 * Runs all tasks for the current installation request.
538 539 540 541 542 543 544 545 546
 *
 * In the case of an interactive installation, all tasks will be attempted
 * until one is reached that has output which needs to be displayed to the
 * user, or until a page redirect is required. Otherwise, tasks will be
 * attempted until the installation is finished.
 *
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   passed along to each task, so it can be modified if necessary.
547
 *
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
 * @return
 *   HTML output from the last completed task.
 */
function install_run_tasks(&$install_state) {
  do {
    // Obtain a list of tasks to perform. The list of tasks itself can be
    // dynamic (e.g., some might be defined by the installation profile,
    // which is not necessarily known until the earlier tasks have run),
    // so we regenerate the remaining tasks based on the installation state,
    // each time through the loop.
    $tasks_to_perform = install_tasks_to_perform($install_state);
    // Run the first task on the list.
    reset($tasks_to_perform);
    $task_name = key($tasks_to_perform);
    $task = array_shift($tasks_to_perform);
    $install_state['active_task'] = $task_name;
    $original_parameters = $install_state['parameters'];
    $output = install_run_task($task, $install_state);
    $install_state['parameters_changed'] = ($install_state['parameters'] != $original_parameters);
    // Store this task as having been performed during the current request,
    // and save it to the database as completed, if we need to and if the
    // database is in a state that allows us to do so. Also mark the
    // installation as 'done' when we have run out of tasks.
    if (!$install_state['task_not_complete']) {
      $install_state['tasks_performed'][] = $task_name;
      $install_state['installation_finished'] = empty($tasks_to_perform);
574
      if ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished']) {
575
        \Drupal::state()->set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
576 577 578 579 580 581 582 583 584 585 586 587
      }
    }
    // Stop when there are no tasks left. In the case of an interactive
    // installation, also stop if we have some output to send to the browser,
    // the URL parameters have changed, or an end to the page request was
    // specifically called for.
    $finished = empty($tasks_to_perform) || ($install_state['interactive'] && (isset($output) || $install_state['parameters_changed'] || $install_state['stop_page_request']));
  } while (!$finished);
  return $output;
}

/**
588
 * Runs an individual installation task.
589 590 591 592 593 594
 *
 * @param $task
 *   An array of information about the task to be run.
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   passed in by reference so that it can be modified by the task.
595
 *
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
 * @return
 *   The output of the task function, if there is any.
 */
function install_run_task($task, &$install_state) {
  $function = $task['function'];

  if ($task['type'] == 'form') {
    if ($install_state['interactive']) {
      // For interactive forms, build the form and ensure that it will not
      // redirect, since the installer handles its own redirection only after
      // marking the form submission task complete.
      $form_state = array(
        // We need to pass $install_state by reference in order for forms to
        // modify it, since the form API will use it in call_user_func_array(),
        // which requires that referenced variables be passed explicitly.
        'build_info' => array('args' => array(&$install_state)),
        'no_redirect' => TRUE,
      );
      $form = drupal_build_form($function, $form_state);
      // If a successful form submission did not occur, the form needs to be
      // rendered, which means the task is not complete yet.
      if (empty($form_state['executed'])) {
        $install_state['task_not_complete'] = TRUE;
        return drupal_render($form);
      }
      // Otherwise, return nothing so the next task will run in the same
      // request.
      return;
    }
    else {
      // For non-interactive forms, submit the form programmatically with the
      // values taken from the installation state. Throw an exception if any
      // errors were encountered.
629 630 631 632 633 634 635 636
      $form_state = array(
        'values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array(),
        // We need to pass $install_state by reference in order for forms to
        // modify it, since the form API will use it in call_user_func_array(),
        // which requires that referenced variables be passed explicitly.
        'build_info' => array('args' => array(&$install_state)),
      );
      drupal_form_submit($function, $form_state);
637
      $errors = form_get_errors($form_state);
638 639 640 641 642 643 644 645 646
      if (!empty($errors)) {
        throw new Exception(implode("\n", $errors));
      }
    }
  }

  elseif ($task['type'] == 'batch') {
    // Start a new batch based on the task function, if one is not running
    // already.
647
    $current_batch = \Drupal::state()->get('install_current_batch');
648 649 650 651 652 653 654 655 656 657 658 659
    if (!$install_state['interactive'] || !$current_batch) {
      $batch = $function($install_state);
      if (empty($batch)) {
        // If the task did some processing and decided no batch was necessary,
        // there is nothing more to do here.
        return;
      }
      batch_set($batch);
      // For interactive batches, we need to store the fact that this batch
      // task is currently running. Otherwise, we need to make sure the batch
      // will complete in one page request.
      if ($install_state['interactive']) {
660
        \Drupal::state()->set('install_current_batch', $function);
661 662 663 664 665 666 667
      }
      else {
        $batch =& batch_get();
        $batch['progressive'] = FALSE;
      }
      // Process the batch. For progressive batches, this will redirect.
      // Otherwise, the batch will complete.
668 669 670 671 672 673 674 675
      $response = batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state));
      if ($response instanceof Response) {
        // Save $_SESSION data from batch.
        drupal_session_commit();
        // Send the response.
        $response->send();
        exit;
      }
676 677 678 679
    }
    // If we are in the middle of processing this batch, keep sending back
    // any output from the batch process, until the task is complete.
    elseif ($current_batch == $function) {
680
      $output = _batch_page(\Drupal::request());
681
      // Because Batch API now returns a JSON response for intermediary steps,
682 683 684 685
      // but the installer doesn't handle Response objects yet, just send the
      // output here and emulate the old model.
      // @todo Replace this when we refactor the installer to use a request-
      //   response workflow.
686 687
      if ($output instanceof Response) {
        $output->send();
688
        $output = NULL;
689
      }
690 691 692
      // The task is complete when we try to access the batch page and receive
      // FALSE in return, since this means we are at a URL where we are no
      // longer requesting a batch ID.
693
      if ($output === FALSE) {
694
        // Return nothing so the next task will run in the same request.
695
        \Drupal::state()->delete('install_current_batch');
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        return;
      }
      else {
        // We need to force the page request to end if the task is not
        // complete, since the batch API sometimes prints JSON output
        // rather than returning a themed page.
        $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
        return $output;
      }
    }
  }

  else {
    // For normal tasks, just return the function result, whatever it is.
    return $function($install_state);
  }
}

/**
715
 * Returns a list of tasks to perform during the current installation request.
716 717 718 719 720 721 722
 *
 * Note that the list of tasks can change based on the installation state as
 * the page request evolves (for example, if an installation profile hasn't
 * been selected yet, we don't yet know which profile tasks need to be run).
 *
 * @param $install_state
 *   An array of information about the current installation state.
723
 *
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
 * @return
 *   A list of tasks to be performed, with associated metadata.
 */
function install_tasks_to_perform($install_state) {
  // Start with a list of all currently available tasks.
  $tasks = install_tasks($install_state);
  foreach ($tasks as $name => $task) {
    // Remove any tasks that were already performed or that never should run.
    // Also, if we started this page request with an indication of the last
    // task that was completed, skip that task and all those that come before
    // it, unless they are marked as always needing to run.
    if ($task['run'] == INSTALL_TASK_SKIP || in_array($name, $install_state['tasks_performed']) || (!empty($install_state['completed_task']) && empty($completed_task_found) && $task['run'] != INSTALL_TASK_RUN_IF_REACHED)) {
      unset($tasks[$name]);
    }
    if (!empty($install_state['completed_task']) && $name == $install_state['completed_task']) {
      $completed_task_found = TRUE;
    }
  }
  return $tasks;
}

/**
746
 * Returns a list of all tasks the installer currently knows about.
747 748 749 750 751 752 753 754 755
 *
 * This function will return tasks regardless of whether or not they are
 * intended to run on the current page request. However, the list can change
 * based on the installation state (for example, if an installation profile
 * hasn't been selected yet, we don't yet know which profile tasks will be
 * available).
 *
 * @param $install_state
 *   An array of information about the current installation state.
756
 *
757 758 759 760
 * @return
 *   A list of tasks, with associated metadata.
 */
function install_tasks($install_state) {
761 762 763
  // Determine whether a translation file must be imported during the
  // 'install_import_translations' task. Import when a non-English language is
  // available and selected.
764
  $needs_translations = count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en';
765 766 767 768
  // Determine whether a translation file must be downloaded during the
  // 'install_download_translation' task. Download when a non-English language
  // is selected, but no translation is yet in the translations directory.
  $needs_download = isset($install_state['parameters']['langcode']) && !isset($install_state['translations'][$install_state['parameters']['langcode']]) && $install_state['parameters']['langcode'] != 'en';
769

770
  // Start with the core installation tasks that run before handing control
771
  // to the installation profile.
772
  $tasks = array(
773
    'install_select_language' => array(
774
      'display_name' => t('Choose language'),
775 776
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
777 778 779
    'install_download_translation' => array(
      'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
    ),
780
    'install_select_profile' => array(
781
      'display_name' => t('Choose profile'),
782 783 784 785 786 787 788
      'display' => count($install_state['profiles']) != 1,
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_load_profile' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_verify_requirements' => array(
789
      'display_name' => t('Verify requirements'),
790 791
    ),
    'install_settings_form' => array(
792
      'display_name' => t('Set up database'),
793
      'type' => 'form',
794 795 796
      // Even though the form only allows the user to enter database settings,
      // we still need to display it if settings.php is invalid in any way,
      // since the form submit handler is where settings.php is rewritten.
797 798
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    ),
799
    'install_base_system' => array(
800
      'run' => $install_state['base_system_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
801
    ),
802
    // All tasks below are executed in a regular, full Drupal environment.
803 804 805 806
    'install_bootstrap_full' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_profile_modules' => array(
807
      'display_name' => count($install_state['profiles']) == 1 ? t('Install site') : t('Installation profile'),
808 809
      'type' => 'batch',
    ),
810
    'install_import_translations' => array(
811
      'display_name' => t('Set up translations'),
812 813 814 815 816
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_configure_form' => array(
817
      'display_name' => t('Configure site'),
818 819 820 821 822 823
      'type' => 'form',
    ),
  );

  // Now add any tasks defined by the installation profile.
  if (!empty($install_state['parameters']['profile'])) {
824 825
    // Load the profile install file, because it is not always loaded when
    // hook_install_tasks() is invoked (e.g. batch processing).
826 827
    $profile = $install_state['parameters']['profile'];
    $profile_install_file = dirname($install_state['profiles'][$profile]->uri) . '/' . $profile . '.install';
828
    if (file_exists($profile_install_file)) {
829
      include_once DRUPAL_ROOT . '/' . $profile_install_file;
830
    }
831 832 833 834 835 836 837 838 839 840 841
    $function = $install_state['parameters']['profile'] . '_install_tasks';
    if (function_exists($function)) {
      $result = $function($install_state);
      if (is_array($result)) {
        $tasks += $result;
      }
    }
  }

  // Finish by adding the remaining core tasks.
  $tasks += array(
842
    'install_import_translations_remaining' => array(
843
      'display_name' => t('Finish translations'),
844 845 846 847
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
848
    'install_update_configuration_translations' => array(
849
      'display_name' => t('Translate configuration'),
850 851 852 853
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
854
    'install_finished' => array(
855
      'display_name' => t('Finished'),
856 857 858 859 860
    ),
  );

  // Allow the installation profile to modify the full list of tasks.
  if (!empty($install_state['parameters']['profile'])) {
861 862
    $profile = $install_state['parameters']['profile'];
    $profile_file = $install_state['profiles'][$profile]->uri;
863
    if (file_exists($profile_file)) {
864
      include_once DRUPAL_ROOT . '/' .  $profile_file;
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
      $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
      if (function_exists($function)) {
        $function($tasks, $install_state);
      }
    }
  }

  // Fill in default parameters for each task before returning the list.
  foreach ($tasks as $task_name => &$task) {
    $task += array(
      'display_name' => NULL,
      'display' => !empty($task['display_name']),
      'type' => 'normal',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
      'function' => $task_name,
    );
  }
  return $tasks;
}

/**
886
 * Returns a list of tasks that should be displayed to the end user.
887 888 889 890 891 892
 *
 * The output of this function is a list suitable for sending to
 * theme_task_list().
 *
 * @param $install_state
 *   An array of information about the current installation state.
893
 *
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
 * @return
 *   A list of tasks, with keys equal to the machine-readable task name and
 *   values equal to the name that should be displayed.
 *
 * @see theme_task_list()
 */
function install_tasks_to_display($install_state) {
  $displayed_tasks = array();
  foreach (install_tasks($install_state) as $name => $task) {
    if ($task['display']) {
      $displayed_tasks[$name] = $task['display_name'];
    }
  }
  return $displayed_tasks;
}

/**
911
 * Returns the URL that should be redirected to during an installation request.
912 913 914 915 916
 *
 * The output of this function is suitable for sending to install_goto().
 *
 * @param $install_state
 *   An array of information about the current installation state.
917
 *
918 919 920 921 922 923
 * @return
 *   The URL to redirect to.
 *
 * @see install_full_redirect_url()
 */
function install_redirect_url($install_state) {
924
  return 'core/install.php?' . drupal_http_build_query($install_state['parameters']);
925 926 927
}

/**
928
 * Returns the complete URL redirected to during an installation request.
929 930 931
 *
 * @param $install_state
 *   An array of information about the current installation state.
932
 *
933 934 935 936 937 938 939 940 941 942 943
 * @return
 *   The complete URL to redirect to.
 *
 * @see install_redirect_url()
 */
function install_full_redirect_url($install_state) {
  global $base_url;
  return $base_url . '/' . install_redirect_url($install_state);
}

/**
944
 * Displays themed installer output and ends the page request.
945 946 947 948 949 950 951 952 953 954 955 956
 *
 * Installation tasks should use drupal_set_title() to set the desired page
 * title, but otherwise this function takes care of theming the overall page
 * output during every step of the installation.
 *
 * @param $output
 *   The content to display on the main part of the page.
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_display_output($output, $install_state) {
  drupal_page_header();
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

  // Prevent install.php from being indexed when installed in a sub folder.
  // robots.txt rules are not read if the site is within domain.com/subfolder
  // resulting in /subfolder/install.php being found through search engines.
  // When settings.php is writeable this can be used via an external database
  // leading a malicious user to gain php access to the server.
  $noindex_meta_tag = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'robots',
      'content' => 'noindex, nofollow',
    ),
  );
  drupal_add_html_head($noindex_meta_tag, 'install_meta_robots');

972 973 974 975 976 977 978
  // Only show the task list if there is an active task; otherwise, the page
  // request has ended before tasks have even been started, so there is nothing
  // meaningful to show.
  if (isset($install_state['active_task'])) {
    // Let the theming function know when every step of the installation has
    // been completed.
    $active_task = $install_state['installation_finished'] ? NULL : $install_state['active_task'];
979
    drupal_add_region_content('sidebar_first', theme('task_list', array('items' => install_tasks_to_display($install_state), 'active' => $active_task, 'variant' => 'install')));
980
  }
981
  print theme('install_page', array('content' => $output));
982 983 984 985
  exit;
}

/**
986
 * Verifies the requirements for installing Drupal.
987 988 989
 *
 * @param $install_state
 *   An array of information about the current installation state.
990
 *
991 992 993 994 995 996 997 998 999 1000
 * @return
 *   A themed status report, or an exception if there are requirement errors.
 */
function install_verify_requirements(&$install_state) {
  // Check the installation requirements for Drupal and this profile.
  $requirements = install_check_requirements($install_state);

  // Verify existence of all required modules.
  $requirements += drupal_verify_profile($install_state);

1001
  return install_display_requirements($install_state, $requirements);
1002 1003 1004
}

/**
1005
 * Installation task; install the base functionality Drupal needs to bootstrap.
1006 1007 1008 1009
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
1010
function install_base_system(&$install_state) {
1011 1012
  // Install system.module.
  drupal_install_system();
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022
  // Call file_ensure_htaccess() to ensure that all of Drupal's standard
  // directories (e.g., the public files directory and config directory) have
  // appropriate .htaccess files. These directories will have already been
  // created by this point in the installer, since Drupal creates them during
  // the install_verify_requirements() task. Note that we cannot call
  // file_ensure_access() any earlier than this, since it relies on
  // system.module in order to work.
  file_ensure_htaccess();

1023 1024
  // Enable the user module so that sessions can be recorded during the
  // upcoming bootstrap step.
1025
  \Drupal::moduleHandler()->install(array('user'), FALSE);
1026

1027
  // Save the list of other modules to install for the upcoming tasks.
1028
  // State can be set to the database now that system.module is installed.
1029 1030
  $modules = $install_state['profile_info']['dependencies'];

1031
  // The installation profile is also a module, which needs to be installed
1032 1033 1034
  // after all the dependencies have been installed.
  $modules[] = drupal_get_profile();

1035
  \Drupal::state()->set('install_profile_modules', array_diff($modules, array('system')));
1036
  $install_state['base_system_verified'] = TRUE;
1037 1038 1039
}

/**
1040
 * Verifies and returns the last installation task that was completed.
1041 1042 1043 1044 1045 1046
 *
 * @return
 *   The last completed task, if there is one. An exception is thrown if Drupal
 *   is already installed.
 */
function install_verify_completed_task() {
1047
  try {
1048
    $task = \Drupal::state()->get('install_task');
1049 1050 1051 1052 1053 1054
  }
  // Do not trigger an error if the database query fails, since the database
  // might not be set up yet.
  catch (Exception $e) {
  }
  if (isset($task)) {
1055 1056 1057 1058 1059 1060 1061 1062
    if ($task == 'done') {
      throw new Exception(install_already_done_error());
    }
    return $task;
  }
}

/**
1063
 * Verifies that settings.php specifies a valid database connection.
1064
 */
1065
function install_verify_database_settings() {
1066
  global $databases;
1067
  if (!empty($databases)) {
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    $database = $databases['default']['default'];
    drupal_static_reset('conf_path');
    $settings_file = './' . conf_path(FALSE) . '/settings.php';
    $errors = install_database_errors($database, $settings_file);
    if (empty($errors)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
1080
 * Form constructor for a form to configure and rewrite settings.php.
1081 1082 1083
 *
 * @param $install_state
 *   An array of information about the current installation state.
1084
 *
1085 1086
 * @see install_settings_form_validate()
 * @see install_settings_form_submit()
1087
 * @ingroup forms
1088 1089
 */
function install_settings_form($form, &$form_state, &$install_state) {
1090
  global $databases;
1091 1092 1093 1094 1095 1096

  drupal_static_reset('conf_path');
  $conf_path = './' . conf_path(FALSE);
  $settings_file = $conf_path . '/settings.php';
  $database = isset($databases['default']['default']) ? $databases['default']['default'] : array();

1097
  drupal_set_title(t('Database configuration'));
1098

1099
  $drivers = drupal_get_database_types();
1100
  $drivers_keys = array_keys($drivers);
1101

1102 1103
  $form['driver'] = array(
    '#type' => 'radios',
1104
    '#title' => t('Database type'),
1105
    '#required' => TRUE,
1106
    '#default_value' => !empty($database['driver']) ? $database['driver'] : current($drivers_keys),
1107 1108 1109
  );
  if (count($drivers) == 1) {
    $form['driver']['#disabled'] = TRUE;
1110 1111
  }

1112 1113 1114 1115 1116
  // Add driver specific configuration options.
  foreach ($drivers as $key => $driver) {
    $form['driver']['#options'][$key] = $driver->name();

    $form['settings'][$key] = $driver->getFormOptions($database);
1117
    $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . t('@driver_name settings', array('@driver_name' => $driver->name())) . '</h2>';
1118 1119 1120 1121 1122 1123 1124 1125 1126
    $form['settings'][$key]['#type'] = 'container';
    $form['settings'][$key]['#tree'] = TRUE;
    $form['settings'][$key]['advanced_options']['#parents'] = array($key);
    $form['settings'][$key]['#states'] = array(
      'visible' => array(
        ':input[name=driver]' => array('value' => $key),
      )
    );
  }
1127

1128
  $form['actions'] = array('#type' => 'actions');
1129 1130
  $form['actions']['save'] = array(
    '#type' => 'submit',
1131
    '#value' => t('Save and continue'),
1132
    '#button_type' => 'primary',
1133 1134 1135 1136 1137
    '#limit_validation_errors' => array(
      array('driver'),
      array(isset($form_state['input']['driver']) ? $form_state['input']['driver'] : current($drivers_keys)),
    ),
    '#submit' => array('install_settings_form_submit'),
1138 1139 1140 1141
  );

  $form['errors'] = array();
  $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file);
1142 1143 1144 1145 1146

  return $form;
}

/**
1147 1148 1149
 * Form validation handler for install_settings_form().
 *
 * @see install_settings_form_submit()
1150 1151
 */
function install_settings_form_validate($form, &$form_state) {
1152 1153
  $driver = $form_state['values']['driver'];
  $database = $form_state['values'][$driver];
1154 1155 1156 1157 1158 1159
  // When testing the interactive installer, copy the database password and
  // the test prefix.
  if ($test_prefix = drupal_valid_test_ua()) {
    $database['prefix'] = $test_prefix;
    $database['password'] = $GLOBALS['databases']['default']['default']['password'];
  }
1160 1161 1162 1163 1164
  $drivers = drupal_get_database_types();
  $reflection = new \ReflectionClass($drivers[$driver]);
  $install_namespace = $reflection->getNamespaceName();
  // Cut the trailing \Install from namespace.
  $database['namespace'] = substr($install_namespace, 0, strrpos($install_namespace, '\\'));
1165 1166
  $database['driver'] = $driver;

1167 1168 1169 1170 1171
  // @todo PIFR uses 'db_prefix' instead of 'prefix'. Remove this when it gets
  //   fixed.
  if (!$test_prefix) {
    $database['prefix'] = $database['db_prefix'];
  }
1172
  unset($database['db_prefix']);
1173

1174 1175
  $form_state['storage']['database'] = $database;
  $errors = install_database_errors($database, $form_state['values']['settings_file']);
1176
  foreach ($errors as $name => $message) {
1177
    form_set_error($name, $form_state, $message);
1178 1179 1180 1181
  }
}

/**
1182
 * Checks a database connection and returns any errors.
1183 1184 1185 1186 1187
 */
function install_database_errors($database, $settings_file) {
  global $databases;
  $errors = array();

1188
  // Check database type.
1189
  $database_types = drupal_get_database_types();
1190 1191
  $driver = $database['driver'];
  if (!isset($database_types[$driver])) {
1192
    $errors['driver'] = t("In your %settings_file file you have configured @drupal to use a %driver server, however your PHP installation currently does not support this database type.", array('%settings_file' => $settings_file, '@drupal' => drupal_install_profile_distribution_name(), '%driver' => $driver));
1193 1194
  }
  else {
1195 1196 1197
    // Run driver specific validation
    $errors += $database_types[$driver]->validateDatabaseSettings($database);

1198
    // Run tasks associated with the database type. Any errors are caught in the
1199
    // calling function.
1200 1201
    $databases['default']['default'] = $database;
    // Just changing the global doesn't get the new information processed.
1202 1203 1204 1205 1206
    // We need to close any active connections and tell the Database class to
    // re-parse $databases.
    if (Database::isActiveConnection()) {
      Database::closeConnection();
    }
1207 1208 1209
    Database::parseConnectionInfo();

    try {
1210
      db_run_tasks($driver);
1211
    }
1212
    catch (TaskException $e) {
1213 1214 1215
      // These are generic errors, so we do not have any specific key of the
      // database connection array to attach them to; therefore, we just put
      // them in the error array with standard numeric keys.
1216
      $errors[$driver . '][0'] = $e->getMessage();
1217 1218 1219 1220 1221 1222
    }
  }
  return $errors;
}

/**
1223 1224 1225
 * Form submission handler for install_settings_form().
 *
 * @see install_settings_form_validate()
1226 1227
 */
function install_settings_form_submit($form, &$form_state) {
1228
  global $install_state, $conf;
1229

1230
  // Update global settings array and save.
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
  $settings = array();
  $database = $form_state['storage']['database'];
  // Ideally, there is no difference between the code executed by the
  // automated test browser and an ordinary browser. However, the database
  // settings need a different format and also need to skip the password
  // when testing. The hash salt also needs to be skipped because the original
  // salt is used to verify the validity of the automated test browser.
  // Because of these, there's a little difference in the code following but
  // it is small and self-contained.
  if ($test_prefix = drupal_valid_test_ua()) {
    foreach ($form_state['storage']['database'] as $k => $v) {
      if ($k != 'password') {
        $settings['databases']['default']['default'][$k] = (object) array(
          'value'    => $v,
          'required' => TRUE,
        );
      }
    }
  }
  else {
    $settings['databases']['default']['default'] = (object) array(
      'value'    => $database,
      'required' => TRUE,
    );
    $settings['drupal_hash_salt'] = (object) array(
      'value'    => Crypt::randomStringHashed(55),
      'required' => TRUE,
    );
  }
1260

1261 1262 1263 1264 1265 1266 1267 1268
  // Remember the profile which was used.
  $settings['settings'] = array(
    'install_profile' => (object) array(
      'value' => $install_state['parameters']['profile'],
      'required' => TRUE,
    ),
  );

1269
  drupal_rewrite_settings($settings);
gdd's avatar
gdd committed
1270

1271
  // Add the config directories to settings.php.
1272
  drupal_install_config_directories();
gdd's avatar
gdd committed
1273

1274 1275 1276 1277 1278
  // Indicate that the settings file has been verified, and check the database
  // for the last completed task, now that we have a valid connection. This
  // last step is important since we want to trigger an error if the new
  // database already has Drupal installed.
  $install_state['settings_verified'] = TRUE;
1279 1280
  $install_state['config_verified'] = TRUE;
  $install_state['database_verified'] = TRUE;
1281 1282 1283 1284
  $install_state['completed_task'] = install_verify_completed_task();
}

/**
1285
 * Selects which profile to install.
1286 1287 1288 1289 1290
 *
 * @param $install_state
 *   An array of information about the current installation state. The chosen
 *   profile will be added here, if it was not already selected previously, as
 *   will a list of all available profiles.
1291
 *
1292 1293