install.php 71.1 KB
Newer Older
1 2 3
<?php
// $Id$

4 5 6
/**
 * Root directory of Drupal installation.
 */
7
define('DRUPAL_ROOT', getcwd());
8 9

require_once DRUPAL_ROOT . '/includes/install.inc';
10

11 12 13
/**
 * Global flag to indicate that site is in installation mode.
 */
14 15
define('MAINTENANCE_MODE', 'install');

16
/**
17 18
 * Global flag to indicate that a task should not be run during the current
 * installation request.
19
 *
20 21 22 23 24 25 26
 * 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.
27
 */
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
define('INSTALL_TASK_SKIP', 1);

/**
 * Global flag to indicate that a task should be run on each installation
 * request that reaches it.
 *
 * This is primarily used by the Drupal installer for bootstrap-related tasks.
 */
define('INSTALL_TASK_RUN_IF_REACHED', 2);

/**
 * Global flag to indicate that a task should be run on each installation
 * request that reaches it, until the database is set up and we are able to
 * record the fact that it already ran.
 *
 * 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
48
 * basic site information and sets up the site maintenance account.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
 */
define('INSTALL_TASK_RUN_IF_NOT_COMPLETED', 3);

/**
 * Install Drupal either interactively or via an array of passed-in settings.
 *
 * 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;
    }
  }
  // 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.
  if ($install_state['interactive']) {
    if ($install_state['parameters_changed']) {
      // Redirect to the correct page if the URL parameters have changed.
      install_goto(install_redirect_url($install_state));
    }
    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.
      install_display_output($output, $install_state);
    }
  }
}

/**
 * Return an array of default settings for the global installation state.
 *
 * 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
 * 'locale' that are normally passed in via the URL) and 'forms' (which can
 * 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,
    // This becomes TRUE only when Drupal's system module is installed.
    'database_tables_exist' => FALSE,
    // 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 available languages for the installation.
    'locales' => array(),
    // 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)
    // and 'locale' (the name of the chosen installation language), since
    // 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
    // be filled in based on the profile's .info file.
    '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(),
    // This becomes TRUE only when a valid database connection can be
    // established.
    'settings_verified' => FALSE,
    // 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(),
  );
  return $defaults;
}

/**
 * Begin an installation request, modifying the installation state as needed.
 *
 * 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) {
  // Allow command line scripts to override server variables used by Drupal.
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  if (!$install_state['interactive']) {
    drupal_override_server_variables($install_state['server']);
  }

227
  // The user agent header is used to pass a database prefix in the request when
228
  // running tests. However, for security reasons, it is imperative that no
229
  // installation be permitted using such a prefix.
230
  if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], "simpletest") !== FALSE) {
231
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
232
    exit;
233 234
  }

235
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
236

237
  // This must go after drupal_bootstrap(), which unsets globals!
238
  global $conf;
239

240
  require_once DRUPAL_ROOT . '/modules/system/system.install';
241
  require_once DRUPAL_ROOT . '/includes/common.inc';
242
  require_once DRUPAL_ROOT . '/includes/file.inc';
243
  require_once DRUPAL_ROOT . '/includes/path.inc';
244

245
  // Load module basics (needed for hook invokes).
246
  include_once DRUPAL_ROOT . '/includes/module.inc';
247
  include_once DRUPAL_ROOT . '/includes/session.inc';
248 249 250 251

  // Set up $language, so t() caller functions will still work.
  drupal_language_initialize();

252
  include_once DRUPAL_ROOT . '/includes/entity.inc';
253 254
  $module_list['system']['filename'] = 'modules/system/system.module';
  $module_list['filter']['filename'] = 'modules/filter/filter.module';
255
  $module_list['user']['filename'] = 'modules/user/user.module';
256
  module_list(TRUE, FALSE, FALSE, $module_list);
257 258
  drupal_load('module', 'system');
  drupal_load('module', 'filter');
259
  drupal_load('module', 'user');
260

261 262 263 264 265 266 267 268 269
  // Load the cache infrastructure using a "fake" cache implementation that
  // does not attempt to write to the database. We need this during the initial
  // part of the installer because the database is not available yet. We
  // continue to use it even when the database does become available, in order
  // to preserve consistency between interactive and command-line installations
  // (the latter complete in one page request and therefore are forced to
  // continue using the cache implementation they started with) and also
  // because any data put in the cache during the installer is inherently
  // suspect, due to the fact that Drupal is not fully set up yet.
270 271 272 273
  require_once DRUPAL_ROOT . '/includes/cache.inc';
  require_once DRUPAL_ROOT . '/includes/cache-install.inc';
  $conf['cache_inc'] = 'includes/cache.inc';
  $conf['cache_default_class'] = 'DrupalFakeCache';
274

275 276 277 278 279 280
  // Prepare for themed output, if necessary. We need to run this at the
  // beginning of the page request to avoid a different theme accidentally
  // getting set.
  if ($install_state['interactive']) {
    drupal_maintenance_theme();
  }
281

282
  // Check existing settings.php.
283
  $install_state['settings_verified'] = install_verify_settings();
284

285
  if ($install_state['settings_verified']) {
286
    // Initialize the database system. Note that the connection
287
    // won't be initialized until it is actually requested.
288
    require_once DRUPAL_ROOT . '/includes/database/database.inc';
289

290 291
    // Verify the last completed task in the database, if there is one.
    $task = install_verify_completed_task();
292
  }
293 294
  else {
    $task = NULL;
295 296 297 298 299 300 301 302 303

    // Since previous versions of Drupal stored database connection information
    // in the 'db_url' variable, we should never let an installation proceed if
    // this variable is defined and the settings file was not verified above
    // (otherwise we risk installing over an existing site whose settings file
    // has not yet been updated).
    if (!empty($GLOBALS['db_url'])) {
      throw new Exception(install_already_done_error());
    }
304
  }
305

306 307 308 309 310 311 312 313 314 315
  // Modify the installation state as appropriate.
  $install_state['completed_task'] = $task;
  $install_state['database_tables_exist'] = !empty($task);

  // Add any installation parameters passed in via the URL.
  $install_state['parameters'] += $_GET;

  // 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']);
316
  }
317 318
  if (!empty($install_state['parameters']['locale'])) {
    $install_state['parameters']['locale'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['locale']);
319
  }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
}

/**
 * Run all tasks for the current installation request.
 *
 * 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.
 * @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);
      if ($install_state['database_tables_exist'] && ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished'])) {
        drupal_install_initialize_database();
        variable_set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
      }
    }
    // 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;
}

/**
 * Run an individual installation task.
 *
 * @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.
 * @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') {
    require_once DRUPAL_ROOT . '/includes/form.inc';
    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(
394 395 396
        // 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.
397
        'build_info' => array('args' => array(&$install_state)),
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        '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.
      $form_state = array('values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array());
      drupal_form_submit($function, $form_state, $install_state);
      $errors = form_get_errors();
      if (!empty($errors)) {
        throw new Exception(implode("\n", $errors));
      }
    }
422
  }
drumm's avatar
drumm committed
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  elseif ($task['type'] == 'batch') {
    // Start a new batch based on the task function, if one is not running
    // already.
    $current_batch = variable_get('install_current_batch');
    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']) {
        variable_set('install_current_batch', $function);
      }
      else {
        $batch =& batch_get();
        $batch['progressive'] = FALSE;
      }
      // Process the batch. For progressive batches, this will redirect.
      // Otherwise, the batch will complete.
      batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state));
    }
    // 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) {
      include_once DRUPAL_ROOT . '/includes/batch.inc';
      $output = _batch_page();
      // 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.
      if ($output === FALSE) {
        // Return nothing so the next task will run in the same request.
        variable_del('install_current_batch');
        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;
      }
    }
  }
472

473 474 475
  else {
    // For normal tasks, just return the function result, whatever it is.
    return $function($install_state);
drumm's avatar
drumm committed
476
  }
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
}

/**
 * Return a list of tasks to perform during the current installation request.
 *
 * 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.
 * @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;
    }
drumm's avatar
drumm committed
505
  }
506 507
  return $tasks;
}
drumm's avatar
drumm committed
508

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
/**
 * Return a list of all tasks the installer currently knows about.
 *
 * 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.
 * @return
 *   A list of tasks, with associated metadata.
 */
