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

3 4 5 6 7
/**
 * @file
 * API functions for installing Drupal.
 */

8
use Drupal\Component\Utility\UrlHelper;
9 10 11 12
use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\ConfigImporterException;
use Drupal\Core\Config\Importer\ConfigImporterBatch;
13
use Drupal\Core\Config\FileStorage;
14
use Drupal\Core\Config\StorageComparer;
katbailey's avatar
katbailey committed
15
use Drupal\Core\DrupalKernel;
16
use Drupal\Core\Database\Database;
17
use Drupal\Core\Database\DatabaseExceptionWrapper;
18
use Drupal\Core\File\FileSystemInterface;
19
use Drupal\Core\Form\FormState;
20 21 22
use Drupal\Core\Installer\Exception\AlreadyInstalledException;
use Drupal\Core\Installer\Exception\InstallerException;
use Drupal\Core\Installer\Exception\NoProfilesException;
23
use Drupal\Core\Installer\InstallerKernel;
24
use Drupal\Core\Language\Language;
25
use Drupal\Core\Language\LanguageManager;
26
use Drupal\Core\Logger\LoggerChannelFactory;
27
use Drupal\Core\Site\Settings;
28
use Drupal\Core\StringTranslation\Translator\FileTranslation;
29
use Drupal\Core\StackMiddleware\ReverseProxyMiddleware;
30
use Drupal\Core\Extension\ExtensionDiscovery;
31
use Drupal\Core\DependencyInjection\ContainerBuilder;
32
use Drupal\Core\Url;
33
use Drupal\language\Entity\ConfigurableLanguage;
34
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
35
use Symfony\Component\DependencyInjection\Reference;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\Response;
38
use Symfony\Component\Routing\Route;
39
use Drupal\user\Entity\User;
40
use GuzzleHttp\Exception\RequestException;
41

42
/**
43
 * Do not run the task during the current installation request.
44 45 46 47 48 49 50 51 52
 *
 * 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.
 */
53
const INSTALL_TASK_SKIP = 1;
54 55

/**
56
 * Run the task on each installation request that reaches it.
57 58 59
 *
 * This is primarily used by the Drupal installer for bootstrap-related tasks.
 */
60
const INSTALL_TASK_RUN_IF_REACHED = 2;
61 62

/**
63
 * Run the task on each installation request until the database is set up.
64 65 66 67 68 69 70 71
 *
 * 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.
 */
72
const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
73 74

/**
75
 * Installs Drupal either interactively or via an array of passed-in settings.
76 77 78 79 80 81 82 83 84
 *
 * 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).
 *
85 86 87 88
 * @param $class_loader
 *   The class loader. Normally Composer's ClassLoader, as included by the
 *   front controller, but may also be decorated; e.g.,
 *   \Symfony\Component\ClassLoader\ApcClassLoader.
89 90 91 92 93 94 95 96
 * @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.
97 98 99
 * @param callable $callback
 *   (optional) A callback to allow command line processes to update a progress
 *   bar. The callback is passed the $install_state variable.
100 101 102
 *
 * @see install_state_defaults()
 */
103
function install_drupal($class_loader, $settings = [], callable $callback = NULL) {
104 105 106 107 108
  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);
109
  $install_state = $settings + ['interactive' => $interactive] + install_state_defaults();
110

111 112 113
  try {
    // Begin the page request. This adds information about the current state of
    // the Drupal installation to the passed-in array.
114
    install_begin_request($class_loader, $install_state);
115 116
    // Based on the installation state, run the remaining tasks for this page
    // request, and collect any output.
117
    $output = install_run_tasks($install_state, $callback);
118 119 120 121 122 123
  }
  catch (InstallerException $e) {
    // In the non-interactive installer, exceptions are always thrown directly.
    if (!$install_state['interactive']) {
      throw $e;
    }
124
    $output = [
125 126
      '#title' => $e->getTitle(),
      '#markup' => $e->getMessage(),
127
    ];
128
  }
