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

3
use Drupal\Component\Utility\SafeMarkup;
4
use Drupal\Component\Utility\UrlHelper;
katbailey's avatar
katbailey committed
5
use Drupal\Core\DrupalKernel;
6
use Drupal\Core\Config\BootstrapConfigStorageFactory;
7
use Drupal\Core\Database\Database;
8
use Drupal\Core\Database\DatabaseExceptionWrapper;
9
use Drupal\Core\Database\Install\TaskException;
10
use Drupal\Core\Form\FormState;
11
12
13
use Drupal\Core\Installer\Exception\AlreadyInstalledException;
use Drupal\Core\Installer\Exception\InstallerException;
use Drupal\Core\Installer\Exception\NoProfilesException;
14
use Drupal\Core\Installer\InstallerKernel;
15
use Drupal\Core\Language\Language;
16
use Drupal\Core\Language\LanguageManager;
17
use Drupal\Core\Site\Settings;
18
use Drupal\Core\StringTranslation\Translator\FileTranslation;
19
use Drupal\Core\Extension\ExtensionDiscovery;
20
use Drupal\Core\DependencyInjection\ContainerBuilder;
21
use Drupal\language\Entity\ConfigurableLanguage;
22
use Symfony\Component\DependencyInjection\Reference;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25

26
use GuzzleHttp\Exception\RequestException;
27

28
29
30
31
32
33
/**
 * @file
 * API functions for installing Drupal.
 */

/**
34
 * Do not run the task during the current installation request.
35
36
37
38
39
40
41
42
43
 *
 * 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.
 */
44
const INSTALL_TASK_SKIP = 1;
45
46

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

/**
54
 * Run the task on each installation request until the database is set up.
55
56
57
58
59
60
61
62
 *
 * 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.
 */
63
const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
64
65

/**
66
 * Installs Drupal either interactively or via an array of passed-in settings.
67
68
69
70
71
72
73
74
75
 *
 * 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).
 *
76
77
78
79
 * @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.
80
81
82
83
84
85
86
87
88
89
90
 * @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()
 */
91
92
93
94
95
96
97
98
99
function install_drupal($class_loader, $settings = array()) {
  // Support the old way of calling this function with just a settings array.
  // @todo Remove this when Drush is updated in the Drupal testing
  //   infrastructure in https://www.drupal.org/node/2389243
  if (is_array($class_loader) && $settings === array()) {
    $settings = $class_loader;
    $class_loader = require __DIR__ . '/../vendor/autoload.php';
  }

100
101
102
103
104
105
  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();
106

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

126
127
128
129
130
131
132
  // 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'])) {
133
    unset($GLOBALS['install_state']);
134
135
  }

136
137
138
  // 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.
139
140
  if ($state['interactive']) {
    if ($state['parameters_changed']) {
141
      // Redirect to the correct page if the URL parameters have changed.
142
      install_goto(install_redirect_url($state));
143
144
145
146
147
    }
    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.
148
      install_display_output($output, $state);
149
    }
150
151
152
153
    elseif ($state['installation_finished']) {
      // Redirect to the newly installed site.
      install_goto('');
    }
154
155
156
157
  }
}

/**
158
 * Returns an array of default settings for the global installation state.
159
160
161
162
163
164
165
166
 *
 * 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
167
 * 'langcode' that are normally passed in via the URL) and 'forms' (which can
168
169
 * be used to programmatically submit forms during the installation; the keys
 * of each element indicate the name of the installation task that the form
170
 * submission is for, and the values are used as the $form_state->getValues()
171
172
 * array that is passed on to the form submission via drupal_form_submit()).
 *
173
 * @see \Drupal\Core\Form\FormBuilderInterface::submitForm()
174
175
176
177
178
179
180
181
 */
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,
182
    // TRUE when there are valid config directories.
183
    'config_verified' => FALSE,
184
    // TRUE when there is a valid database connection.
185
    'database_verified' => FALSE,
186
187
    // TRUE if database is empty & ready to install.
    'database_ready' => FALSE,
188
189
190
191
192
    // 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,
193
194
195
    // Whether a translation file for the selected language will be downloaded
    // from the translation server.
    'download_translation' => FALSE,