function install_tasks($install_state) {
  // Determine whether translation import tasks will need to be performed.
  $needs_translations = count($install_state['locales']) > 1 && !empty($install_state['parameters']['locale']) && $install_state['parameters']['locale'] != 'en';
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  // Start with the core installation tasks that run before handing control
  // to the install profile.
  $tasks = array(
    'install_select_profile' => array(
      'display_name' => st('Choose profile'),
      'display' => count($install_state['profiles']) != 1,
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_select_locale' => array(
      'display_name' => st('Choose language'),
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_load_profile' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_verify_requirements' => array(
      'display_name' => st('Verify requirements'),
    ),
    'install_settings_form' => array(
      'display_name' => st('Set up database'),
      'type' => 'form',
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    ),
    'install_system_module' => array(
    ),
    'install_bootstrap_full' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_profile_modules' => array(
      'display_name' => count($install_state['profiles']) == 1 ? st('Install site') : st('Install profile'),
      'type' => 'batch',
    ),
    'install_import_locales' => array(
      'display_name' => st('Set up translations'),
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_configure_form' => array(
      'display_name' => st('Configure site'),
      'type' => 'form',
    ),
  );
570

571 572
  // Now add any tasks defined by the installation profile.
  if (!empty($install_state['parameters']['profile'])) {
573
    $function = $install_state['parameters']['profile'] . '_install_tasks';
574 575 576 577 578
    if (function_exists($function)) {
      $result = $function($install_state);
      if (is_array($result)) {
        $tasks += $result;
      }
579
    }
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  }

  // Finish by adding the remaining core tasks.
  $tasks += array(
    'install_import_locales_remaining' => array(
      'display_name' => st('Finish translations'),
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_finished' => array(
      'display_name' => st('Finished'),
    ),
  );

595 596 597 598 599 600 601 602 603 604 605 606
  // Allow the installation profile to modify the full list of tasks.
  if (!empty($install_state['parameters']['profile'])) {
    $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
    if (is_file($profile_file)) {
      include_once $profile_file;
      $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
      if (function_exists($function)) {
        $function($tasks, $install_state);
      }
    }
  }

607 608 609 610 611 612 613 614 615 616 617 618
  // 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;
}
619

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
/**
 * Return a list of tasks that should be displayed to the end user.
 *
 * 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.
 * @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;
}

/**
 * Return the URL that should be redirected to during an installation request.
 *
 * The output of this function is suitable for sending to install_goto().
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The URL to redirect to.
 *
 * @see install_full_redirect_url()
 */