129

130 131 132 133 134 135 136
  // 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'])) {
137
    unset($GLOBALS['install_state']);
138 139 140
    // If installation is finished ensure any further container rebuilds do not
    // use the installer's service provider.
    unset($GLOBALS['conf']['container_service_providers']['InstallerServiceProvider']);
141 142
  }

143 144 145
  // 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.
146
  if ($state['interactive']) {
147
    // If a session has been initiated in this request, make sure to save it.
148 149
    if (\Drupal::request()->hasSession()) {
      \Drupal::request()->getSession()->save();
150
    }
151
    if ($state['parameters_changed']) {
152
      // Redirect to the correct page if the URL parameters have changed.
153
      install_goto(install_redirect_url($state));
154 155 156 157 158
    }
    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.
159
      install_display_output($output, $state);
160
    }
161 162
    elseif ($state['installation_finished']) {
      // Redirect to the newly installed site.
163 164 165 166 167
      $finish_url = '';
      if (isset($install_state['profile_info']['distribution']['install']['finish_url'])) {
        $finish_url = $install_state['profile_info']['distribution']['install']['finish_url'];
      }
      install_goto($finish_url);
168
    }
169 170 171 172
  }
}

/**
173
 * Returns an array of default settings for the global installation state.
174 175 176 177 178 179 180 181
 *
 * 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
182
 * 'langcode' that are normally passed in via the URL) and 'forms' (which can
183 184
 * be used to programmatically submit forms during the installation; the keys
 * of each element indicate the name of the installation task that the form
185
 * submission is for, and the values are used as the $form_state->getValues()
186 187
 * array that is passed on to the form submission via
 * \Drupal::formBuilder()->submitForm()).
188
 *
189
 * @see \Drupal\Core\Form\FormBuilderInterface::submitForm()
190 191
 */
function install_state_defaults() {
192
  $defaults = [
193 194 195 196 197
    // The current task being processed.
    'active_task' => NULL,
    // The last task that was completed during the previous installation
    // request.
    'completed_task' => NULL,
198 199 200 201
    // Partial configuration cached during an installation from existing config.
    'config' => NULL,
    // The path to the configuration to install when installing from config.
    'config_install_path' => NULL,
202
    // TRUE when there are valid config directories.
203
    'config_verified' => FALSE,
204
    // TRUE when there is a valid database connection.
205
    'database_verified' => FALSE,
206 207
    // TRUE if database is empty & ready to install.
    'database_ready' => FALSE,
208 209 210 211 212
    // 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,
213 214 215
    // Whether a translation file for the selected language will be downloaded
    // from the translation server.
    'download_translation' => FALSE,
216 217 218
    // 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
219
    // used as the $form_state->getValues() array that is passed on to the form
220
    // submission via \Drupal::formBuilder()->submitForm().
221
    'forms' => [],
222 223 224 225 226 227 228 229 230 231 232 233 234
    // 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)
235
    // and 'langcode' (the code of the chosen installation language), since
236 237
    // these settings need to persist from page request to page request before
    // the database is available for storage.
238
    'parameters' => [],
239 240 241 242 243
    // 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
244
    // be filled in based on the profile's .info.yml file.
245
    'profile_info' => [],
246
    // An array of available installation profiles.
247
    'profiles' => [],
248 249
    // The name of the theme to use during installation.
    'theme' => 'seven',
250 251 252 253
    // 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',
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    // 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.
275
    'tasks_performed' => [],
276 277
    // An array of translation files URIs available for the installation. Keyed
    // by the translation language code.
278 279
    'translations' => [],
  ];
280 281 282 283
  return $defaults;
}

/**
284
 * Begins an installation request, modifying the installation state as needed.
285 286 287 288
 *
 * This function performs commands that must run at the beginning of every page
 * request. It throws an exception if the installation should not proceed.
 *
289 290 291 292
 * @param $class_loader
 *   The class loader. Normally Composer's ClassLoader, as included by the
 *   front controller, but may also be decorated; e.g.,
 *   \Symfony\Component\ClassLoader\ApcClassLoader.
293 294 295
 * @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.
296 297
 *
 * @see install_drupal()
298
 */