196
197
198
    // 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
199
    // used as the $form_state->getValues() array that is passed on to the form
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    // submission via drupal_form_submit().
    'forms' => array(),
    // This becomes TRUE only at the end of the installation process, after
    // all available tasks have been completed and Drupal is fully installed.
    // It is used by the installer to store correct information in the database
    // about the completed installation, as well as to inform theme functions
    // that all tasks are finished (so that the task list can be displayed
    // correctly).
    'installation_finished' => FALSE,
    // Whether or not this installation is interactive. By default this will
    // be set to FALSE if settings are passed in to install_drupal().
    'interactive' => TRUE,
    // An array of parameters for the installation, pre-populated by the URL
    // or by the settings passed in to install_drupal(). This is primarily
    // used to store 'profile' (the name of the chosen installation profile)
215
    // and 'langcode' (the code of the chosen installation language), since
216
217
218
219
220
221
222
223
    // 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
224
    // be filled in based on the profile's .info.yml file.
225
226
227
    'profile_info' => array(),
    // An array of available installation profiles.
    'profiles' => array(),
228
229
    // The name of the theme to use during installation.
    'theme' => 'seven',
230
231
232
233
    // 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',
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    // 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(),
256
257
258
    // An array of translation files URIs available for the installation. Keyed
    // by the translation language code.
    'translations' => array(),
259
260
261
262
263
  );
  return $defaults;
}

/**
264
 * Begins an installation request, modifying the installation state as needed.
265
266
267
268
 *
 * This function performs commands that must run at the beginning of every page
 * request. It throws an exception if the installation should not proceed.
 *
269
270
271
272
 * @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.
273
274
275
276
 * @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.
 */
277
function install_begin_request($class_loader, &$install_state) {
278
279
  $request = Request::createFromGlobals();

280
  // Add any installation parameters passed in via the URL.
281
  if ($install_state['interactive']) {
282
    $install_state['parameters'] += $request->query->all();
283
  }
284
285
286
287
288

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

293
  // Allow command line scripts to override server variables used by Drupal.
294
  require_once __DIR__ . '/bootstrap.inc';
295

296
  // If the hash salt leaks, it becomes possible to forge a valid testing user
297
298
299
300
301
  // 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.
  if ($install_state['interactive'] && strpos($request->server->get('HTTP_USER_AGENT'), 'simpletest') !== FALSE && !drupal_valid_test_ua()) {
302
    header($request->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
303
304
305
    exit;
  }

306
  $site_path = DrupalKernel::findSitePath($request, FALSE);
307
  Settings::initialize(dirname(dirname(__DIR__)), $site_path, $class_loader);
308

309
310
  // Ensure that procedural dependencies are loaded as early as possible,
  // since the error/exception handlers depend on them.
311
312
313
314
315
  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';
316
  require_once __DIR__ . '/path.inc';
317
318
319
  require_once __DIR__ . '/database.inc';
  require_once __DIR__ . '/form.inc';
  require_once __DIR__ . '/batch.inc';
320
321

  // Load module basics (needed for hook invokes).
322
323
  include_once __DIR__ . '/module.inc';
  require_once __DIR__ . '/entity.inc';
324

325
326
327
328
329
330
331
332
  // 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')
333
    ->addArgument('%language.default_values%');
334
335
  $container
    ->register('language_manager', 'Drupal\Core\Language\LanguageManager')
336
    ->addArgument(new Reference('language.default'));
337
338
339
  $container
    ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
    ->addArgument(new Reference('language_manager'));
340

341
342
343
344
345
346
  // Register the stream wrapper manager.
  $container
    ->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
    ->addArgument(new Reference('module_handler'))
    ->addMethodCall('setContainer', array(new Reference('service_container')));

347
  \Drupal::setContainer($container);
348

349
  // Determine whether base system services are ready to operate.
350
  $install_state['config_verified'] = install_ensure_config_directory(CONFIG_ACTIVE_DIRECTORY) && install_ensure_config_directory(CONFIG_STAGING_DIRECTORY);
351
352
  $install_state['database_verified'] = install_verify_database_settings();
  $install_state['settings_verified'] = $install_state['config_verified'] && $install_state['database_verified'];
353

354
355
356
357
358
359
360
  // 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'));
  }

361
  if ($install_state['settings_verified']) {
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
    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.
    }
  }