function install_redirect_url($install_state) {
657
  return 'install.php?' . drupal_http_build_query($install_state['parameters']);
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
}

/**
 * Return the complete URL that should be redirected to during an installation
 * request.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @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);
}

/**
 * Display themed installer output and end the page request.
 *
 * 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();
  // 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'];
697
    drupal_add_region_content('sidebar_first', theme('task_list', array('items' => install_tasks_to_display($install_state), 'active' => $active_task)));
698
  }
699
  print theme($install_state['database_tables_exist'] ? 'maintenance_page' : 'install_page', array('content' => $output));
700 701 702 703 704 705 706 707 708 709 710 711 712 713
  exit;
}

/**
 * Installation task; verify the requirements for installing Drupal.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   A themed status report, or an exception if there are requirement errors.
 *   Otherwise, no output is returned, so that the next task can be run
 *   in the same page request.
 */
function install_verify_requirements(&$install_state) {
714 715
  // Check the installation requirements for Drupal and this profile.
  $requirements = install_check_requirements($install_state);
716

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

720 721
  // Check the severity of the requirements reported.
  $severity = drupal_requirements_severity($requirements);
722

723 724 725
  if ($severity == REQUIREMENT_ERROR) {
    if ($install_state['interactive']) {
      drupal_set_title(st('Requirements problem'));
726
      $status_report = theme('status_report', array('requirements' => $requirements));
727
      $status_report .= st('Check the error messages and <a href="!url">proceed with the installation</a>.', array('!url' => request_uri()));
728 729 730 731 732 733 734 735
      return $status_report;
    }
    else {
      // Throw an exception showing all unmet requirements.
      $failures = array();
      foreach ($requirements as $requirement) {
        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
          $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
736 737
        }
      }
738
      throw new Exception(implode("\n\n", $failures));
739
    }
740
  }
741
}
742

743 744 745 746 747 748 749
/**
 * Installation task; install the Drupal system module.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_system_module(&$install_state) {
750 751 752 753 754 755 756 757 758 759 760 761 762
  // Install system.module.
  drupal_install_system();
  // Save the list of other modules to install for the upcoming tasks.
  // variable_set() can be used now that system.module is installed and
  // Drupal is bootstrapped.
  $modules = $install_state['profile_info']['dependencies'];

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

  variable_set('install_profile_modules', array_diff($modules, array('system')));
  $install_state['database_tables_exist'] = TRUE;
763 764 765
}

/**
766 767 768 769 770
 * Verify and return the last installation task that was completed.
 *
 * @return
 *   The last completed task, if there is one. An exception is thrown if Drupal
 *   is already installed.
771
 */
772
function install_verify_completed_task() {
773
  try {
774 775
    if ($result = db_query("SELECT value FROM {variable} WHERE name = :name", array('name' => 'install_task'))) {
      $task = unserialize($result->fetchField());
776 777
    }
  }
778 779
  // Do not trigger an error if the database query fails, since the database
  // might not be set up yet.
780
  catch (Exception $e) {
781
  }
782 783 784 785 786 787
  if (isset($task)) {
    if ($task == 'done') {
      throw new Exception(install_already_done_error());
    }
    return $task;
  }
788 789 790 791 792 793
}

/**
 * Verify existing settings.php
 */
function install_verify_settings() {
794
  global $db_prefix, $databases;
795 796

  // Verify existing settings (if any).
797 798
  if (!empty($databases)) {
    $database = $databases['default']['default'];
799 800
    drupal_static_reset('conf_path');
    $settings_file = './' . conf_path(FALSE) . '/settings.php';
801 802
    $errors = install_database_errors($database, $settings_file);
    if (empty($errors)) {
803 804 805 806 807 808 809
      return TRUE;
    }
  }
  return FALSE;
}

/**
810 811 812 813 814 815 816 817
 * Installation task; define a form to configure and rewrite settings.php.
 *
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The form API definition for the database configuration form.
818
 */