299
function install_begin_request($class_loader, &$install_state) {
300 301
  $request = Request::createFromGlobals();

302
  // Add any installation parameters passed in via the URL.
303
  if ($install_state['interactive']) {
304
    $install_state['parameters'] += $request->query->all();
305
  }
306 307 308 309 310

  // 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']);
  }
311 312
  if (!empty($install_state['parameters']['langcode'])) {
    $install_state['parameters']['langcode'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['langcode']);
313 314
  }

315
  // Allow command line scripts to override server variables used by Drupal.
316
  require_once __DIR__ . '/bootstrap.inc';
317

318
  // If the hash salt leaks, it becomes possible to forge a valid testing user
319 320 321 322
  // agent, install a new copy of Drupal, and take over the original site.
  // The user agent header is used to pass a database prefix in the request when
  // running tests. However, for security reasons, it is imperative that no
  // installation be permitted using such a prefix.
323 324
  $user_agent = $request->cookies->get('SIMPLETEST_USER_AGENT') ?: $request->server->get('HTTP_USER_AGENT');
  if ($install_state['interactive'] && strpos($user_agent, 'simpletest') !== FALSE && !drupal_valid_test_ua()) {
325
    header($request->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
326 327
    exit;
  }
328 329 330 331 332 333 334 335
  if ($install_state['interactive'] && drupal_valid_test_ua()) {
    // Set the default timezone. While this doesn't cause any tests to fail, PHP
    // complains if 'date.timezone' is not set in php.ini. The Australia/Sydney
    // timezone is chosen so all tests are run using an edge case scenario
    // (UTC+10  and DST). This choice is made to prevent timezone related
    // regressions and reduce the fragility of the testing system in general.
    date_default_timezone_set('Australia/Sydney');
  }
336

337
  $site_path = empty($install_state['site_path']) ? DrupalKernel::findSitePath($request, FALSE) : $install_state['site_path'];
338
  Settings::initialize(dirname(__DIR__, 2), $site_path, $class_loader);
339

340 341
  // Ensure that procedural dependencies are loaded as early as possible,
  // since the error/exception handlers depend on them.
342 343 344 345 346
  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';
347 348
  require_once __DIR__ . '/form.inc';
  require_once __DIR__ . '/batch.inc';
349 350

  // Load module basics (needed for hook invokes).
351
  include_once __DIR__ . '/module.inc';
352

353 354 355 356 357 358 359 360
  // Create a minimal mocked container to support calls to t() in the pre-kernel
  // base system verification code paths below. The strings are not actually
  // used or output for these calls.
  // @todo Separate API level checks from UI-facing error messages.
  $container = new ContainerBuilder();
  $container->setParameter('language.default_values', Language::$defaultValues);
  $container
    ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
361
    ->addArgument('%language.default_values%');
362 363
  $container
    ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
364
    ->addArgument(new Reference('language.default'));
365

366 367 368
  // Register the stream wrapper manager.
  $container
    ->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
369
    ->addMethodCall('setContainer', [new Reference('service_container')]);
370 371 372 373 374
  $container
    ->register('file_system', 'Drupal\Core\File\FileSystem')
    ->addArgument(new Reference('stream_wrapper_manager'))
    ->addArgument(Settings::getInstance())
    ->addArgument((new LoggerChannelFactory())->get('file'));
375

376 377 378 379 380
  // Register the class loader so contrib and custom database drivers can be
  // autoloaded.
  // @see drupal_get_database_types()
  $container->set('class_loader', $class_loader);

381
  \Drupal::setContainer($container);
382

383
  // Determine whether base system services are ready to operate.
384
  try {
385
    $sync_directory = Settings::get('config_sync_directory', FALSE);
386 387 388 389 390
    $install_state['config_verified'] = file_exists($sync_directory);
  }
  catch (Exception $e) {
    $install_state['config_verified'] = FALSE;
  }
391
  $install_state['database_verified'] = install_verify_database_settings($site_path);
392
  // A valid settings.php has database settings and a hash_salt value. Other
393
  // settings will be checked by system_requirements().
394
  $install_state['settings_verified'] = $install_state['database_verified'] && (bool) Settings::get('hash_salt', FALSE);
395

396 397 398 399 400 401 402
  // Install factory tables only after checking the database.
  if ($install_state['database_verified'] && $install_state['database_ready']) {
    $container
      ->register('path.matcher', 'Drupal\Core\Path\PathMatcher')
      ->addArgument(new Reference('config.factory'));
  }

403
  if ($install_state['settings_verified']) {
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    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.
    }
  }