377
378
379
380
381
  // 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';
382
383
  }
  else {
384
385
    $environment = 'prod';
  }
386

387
  // Only allow dumping the container once the hash salt has been created.
388
  $kernel = InstallerKernel::createFromRequest($request, $class_loader, $environment, (bool) Settings::get('hash_salt', FALSE));
389
  $kernel->setSitePath($site_path);
390
391
  $kernel->boot();
  $container = $kernel->getContainer();
392
  $container->get('request_stack')->push($request);
393

394
  // Register the file translation service.
395
396
  if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
    $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
397
  }
398
  else {
399
    $directory = $site_path . '/files/translations';
400
401
402
403
  }
  $container->set('string_translator.file_translation', new FileTranslation($directory));
  $container->get('string_translation')
    ->addTranslator($container->get('string_translator.file_translation'));
404

405
  // Set the default language to the selected language, if any.
406
  if (isset($install_state['parameters']['langcode'])) {
407
408
    $default_language = new Language(array('id' => $install_state['parameters']['langcode']));
    $container->get('language.default')->set($default_language);
409
    \Drupal::translation()->setDefaultLangcode($install_state['parameters']['langcode']);
410
  }
411

412
  // Add list of all available profiles to the installation state.
413
  $listing = new ExtensionDiscovery($container->get('app.root'));
414
415
416
417
418
  $listing->setProfileDirectories(array());
  $install_state['profiles'] += $listing->scan('profile');

  // Prime drupal_get_filename()'s static cache.
  foreach ($install_state['profiles'] as $name => $profile) {
419
    drupal_get_filename('profile', $name, $profile->getPathname());
420
  }
421

422
423
424
425
426
427
428
429
430
431
432
  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'];
    }
  }

  // Override the module list with a minimal set of modules.
  $module_handler = \Drupal::moduleHandler();
  if (!$module_handler->moduleExists('system')) {
433
    $module_handler->addModule('system', 'core/modules/system');
434
435
  }
  if ($profile && !$module_handler->moduleExists($profile)) {
436
    $module_handler->addProfile($profile, $install_state['profiles'][$profile]->getPath());
437
438
439
440
441
442
443
  }
  // After setting up a custom and finite module list in a custom low-level
  // bootstrap like here, ensure to use ModuleHandler::loadAll() so that
  // ModuleHandler::isLoaded() returns TRUE, since that is a condition being
  // checked by other subsystems (e.g., the theme system).
  $module_handler->loadAll();

444
445
  $kernel->prepareLegacyRequest($request);

446
447
448
449
450
451
  // 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();
452

453
  if ($install_state['database_verified']) {
454
455
456
457
458
459
    // Verify the last completed task in the database, if there is one.
    $task = install_verify_completed_task();
  }
  else {
    $task = NULL;

460
    // Do not install over a configured settings.php.
461
    if (Database::getConnectionInfo()) {
462
      throw new AlreadyInstalledException($container->get('string_translation'));
463
464
465
    }
  }

466
  // Ensure that the active configuration is empty before installation starts.
467
  if ($install_state['config_verified'] && empty($task)) {
468
    $config = BootstrapConfigStorageFactory::get()->listAll();
469
470
    if (!empty($config)) {
      $task = NULL;
471
      throw new AlreadyInstalledException($container->get('string_translation'));
472
473
474
    }
  }

475
476
477
478
479
  // Modify the installation state as appropriate.
  $install_state['completed_task'] = $task;
}