819
function install_settings_form($form, &$form_state, &$install_state) {
820
  global $databases, $db_prefix;
821 822
  $profile = $install_state['parameters']['profile'];
  $install_locale = $install_state['parameters']['locale'];
823

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

drumm's avatar
drumm committed
829
  drupal_set_title(st('Database configuration'));
830

831
  $drivers = drupal_detect_database_types();
832

833
  if (!$drivers) {
834 835 836
    // There is no point submitting the form if there are no database drivers
    // at all, so throw an exception here.
    throw new Exception(st('Your web server does not appear to support any common database types. Check with your hosting provider to see if they offer any databases that <a href="@drupal-databases">Drupal supports</a>.', array('@drupal-databases' => 'http://drupal.org/node/270#database')));
837 838 839 840
  }
  else {
    $form['basic_options'] = array(
      '#type' => 'fieldset',
drumm's avatar
drumm committed
841
      '#title' => st('Basic options'),
842 843
    );

844 845 846 847 848 849 850 851
    $form['basic_options']['driver'] = array(
      '#type' => 'radios',
      '#title' => st('Database type'),
      '#required' => TRUE,
      '#options' => $drivers,
      '#default_value' => !empty($database['driver']) ? $database['driver'] : current(array_keys($drivers)),
      '#description' => st('The type of database your @drupal data will be stored in.', array('@drupal' => drupal_install_profile_name())),
    );
852
    if (count($drivers) == 1) {
853 854
      $form['basic_options']['driver']['#disabled'] = TRUE;
      $form['basic_options']['driver']['#description'] .= ' ' . st('Your PHP configuration only supports the %driver database type so it has been automatically selected.', array('%driver' => current($drivers)));
855 856 857
    }

    // Database name
858
    $form['basic_options']['database'] = array(
859
      '#type' => 'textfield',
drumm's avatar
drumm committed
860
      '#title' => st('Database name'),
861
      '#default_value' => empty($database['database']) ? '' : $database['database'],
862 863
      '#size' => 45,
      '#required' => TRUE,
864
      '#description' => st('The name of the database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('@drupal' => drupal_install_profile_name())),
865 866 867
    );

    // Database username
868
    $form['basic_options']['username'] = array(
869
      '#type' => 'textfield',
drumm's avatar
drumm committed
870
      '#title' => st('Database username'),
871
      '#default_value' => empty($database['username']) ? '' : $database['username'],
872 873 874
      '#size' => 45,
    );

875
    // Database password
876
    $form['basic_options']['password'] = array(
877
      '#type' => 'password',
drumm's avatar
drumm committed
878
      '#title' => st('Database password'),
879
      '#default_value' => empty($database['password']) ? '' : $database['password'],
880 881 882 883 884
      '#size' => 45,
    );

    $form['advanced_options'] = array(
      '#type' => 'fieldset',
drumm's avatar
drumm committed
885
      '#title' => st('Advanced options'),
886 887
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
888
      '#description' => st("These options are only necessary for some sites. If you're not sure what you should enter here, leave the default settings or check with your hosting provider.")
889 890 891
    );

    // Database host
892
    $form['advanced_options']['host'] = array(
893
      '#type' => 'textfield',
drumm's avatar
drumm committed
894
      '#title' => st('Database host'),
895
      '#default_value' => empty($database['host']) ? 'localhost' : $database['host'],
896
      '#size' => 45,
897 898
      // Hostnames can be 255 characters long.
      '#maxlength' => 255,
899
      '#required' => TRUE,
drumm's avatar
drumm committed
900
      '#description' => st('If your database is located on a different server, change this.'),
901 902
    );

903
    // Database port
904
    $form['advanced_options']['port'] = array(
905 906
      '#type' => 'textfield',
      '#title' => st('Database port'),
907
      '#default_value' => empty($database['port']) ? '' : $database['port'],
908
      '#size' => 45,
909 910
      // The maximum port number is 65536, 5 digits.
      '#maxlength' => 5,
911 912 913
      '#description' => st('If your database server is listening to a non-standard port, enter its number.'),
    );

914
    // Table prefix
915
    $db_prefix = ($profile == 'default') ? 'drupal_' : $profile . '_';
916 917
    $form['advanced_options']['db_prefix'] = array(
      '#type' => 'textfield',
918
      '#title' => st('Table prefix'),
919
      '#default_value' => '',
920
      '#size' => 45,
921
      '#description' => st('If more than one application will be sharing this database, enter a table prefix such as %prefix for your @drupal site here.', array('@drupal' => drupal_install_profile_name(), '%prefix' => $db_prefix)),
922 923 924 925
    );

    $form['save'] = array(
      '#type' => 'submit',
926
      '#value' => st('Save and continue'),
927 928 929 930
    );

    $form['errors'] = array();
    $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file);
931
    $form['_database'] = array('#type' => 'value');
932
  }
933
  return $form;
934
}
935

936 937 938
/**
 * Form API validate for install_settings form.
 */