419 420 421 422 423
  // Replace services with in-memory and null implementations. This kernel is
  // replaced with a regular one in drupal_install_system().
  if (!$install_state['base_system_verified']) {
    $environment = 'install';
    $GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\InstallerServiceProvider';
424 425
  }
  else {
426
    $environment = 'prod';
427
    $GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\NormalInstallerServiceProvider';
428
  }
429
  $GLOBALS['conf']['container_service_providers']['InstallerConfigOverride'] = 'Drupal\Core\Installer\ConfigOverride';
430

431
  // Note, InstallerKernel::createFromRequest() is not used because Settings is
432
  // already initialized.
433
  $kernel = new InstallerKernel($environment, $class_loader, FALSE);
434
  $kernel::bootEnvironment();
435
  $kernel->setSitePath($site_path);
436 437
  $kernel->boot();
  $container = $kernel->getContainer();
438 439
  // If Drupal is being installed behind a proxy, configure the request.
  ReverseProxyMiddleware::setSettingsOnRequest($request, Settings::getInstance());
440

441
  // Register the file translation service.
442 443
  if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
    $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
444
  }
445
  else {
446
    $directory = $site_path . '/files/translations';
447
  }
448 449 450
  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
  $file_system = $container->get('file_system');
  $container->set('string_translator.file_translation', new FileTranslation($directory, $file_system));
451 452
  $container->get('string_translation')
    ->addTranslator($container->get('string_translator.file_translation'));
453

454
  // Add list of all available profiles to the installation state.
455
  $listing = new ExtensionDiscovery($container->getParameter('app.root'));
456
  $listing->setProfileDirectories([]);
457 458 459 460
  $install_state['profiles'] += $listing->scan('profile');

  // Prime drupal_get_filename()'s static cache.
  foreach ($install_state['profiles'] as $name => $profile) {
461
    drupal_get_filename('profile', $name, $profile->getPathname());
462 463 464
    // drupal_get_filename() is called both with 'module' and 'profile', see
    // \Drupal\Core\Config\ConfigInstaller::getProfileStorages for example.
    drupal_get_filename('module', $name, $profile->getPathname());
465
  }
466

467 468 469 470 471 472 473 474
  if ($profile = _install_select_profile($install_state)) {
    $install_state['parameters']['profile'] = $profile;
    install_load_profile($install_state);
    if (isset($install_state['profile_info']['distribution']['install']['theme'])) {
      $install_state['theme'] = $install_state['profile_info']['distribution']['install']['theme'];
    }
  }

475 476 477 478 479 480
  // Before having installed the system module and being able to do a module
  // rebuild, prime the drupal_get_filename() static cache with the system
  // module's location.
  // @todo Remove as part of https://www.drupal.org/node/2186491
  drupal_get_filename('module', 'system', 'core/modules/system/system.info.yml');