/**
480
 * Runs all tasks for the current installation request.
481
482
483
484
485
486
487
488
489
 *
 * 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.
490
 *
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
 * @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);
509
510
511
512
513
    // 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();

514
515
516
517
518
519
520
521
    $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);
522
      if ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished']) {
523
        \Drupal::state()->set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
524
525
526
527
528
529
530
531
532
533
534
535
      }
    }
    // 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;
}

/**
536
 * Runs an individual installation task.
537
538
539
540
541
542
 *
 * @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.
543
 *
544
545
546
547
548
549
550
 * @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') {
551
    return install_get_form($function, $install_state);
552
553
554
555
  }
  elseif ($task['type'] == 'batch') {
    // Start a new batch based on the task function, if one is not running
    // already.
556
    $current_batch = \Drupal::state()->get('install_current_batch');
557
558
559
560
561
562
563
564
565
566
567
568
    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']) {
569
        \Drupal::state()->set('install_current_batch', $function);
570
571
572
573
574
575
576
      }
      else {
        $batch =& batch_get();
        $batch['progressive'] = FALSE;
      }
      // Process the batch. For progressive batches, this will redirect.
      // Otherwise, the batch will complete.
577
578
579
580
      // install_redirect_url() returns core/install.php, so let's ensure to
      // drop it from it and use base:// as batch_process() is using the
      // unrouted URL assembler, which requires base://.
      $response = batch_process(preg_replace('@^core/@', 'base://', install_redirect_url($install_state)), install_full_redirect_url($install_state));
581
582
      if ($response instanceof Response) {
        // Save $_SESSION data from batch.
583
        \Drupal::service('session_manager')->save();
584
585
586
587
        // Send the response.
        $response->send();
        exit;
      }
588
589
590
591
    }
    // 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) {
592
      $output = _batch_page(\Drupal::request());
593
      // Because Batch API now returns a JSON response for intermediary steps,
594
595
596
597
      // 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.
598
599
      if ($output instanceof Response) {
        $output->send();
600
        $output = NULL;
601
      }
602
603
604
      // 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.
605
      if ($output === FALSE) {
606
        // Return nothing so the next task will run in the same request.
607
        \Drupal::state()->delete('install_current_batch');
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
        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);
  }
}

/**
627
 * Returns a list of tasks to perform during the current installation request.
628
629
630
631
632
633
634
 *
 * 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.
635
 *
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
 * @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;
}

/**
658
 * Returns a list of all tasks the installer currently knows about.
659
660
661
662
663
664
665
666
667
 *
 * 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.
668
 *
669
670
671
672
 * @return
 *   A list of tasks, with associated metadata.
 */