939
function install_settings_form_validate($form, &$form_state) {
940 941 942 943 944
  form_set_value($form['_database'], $form_state['values'], $form_state);
  $errors = install_database_errors($form_state['values'], $form_state['values']['settings_file']);
  foreach ($errors as $name => $message) {
    form_set_error($name, $message);
  }
945 946 947
}

/**
948
 * Check a database connection and return any errors.
949
 */
950
function install_database_errors($database, $settings_file) {
951
  global $databases;
952
  $errors = array();
953
  // Verify the table prefix
954
  if (!empty($database['db_prefix']) && is_string($database['db_prefix']) && !preg_match('/^[A-Za-z0-9_.]+$/', $database['db_prefix'])) {
955
    $errors['db_prefix'] = st('The database table prefix you have entered, %db_prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%db_prefix' => $database['db_prefix']));
956 957
  }

958
  if (!empty($database['port']) && !is_numeric($database['port'])) {
959
    $errors['db_port'] = st('Database port must be a number.');
960 961
  }

962
  // Check database type
963 964 965
  $database_types = drupal_detect_database_types();
  $driver = $database['driver'];
  if (!isset($database_types[$driver])) {
966
    $errors['driver'] = st("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_name(), '%driver' => $database['driver']));
967 968
  }
  else {
969 970
    // Run tasks associated with the database type. Any errors are caught in the
    // calling function
971
    $databases['default']['default'] = $database;
972 973 974 975
    // Just changing the global doesn't get the new information processed.
    // We tell tell the Database class to re-parse $databases.
    Database::parseConnectionInfo();

976 977 978 979
    try {
      db_run_tasks($database['driver']);
    } 
    catch (DatabaseTaskException $e) {
980 981 982 983
      // 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.
      $errors[] = $e->getMessage();
984 985
    }
  }
986
  return $errors;
987 988 989 990 991
}

/**
 * Form API submit for install_settings form.
 */
992
function install_settings_form_submit($form, &$form_state) {
993
  global $install_state;
994

995
  $database = array_intersect_key($form_state['values']['_database'], array_flip(array('driver', 'database', 'username', 'password', 'host', 'port')));
996
  // Update global settings array and save
997 998
  $settings['databases'] = array(
    'value'    => array('default' => array('default' => $database)),
999 1000 1001
    'required' => TRUE,
  );
  $settings['db_prefix'] = array(
1002
    'value'    => $form_state['values']['db_prefix'],
1003 1004 1005
    'required' => TRUE,
  );
  drupal_rewrite_settings($settings);
1006 1007 1008 1009 1010 1011
  // 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;
  $install_state['completed_task'] = install_verify_completed_task();
1012 1013 1014
}

/**
1015 1016 1017
 * Find all .profile files.
 */
function install_find_profiles() {
1018
  return file_scan_directory('./profiles', '/\.profile$/', array('key' => 'name'));
1019 1020 1021
}

/**
1022
 * Installation task; select which profile to install.
1023
 *
1024 1025 1026 1027
 * @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.
1028
 * @return
1029 1030 1031
 *   For interactive installations, a form allowing the profile to be selected,
 *   if the user has a choice that needs to be made. Otherwise, an exception is
 *   thrown if a profile cannot be chosen automatically.
1032
 */
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
function install_select_profile(&$install_state) {
  $install_state['profiles'] += install_find_profiles();
  if (empty($install_state['parameters']['profile'])) {
    // Try to find a profile.
    $profile = _install_select_profile($install_state['profiles']);
    if (empty($profile)) {
      // We still don't have a profile, so display a form for selecting one.
      // Only do this in the case of interactive installations, since this is
      // not a real form with submit handlers (the database isn't even set up
      // yet), rather just a convenience method for setting parameters in the
      // URL.
      if ($install_state['interactive']) {
        include_once DRUPAL_ROOT . '/includes/form.inc';
        drupal_set_title(st('Select an installation profile'));
1047 1048
        $form = drupal_get_form('install_select_profile_form', $install_state['profiles']);
        return drupal_render($form);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
      }
      else {
        throw new Exception(install_no_profile_error());
      }
    }
    else {
      $install_state['parameters']['profile'] = $profile;
    }
  }
}
1059

1060 1061 1062 1063 1064 1065 1066 1067
/**
 * Helper function for automatically selecting an installation profile from a
 * list or from a selection passed in via $_POST.
 */
function _install_select_profile($profiles) {
  if (sizeof($profiles) == 0) {
    throw new Exception(install_no_profile_error());
  }
1068 1069 1070
  // Don't need to choose profile if only one available.
  if (sizeof($profiles) == 1) {
    $profile = array_pop($profiles);
1071 1072
    // TODO: is this right?
    require_once $profile->uri;
1073 1074
    return $profile->name;
  }
1075
  else {
1076
    foreach ($profiles as $profile) {
1077
      if (!empty($_POST['profile']) && ($_POST['profile'] == $profile->name)) {
1078 1079 1080 1081 1082 1083
        return $profile->name;
      }
    }
  }
}

1084 1085
/**
 * Form API array definition for the profile selection form.
1086 1087 1088 1089 1090
 *
 * @param $form_state
 *   Array of metadata about state of form processing.
 * @param $profile_files
 *   Array of .profile files, as returned from file_scan_directory().
1091
 */
1092
function install_select_profile_form($form, &$form_state, $profile_files) {
1093 1094 1095 1096
  $profiles = array();
  $names = array();

  foreach ($profile_files as $profile) {
1097 1098
    // TODO: is this right?
    include_once DRUPAL_ROOT . '/' . $profile->uri;
1099 1100
    
    $details = install_profile_info($profile->name);
1101 1102 1103 1104
    $profiles[$profile->name] = $details;

    // Determine the name of the profile; default to file name if defined name
    // is unspecified.
1105
    $name = isset($details['name']) ? $details['name'] : $profile->name;
1106 1107 1108 1109 1110 1111 1112
    $names[$profile->name] = $name;
  }

  // Display radio buttons alphabetically by human-readable name.
  natcasesort($names);

  foreach ($names as $profile => $name) {
1113 1114 1115
    $form['profile'][$name] = array(
      '#type' => 'radio',
      '#value' => 'default',
1116
      '#return_value' => $profile,
1117
      '#title' => $name,
1118
      '#description' => isset($profiles[$profile]['description']) ? $profiles[$profile]['description'] : '',
1119 1120 1121 1122 1123
      '#parents' => array('profile'),
    );
  }
  $form['submit'] =  array(
    '#type' => 'submit',
1124
    '#value' => st('Save and continue'),
drumm's avatar
drumm committed
1125 1126 1127 1128 1129
  );
  return $form;
}

/**
1130 1131 1132
 * Find all .po files for the current profile.
 */
function install_find_locales($profilename) {
1133
  $locales = file_scan_directory('./profiles/' . $profilename . '/translations', '/\.po$/', array('recurse' => FALSE));
1134 1135 1136 1137 1138
  array_unshift($locales, (object) array('name' => 'en'));
  return $locales;
}

/**
1139
 * Installation task; select which locale to use for the current profile.
drumm's avatar
drumm committed
1140
 *
1141 1142 1143 1144
 * @param $install_state
 *   An array of information about the current installation state. The chosen
 *   locale will be added here, if it was not already selected previously, as
 *   will a list of all available locales.
drumm's avatar
drumm committed
1145
 * @return
1146 1147 1148 1149
 *   For interactive installations, a form or other page output allowing the
 *   locale to be selected or providing information about locale selection, if
 *   a locale has not been chosen. Otherwise, an exception is thrown if a
 *   locale cannot be chosen automatically.
drumm's avatar
drumm committed
1150
 */
1151
function install_select_locale(&$install_state) {
1152
  // Find all available locales.
1153
  $profilename = $install_state['parameters']['profile'];
1154
  $locales = install_find_locales($profilename);
1155 1156
  $install_state['locales'] += $locales;
  if (empty($install_state['parameters']['locale'])) {
1157 1158 1159 1160
    // If only the built-in (English) language is available, and we are using
    // the default profile and performing an interactive installation, inform
    // the user that the installer can be localized. Otherwise we assume the
    // user knows what he is doing.
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    if (count($locales) == 1) {
      if ($profilename == 'default' && $install_state['interactive']) {
        drupal_set_title(st('Choose language'));
        if (!empty($install_state['parameters']['localize'])) {
          $output = '<p>' . st('With the addition of an appropriate translation package, this installer is capable of proceeding in another language of your choice. To install and use Drupal in a language other than English:') . '</p>';
          $output .= '<ul><li>' . st('Determine if <a href="@translations" target="_blank">a translation of this Drupal version</a> is available in your language of choice. A translation is provided via a translation package; each translation package enables the display of a specific version of Drupal in a specific language. Not all languages are available for every version of Drupal.', array('@translations' => 'http://drupal.org/project/translations')) . '</li>';
          $output .= '<li>' . st('If an alternative translation package of your choice is available, download and extract its contents to your Drupal root directory.') . '</li>';
          $output .= '<li>' . st('Return to choose language using the second link below and select your desired language from the displayed list. Reloading the page allows the list to automatically adjust to the presence of new translation packages.') . '</li>';
          $output .= '</ul><p>' . st('Alternatively, to install and use Drupal in English, or to defer the selection of an alternative language until after installation, select the first link below.') . '</p>';
          $output .= '<p>' . st('How should the installation continue?') . '</p>';
          $output .= '<ul><li><a href="install.php?profile=' . $profilename . '&amp;locale=en">' . st('Continue installation in English') . '</a></li><li><a href="install.php?profile=' . $profilename . '">' . st('Return to choose a language') . '</a></li></ul>';
        }
        else {
          $output = '<ul><li><a href="install.php?profile=' . $profilename . '&amp;locale=en">' . st('Install Drupal in English') . '</a></li><li><a href="install.php?profile=' . $profilename . '&amp;localize=true">' . st('Learn how to install Drupal in other languages') . '</a></li></ul>';
        }
        return $output;
1177
      }
1178 1179 1180 1181 1182
      // One language, but not the default profile or not an interactive
      // installation. Assume the user knows what he is doing.
      $locale = current($locales);
      $install_state['parameters']['locale'] = $locale->name;
      return;
1183
    }
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    else {
      // Allow profile to pre-select the language, skipping the selection.
      $function = $profilename . '_profile_details';
      if (function_exists($function)) {
        $details = $function();
        if (isset($details['language'])) {
          foreach ($locales as $locale) {
            if ($details['language'] == $locale->name) {
              $install_state['parameters']['locale'] = $locale->name;
              return;
            }
1195 1196 1197 1198
          }
        }
      }

1199 1200 1201 1202 1203 1204
      if (!empty($_POST['locale'])) {
        foreach ($locales as $locale) {
          if ($_POST['locale'] == $locale->name) {
            $install_state['parameters']['locale'] = $locale->name;
            return;
          }
1205
        }
drumm's avatar
drumm committed
1206 1207
      }

1208 1209 1210 1211 1212
      // We still don't have a locale, so display a form for selecting one.
      // Only do this in the case of interactive installations, since this is
      // not a real form with submit handlers (the database isn't even set up
      // yet), rather just a convenience method for setting parameters in the
      // URL.
1213 1214 1215 1216 1217 1218 1219 1220
      if ($install_state['interactive']) {
        drupal_set_title(st('Choose language'));
        include_once DRUPAL_ROOT . '/includes/form.inc';
        return drupal_render(drupal_get_form('install_select_locale_form', $locales));
      }
      else {
        throw new Exception(st('Sorry, you must select a language to continue the installation.'));
      }
1221 1222
    }
  }
drumm's avatar
drumm committed
1223 1224
}

1225 1226 1227
/**
 * Form API array definition for language selection.
 */
1228
function install_select_locale_form($form, &$form_state, $locales) {
1229
  include_once DRUPAL_ROOT . '/includes/iso.inc';
1230
  $languages = _locale_get_predefined_list();
drumm's avatar
drumm committed
1231 1232 1233 1234
  foreach ($locales as $locale) {
    // Try to use verbose locale name
    $name = $locale->name;
    if (isset($languages[$name])) {
1235
      $name = $languages[$name][0] . (isset($languages[$name][1]) ? ' ' . st('(@language)', array('@language' => $languages[$name][1])) : '');
drumm's avatar
drumm committed
1236 1237 1238 1239
    }
    $form['locale'][$locale->name] = array(
      '#type' => 'radio',
      '#return_value' => $locale->name,
1240
      '#default_value' => $locale->name == 'en',
1241
      '#title' => $name . ($locale->name == 'en' ? ' ' . st('(built-in)') : ''),
drumm's avatar
drumm committed
1242 1243 1244 1245 1246
      '#parents' => array('locale')
    );
  }
  $form['submit'] =  array(
    '#type' => 'submit',
1247
    '#value' => st('Select language'),
1248 1249 1250 1251
  );
  return $form;
}

1252
/**
1253
 * Indicate that there are no profiles available.
1254 1255
 */
function install_no_profile_error() {
drumm's avatar
drumm committed
1256
  drupal_set_title(st('No profiles available'));
1257
  return st('We were unable to find any installation profiles. Installation profiles tell us what modules to enable and what schema to install in the database. A profile is necessary to continue with the installation process.');
1258 1259 1260
}

/**
1261
 * Indicate that Drupal has already been installed.
1262 1263
 */
function install_already_done_error() {
1264 1265
  global $base_url;

drumm's avatar
drumm committed
1266
  drupal_set_title(st('Drupal already installed'));
1267
  return st('<ul><li>To start over, you must empty your existing database.</li><li>To install to a different database, edit the appropriate <em>settings.php</em> file in the <em>sites</em> folder.</li><li>To upgrade an existing installation, proceed to the <a href="@base-url/update.php">update script</a>.</li><li>View your <a href="@base-url">existing site</a>.</li></ul>', array('@base-url' => $base_url));
1268 1269 1270
}

/**
1271 1272 1273 1274 1275 1276
 * Installation task; load information about the chosen profile.
 *
 * @param $install_state
 *   An array of information about the current installation state. The loaded
 *   profile information will be added here, or an exception will be thrown if
 *   the profile cannot be loaded.
1277
 */
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
function install_load_profile(&$install_state) {
  $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
  if (is_file($profile_file)) {
    include_once $profile_file;
    $install_state['profile_info'] = install_profile_info($install_state['parameters']['profile'], $install_state['parameters']['locale']);
  }
  else {
    throw new Exception(st('Sorry, the profile you have chosen cannot be loaded.'));
  }
}
1288

1289 1290 1291 1292 1293 1294 1295
/**
 * Installation task; perform a full bootstrap of Drupal.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_bootstrap_full(&$install_state) {
1296
  // Bootstrap newly installed Drupal, while preserving existing messages.
1297
  $messages = isset($_SESSION['messages']) ? $_SESSION['messages'] : '';
1298
  drupal_install_initialize_database();
1299

1300
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
1301
  $_SESSION['messages'] = $messages;
1302
}
1303

1304 1305 1306 1307 1308 1309 1310 1311 1312
/**
 * Installation task; install required modules via a batch process.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The batch definition.
 */
function install_profile_modules(&$install_state) {
1313
  $modules = variable_get('install_profile_modules', array());
1314
  $files = system_rebuild_module_data();
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
  variable_del('install_profile_modules');
  $operations = array();
  foreach ($modules as $module) {
    $operations[] = array('_install_module_batch', array($module, $files[$module]->info['name']));
  }
  $batch = array(
    'operations' => $operations,
    'title' => st('Installing @drupal', array('@drupal' => drupal_install_profile_name())),
    'error_message' => st('The installation has encountered an error.'),
  );
  return $batch;
1326
}
1327

1328 1329 1330 1331 1332 1333 1334 1335 1336
/**
 * Installation task; import languages via a batch process.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The batch definition, if there are language files to import.
 */
function install_import_locales(&$install_state) {
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  include_once DRUPAL_ROOT . '/includes/locale.inc';
  $install_locale = $install_state['parameters']['locale'];
  // Enable installation language as default site language.
  locale_add_language($install_locale, NULL, NULL, NULL, '', NULL, 1, TRUE);
  // Collect files to import for this language.
  $batch = locale_batch_by_language($install_locale, NULL);
  if (!empty($batch)) {
    // Remember components we cover in this batch set.
    variable_set('install_locale_batch_components', $batch['#components']);
    return $batch;
  }
1348
}
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
/**
 * Installation task; configure settings for the new site.
 *
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The form API definition for the site configuration form.
 */
1360
function install_configure_form($form, &$form_state, &$install_state) {
1361
  if (variable_get('site_name', FALSE) || variable_get('site_mail', FALSE)) {
1362 1363 1364
    // Site already configured: This should never happen, means re-running the
    // installer, possibly by an attacker after the 'install_task' variable got
    // accidentally blown somewhere. Stop it now.
1365 1366
    throw new Exception(install_already_done_error());
  }
1367

1368
  drupal_set_title(st('Configure site'));
1369

1370 1371 1372 1373
  // Warn about settings.php permissions risk
  $settings_dir = './' . conf_path();
  $settings_file = $settings_dir . '/settings.php';
  if (!drupal_verify_install_file($settings_file, FILE_EXIST|FILE_READABLE|FILE_NOT_WRITABLE) || !drupal_verify_install_file($settings_dir, FILE_NOT_WRITABLE, 'dir')) {
1374
    drupal_set_message(st('All necessary changes to %dir and %file have been made, so you should remove write permissions to them now in order to avoid security risks. If you are unsure how to do so, consult the <a href="@handbook_url">online handbook</a>.', array('%dir' => $settings_dir, '%file' => $settings_file, '@handbook_url' => 'http://drupal.org/server-permissions')), 'error');
1375 1376 1377 1378
  }
  else {
    drupal_set_message(st('All necessary changes to %dir and %file have been made. They have been set to read-only for security.', array('%dir' => $settings_dir, '%file' => $settings_file)));
  }
1379

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
  // Add JavaScript validation.
  _user_password_dynamic_validation();
  drupal_add_js(drupal_get_path('module', 'system') . '/system.js');
  // Add JavaScript time zone detection.
  drupal_add_js('misc/timezone.js');
  // We add these strings as settings because JavaScript translation does not
  // work on install time.
  drupal_add_js(array('copyFieldValue' => array('edit-site-mail' => array('edit-account-mail'))), 'setting');
  drupal_add_js('jQuery(function () { Drupal.cleanURLsInstallCheck(); });', 'inline');
  // Add JS to show / hide the 'Email administrator about site updates' elements
  drupal_add_js('jQuery(function () { Drupal.hideEmailAdministratorCheckbox() });', 'inline');
  // Build menu to allow clean URL check.
  menu_rebuild();
1393

1394 1395 1396 1397 1398
  // Cache a fully-built schema. This is necessary for any invocation of
  // index.php because: (1) setting cache table entries requires schema
  // information, (2) that occurs during bootstrap before any module are
  // loaded, so (3) if there is no cached schema, drupal_get_schema() will
  // try to generate one but with no loaded modules will return nothing.
1399
  //
1400 1401
  // This logically could be done during the 'install_finished' task, but the
  // clean URL check requires it now.
1402
  drupal_get_schema(NULL, TRUE);
1403

1404
  // Return the form.
1405
  return _install_configure_form($form, $form_state, $install_state);
1406
}
1407

1408 1409 1410 1411 1412 1413 1414 1415 1416
/**
 * Installation task; import remaining languages via a batch process.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 * @return
 *   The batch definition, if there are language files to import.
 */
function install_import_locales_remaining(&$install_state) {
1417