481 482 483 484 485 486 487
  // Use the language from profile configuration if available.
  if (!empty($install_state['config_install_path']) && $install_state['config']['system.site']) {
    $install_state['parameters']['langcode'] = $install_state['config']['system.site']['default_langcode'];
  }
  elseif (isset($install_state['profile_info']['distribution']['langcode'])) {
    // Otherwise, Use the language from the profile configuration, if available,
    // to override the language previously set in the parameters.
488 489 490 491 492
    $install_state['parameters']['langcode'] = $install_state['profile_info']['distribution']['langcode'];
  }

  // Set the default language to the selected language, if any.
  if (isset($install_state['parameters']['langcode'])) {
493
    $default_language = new Language(['id' => $install_state['parameters']['langcode']]);
494 495 496 497
    $container->get('language.default')->set($default_language);
    \Drupal::translation()->setDefaultLangcode($install_state['parameters']['langcode']);
  }

498 499 500
  // Override the module list with a minimal set of modules.
  $module_handler = \Drupal::moduleHandler();
  if (!$module_handler->moduleExists('system')) {
501
    $module_handler->addModule('system', 'core/modules/system');
502 503
  }
  if ($profile && !$module_handler->moduleExists($profile)) {
504
    $module_handler->addProfile($profile, $install_state['profiles'][$profile]->getPath());
505 506
  }

507 508 509 510 511 512 513 514
  // Load all modules and perform request related initialization.
  $kernel->preHandle($request);

  // Initialize a route on this legacy request similar to
  // \Drupal\Core\DrupalKernel::prepareLegacyRequest() since normal routing
  // will not happen.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
515

516 517 518 519 520 521
  // 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();
522

523
  if ($install_state['database_verified']) {
524 525 526 527 528 529
    // Verify the last completed task in the database, if there is one.
    $task = install_verify_completed_task();
  }
  else {
    $task = NULL;

530
    // Do not install over a configured settings.php.
531
    if (Database::getConnectionInfo()) {
532
      throw new AlreadyInstalledException($container->get('string_translation'));
533 534 535
    }
  }

536
  // Ensure that the active configuration is empty before installation starts.
537
  if ($install_state['config_verified'] && empty($task)) {
538
    if (count($kernel->getConfigStorage()->listAll())) {
539
      $task = NULL;
540
      throw new AlreadyInstalledException($container->get('string_translation'));
541 542 543
    }
  }

544 545 546 547 548
  // Modify the installation state as appropriate.
  $install_state['completed_task'] = $task;
}

/**
549
 * Runs all tasks for the current installation request.
550 551 552 553 554 555 556 557 558
 *
 * 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.
559 560 561
 * @param callable $callback
 *   (optional) A callback to allow command line processes to update a progress
 *   bar. The callback is passed the $install_state variable.
562
 *
563 564 565
 * @return
 *   HTML output from the last completed task.
 */
566
function install_run_tasks(&$install_state, callable $callback = NULL) {
567 568 569 570 571 572 573 574 575 576 577 578 579 580
  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);
581 582 583 584 585
    // Ensure the maintenance theme is initialized. If the install task has
    // rebuilt the container the active theme will not be set. This can occur if
    // the task has installed a module.
    drupal_maintenance_theme();

586 587 588 589 590 591 592 593
    $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);
594
      if ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished']) {
595
        \Drupal::state()->set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
596 597
      }
    }
598 599 600
    if ($callback) {
      $callback($install_state);
    }
601 602 603 604 605 606 607 608 609 610
    // 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;
}

/**
611
 * Runs an individual installation task.
612 613
 *
 * @param $task
614
 *   An array of information about the task to be run as returned by
615
 *   hook_install_tasks().
616 617 618
 * @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.
619
 *
620 621 622 623 624 625 626
 * @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') {
627
    return install_get_form($function, $install_state);
628 629 630 631
  }
  elseif ($task['type'] == 'batch') {
    // Start a new batch based on the task function, if one is not running
    // already.
632
    $current_batch = \Drupal::state()->get('install_current_batch');
633
    if (!$install_state['interactive'] || !$current_batch) {
634 635
      $batches = $function($install_state);
      if (empty($batches)) {
636 637 638 639
        // If the task did some processing and decided no batch was necessary,
        // there is nothing more to do here.
        return;
      }
640 641
      // Create a one item list of batches if only one batch was provided.
      if (isset($batches['operations'])) {
642
        $batches = [$batches];
643
      }
644 645 646 647 648 649 650 651 652 653 654 655
      foreach ($batches as $batch) {
        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']) {
          \Drupal::state()->set('install_current_batch', $function);
        }
        else {
          $batch =& batch_get();
          $batch['progressive'] = FALSE;
        }
656 657 658
      }
      // Process the batch. For progressive batches, this will redirect.
      // Otherwise, the batch will complete.
659 660
      // Disable the default script for the URL and clone the object, as
      // batch_process() will add additional options to the batch URL.
661
      $url = Url::fromUri('base:install.php', ['query' => $install_state['parameters'], 'script' => '']);
662
      $response = batch_process($url, clone $url);
663
      if ($response instanceof Response) {
664 665
        if (\Drupal::request()->hasSession()) {
          \Drupal::request()->getSession()->save();
666
        }
667 668 669 670
        // Send the response.
        $response->send();
        exit;
      }
671 672 673 674
    }
    // 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) {
675
      $output = _batch_page(\Drupal::request());
676
      // Because Batch API now returns a JSON response for intermediary steps,
677 678 679 680
      // 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.
681 682
      if ($output instanceof Response) {
        $output->send();
683
        $output = NULL;
684
      }
685 686 687
      // 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.
688
      if ($output === FALSE) {
689
        // Return nothing so the next task will run in the same request.
690
        \Drupal::state()->delete('install_current_batch');
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
        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);
  }
}

/**
710
 * Returns a list of tasks to perform during the current installation request.
711 712 713 714 715 716 717
 *
 * 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.
718
 *
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
 * @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;
}

/**
741
 * Returns a list of all tasks the installer currently knows about.
742 743 744 745 746 747 748
 *
 * 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).
 *
749 750
 * You can override this using hook_install_tasks() or
 * hook_install_tasks_alter().
751
 *
752 753
 * @param $install_state
 *   An array of information about the current installation state.
754
 *
755
 * @return
756 757
 *   A list of tasks, with associated metadata as returned by
 *   hook_install_tasks().
758 759
 */
function install_tasks($install_state) {
760 761
  // Determine whether a translation file must be imported during the
  // 'install_import_translations' task. Import when a non-English language is
762 763
  // available and selected. Also we will need translations even if the
  // installer language is English but there are other languages on the system.
764 765
  $locale_module_installed = \Drupal::moduleHandler()->moduleExists('locale');
  $needs_translations = $locale_module_installed && ((count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en') || \Drupal::languageManager()->isMultilingual());
766 767 768 769
  // 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';
770

771
  // Start with the core installation tasks that run before handing control
772
  // to the installation profile.
773 774
  $tasks = [
    'install_select_language' => [
775
      'display_name' => t('Choose language'),
776
      'run' => INSTALL_TASK_RUN_IF_REACHED,
777 778
    ],
    'install_download_translation' => [
779
      'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
780 781
    ],
    'install_select_profile' => [
782
      'display_name' => t('Choose profile'),
783
      'display' => empty($install_state['profile_info']['distribution']['name']) && count($install_state['profiles']) != 1,
784
      'run' => INSTALL_TASK_RUN_IF_REACHED,
785 786
    ],
    'install_load_profile' => [
787
      'run' => INSTALL_TASK_RUN_IF_REACHED,
788 789
    ],
    'install_verify_requirements' => [
790
      'display_name' => t('Verify requirements'),
791 792
    ],
    'install_settings_form' => [
793
      'display_name' => t('Set up database'),
794
      'type' => 'form',
795 796 797
      // 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.
798
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
799
      'function' => 'Drupal\Core\Installer\Form\SiteSettingsForm',
800 801
    ],
    'install_verify_database_ready' => [
802
      'run' => $install_state['database_ready'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
803 804
    ],
    'install_base_system' => [
805
      'run' => $install_state['base_system_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
806
    ],
807
    // All tasks below are executed in a regular, full Drupal environment.
808
    'install_bootstrap_full' => [
809
      'run' => INSTALL_TASK_RUN_IF_REACHED,
810 811
    ],
    'install_profile_modules' => [
812
      'display_name' => t('Install site'),
813
      'type' => 'batch',
814
    ],
815 816
    'install_profile_themes' => [],
    'install_install_profile' => [],
817
    'install_import_translations' => [
818
      'display_name' => t('Set up translations'),
819 820 821
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
822 823
    ],
    'install_configure_form' => [
824
      'display_name' => t('Configure site'),
825
      'type' => 'form',
826
      'function' => 'Drupal\Core\Installer\Form\SiteConfigureForm',
827 828
    ],
  ];
829

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
  if (!empty($install_state['config_install_path'])) {
    // The chosen profile indicates that rather than installing a new site, an
    // instance of the same site should be installed from the given
    // configuration.
    // That means we need to remove the steps installing the extensions and
    // replace them with a configuration synchronization step.
    unset($tasks['install_download_translation']);
    $key = array_search('install_profile_modules', array_keys($tasks), TRUE);
    unset($tasks['install_profile_modules']);
    unset($tasks['install_profile_themes']);
    unset($tasks['install_install_profile']);
    $config_tasks = [
      'install_config_import_batch' => [
        'display_name' => t('Install configuration'),
        'type' => 'batch',
      ],
      'install_config_download_translations' => [],
      'install_config_revert_install_changes' => [],
    ];
    $tasks = array_slice($tasks, 0, $key, TRUE) +
      $config_tasks +
      array_slice($tasks, $key, NULL, TRUE);
  }

854 855
  // Now add any tasks defined by the installation profile.
  if (!empty($install_state['parameters']['profile'])) {
856 857
    // Load the profile install file, because it is not always loaded when
    // hook_install_tasks() is invoked (e.g. batch processing).
858
    $profile = $install_state['parameters']['profile'];
859
    $profile_install_file = $install_state['profiles'][$profile]->getPath() . '/' . $profile . '.install';
860
    if (file_exists($profile_install_file)) {
861
      include_once \Drupal::root() . '/' . $profile_install_file;
862
    }
863 864 865 866 867 868 869 870 871 872
    $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.
873 874
  $tasks += [
    'install_finish_translations' => [
875
      'display_name' => t('Finish translations'),
876 877 878
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
879
    ],
880
    'install_finished' => [],
881
  ];
882 883 884

  // Allow the installation profile to modify the full list of tasks.
  if (!empty($install_state['parameters']['profile'])) {
885
    $profile = $install_state['parameters']['profile'];
886
    if ($install_state['profiles'][$profile]->load()) {
887 888 889 890 891 892 893 894 895
      $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) {
896
    $task += [
897 898 899 900 901
      'display_name' => NULL,
      'display' => !empty($task['display_name']),
      'type' => 'normal',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
      'function' => $task_name,
902
    ];
903 904 905 906 907
  }
  return $tasks;
}

/**
908
 * Returns a list of tasks that should be displayed to the end user.
909 910
 *
 * The output of this function is a list suitable for sending to
911
 * maintenance-task-list.html.twig.
912 913 914
 *
 * @param $install_state
 *   An array of information about the current installation state.
915
 *
916 917 918 919
 * @return
 *   A list of tasks, with keys equal to the machine-readable task name and
 *   values equal to the name that should be displayed.
 *
920
 * @see maintenance-task-list.html.twig
921 922
 */
function install_tasks_to_display($install_state) {
923
  $displayed_tasks = [];
924 925 926 927 928 929 930 931
  foreach (install_tasks($install_state) as $name => $task) {
    if ($task['display']) {
      $displayed_tasks[$name] = $task['display_name'];
    }
  }
  return $displayed_tasks;
}

932 933 934 935 936 937 938