function install_tasks($install_state) {
673
674
  // Determine whether a translation file must be imported during the
  // 'install_import_translations' task. Import when a non-English language is
675
676
677
  // available and selected. Also we will need translations even if the
  // installer language is English but there are other languages on the system.
  $needs_translations = (count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en') || \Drupal::languageManager()->isMultilingual();
678
679
680
681
  // 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';
682

683
  // Start with the core installation tasks that run before handing control
684
  // to the installation profile.
685
  $tasks = array(
686
    'install_select_language' => array(
687
      'display_name' => t('Choose language'),
688
689
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
690
691
692
    'install_download_translation' => array(
      'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
    ),
693
    'install_select_profile' => array(
694
      'display_name' => t('Choose profile'),
695
      'display' => empty($install_state['profile_info']['distribution']['name']) && count($install_state['profiles']) != 1,
696
697
698
699
700
701
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_load_profile' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_verify_requirements' => array(
702
      'display_name' => t('Verify requirements'),
703
704
    ),
    'install_settings_form' => array(
705
      'display_name' => t('Set up database'),
706
      'type' => 'form',
707
708
709
      // 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.
710
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
711
      'function' => 'Drupal\Core\Installer\Form\SiteSettingsForm',
712
    ),
713
714
715
    'install_verify_database_ready' => array(
      'run' => $install_state['database_ready'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    ),
716
    'install_base_system' => array(
717
      'run' => $install_state['base_system_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
718
    ),
719
    // All tasks below are executed in a regular, full Drupal environment.
720
721
722
723
    'install_bootstrap_full' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_profile_modules' => array(
724
      'display_name' => t('Install site'),
725
726
      'type' => 'batch',
    ),
727
728
    'install_profile_themes' => array(
    ),
729
    'install_import_translations' => array(
730
      'display_name' => t('Set up translations'),
731
732
733
734
735
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_configure_form' => array(
736
      'display_name' => t('Configure site'),
737
      'type' => 'form',
738
      'function' => 'Drupal\Core\Installer\Form\SiteConfigureForm',
739
740
741
742
743
    ),
  );

  // Now add any tasks defined by the installation profile.
  if (!empty($install_state['parameters']['profile'])) {
744
745
    // Load the profile install file, because it is not always loaded when
    // hook_install_tasks() is invoked (e.g. batch processing).
746
    $profile = $install_state['parameters']['profile'];
747
    $profile_install_file = $install_state['profiles'][$profile]->getPath() . '/' . $profile . '.install';
748
    if (file_exists($profile_install_file)) {
749
      include_once \Drupal::root() . '/' . $profile_install_file;
750
    }
751
752
753
754
755
756
757
758
759
760
761
    $function = $install_state['parameters']['profile'] . '_install_tasks';
    if (function_exists($function)) {
      $result = $function($install_state);
      if (is_array($result)) {
        $tasks += $result;
      }
    }
  }

  // Finish by adding the remaining core tasks.
  $tasks += array(
762
    'install_import_translations_remaining' => array(
763
      'display_name' => t('Finish translations'),
764
765
766
767
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
768
    'install_update_configuration_translations' => array(
769
      'display_name' => t('Translate configuration'),
770
771
772
773
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
774
775
776
777
778
779
    'install_finished' => array(
    ),
  );

  // Allow the installation profile to modify the full list of tasks.
  if (!empty($install_state['parameters']['profile'])) {
780
    $profile = $install_state['parameters']['profile'];
781
    if ($install_state['profiles'][$profile]->load()) {
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
      $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
      if (function_exists($function)) {
        $function($tasks, $install_state);
      }
    }
  }

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

/**
803
 * Returns a list of tasks that should be displayed to the end user.
804
805
 *
 * The output of this function is a list suitable for sending to
806
 * maintenance-task-list.html.twig.
807
808
809
 *
 * @param $install_state
 *   An array of information about the current installation state.
810
 *
811
812
813
814
 * @return
 *   A list of tasks, with keys equal to the machine-readable task name and
 *   values equal to the name that should be displayed.
 *
815
 * @see maintenance-task-list.html.twig
816
817
818
819
820
821
822
823
824
825
826
 */
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;
}

827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/**
 * Builds and processes a form for the installer environment.
 *
 * Ensures that FormBuilder does not redirect after submitting a form, since the
 * installer uses a custom step/flow logic via install_run_tasks().
 *
 * @param string|array $form_id
 *   The form ID to build and process.
 * @param array $install_state
 *   The current state of the installation.
 *
 * @return array|null
 *   A render array containing the form to render, or NULL in case the form was
 *   successfully submitted.
 *
 * @throws \Drupal\Core\Installer\Exception\InstallerException
 */
function install_get_form($form_id, array &$install_state) {
  // Ensure the form will not redirect, since install_run_tasks() uses a custom
  // redirection logic.
847
848
849
  $form_state = (new FormState())
    ->addBuildInfo('args', [&$install_state])
    ->disableRedirect();
850
  $form_builder = \Drupal::formBuilder();
851
  if ($install_state['interactive']) {
852
    $form = $form_builder->buildForm($form_id, $form_state);
853
854
    // If the form submission was not successful, the form needs to be rendered,
    // which means the task is not complete yet.
855
    if (!$form_state->isExecuted()) {
856
857
858
859
860
861
862
      $install_state['task_not_complete'] = TRUE;
      return $form;
    }
  }
  else {
    // For non-interactive installs, submit the form programmatically with the
    // values taken from the installation state.
863
864
    $install_form_id = $form_builder->getFormId($form_id, $form_state);
    if (!empty($install_state['forms'][$install_form_id])) {
865
      $form_state->setValues($install_state['forms'][$install_form_id]);
866
    }
867
    $form_builder->submitForm($form_id, $form_state);
868
869

    // Throw an exception in case of any form validation error.
870
    if ($errors = $form_state->getErrors()) {
871
872
873
874
875
      throw new InstallerException(implode("\n", $errors));
    }
  }
}

876
/**
877
 * Returns the URL that should be redirected to during an installation request.
878
879
880
881
882
 *
 * The output of this function is suitable for sending to install_goto().
 *
 * @param $install_state
 *   An array of information about the current installation state.
883
 *
884
885
886
887
888
889
 * @return
 *   The URL to redirect to.
 *
 * @see install_full_redirect_url()
 */
function install_redirect_url($install_state) {
890
  return 'core/install.php?' . UrlHelper::buildQuery($install_state['parameters']);
891
892
893
}

/**
894
 * Returns the complete URL redirected to during an installation request.
895
896
897
 *
 * @param $install_state
 *   An array of information about the current installation state.
898
 *
899
900
901
902
903
904
905
906
907
908
909
 * @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);
}

/**
910
 * Displays themed installer output and ends the page request.
911
 *
912
 * Installation tasks should use #title to set the desired page
913
914
915
916
917
918
919
920
921
 * 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) {
922
923
924
925
926
  // Ensure the maintenance theme is initialized.
  // The regular initialization call in install_begin_request() may not be
  // reached in case of an early installer error.
  drupal_maintenance_theme();

927
928
929
930
931
932
933
934
935
936
937
938
  // Prevent install.php from being indexed when installed in a sub folder.
  // robots.txt rules are not read if the site is within domain.com/subfolder
  // resulting in /subfolder/install.php being found through search engines.
  // When settings.php is writeable this can be used via an external database
  // leading a malicious user to gain php access to the server.
  $noindex_meta_tag = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'robots',
      'content' => 'noindex, nofollow',
    ),
  );
939
  $output['#attached']['html_head'][] = [$noindex_meta_tag, 'install_meta_robots'];
940

941
942
943
  // 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.
944
  $regions = array();
945
946
947
948
  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'];
949
    $task_list = array(
950
      '#theme' => 'maintenance_task_list',
951
952
953
      '#items' => install_tasks_to_display($install_state),
      '#active' => $active_task,
    );
954
    $regions['sidebar_first'] = $task_list;
955
  }
956

957
958
959
960
961
962
963
964
  $response = new Response();
  $default_headers = array(
    'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
    'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
    'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
    'ETag' => '"' . REQUEST_TIME . '"',
  );
  $response->headers->add($default_headers);
965
  $response->setContent(\Drupal::service('bare_html_page_renderer')->renderBarePage($output, $output['#title'], 'install_page', $regions));
966
  $response->send();
967
968
969
970
  exit;
}

/**
971
 * Verifies the requirements for installing Drupal.
972
973
974
 *
 * @param $install_state
 *   An array of information about the current installation state.
975
 *
976
977
978
979
980
981
982
983
984
985
 * @return
 *   A themed status report, or an exception if there are requirement errors.
 */
function install_verify_requirements(&$install_state) {
  // Check the installation requirements for Drupal and this profile.
  $requirements = install_check_requirements($install_state);

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

986
  return install_display_requirements($install_state, $requirements);
987
988
989
}

/**
990
 * Installation task; install the base functionality Drupal needs to bootstrap.
991
992
993
994
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
995
function install_base_system(&$install_state) {
996
  // Install system.module.
997
  drupal_install_system($install_state);
998

999
1000
1001
1002
1003
1004
1005
1006
1007
  // Call file_ensure_htaccess() to ensure that all of Drupal's standard
  // directories (e.g., the public files directory and config directory) have
  // appropriate .htaccess files. These directories will have already been
  // created by this point in the installer, since Drupal creates them during
  // the install_verify_requirements() task. Note that we cannot call
  // file_ensure_access() any earlier than this, since it relies on
  // system.module in order to work.
  file_ensure_htaccess();

1008
1009
  // Enable the user module so that sessions can be recorded during the
  // upcoming bootstrap step.
1010
  \Drupal::service('module_installer')->install(array('user'), FALSE);
1011

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

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

1020
  \Drupal::state()->set('install_profile_modules', array_diff($modules, array('system')));
1021
  $install_state['base_system_verified'] = TRUE;
1022
1023
1024
}

/**
1025
 * Verifies and returns the last installation task that was completed.
1026
1027
1028
1029
1030
1031
 *
 * @return
 *   The last completed task, if there is one. An exception is thrown if Drupal
 *   is already installed.
 */
function install_verify_completed_task() {
1032
  try {
1033
    $task = \Drupal::state()->get('install_task');
1034
1035
1036
  }
  // Do not trigger an error if the database query fails, since the database
  // might not be set up yet.
1037
  catch (\Exception $e) {
1038
1039
  }
  if (isset($task)) {
1040
    if ($task == 'done') {
1041
      throw new AlreadyInstalledException(\Drupal::service('string_translation'));
1042
1043
1044
1045
1046
1047
    }
    return $task;
  }
}

/**
1048
 * Verifies that settings.php specifies a valid database connection.
1049
 */
1050
function install_verify_database_settings() {
1051
1052
  if ($database = Database::getConnectionInfo()) {
    $database = $database['default'];
1053
1054
1055
1056
1057
1058
1059
1060
1061
    $settings_file = './' . conf_path(FALSE) . '/settings.php';
    $errors = install_database_errors($database, $settings_file);
    if (empty($errors)) {
      return TRUE;
    }
  }
  return FALSE;
}

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
/**
 * Verify that the database is ready (no existing Drupal installation).
 */
function install_verify_database_ready() {
  $system_schema = system_schema();
  end($system_schema);
  $table = key($system_schema);

  if ($database = Database::getConnectionInfo()) {
    if (Database::getConnection()->schema()->tableExists($table)) {
      throw new AlreadyInstalledException(\Drupal::service('string_translation'));
    }
  }
}

1077
/**
1078
 * Checks a database connection and returns any errors.
1079
1080
1081
1082
 */
function install_database_errors($database, $settings_file) {
  $errors = array();

1083
  // Check database type.
1084
  $database_types = drupal_get_database_types();
1085
1086
  $driver = $database['driver'];
  if (!isset($database_types[$driver])) {
1087
    $errors['driver'] = t("In your %settings_file file you have configured @drupal to use a %driver server, however your PHP installation currently does not support this database type.", array('%settings_file' => $settings_file, '@drupal' => drupal_install_profile_distribution_name(), '%driver' => $driver));
1088
1089
  }
  else {
1090
1091
    // Run driver specific validation
    $errors += $database_types[$driver]->validateDatabaseSettings($database);
1092
1093
1094
1095
    if (!empty($errors)) {
      // No point to try further.
      return $errors;
    }
1096
    // Run tasks associated with the database type. Any errors are caught in the
1097
    // calling function.
1098
    Database::addConnectionInfo('default', 'default', $database);
1099
    try {
1100
      db_run_tasks($driver);
1101
    }
1102
    catch (TaskException $e) {
1103
1104
1105
      // 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.
1106
      $errors[$driver . '][0'] = $e->getMessage();
1107
1108
1109
1110
1111
1112
    }
  }
  return $errors;
}

/**
1113
 * Selects which profile to install.
1114
1115
1116
1117
1118
 *
 * @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.
1119
 *
1120
1121
1122
1123
1124
1125
1126
 * @return
 *   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.
 */
function install_select_profile(&$install_state) {
  if (empty($install_state['parameters']['profile'])) {
1127
1128
1129
    // If there are no profiles at all, installation cannot proceed.
    if (empty($install_state['profiles'])) {
      throw new NoProfilesException(\Drupal::service('string_translation'));
1130
    }
1131
    // Try to automatically select a profile.
1132
    if ($profile = _install_select_profile($install_state)) {
1133
1134
      $install_state['parameters']['profile'] = $profile;
    }
1135
1136
1137
1138
1139
1140
    else {
      // The non-interactive installer requires a profile parameter.
      if (!$install_state['interactive']) {
        throw new InstallerException(t('Missing profile parameter.'));
      }
      // Otherwise, display a form to select a profile.
1141
      return install_get_form('Drupal\Core\Installer\Form\SelectProfileForm', $install_state);
1142
    }
1143
1144
1145
1146
  }
}

/**
1147
 * Determines the installation profile to use in the installer.
1148
 *
1149
 * A profile will be selected in the following order of conditions: