comparison core/includes/install.core.inc @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 /**
4 * @file
5 * API functions for installing Drupal.
6 */
7
8 use Drupal\Component\Utility\UrlHelper;
9 use Drupal\Core\DrupalKernel;
10 use Drupal\Core\Database\Database;
11 use Drupal\Core\Database\DatabaseExceptionWrapper;
12 use Drupal\Core\Form\FormState;
13 use Drupal\Core\Installer\Exception\AlreadyInstalledException;
14 use Drupal\Core\Installer\Exception\InstallerException;
15 use Drupal\Core\Installer\Exception\InstallProfileMismatchException;
16 use Drupal\Core\Installer\Exception\NoProfilesException;
17 use Drupal\Core\Installer\InstallerKernel;
18 use Drupal\Core\Language\Language;
19 use Drupal\Core\Language\LanguageManager;
20 use Drupal\Core\Logger\LoggerChannelFactory;
21 use Drupal\Core\Site\Settings;
22 use Drupal\Core\StringTranslation\Translator\FileTranslation;
23 use Drupal\Core\StackMiddleware\ReverseProxyMiddleware;
24 use Drupal\Core\StreamWrapper\PublicStream;
25 use Drupal\Core\Extension\ExtensionDiscovery;
26 use Drupal\Core\DependencyInjection\ContainerBuilder;
27 use Drupal\Core\Url;
28 use Drupal\language\Entity\ConfigurableLanguage;
29 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
30 use Symfony\Component\DependencyInjection\Reference;
31 use Symfony\Component\HttpFoundation\Request;
32 use Symfony\Component\HttpFoundation\Response;
33 use Symfony\Component\Routing\Route;
34 use Drupal\user\Entity\User;
35 use GuzzleHttp\Exception\RequestException;
36
37 /**
38 * Do not run the task during the current installation request.
39 *
40 * This can be used to skip running an installation task when certain
41 * conditions are met, even though the task may still show on the list of
42 * installation tasks presented to the user. For example, the Drupal installer
43 * uses this flag to skip over the database configuration form when valid
44 * database connection information is already available from settings.php. It
45 * also uses this flag to skip language import tasks when the installation is
46 * being performed in English.
47 */
48 const INSTALL_TASK_SKIP = 1;
49
50 /**
51 * Run the task on each installation request that reaches it.
52 *
53 * This is primarily used by the Drupal installer for bootstrap-related tasks.
54 */
55 const INSTALL_TASK_RUN_IF_REACHED = 2;
56
57 /**
58 * Run the task on each installation request until the database is set up.
59 *
60 * This is the default method for running tasks and should be used for most
61 * tasks that occur after the database is set up; these tasks will then run
62 * once and be marked complete once they are successfully finished. For
63 * example, the Drupal installer uses this flag for the batch installation of
64 * modules on the new site, and also for the configuration form that collects
65 * basic site information and sets up the site maintenance account.
66 */
67 const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
68
69 /**
70 * Installs Drupal either interactively or via an array of passed-in settings.
71 *
72 * The Drupal installation happens in a series of steps, which may be spread
73 * out over multiple page requests. Each request begins by trying to determine
74 * the last completed installation step (also known as a "task"), if one is
75 * available from a previous request. Control is then passed to the task
76 * handler, which processes the remaining tasks that need to be run until (a)
77 * an error is thrown, (b) a new page needs to be displayed, or (c) the
78 * installation finishes (whichever happens first).
79 *
80 * @param $class_loader
81 * The class loader. Normally Composer's ClassLoader, as included by the
82 * front controller, but may also be decorated; e.g.,
83 * \Symfony\Component\ClassLoader\ApcClassLoader.
84 * @param $settings
85 * An optional array of installation settings. Leave this empty for a normal,
86 * interactive, browser-based installation intended to occur over multiple
87 * page requests. Alternatively, if an array of settings is passed in, the
88 * installer will attempt to use it to perform the installation in a single
89 * page request (optimized for the command line) and not send any output
90 * intended for the web browser. See install_state_defaults() for a list of
91 * elements that are allowed to appear in this array.
92 *
93 * @see install_state_defaults()
94 */
95 function install_drupal($class_loader, $settings = []) {
96 // Support the old way of calling this function with just a settings array.
97 // @todo Remove this when Drush is updated in the Drupal testing
98 // infrastructure in https://www.drupal.org/node/2389243
99 if (is_array($class_loader) && $settings === []) {
100 $settings = $class_loader;
101 $class_loader = require __DIR__ . '/../../autoload.php';
102 }
103
104 global $install_state;
105 // Initialize the installation state with the settings that were passed in,
106 // as well as a boolean indicating whether or not this is an interactive
107 // installation.
108 $interactive = empty($settings);
109 $install_state = $settings + ['interactive' => $interactive] + install_state_defaults();
110
111 try {
112 // Begin the page request. This adds information about the current state of
113 // the Drupal installation to the passed-in array.
114 install_begin_request($class_loader, $install_state);
115 // Based on the installation state, run the remaining tasks for this page
116 // request, and collect any output.
117 $output = install_run_tasks($install_state);
118 }
119 catch (InstallerException $e) {
120 // In the non-interactive installer, exceptions are always thrown directly.
121 if (!$install_state['interactive']) {
122 throw $e;
123 }
124 $output = [
125 '#title' => $e->getTitle(),
126 '#markup' => $e->getMessage(),
127 ];
128 }
129
130 // After execution, all tasks might be complete, in which case
131 // $install_state['installation_finished'] is TRUE. In case the last task
132 // has been processed, remove the global $install_state, so other code can
133 // reliably check whether it is running during the installer.
134 // @see drupal_installation_attempted()
135 $state = $install_state;
136 if (!empty($install_state['installation_finished'])) {
137 unset($GLOBALS['install_state']);
138 }
139
140 // All available tasks for this page request are now complete. Interactive
141 // installations can send output to the browser or redirect the user to the
142 // next page.
143 if ($state['interactive']) {
144 // If a session has been initiated in this request, make sure to save it.
145 if ($session = \Drupal::request()->getSession()) {
146 $session->save();
147 }
148 if ($state['parameters_changed']) {
149 // Redirect to the correct page if the URL parameters have changed.
150 install_goto(install_redirect_url($state));
151 }
152 elseif (isset($output)) {
153 // Display a page only if some output is available. Otherwise it is
154 // possible that we are printing a JSON page and theme output should
155 // not be shown.
156 install_display_output($output, $state);
157 }
158 elseif ($state['installation_finished']) {
159 // Redirect to the newly installed site.
160 install_goto('');
161 }
162 }
163 }
164
165 /**
166 * Returns an array of default settings for the global installation state.
167 *
168 * The installation state is initialized with these settings at the beginning
169 * of each page request. They may evolve during the page request, but they are
170 * initialized again once the next request begins.
171 *
172 * Non-interactive Drupal installations can override some of these default
173 * settings by passing in an array to the installation script, most notably
174 * 'parameters' (which contains one-time parameters such as 'profile' and
175 * 'langcode' that are normally passed in via the URL) and 'forms' (which can
176 * be used to programmatically submit forms during the installation; the keys
177 * of each element indicate the name of the installation task that the form
178 * submission is for, and the values are used as the $form_state->getValues()
179 * array that is passed on to the form submission via
180 * \Drupal::formBuilder()->submitForm()).
181 *
182 * @see \Drupal\Core\Form\FormBuilderInterface::submitForm()
183 */
184 function install_state_defaults() {
185 $defaults = [
186 // The current task being processed.
187 'active_task' => NULL,
188 // The last task that was completed during the previous installation
189 // request.
190 'completed_task' => NULL,
191 // TRUE when there are valid config directories.
192 'config_verified' => FALSE,
193 // TRUE when there is a valid database connection.
194 'database_verified' => FALSE,
195 // TRUE if database is empty & ready to install.
196 'database_ready' => FALSE,
197 // TRUE when a valid settings.php exists (containing both database
198 // connection information and config directory names).
199 'settings_verified' => FALSE,
200 // TRUE when the base system has been installed and is ready to operate.
201 'base_system_verified' => FALSE,
202 // Whether a translation file for the selected language will be downloaded
203 // from the translation server.
204 'download_translation' => FALSE,
205 // An array of forms to be programmatically submitted during the
206 // installation. The keys of each element indicate the name of the
207 // installation task that the form submission is for, and the values are
208 // used as the $form_state->getValues() array that is passed on to the form
209 // submission via \Drupal::formBuilder()->submitForm().
210 'forms' => [],
211 // This becomes TRUE only at the end of the installation process, after
212 // all available tasks have been completed and Drupal is fully installed.
213 // It is used by the installer to store correct information in the database
214 // about the completed installation, as well as to inform theme functions
215 // that all tasks are finished (so that the task list can be displayed
216 // correctly).
217 'installation_finished' => FALSE,
218 // Whether or not this installation is interactive. By default this will
219 // be set to FALSE if settings are passed in to install_drupal().
220 'interactive' => TRUE,
221 // An array of parameters for the installation, pre-populated by the URL
222 // or by the settings passed in to install_drupal(). This is primarily
223 // used to store 'profile' (the name of the chosen installation profile)
224 // and 'langcode' (the code of the chosen installation language), since
225 // these settings need to persist from page request to page request before
226 // the database is available for storage.
227 'parameters' => [],
228 // Whether or not the parameters have changed during the current page
229 // request. For interactive installations, this will trigger a page
230 // redirect.
231 'parameters_changed' => FALSE,
232 // An array of information about the chosen installation profile. This will
233 // be filled in based on the profile's .info.yml file.
234 'profile_info' => [],
235 // An array of available installation profiles.
236 'profiles' => [],
237 // The name of the theme to use during installation.
238 'theme' => 'seven',
239 // The server URL where the interface translation files can be downloaded.
240 // Tokens in the pattern will be replaced by appropriate values for the
241 // required translation file.
242 'server_pattern' => 'http://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po',
243 // Installation tasks can set this to TRUE to force the page request to
244 // end (even if there is no themable output), in the case of an interactive
245 // installation. This is needed only rarely; for example, it would be used
246 // by an installation task that prints JSON output rather than returning a
247 // themed page. The most common example of this is during batch processing,
248 // but the Drupal installer automatically takes care of setting this
249 // parameter properly in that case, so that individual installation tasks
250 // which implement the batch API do not need to set it themselves.
251 'stop_page_request' => FALSE,
252 // Installation tasks can set this to TRUE to indicate that the task should
253 // be run again, even if it normally wouldn't be. This can be used, for
254 // example, if a single task needs to be spread out over multiple page
255 // requests, or if it needs to perform some validation before allowing
256 // itself to be marked complete. The most common examples of this are batch
257 // processing and form submissions, but the Drupal installer automatically
258 // takes care of setting this parameter properly in those cases, so that
259 // individual installation tasks which implement the batch API or form API
260 // do not need to set it themselves.
261 'task_not_complete' => FALSE,
262 // A list of installation tasks which have already been performed during
263 // the current page request.
264 'tasks_performed' => [],
265 // An array of translation files URIs available for the installation. Keyed
266 // by the translation language code.
267 'translations' => [],
268 ];
269 return $defaults;
270 }
271
272 /**
273 * Begins an installation request, modifying the installation state as needed.
274 *
275 * This function performs commands that must run at the beginning of every page
276 * request. It throws an exception if the installation should not proceed.
277 *
278 * @param $class_loader
279 * The class loader. Normally Composer's ClassLoader, as included by the
280 * front controller, but may also be decorated; e.g.,
281 * \Symfony\Component\ClassLoader\ApcClassLoader.
282 * @param $install_state
283 * An array of information about the current installation state. This is
284 * modified with information gleaned from the beginning of the page request.
285 */
286 function install_begin_request($class_loader, &$install_state) {
287 $request = Request::createFromGlobals();
288
289 // Add any installation parameters passed in via the URL.
290 if ($install_state['interactive']) {
291 $install_state['parameters'] += $request->query->all();
292 }
293
294 // Validate certain core settings that are used throughout the installation.
295 if (!empty($install_state['parameters']['profile'])) {
296 $install_state['parameters']['profile'] = preg_replace('/[^a-zA-Z_0-9]/', '', $install_state['parameters']['profile']);
297 }
298 if (!empty($install_state['parameters']['langcode'])) {
299 $install_state['parameters']['langcode'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['langcode']);
300 }
301
302 // Allow command line scripts to override server variables used by Drupal.
303 require_once __DIR__ . '/bootstrap.inc';
304
305 // Before having installed the system module and being able to do a module
306 // rebuild, prime the drupal_get_filename() static cache with the module's
307 // exact location.
308 // @todo Remove as part of https://www.drupal.org/node/2186491
309 drupal_get_filename('module', 'system', 'core/modules/system/system.info.yml');
310
311 // If the hash salt leaks, it becomes possible to forge a valid testing user
312 // agent, install a new copy of Drupal, and take over the original site.
313 // The user agent header is used to pass a database prefix in the request when
314 // running tests. However, for security reasons, it is imperative that no
315 // installation be permitted using such a prefix.
316 $user_agent = $request->cookies->get('SIMPLETEST_USER_AGENT') ?: $request->server->get('HTTP_USER_AGENT');
317 if ($install_state['interactive'] && strpos($user_agent, 'simpletest') !== FALSE && !drupal_valid_test_ua()) {
318 header($request->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
319 exit;
320 }
321 if ($install_state['interactive'] && drupal_valid_test_ua()) {
322 // Set the default timezone. While this doesn't cause any tests to fail, PHP
323 // complains if 'date.timezone' is not set in php.ini. The Australia/Sydney
324 // timezone is chosen so all tests are run using an edge case scenario
325 // (UTC+10 and DST). This choice is made to prevent timezone related
326 // regressions and reduce the fragility of the testing system in general.
327 date_default_timezone_set('Australia/Sydney');
328 }
329
330 $site_path = DrupalKernel::findSitePath($request, FALSE);
331 Settings::initialize(dirname(dirname(__DIR__)), $site_path, $class_loader);
332
333 // Ensure that procedural dependencies are loaded as early as possible,
334 // since the error/exception handlers depend on them.
335 require_once __DIR__ . '/../modules/system/system.install';
336 require_once __DIR__ . '/common.inc';
337 require_once __DIR__ . '/file.inc';
338 require_once __DIR__ . '/install.inc';
339 require_once __DIR__ . '/schema.inc';
340 require_once __DIR__ . '/database.inc';
341 require_once __DIR__ . '/form.inc';
342 require_once __DIR__ . '/batch.inc';
343
344 // Load module basics (needed for hook invokes).
345 include_once __DIR__ . '/module.inc';
346 require_once __DIR__ . '/entity.inc';
347
348 // Create a minimal mocked container to support calls to t() in the pre-kernel
349 // base system verification code paths below. The strings are not actually
350 // used or output for these calls.
351 // @todo Separate API level checks from UI-facing error messages.
352 $container = new ContainerBuilder();
353 $container->setParameter('language.default_values', Language::$defaultValues);
354 $container
355 ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
356 ->addArgument('%language.default_values%');
357 $container
358 ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
359 ->addArgument(new Reference('language.default'));
360
361 // Register the stream wrapper manager.
362 $container
363 ->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
364 ->addMethodCall('setContainer', [new Reference('service_container')]);
365 $container
366 ->register('file_system', 'Drupal\Core\File\FileSystem')
367 ->addArgument(new Reference('stream_wrapper_manager'))
368 ->addArgument(Settings::getInstance())
369 ->addArgument((new LoggerChannelFactory())->get('file'));
370
371 \Drupal::setContainer($container);
372
373 // Determine whether base system services are ready to operate.
374 try {
375 $sync_directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
376 $install_state['config_verified'] = file_exists($sync_directory);
377 }
378 catch (Exception $e) {
379 $install_state['config_verified'] = FALSE;
380 }
381 $install_state['database_verified'] = install_verify_database_settings($site_path);
382 // A valid settings.php has database settings and a hash_salt value. Other
383 // settings like config_directories will be checked by system_requirements().
384 $install_state['settings_verified'] = $install_state['database_verified'] && (bool) Settings::get('hash_salt', FALSE);
385
386 // Install factory tables only after checking the database.
387 if ($install_state['database_verified'] && $install_state['database_ready']) {
388 $container
389 ->register('path.matcher', 'Drupal\Core\Path\PathMatcher')
390 ->addArgument(new Reference('config.factory'));
391 }
392
393 if ($install_state['settings_verified']) {
394 try {
395 $system_schema = system_schema();
396 end($system_schema);
397 $table = key($system_schema);
398 $install_state['base_system_verified'] = Database::getConnection()->schema()->tableExists($table);
399 }
400 catch (DatabaseExceptionWrapper $e) {
401 // The last defined table of the base system_schema() does not exist yet.
402 // $install_state['base_system_verified'] defaults to FALSE, so the code
403 // following below will use the minimal installer service container.
404 // As soon as the base system is verified here, the installer operates in
405 // a full and regular Drupal environment, without any kind of exceptions.
406 }
407 }
408
409 // Replace services with in-memory and null implementations. This kernel is
410 // replaced with a regular one in drupal_install_system().
411 if (!$install_state['base_system_verified']) {
412 $environment = 'install';
413 $GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\InstallerServiceProvider';
414 }
415 else {
416 $environment = 'prod';
417 }
418
419 // Only allow dumping the container once the hash salt has been created.
420 $kernel = InstallerKernel::createFromRequest($request, $class_loader, $environment, (bool) Settings::get('hash_salt', FALSE));
421 $kernel->setSitePath($site_path);
422 $kernel->boot();
423 $container = $kernel->getContainer();
424 // If Drupal is being installed behind a proxy, configure the request.
425 ReverseProxyMiddleware::setSettingsOnRequest($request, Settings::getInstance());
426
427 // Register the file translation service.
428 if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
429 $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
430 }
431 else {
432 $directory = $site_path . '/files/translations';
433 }
434 $container->set('string_translator.file_translation', new FileTranslation($directory));
435 $container->get('string_translation')
436 ->addTranslator($container->get('string_translator.file_translation'));
437
438 // Add list of all available profiles to the installation state.
439 $listing = new ExtensionDiscovery($container->get('app.root'));
440 $listing->setProfileDirectories([]);
441 $install_state['profiles'] += $listing->scan('profile');
442
443 // Prime drupal_get_filename()'s static cache.
444 foreach ($install_state['profiles'] as $name => $profile) {
445 drupal_get_filename('profile', $name, $profile->getPathname());
446 }
447
448 if ($profile = _install_select_profile($install_state)) {
449 $install_state['parameters']['profile'] = $profile;
450 install_load_profile($install_state);
451 if (isset($install_state['profile_info']['distribution']['install']['theme'])) {
452 $install_state['theme'] = $install_state['profile_info']['distribution']['install']['theme'];
453 }
454 }
455
456 // Use the language from the profile configuration, if available, to override
457 // the language previously set in the parameters.
458 if (isset($install_state['profile_info']['distribution']['langcode'])) {
459 $install_state['parameters']['langcode'] = $install_state['profile_info']['distribution']['langcode'];
460 }
461
462 // Set the default language to the selected language, if any.
463 if (isset($install_state['parameters']['langcode'])) {
464 $default_language = new Language(['id' => $install_state['parameters']['langcode']]);
465 $container->get('language.default')->set($default_language);
466 \Drupal::translation()->setDefaultLangcode($install_state['parameters']['langcode']);
467 }
468
469 // Override the module list with a minimal set of modules.
470 $module_handler = \Drupal::moduleHandler();
471 if (!$module_handler->moduleExists('system')) {
472 $module_handler->addModule('system', 'core/modules/system');
473 }
474 if ($profile && !$module_handler->moduleExists($profile)) {
475 $module_handler->addProfile($profile, $install_state['profiles'][$profile]->getPath());
476 }
477
478 // Load all modules and perform request related initialization.
479 $kernel->preHandle($request);
480
481 // Initialize a route on this legacy request similar to
482 // \Drupal\Core\DrupalKernel::prepareLegacyRequest() since normal routing
483 // will not happen.
484 $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
485 $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
486
487 // Prepare for themed output. We need to run this at the beginning of the
488 // page request to avoid a different theme accidentally getting set. (We also
489 // need to run it even in the case of command-line installations, to prevent
490 // any code in the installer that happens to initialize the theme system from
491 // accessing the database before it is set up yet.)
492 drupal_maintenance_theme();
493
494 if ($install_state['database_verified']) {
495 // Verify the last completed task in the database, if there is one.
496 $task = install_verify_completed_task();
497 }
498 else {
499 $task = NULL;
500
501 // Do not install over a configured settings.php.
502 if (Database::getConnectionInfo()) {
503 throw new AlreadyInstalledException($container->get('string_translation'));
504 }
505 }
506
507 // Ensure that the active configuration is empty before installation starts.
508 if ($install_state['config_verified'] && empty($task)) {
509 if (count($kernel->getConfigStorage()->listAll())) {
510 $task = NULL;
511 throw new AlreadyInstalledException($container->get('string_translation'));
512 }
513 }
514
515 // Modify the installation state as appropriate.
516 $install_state['completed_task'] = $task;
517 }
518
519 /**
520 * Runs all tasks for the current installation request.
521 *
522 * In the case of an interactive installation, all tasks will be attempted
523 * until one is reached that has output which needs to be displayed to the
524 * user, or until a page redirect is required. Otherwise, tasks will be
525 * attempted until the installation is finished.
526 *
527 * @param $install_state
528 * An array of information about the current installation state. This is
529 * passed along to each task, so it can be modified if necessary.
530 *
531 * @return
532 * HTML output from the last completed task.
533 */
534 function install_run_tasks(&$install_state) {
535 do {
536 // Obtain a list of tasks to perform. The list of tasks itself can be
537 // dynamic (e.g., some might be defined by the installation profile,
538 // which is not necessarily known until the earlier tasks have run),
539 // so we regenerate the remaining tasks based on the installation state,
540 // each time through the loop.
541 $tasks_to_perform = install_tasks_to_perform($install_state);
542 // Run the first task on the list.
543 reset($tasks_to_perform);
544 $task_name = key($tasks_to_perform);
545 $task = array_shift($tasks_to_perform);
546 $install_state['active_task'] = $task_name;
547 $original_parameters = $install_state['parameters'];
548 $output = install_run_task($task, $install_state);
549 // Ensure the maintenance theme is initialized. If the install task has
550 // rebuilt the container the active theme will not be set. This can occur if
551 // the task has installed a module.
552 drupal_maintenance_theme();
553
554 $install_state['parameters_changed'] = ($install_state['parameters'] != $original_parameters);
555 // Store this task as having been performed during the current request,
556 // and save it to the database as completed, if we need to and if the
557 // database is in a state that allows us to do so. Also mark the
558 // installation as 'done' when we have run out of tasks.
559 if (!$install_state['task_not_complete']) {
560 $install_state['tasks_performed'][] = $task_name;
561 $install_state['installation_finished'] = empty($tasks_to_perform);
562 if ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished']) {
563 \Drupal::state()->set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
564 }
565 }
566 // Stop when there are no tasks left. In the case of an interactive
567 // installation, also stop if we have some output to send to the browser,
568 // the URL parameters have changed, or an end to the page request was
569 // specifically called for.
570 $finished = empty($tasks_to_perform) || ($install_state['interactive'] && (isset($output) || $install_state['parameters_changed'] || $install_state['stop_page_request']));
571 } while (!$finished);
572 return $output;
573 }
574
575 /**
576 * Runs an individual installation task.
577 *
578 * @param $task
579 * An array of information about the task to be run as returned by
580 * hook_install_tasks().
581 * @param $install_state
582 * An array of information about the current installation state. This is
583 * passed in by reference so that it can be modified by the task.
584 *
585 * @return
586 * The output of the task function, if there is any.
587 */
588 function install_run_task($task, &$install_state) {
589 $function = $task['function'];
590
591 if ($task['type'] == 'form') {
592 return install_get_form($function, $install_state);
593 }
594 elseif ($task['type'] == 'batch') {
595 // Start a new batch based on the task function, if one is not running
596 // already.
597 $current_batch = \Drupal::state()->get('install_current_batch');
598 if (!$install_state['interactive'] || !$current_batch) {
599 $batches = $function($install_state);
600 if (empty($batches)) {
601 // If the task did some processing and decided no batch was necessary,
602 // there is nothing more to do here.
603 return;
604 }
605 // Create a one item list of batches if only one batch was provided.
606 if (isset($batches['operations'])) {
607 $batches = [$batches];
608 }
609 foreach ($batches as $batch) {
610 batch_set($batch);
611 // For interactive batches, we need to store the fact that this batch
612 // task is currently running. Otherwise, we need to make sure the batch
613 // will complete in one page request.
614 if ($install_state['interactive']) {
615 \Drupal::state()->set('install_current_batch', $function);
616 }
617 else {
618 $batch =& batch_get();
619 $batch['progressive'] = FALSE;
620 }
621 }
622 // Process the batch. For progressive batches, this will redirect.
623 // Otherwise, the batch will complete.
624 // Disable the default script for the URL and clone the object, as
625 // batch_process() will add additional options to the batch URL.
626 $url = Url::fromUri('base:install.php', ['query' => $install_state['parameters'], 'script' => '']);
627 $response = batch_process($url, clone $url);
628 if ($response instanceof Response) {
629 if ($session = \Drupal::request()->getSession()) {
630 $session->save();
631 }
632 // Send the response.
633 $response->send();
634 exit;
635 }
636 }
637 // If we are in the middle of processing this batch, keep sending back
638 // any output from the batch process, until the task is complete.
639 elseif ($current_batch == $function) {
640 $output = _batch_page(\Drupal::request());
641 // Because Batch API now returns a JSON response for intermediary steps,
642 // but the installer doesn't handle Response objects yet, just send the
643 // output here and emulate the old model.
644 // @todo Replace this when we refactor the installer to use a request-
645 // response workflow.
646 if ($output instanceof Response) {
647 $output->send();
648 $output = NULL;
649 }
650 // The task is complete when we try to access the batch page and receive
651 // FALSE in return, since this means we are at a URL where we are no
652 // longer requesting a batch ID.
653 if ($output === FALSE) {
654 // Return nothing so the next task will run in the same request.
655 \Drupal::state()->delete('install_current_batch');
656 return;
657 }
658 else {
659 // We need to force the page request to end if the task is not
660 // complete, since the batch API sometimes prints JSON output
661 // rather than returning a themed page.
662 $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
663 return $output;
664 }
665 }
666 }
667
668 else {
669 // For normal tasks, just return the function result, whatever it is.
670 return $function($install_state);
671 }
672 }
673
674 /**
675 * Returns a list of tasks to perform during the current installation request.
676 *
677 * Note that the list of tasks can change based on the installation state as
678 * the page request evolves (for example, if an installation profile hasn't
679 * been selected yet, we don't yet know which profile tasks need to be run).
680 *
681 * @param $install_state
682 * An array of information about the current installation state.
683 *
684 * @return
685 * A list of tasks to be performed, with associated metadata.
686 */
687 function install_tasks_to_perform($install_state) {
688 // Start with a list of all currently available tasks.
689 $tasks = install_tasks($install_state);
690 foreach ($tasks as $name => $task) {
691 // Remove any tasks that were already performed or that never should run.
692 // Also, if we started this page request with an indication of the last
693 // task that was completed, skip that task and all those that come before
694 // it, unless they are marked as always needing to run.
695 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)) {
696 unset($tasks[$name]);
697 }
698 if (!empty($install_state['completed_task']) && $name == $install_state['completed_task']) {
699 $completed_task_found = TRUE;
700 }
701 }
702 return $tasks;
703 }
704
705 /**
706 * Returns a list of all tasks the installer currently knows about.
707 *
708 * This function will return tasks regardless of whether or not they are
709 * intended to run on the current page request. However, the list can change
710 * based on the installation state (for example, if an installation profile
711 * hasn't been selected yet, we don't yet know which profile tasks will be
712 * available).
713 *
714 * You can override this using hook_install_tasks() or
715 * hook_install_tasks_alter().
716 *
717 * @param $install_state
718 * An array of information about the current installation state.
719 *
720 * @return
721 * A list of tasks, with associated metadata as returned by
722 * hook_install_tasks().
723 */
724 function install_tasks($install_state) {
725 // Determine whether a translation file must be imported during the
726 // 'install_import_translations' task. Import when a non-English language is
727 // available and selected. Also we will need translations even if the
728 // installer language is English but there are other languages on the system.
729 $needs_translations = (count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en') || \Drupal::languageManager()->isMultilingual();
730 // Determine whether a translation file must be downloaded during the
731 // 'install_download_translation' task. Download when a non-English language
732 // is selected, but no translation is yet in the translations directory.
733 $needs_download = isset($install_state['parameters']['langcode']) && !isset($install_state['translations'][$install_state['parameters']['langcode']]) && $install_state['parameters']['langcode'] != 'en';
734
735 // Start with the core installation tasks that run before handing control
736 // to the installation profile.
737 $tasks = [
738 'install_select_language' => [
739 'display_name' => t('Choose language'),
740 'run' => INSTALL_TASK_RUN_IF_REACHED,
741 ],
742 'install_download_translation' => [
743 'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
744 ],
745 'install_select_profile' => [
746 'display_name' => t('Choose profile'),
747 'display' => empty($install_state['profile_info']['distribution']['name']) && count($install_state['profiles']) != 1,
748 'run' => INSTALL_TASK_RUN_IF_REACHED,
749 ],
750 'install_load_profile' => [
751 'run' => INSTALL_TASK_RUN_IF_REACHED,
752 ],
753 'install_verify_requirements' => [
754 'display_name' => t('Verify requirements'),
755 ],
756 'install_settings_form' => [
757 'display_name' => t('Set up database'),
758 'type' => 'form',
759 // Even though the form only allows the user to enter database settings,
760 // we still need to display it if settings.php is invalid in any way,
761 // since the form submit handler is where settings.php is rewritten.
762 'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
763 'function' => 'Drupal\Core\Installer\Form\SiteSettingsForm',
764 ],
765 'install_write_profile' => [],
766 'install_verify_database_ready' => [
767 'run' => $install_state['database_ready'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
768 ],
769 'install_base_system' => [
770 'run' => $install_state['base_system_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
771 ],
772 // All tasks below are executed in a regular, full Drupal environment.
773 'install_bootstrap_full' => [
774 'run' => INSTALL_TASK_RUN_IF_REACHED,
775 ],
776 'install_profile_modules' => [
777 'display_name' => t('Install site'),
778 'type' => 'batch',
779 ],
780 'install_profile_themes' => [],
781 'install_install_profile' => [],
782 'install_import_translations' => [
783 'display_name' => t('Set up translations'),
784 'display' => $needs_translations,
785 'type' => 'batch',
786 'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
787 ],
788 'install_configure_form' => [
789 'display_name' => t('Configure site'),
790 'type' => 'form',
791 'function' => 'Drupal\Core\Installer\Form\SiteConfigureForm',
792 ],
793 ];
794
795 // Now add any tasks defined by the installation profile.
796 if (!empty($install_state['parameters']['profile'])) {
797 // Load the profile install file, because it is not always loaded when
798 // hook_install_tasks() is invoked (e.g. batch processing).
799 $profile = $install_state['parameters']['profile'];
800 $profile_install_file = $install_state['profiles'][$profile]->getPath() . '/' . $profile . '.install';
801 if (file_exists($profile_install_file)) {
802 include_once \Drupal::root() . '/' . $profile_install_file;
803 }
804 $function = $install_state['parameters']['profile'] . '_install_tasks';
805 if (function_exists($function)) {
806 $result = $function($install_state);
807 if (is_array($result)) {
808 $tasks += $result;
809 }
810 }
811 }
812
813 // Finish by adding the remaining core tasks.
814 $tasks += [
815 'install_finish_translations' => [
816 'display_name' => t('Finish translations'),
817 'display' => $needs_translations,
818 'type' => 'batch',
819 'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
820 ],
821 'install_finished' => [],
822 ];
823
824 // Allow the installation profile to modify the full list of tasks.
825 if (!empty($install_state['parameters']['profile'])) {
826 $profile = $install_state['parameters']['profile'];
827 if ($install_state['profiles'][$profile]->load()) {
828 $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
829 if (function_exists($function)) {
830 $function($tasks, $install_state);
831 }
832 }
833 }
834
835 // Fill in default parameters for each task before returning the list.
836 foreach ($tasks as $task_name => &$task) {
837 $task += [
838 'display_name' => NULL,
839 'display' => !empty($task['display_name']),
840 'type' => 'normal',
841 'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
842 'function' => $task_name,
843 ];
844 }
845 return $tasks;
846 }
847
848 /**
849 * Returns a list of tasks that should be displayed to the end user.
850 *
851 * The output of this function is a list suitable for sending to
852 * maintenance-task-list.html.twig.
853 *
854 * @param $install_state
855 * An array of information about the current installation state.
856 *
857 * @return
858 * A list of tasks, with keys equal to the machine-readable task name and
859 * values equal to the name that should be displayed.
860 *
861 * @see maintenance-task-list.html.twig
862 */
863 function install_tasks_to_display($install_state) {
864 $displayed_tasks = [];
865 foreach (install_tasks($install_state) as $name => $task) {
866 if ($task['display']) {
867 $displayed_tasks[$name] = $task['display_name'];
868 }
869 }
870 return $displayed_tasks;
871 }
872
873 /**
874 * Builds and processes a form for the installer environment.
875 *
876 * Ensures that FormBuilder does not redirect after submitting a form, since the
877 * installer uses a custom step/flow logic via install_run_tasks().
878 *
879 * @param string|array $form_id
880 * The form ID to build and process.
881 * @param array $install_state
882 * The current state of the installation.
883 *
884 * @return array|null
885 * A render array containing the form to render, or NULL in case the form was
886 * successfully submitted.
887 *
888 * @throws \Drupal\Core\Installer\Exception\InstallerException
889 */
890 function install_get_form($form_id, array &$install_state) {
891 // Ensure the form will not redirect, since install_run_tasks() uses a custom
892 // redirection logic.
893 $form_state = (new FormState())
894 ->addBuildInfo('args', [&$install_state])
895 ->disableRedirect();
896 $form_builder = \Drupal::formBuilder();
897 if ($install_state['interactive']) {
898 $form = $form_builder->buildForm($form_id, $form_state);
899 // If the form submission was not successful, the form needs to be rendered,
900 // which means the task is not complete yet.
901 if (!$form_state->isExecuted()) {
902 $install_state['task_not_complete'] = TRUE;
903 return $form;
904 }
905 }
906 else {
907 // For non-interactive installs, submit the form programmatically with the
908 // values taken from the installation state.
909 $install_form_id = $form_builder->getFormId($form_id, $form_state);
910 if (!empty($install_state['forms'][$install_form_id])) {
911 $form_state->setValues($install_state['forms'][$install_form_id]);
912 }
913 $form_builder->submitForm($form_id, $form_state);
914
915 // Throw an exception in case of any form validation error.
916 if ($errors = $form_state->getErrors()) {
917 throw new InstallerException(implode("\n", $errors));
918 }
919 }
920 }
921
922 /**
923 * Returns the URL that should be redirected to during an installation request.
924 *
925 * The output of this function is suitable for sending to install_goto().
926 *
927 * @param $install_state
928 * An array of information about the current installation state.
929 *
930 * @return
931 * The URL to redirect to.
932 *
933 * @see install_full_redirect_url()
934 */
935 function install_redirect_url($install_state) {
936 return 'core/install.php?' . UrlHelper::buildQuery($install_state['parameters']);
937 }
938
939 /**
940 * Returns the complete URL redirected to during an installation request.
941 *
942 * @param $install_state
943 * An array of information about the current installation state.
944 *
945 * @return
946 * The complete URL to redirect to.
947 *
948 * @see install_redirect_url()
949 */
950 function install_full_redirect_url($install_state) {
951 global $base_url;
952 return $base_url . '/' . install_redirect_url($install_state);
953 }
954
955 /**
956 * Displays themed installer output and ends the page request.
957 *
958 * Installation tasks should use #title to set the desired page
959 * title, but otherwise this function takes care of theming the overall page
960 * output during every step of the installation.
961 *
962 * @param $output
963 * The content to display on the main part of the page.
964 * @param $install_state
965 * An array of information about the current installation state.
966 */
967 function install_display_output($output, $install_state) {
968 // Ensure the maintenance theme is initialized.
969 // The regular initialization call in install_begin_request() may not be
970 // reached in case of an early installer error.
971 drupal_maintenance_theme();
972
973 // Prevent install.php from being indexed when installed in a sub folder.
974 // robots.txt rules are not read if the site is within domain.com/subfolder
975 // resulting in /subfolder/install.php being found through search engines.
976 // When settings.php is writeable this can be used via an external database
977 // leading a malicious user to gain php access to the server.
978 $noindex_meta_tag = [
979 '#tag' => 'meta',
980 '#attributes' => [
981 'name' => 'robots',
982 'content' => 'noindex, nofollow',
983 ],
984 ];
985 $output['#attached']['html_head'][] = [$noindex_meta_tag, 'install_meta_robots'];
986
987 // Only show the task list if there is an active task; otherwise, the page
988 // request has ended before tasks have even been started, so there is nothing
989 // meaningful to show.
990 $regions = [];
991 if (isset($install_state['active_task'])) {
992 // Let the theming function know when every step of the installation has
993 // been completed.
994 $active_task = $install_state['installation_finished'] ? NULL : $install_state['active_task'];
995 $task_list = [
996 '#theme' => 'maintenance_task_list',
997 '#items' => install_tasks_to_display($install_state),
998 '#active' => $active_task,
999 ];
1000 $regions['sidebar_first'] = $task_list;
1001 }
1002
1003 $bare_html_page_renderer = \Drupal::service('bare_html_page_renderer');
1004 $response = $bare_html_page_renderer->renderBarePage($output, $output['#title'], 'install_page', $regions);
1005 $default_headers = [
1006 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
1007 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
1008 'Cache-Control' => 'no-cache, must-revalidate',
1009 'ETag' => '"' . REQUEST_TIME . '"',
1010 ];
1011 $response->headers->add($default_headers);
1012 $response->send();
1013 exit;
1014 }
1015
1016 /**
1017 * Verifies the requirements for installing Drupal.
1018 *
1019 * @param $install_state
1020 * An array of information about the current installation state.
1021 *
1022 * @return
1023 * A themed status report, or an exception if there are requirement errors.
1024 */
1025 function install_verify_requirements(&$install_state) {
1026 // Check the installation requirements for Drupal and this profile.
1027 $requirements = install_check_requirements($install_state);
1028
1029 // Verify existence of all required modules.
1030 $requirements += drupal_verify_profile($install_state);
1031
1032 return install_display_requirements($install_state, $requirements);
1033 }
1034
1035 /**
1036 * Installation task; install the base functionality Drupal needs to bootstrap.
1037 *
1038 * @param $install_state
1039 * An array of information about the current installation state.
1040 */
1041 function install_base_system(&$install_state) {
1042 // Install system.module.
1043 drupal_install_system($install_state);
1044
1045 // Prevent the installer from using the system temporary directory after the
1046 // system module has been installed.
1047 if (drupal_valid_test_ua()) {
1048 // While the temporary directory could be preset/enforced in settings.php
1049 // like the public files directory, some tests expect it to be configurable
1050 // in the UI. If declared in settings.php, they would no longer be
1051 // configurable. The temporary directory needs to match what is set in each
1052 // test types ::prepareEnvironment() step.
1053 $temporary_directory = dirname(PublicStream::basePath()) . '/temp';
1054 file_prepare_directory($temporary_directory, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
1055 \Drupal::configFactory()->getEditable('system.file')
1056 ->set('path.temporary', $temporary_directory)
1057 ->save();
1058 }
1059
1060 // Call file_ensure_htaccess() to ensure that all of Drupal's standard
1061 // directories (e.g., the public files directory and config directory) have
1062 // appropriate .htaccess files. These directories will have already been
1063 // created by this point in the installer, since Drupal creates them during
1064 // the install_verify_requirements() task. Note that we cannot call
1065 // file_ensure_access() any earlier than this, since it relies on
1066 // system.module in order to work.
1067 file_ensure_htaccess();
1068
1069 // Prime the drupal_get_filename() static cache with the user module's
1070 // exact location.
1071 // @todo Remove as part of https://www.drupal.org/node/2186491
1072 drupal_get_filename('module', 'user', 'core/modules/user/user.info.yml');
1073
1074 // Enable the user module so that sessions can be recorded during the
1075 // upcoming bootstrap step.
1076 \Drupal::service('module_installer')->install(['user'], FALSE);
1077
1078 // Save the list of other modules to install for the upcoming tasks.
1079 // State can be set to the database now that system.module is installed.
1080 $modules = $install_state['profile_info']['dependencies'];
1081
1082 \Drupal::state()->set('install_profile_modules', array_diff($modules, ['system']));
1083 $install_state['base_system_verified'] = TRUE;
1084 }
1085
1086 /**
1087 * Verifies and returns the last installation task that was completed.
1088 *
1089 * @return
1090 * The last completed task, if there is one. An exception is thrown if Drupal
1091 * is already installed.
1092 */
1093 function install_verify_completed_task() {
1094 try {
1095 $task = \Drupal::state()->get('install_task');
1096 }
1097 // Do not trigger an error if the database query fails, since the database
1098 // might not be set up yet.
1099 catch (\Exception $e) {
1100 }
1101 if (isset($task)) {
1102 if ($task == 'done') {
1103 throw new AlreadyInstalledException(\Drupal::service('string_translation'));
1104 }
1105 return $task;
1106 }
1107 }
1108
1109 /**
1110 * Verifies that settings.php specifies a valid database connection.
1111 *
1112 * @param string $site_path
1113 * The site path.
1114 *
1115 * @return bool
1116 * TRUE if there are no database errors.
1117 */
1118 function install_verify_database_settings($site_path) {
1119 if ($database = Database::getConnectionInfo()) {
1120 $database = $database['default'];
1121 $settings_file = './' . $site_path . '/settings.php';
1122 $errors = install_database_errors($database, $settings_file);
1123 if (empty($errors)) {
1124 return TRUE;
1125 }
1126 }
1127 return FALSE;
1128 }
1129
1130 /**
1131 * Verify that the database is ready (no existing Drupal installation).
1132 */
1133 function install_verify_database_ready() {
1134 $system_schema = system_schema();
1135 end($system_schema);
1136 $table = key($system_schema);
1137
1138 if ($database = Database::getConnectionInfo()) {
1139 if (Database::getConnection()->schema()->tableExists($table)) {
1140 throw new AlreadyInstalledException(\Drupal::service('string_translation'));
1141 }
1142 }
1143 }
1144
1145 /**
1146 * Checks a database connection and returns any errors.
1147 */
1148 function install_database_errors($database, $settings_file) {
1149 $errors = [];
1150
1151 // Check database type.
1152 $database_types = drupal_get_database_types();
1153 $driver = $database['driver'];
1154 if (!isset($database_types[$driver])) {
1155 $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.", ['%settings_file' => $settings_file, '@drupal' => drupal_install_profile_distribution_name(), '%driver' => $driver]);
1156 }
1157 else {
1158 // Run driver specific validation
1159 $errors += $database_types[$driver]->validateDatabaseSettings($database);
1160 if (!empty($errors)) {
1161 // No point to try further.
1162 return $errors;
1163 }
1164 // Run tasks associated with the database type. Any errors are caught in the
1165 // calling function.
1166 Database::addConnectionInfo('default', 'default', $database);
1167
1168 $errors = db_installer_object($driver)->runTasks();
1169 }
1170 return $errors;
1171 }
1172
1173 /**
1174 * Selects which profile to install.
1175 *
1176 * @param $install_state
1177 * An array of information about the current installation state. The chosen
1178 * profile will be added here, if it was not already selected previously, as
1179 * will a list of all available profiles.
1180 *
1181 * @return
1182 * For interactive installations, a form allowing the profile to be selected,
1183 * if the user has a choice that needs to be made. Otherwise, an exception is
1184 * thrown if a profile cannot be chosen automatically.
1185 */
1186 function install_select_profile(&$install_state) {
1187 if (empty($install_state['parameters']['profile'])) {
1188 // If there are no profiles at all, installation cannot proceed.
1189 if (empty($install_state['profiles'])) {
1190 throw new NoProfilesException(\Drupal::service('string_translation'));
1191 }
1192 // Try to automatically select a profile.
1193 if ($profile = _install_select_profile($install_state)) {
1194 $install_state['parameters']['profile'] = $profile;
1195 }
1196 else {
1197 // The non-interactive installer requires a profile parameter.
1198 if (!$install_state['interactive']) {
1199 throw new InstallerException(t('Missing profile parameter.'));
1200 }
1201 // Otherwise, display a form to select a profile.
1202 return install_get_form('Drupal\Core\Installer\Form\SelectProfileForm', $install_state);
1203 }
1204 }
1205 }
1206
1207 /**
1208 * Determines the installation profile to use in the installer.
1209 *
1210 * A profile will be selected in the following order of conditions:
1211 * - Only one profile is available.
1212 * - A specific profile name is requested in installation parameters:
1213 * - For interactive installations via request query parameters.
1214 * - For non-interactive installations via install_drupal() settings.
1215 * - A discovered profile that is a distribution. If multiple profiles are
1216 * distributions, then the first discovered profile will be selected.
1217 * - Only one visible profile is available.
1218 *
1219 * @param array $install_state
1220 * The current installer state, containing a 'profiles' key, which is an
1221 * associative array of profiles with the machine-readable names as keys.
1222 *
1223 * @return
1224 * The machine-readable name of the selected profile or NULL if no profile was
1225 * selected.
1226 */
1227 function _install_select_profile(&$install_state) {
1228 // Don't need to choose profile if only one available.
1229 if (count($install_state['profiles']) == 1) {
1230 return key($install_state['profiles']);
1231 }
1232 if (!empty($install_state['parameters']['profile'])) {
1233 $profile = $install_state['parameters']['profile'];
1234 if (isset($install_state['profiles'][$profile])) {
1235 return $profile;
1236 }
1237 }
1238 // Check for a distribution profile.
1239 foreach ($install_state['profiles'] as $profile) {
1240 $profile_info = install_profile_info($profile->getName());
1241 if (!empty($profile_info['distribution'])) {
1242 return $profile->getName();
1243 }
1244 }
1245
1246 // Get all visible (not hidden) profiles.
1247 $visible_profiles = array_filter($install_state['profiles'], function ($profile) {
1248 $profile_info = install_profile_info($profile->getName());
1249 return !isset($profile_info['hidden']) || !$profile_info['hidden'];
1250 });
1251
1252 if (count($visible_profiles) == 1) {
1253 return (key($visible_profiles));
1254 }
1255 }
1256
1257 /**
1258 * Finds all .po files that are useful to the installer.
1259 *
1260 * @return
1261 * An associative array of file URIs keyed by language code. URIs as
1262 * returned by file_scan_directory().
1263 *
1264 * @see file_scan_directory()
1265 */
1266 function install_find_translations() {
1267 $translations = [];
1268 $files = \Drupal::service('string_translator.file_translation')->findTranslationFiles();
1269 // English does not need a translation file.
1270 array_unshift($files, (object) ['name' => 'en']);
1271 foreach ($files as $uri => $file) {
1272 // Strip off the file name component before the language code.
1273 $langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
1274 // Language codes cannot exceed 12 characters to fit into the {language}
1275 // table.
1276 if (strlen($langcode) <= 12) {
1277 $translations[$langcode] = $uri;
1278 }
1279 }
1280 return $translations;
1281 }
1282
1283 /**
1284 * Selects which language to use during installation.
1285 *
1286 * @param $install_state
1287 * An array of information about the current installation state. The chosen
1288 * langcode will be added here, if it was not already selected previously, as
1289 * will a list of all available languages.
1290 *
1291 * @return
1292 * For interactive installations, a form or other page output allowing the
1293 * language to be selected or providing information about language selection,
1294 * if a language has not been chosen. Otherwise, an exception is thrown if a
1295 * language cannot be chosen automatically.
1296 */
1297 function install_select_language(&$install_state) {
1298 // Find all available translation files.
1299 $files = install_find_translations();
1300 $install_state['translations'] += $files;
1301
1302 // If a valid language code is set, continue with the next installation step.
1303 // When translations from the localization server are used, any language code
1304 // is accepted because the standard language list is kept in sync with the
1305 // languages available at http://localize.drupal.org.
1306 // When files from the translation directory are used, we only accept
1307 // languages for which a file is available.
1308 if (!empty($install_state['parameters']['langcode'])) {
1309 $standard_languages = LanguageManager::getStandardLanguageList();
1310 $langcode = $install_state['parameters']['langcode'];
1311 if ($langcode == 'en' || isset($files[$langcode]) || isset($standard_languages[$langcode])) {
1312 $install_state['parameters']['langcode'] = $langcode;
1313 return;
1314 }
1315 }
1316
1317 if (empty($install_state['parameters']['langcode'])) {
1318 // If we are performing an interactive installation, we display a form to
1319 // select a right language. If no translation files were found in the
1320 // translations directory, the form shows a list of standard languages. If
1321 // translation files were found the form shows a select list of the
1322 // corresponding languages to choose from.
1323 if ($install_state['interactive']) {
1324 return install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', $install_state);
1325 }
1326 // If we are performing a non-interactive installation. If only one language
1327 // (English) is available, assume the user knows what he is doing. Otherwise
1328 // throw an error.
1329 else {
1330 if (count($files) == 1) {
1331 $install_state['parameters']['langcode'] = current(array_keys($files));
1332 return;
1333 }
1334 else {
1335 throw new InstallerException(t('You must select a language to continue the installation.'));
1336 }
1337 }
1338 }
1339 }
1340
1341 /**
1342 * Download a translation file for the selected language.
1343 *
1344 * @param array $install_state
1345 * An array of information about the current installation state.
1346 *
1347 * @return string
1348 * A themed status report, or an exception if there are requirement errors.
1349 * Upon successful download the page is reloaded and no output is returned.
1350 */
1351 function install_download_translation(&$install_state) {
1352 // Check whether all conditions are met to download. Download the translation
1353 // if possible.
1354 $requirements = install_check_translations($install_state['parameters']['langcode'], $install_state['server_pattern']);
1355 if ($output = install_display_requirements($install_state, $requirements)) {
1356 return $output;
1357 }
1358
1359 // The download was successful, reload the page in the new language.
1360 $install_state['translations'][$install_state['parameters']['langcode']] = TRUE;
1361 if ($install_state['interactive']) {
1362 install_goto(install_redirect_url($install_state));
1363 }
1364 }
1365
1366 /**
1367 * Attempts to get a file using a HTTP request and to store it locally.
1368 *
1369 * @param string $uri
1370 * The URI of the file to grab.
1371 * @param string $destination
1372 * Stream wrapper URI specifying where the file should be placed. If a
1373 * directory path is provided, the file is saved into that directory under its
1374 * original name. If the path contains a filename as well, that one will be
1375 * used instead.
1376 *
1377 * @return bool
1378 * TRUE on success, FALSE on failure.
1379 */
1380 function install_retrieve_file($uri, $destination) {
1381 $parsed_url = parse_url($uri);
1382 if (is_dir(drupal_realpath($destination))) {
1383 // Prevent URIs with triple slashes when gluing parts together.
1384 $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
1385 }
1386 else {
1387 $path = $destination;
1388 }
1389
1390 try {
1391 $response = \Drupal::httpClient()->get($uri, ['headers' => ['Accept' => 'text/plain']]);
1392 $data = (string) $response->getBody();
1393 if (empty($data)) {
1394 return FALSE;
1395 }
1396 }
1397 catch (RequestException $e) {
1398 return FALSE;
1399 }
1400 return file_put_contents($path, $data) !== FALSE;
1401 }
1402
1403 /**
1404 * Checks if the localization server can be contacted.
1405 *
1406 * @param string $uri
1407 * The URI to contact.
1408 *
1409 * @return string
1410 * TRUE if the URI was contacted successfully, FALSE if not.
1411 */
1412 function install_check_localization_server($uri) {
1413 try {
1414 \Drupal::httpClient()->head($uri);
1415 return TRUE;
1416 }
1417 catch (RequestException $e) {
1418 return FALSE;
1419 }
1420 }
1421
1422 /**
1423 * Extracts version information from a drupal core version string.
1424 *
1425 * @param string $version
1426 * Version info string (e.g., 8.0.0, 8.1.0, 8.0.0-dev, 8.0.0-unstable1,
1427 * 8.0.0-alpha2, 8.0.0-beta3, and 8.0.0-rc4).
1428 *
1429 * @return array
1430 * Associative array of version info:
1431 * - major: Major version (e.g., "8").
1432 * - minor: Minor version (e.g., "0").
1433 * - patch: Patch version (e.g., "0").
1434 * - extra: Extra version info (e.g., "alpha2").
1435 * - extra_text: The text part of "extra" (e.g., "alpha").
1436 * - extra_number: The number part of "extra" (e.g., "2").
1437 */
1438 function _install_get_version_info($version) {
1439 preg_match('/
1440 (
1441 (?P<major>[0-9]+) # Major release number.
1442 \. # .
1443 (?P<minor>[0-9]+) # Minor release number.
1444 \. # .
1445 (?P<patch>[0-9]+) # Patch release number.
1446 ) #
1447 ( #
1448 - # - separator for "extra" version information.
1449 (?P<extra> #
1450 (?P<extra_text>[a-z]+) # Release extra text (e.g., "alpha").
1451 (?P<extra_number>[0-9]*) # Release extra number (no separator between text and number).
1452 ) #
1453 | # OR no "extra" information.
1454 )
1455 /sx', $version, $matches);
1456
1457 return $matches;
1458 }
1459
1460 /**
1461 * Loads information about the chosen profile during installation.
1462 *
1463 * @param $install_state
1464 * An array of information about the current installation state. The loaded
1465 * profile information will be added here.
1466 */
1467 function install_load_profile(&$install_state) {
1468 $profile = $install_state['parameters']['profile'];
1469 $install_state['profiles'][$profile]->load();
1470 $install_state['profile_info'] = install_profile_info($profile, isset($install_state['parameters']['langcode']) ? $install_state['parameters']['langcode'] : 'en');
1471 }
1472
1473 /**
1474 * Performs a full bootstrap of Drupal during installation.
1475 */
1476 function install_bootstrap_full() {
1477 // Store the session on the request object and start it.
1478 /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
1479 $session = \Drupal::service('session');
1480 \Drupal::request()->setSession($session);
1481 $session->start();
1482 }
1483
1484 /**
1485 * Installs required modules via a batch process.
1486 *
1487 * @param $install_state
1488 * An array of information about the current installation state.
1489 *
1490 * @return
1491 * The batch definition.
1492 */
1493 function install_profile_modules(&$install_state) {
1494 // We need to manually trigger the installation of core-provided entity types,
1495 // as those will not be handled by the module installer.
1496 install_core_entity_type_definitions();
1497
1498 $modules = \Drupal::state()->get('install_profile_modules') ?: [];
1499 $files = system_rebuild_module_data();
1500 \Drupal::state()->delete('install_profile_modules');
1501
1502 // Always install required modules first. Respect the dependencies between
1503 // the modules.
1504 $required = [];
1505 $non_required = [];
1506
1507 // Add modules that other modules depend on.
1508 foreach ($modules as $module) {
1509 if ($files[$module]->requires) {
1510 $modules = array_merge($modules, array_keys($files[$module]->requires));
1511 }
1512 }
1513 $modules = array_unique($modules);
1514 foreach ($modules as $module) {
1515 if (!empty($files[$module]->info['required'])) {
1516 $required[$module] = $files[$module]->sort;
1517 }
1518 else {
1519 $non_required[$module] = $files[$module]->sort;
1520 }
1521 }
1522 arsort($required);
1523 arsort($non_required);
1524
1525 $operations = [];
1526 foreach ($required + $non_required as $module => $weight) {
1527 $operations[] = ['_install_module_batch', [$module, $files[$module]->info['name']]];
1528 }
1529 $batch = [
1530 'operations' => $operations,
1531 'title' => t('Installing @drupal', ['@drupal' => drupal_install_profile_distribution_name()]),
1532 'error_message' => t('The installation has encountered an error.'),
1533 ];
1534 return $batch;
1535 }
1536
1537 /**
1538 * Installs entity type definitions provided by core.
1539 */
1540 function install_core_entity_type_definitions() {
1541 $update_manager = \Drupal::entityDefinitionUpdateManager();
1542 foreach (\Drupal::entityManager()->getDefinitions() as $entity_type) {
1543 if ($entity_type->getProvider() == 'core') {
1544 $update_manager->installEntityType($entity_type);
1545 }
1546 }
1547 }
1548
1549 /**
1550 * Installs themes.
1551 *
1552 * This does not use a batch, since installing themes is faster than modules and
1553 * because an installation profile typically installs 1-3 themes only (default
1554 * theme, base theme, admin theme).
1555 *
1556 * @param $install_state
1557 * An array of information about the current installation state.
1558 */
1559 function install_profile_themes(&$install_state) {
1560 // Install the themes specified by the installation profile.
1561 $themes = $install_state['profile_info']['themes'];
1562 \Drupal::service('theme_handler')->install($themes);
1563
1564 // Ensure that the install profile's theme is used.
1565 // @see _drupal_maintenance_theme()
1566 \Drupal::theme()->resetActiveTheme();
1567 }
1568
1569 /**
1570 * Installs the install profile.
1571 *
1572 * @param $install_state
1573 * An array of information about the current installation state.
1574 */
1575 function install_install_profile(&$install_state) {
1576 \Drupal::service('module_installer')->install([drupal_get_profile()], FALSE);
1577 // Install all available optional config. During installation the module order
1578 // is determined by dependencies. If there are no dependencies between modules
1579 // then the order in which they are installed is dependent on random factors
1580 // like PHP version. Optional configuration therefore might or might not be
1581 // created depending on this order. Ensuring that we have installed all of the
1582 // optional configuration whose dependencies can be met at this point removes
1583 // any disparities that this creates.
1584 \Drupal::service('config.installer')->installOptionalConfig();
1585
1586 // Ensure that the install profile's theme is used.
1587 // @see _drupal_maintenance_theme()
1588 \Drupal::theme()->resetActiveTheme();
1589 }
1590
1591 /**
1592 * Prepares the system for import and downloads additional translations.
1593 *
1594 * @param $install_state
1595 * An array of information about the current installation state.
1596 *
1597 * @return
1598 * The batch definition, if there are language files to download.
1599 */
1600 function install_download_additional_translations_operations(&$install_state) {
1601 \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
1602
1603 $langcode = $install_state['parameters']['langcode'];
1604 if (!($language = ConfigurableLanguage::load($langcode))) {
1605 // Create the language if not already shipped with a profile.
1606 $language = ConfigurableLanguage::createFromLangcode($langcode);
1607 }
1608 $language->save();
1609
1610 // If a non-English language was selected, change the default language and
1611 // remove English.
1612 if ($langcode != 'en') {
1613 \Drupal::configFactory()->getEditable('system.site')
1614 ->set('langcode', $langcode)
1615 ->set('default_langcode', $langcode)
1616 ->save();
1617 \Drupal::service('language.default')->set($language);
1618 if (empty($install_state['profile_info']['keep_english'])) {
1619 entity_delete_multiple('configurable_language', ['en']);
1620 }
1621 }
1622
1623 // If there is more than one language or the single one is not English, we
1624 // should download/import translations.
1625 $languages = \Drupal::languageManager()->getLanguages();
1626 $operations = [];
1627 foreach ($languages as $langcode => $language) {
1628 // The installer language was already downloaded. Check downloads for the
1629 // other languages if any. Ignore any download errors here, since we
1630 // are in the middle of an install process and there is no way back. We
1631 // will not import what we cannot download.
1632 if ($langcode != 'en' && $langcode != $install_state['parameters']['langcode']) {
1633 $operations[] = ['install_check_translations', [$langcode, $install_state['server_pattern']]];
1634 }
1635 }
1636 return $operations;
1637 }
1638
1639 /**
1640 * Imports languages via a batch process during installation.
1641 *
1642 * @param $install_state
1643 * An array of information about the current installation state.
1644 *
1645 * @return
1646 * The batch definition, if there are language files to import.
1647 */
1648 function install_import_translations(&$install_state) {
1649 \Drupal::moduleHandler()->loadInclude('locale', 'translation.inc');
1650
1651 // If there is more than one language or the single one is not English, we
1652 // should import translations.
1653 $operations = install_download_additional_translations_operations($install_state);
1654 $languages = \Drupal::languageManager()->getLanguages();
1655 if (count($languages) > 1 || !isset($languages['en'])) {
1656 $operations[] = ['_install_prepare_import', [array_keys($languages), $install_state['server_pattern']]];
1657
1658 // Set up a batch to import translations for drupal core. Translation import
1659 // for contrib modules happens in install_import_translations_remaining.
1660 foreach ($languages as $language) {
1661 if (locale_translation_use_remote_source()) {
1662 $operations[] = ['locale_translation_batch_fetch_download', ['drupal', $language->getId()]];
1663 }
1664 $operations[] = ['locale_translation_batch_fetch_import', ['drupal', $language->getId(), []]];
1665 }
1666
1667 module_load_include('fetch.inc', 'locale');
1668 $batch = [
1669 'operations' => $operations,
1670 'title' => t('Updating translations.'),
1671 'progress_message' => '',
1672 'error_message' => t('Error importing translation files'),
1673 'finished' => 'locale_translation_batch_fetch_finished',
1674 'file' => drupal_get_path('module', 'locale') . '/locale.batch.inc',
1675 ];
1676 return $batch;
1677 }
1678 }
1679
1680 /**
1681 * Tells the translation import process that Drupal core is installed.
1682 *
1683 * @param array $langcodes
1684 * Language codes used for the translations.
1685 * @param string $server_pattern
1686 * Server access pattern (to replace language code, version number, etc. in).
1687 */
1688 function _install_prepare_import($langcodes, $server_pattern) {
1689 \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
1690 $matches = [];
1691
1692 foreach ($langcodes as $langcode) {
1693 // Get the translation files located in the translations directory.
1694 $files = locale_translate_get_interface_translation_files(['drupal'], [$langcode]);
1695 // Pick the first file which matches the language, if any.
1696 $file = reset($files);
1697 if (is_object($file)) {
1698 $filename = $file->filename;
1699 preg_match('/drupal-([0-9a-z\.-]+)\.' . $langcode . '\.po/', $filename, $matches);
1700 // Get the version information.
1701 if ($version = $matches[1]) {
1702 $info = _install_get_version_info($version);
1703 // Picking the first file does not necessarily result in the right file. So
1704 // we check if at least the major version number is available.
1705 if ($info['major']) {
1706 $core = $info['major'] . '.x';
1707 $data = [
1708 'name' => 'drupal',
1709 'project_type' => 'module',
1710 'core' => $core,
1711 'version' => $version,
1712 'server_pattern' => $server_pattern,
1713 'status' => 1,
1714 ];
1715 \Drupal::service('locale.project')->set($data['name'], $data);
1716 module_load_include('compare.inc', 'locale');
1717 locale_translation_check_projects_local(['drupal'], [$langcode]);
1718 }
1719 }
1720 }
1721 }
1722 }
1723
1724 /**
1725 * Finishes importing files at end of installation.
1726 *
1727 * If other projects besides Drupal core have been installed, their translation
1728 * will be imported here.
1729 *
1730 * @param $install_state
1731 * An array of information about the current installation state.
1732 *
1733 * @return array
1734 * An array of batch definitions.
1735 */
1736 function install_finish_translations(&$install_state) {
1737 \Drupal::moduleHandler()->loadInclude('locale', 'fetch.inc');
1738 \Drupal::moduleHandler()->loadInclude('locale', 'compare.inc');
1739 \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
1740
1741 // Build a fresh list of installed projects. When more projects than core are
1742 // installed, their translations will be downloaded (if required) and imported
1743 // using a batch.
1744 $projects = locale_translation_build_projects();
1745 $languages = \Drupal::languageManager()->getLanguages();
1746 $batches = [];
1747 if (count($projects) > 1) {
1748 $options = _locale_translation_default_update_options();
1749 if ($batch = locale_translation_batch_update_build([], array_keys($languages), $options)) {
1750 $batches[] = $batch;
1751 }
1752 }
1753
1754 // Creates configuration translations.
1755 $batches[] = locale_config_batch_update_components([], array_keys($languages));
1756 return $batches;
1757 }
1758
1759 /**
1760 * Performs final installation steps and displays a 'finished' page.
1761 *
1762 * @param $install_state
1763 * An array of information about the current installation state.
1764 *
1765 * @return
1766 * A message informing the user that the installation is complete.
1767 */
1768 function install_finished(&$install_state) {
1769 $profile = drupal_get_profile();
1770
1771 // Installation profiles are always loaded last.
1772 module_set_weight($profile, 1000);
1773
1774 // Build the router once after installing all modules.
1775 // This would normally happen upon KernelEvents::TERMINATE, but since the
1776 // installer does not use an HttpKernel, that event is never triggered.
1777 \Drupal::service('router.builder')->rebuild();
1778
1779 // Run cron to populate update status tables (if available) so that users
1780 // will be warned if they've installed an out of date Drupal version.
1781 // Will also trigger indexing of profile-supplied content or feeds.
1782 \Drupal::service('cron')->run();
1783
1784 if ($install_state['interactive']) {
1785 // Load current user and perform final login tasks.
1786 // This has to be done after drupal_flush_all_caches()
1787 // to avoid session regeneration.
1788 $account = User::load(1);
1789 user_login_finalize($account);
1790 }
1791
1792 $success_message = t('Congratulations, you installed @drupal!', [
1793 '@drupal' => drupal_install_profile_distribution_name(),
1794 ]);
1795 drupal_set_message($success_message);
1796 }
1797
1798 /**
1799 * Implements callback_batch_operation().
1800 *
1801 * Performs batch installation of modules.
1802 */
1803 function _install_module_batch($module, $module_name, &$context) {
1804 \Drupal::service('module_installer')->install([$module], FALSE);
1805 $context['results'][] = $module;
1806 $context['message'] = t('Installed %module module.', ['%module' => $module_name]);
1807 }
1808
1809 /**
1810 * Checks installation requirements and reports any errors.
1811 *
1812 * @param string $langcode
1813 * Language code to check for download.
1814 * @param string $server_pattern
1815 * Server access pattern (to replace language code, version number, etc. in).
1816 *
1817 * @return array|null
1818 * Requirements compliance array. If the translation was downloaded
1819 * successfully then an empty array is returned. Otherwise the requirements
1820 * error with detailed information. NULL if the file already exists for this
1821 * language code.
1822 */
1823 function install_check_translations($langcode, $server_pattern) {
1824 $requirements = [];
1825
1826 $readable = FALSE;
1827 $writable = FALSE;
1828 // @todo: Make this configurable.
1829 $site_path = \Drupal::service('site.path');
1830 $files_directory = $site_path . '/files';
1831 $translations_directory = $site_path . '/files/translations';
1832 $translations_directory_exists = FALSE;
1833 $online = FALSE;
1834
1835 // First attempt to create or make writable the files directory.
1836 file_prepare_directory($files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1837 // Then, attempt to create or make writable the translations directory.
1838 file_prepare_directory($translations_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1839
1840 // Get values so the requirements errors can be specific.
1841 if (drupal_verify_install_file($translations_directory, FILE_EXIST, 'dir')) {
1842 $readable = is_readable($translations_directory);
1843 $writable = is_writable($translations_directory);
1844 $translations_directory_exists = TRUE;
1845 }
1846
1847 // The file already exists, no need to attempt to download.
1848 if ($existing_file = glob($translations_directory . '/drupal-*.' . $langcode . '.po')) {
1849 return;
1850 }
1851
1852 // Build URL for the translation file and the translation server.
1853 $variables = [
1854 '%project' => 'drupal',
1855 '%version' => \Drupal::VERSION,
1856 '%core' => \Drupal::CORE_COMPATIBILITY,
1857 '%language' => $langcode,
1858 ];
1859 $translation_url = strtr($server_pattern, $variables);
1860
1861 $elements = parse_url($translation_url);
1862 $server_url = $elements['scheme'] . '://' . $elements['host'];
1863
1864 // Build the language name for display.
1865 $languages = LanguageManager::getStandardLanguageList();
1866 $language = isset($languages[$langcode]) ? $languages[$langcode][0] : $langcode;
1867
1868 // Check if any of the desired translation files are available or if the
1869 // translation server can be reached. In other words, check if we are online
1870 // and have an internet connection.
1871 if ($translation_available = install_check_localization_server($translation_url)) {
1872 $online = TRUE;
1873 }
1874 if (!$translation_available) {
1875 if (install_check_localization_server($server_url)) {
1876 $online = TRUE;
1877 }
1878 }
1879
1880 // If the translations directory does not exists, throw an error.
1881 if (!$translations_directory_exists) {
1882 $requirements['translations directory exists'] = [
1883 'title' => t('Translations directory'),
1884 'value' => t('The translations directory does not exist.'),
1885 'severity' => REQUIREMENT_ERROR,
1886 'description' => t('The installer requires that you create a translations directory as part of the installation process. Create the directory %translations_directory . More details about installing Drupal are available in <a href=":install_txt">INSTALL.txt</a>.', ['%translations_directory' => $translations_directory, ':install_txt' => base_path() . 'core/INSTALL.txt']),
1887 ];
1888 }
1889 else {
1890 $requirements['translations directory exists'] = [
1891 'title' => t('Translations directory'),
1892 'value' => t('The directory %translations_directory exists.', ['%translations_directory' => $translations_directory]),
1893 ];
1894 // If the translations directory is not readable, throw an error.
1895 if (!$readable) {
1896 $requirements['translations directory readable'] = [
1897 'title' => t('Translations directory'),
1898 'value' => t('The translations directory is not readable.'),
1899 'severity' => REQUIREMENT_ERROR,
1900 'description' => t('The installer requires read permissions to %translations_directory at all times. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', ['%translations_directory' => $translations_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']),
1901 ];
1902 }
1903 // If translations directory is not writable, throw an error.
1904 if (!$writable) {
1905 $requirements['translations directory writable'] = [
1906 'title' => t('Translations directory'),
1907 'value' => t('The translations directory is not writable.'),
1908 'severity' => REQUIREMENT_ERROR,
1909 'description' => t('The installer requires write permissions to %translations_directory during the installation process. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', ['%translations_directory' => $translations_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']),
1910 ];
1911 }
1912 else {
1913 $requirements['translations directory writable'] = [
1914 'title' => t('Translations directory'),
1915 'value' => t('The translations directory is writable.'),
1916 ];
1917 }
1918 }
1919
1920 // If the translations server can not be contacted, throw an error.
1921 if (!$online) {
1922 $requirements['online'] = [
1923 'title' => t('Internet'),
1924 'value' => t('The translation server is offline.'),
1925 'severity' => REQUIREMENT_ERROR,
1926 'description' => t('The installer requires to contact the translation server to download a translation file. Check your internet connection and verify that your website can reach the translation server at <a href=":server_url">@server_url</a>.', [':server_url' => $server_url, '@server_url' => $server_url]),
1927 ];
1928 }
1929 else {
1930 $requirements['online'] = [
1931 'title' => t('Internet'),
1932 'value' => t('The translation server is online.'),
1933 ];
1934 // If translation file is not found at the translation server, throw an
1935 // error.
1936 if (!$translation_available) {
1937 $requirements['translation available'] = [
1938 'title' => t('Translation'),
1939 'value' => t('The %language translation is not available.', ['%language' => $language]),
1940 'severity' => REQUIREMENT_ERROR,
1941 'description' => t('The %language translation file is not available at the translation server. <a href=":url">Choose a different language</a> or select English and translate your website later.', ['%language' => $language, ':url' => $_SERVER['SCRIPT_NAME']]),
1942 ];
1943 }
1944 else {
1945 $requirements['translation available'] = [
1946 'title' => t('Translation'),
1947 'value' => t('The %language translation is available.', ['%language' => $language]),
1948 ];
1949 }
1950 }
1951
1952 if ($translations_directory_exists && $readable && $writable && $translation_available) {
1953 $translation_downloaded = install_retrieve_file($translation_url, $translations_directory);
1954
1955 if (!$translation_downloaded) {
1956 $requirements['translation downloaded'] = [
1957 'title' => t('Translation'),
1958 'value' => t('The %language translation could not be downloaded.', ['%language' => $language]),
1959 'severity' => REQUIREMENT_ERROR,
1960 'description' => t('The %language translation file could not be downloaded. <a href=":url">Choose a different language</a> or select English and translate your website later.', ['%language' => $language, ':url' => $_SERVER['SCRIPT_NAME']]),
1961 ];
1962 }
1963 }
1964
1965 return $requirements;
1966 }
1967
1968 /**
1969 * Checks installation requirements and reports any errors.
1970 */
1971 function install_check_requirements($install_state) {
1972 $profile = $install_state['parameters']['profile'];
1973
1974 // Check the profile requirements.
1975 $requirements = drupal_check_profile($profile);
1976
1977 if ($install_state['settings_verified']) {
1978 return $requirements;
1979 }
1980
1981 // If Drupal is not set up already, we need to try to create the default
1982 // settings and services files.
1983 $default_files = [];
1984 $default_files['settings.php'] = [
1985 'file' => 'settings.php',
1986 'file_default' => 'default.settings.php',
1987 'title_default' => t('Default settings file'),
1988 'description_default' => t('The default settings file does not exist.'),
1989 'title' => t('Settings file'),
1990 ];
1991
1992 foreach ($default_files as $default_file_info) {
1993 $readable = FALSE;
1994 $writable = FALSE;
1995 $site_path = './' . \Drupal::service('site.path');
1996 $file = $site_path . "/{$default_file_info['file']}";
1997 $default_file = "./sites/default/{$default_file_info['file_default']}";
1998 $exists = FALSE;
1999 // Verify that the directory exists.
2000 if (drupal_verify_install_file($site_path, FILE_EXIST, 'dir')) {
2001 if (drupal_verify_install_file($file, FILE_EXIST)) {
2002 // If it does, make sure it is writable.
2003 $readable = drupal_verify_install_file($file, FILE_READABLE);
2004 $writable = drupal_verify_install_file($file, FILE_WRITABLE);
2005 $exists = TRUE;
2006 }
2007 }
2008
2009 // If the default $default_file does not exist, or is not readable,
2010 // report an error.
2011 if (!drupal_verify_install_file($default_file, FILE_EXIST | FILE_READABLE)) {
2012 $requirements["default $file file exists"] = [
2013 'title' => $default_file_info['title_default'],
2014 'value' => $default_file_info['description_default'],
2015 'severity' => REQUIREMENT_ERROR,
2016 'description' => t('The @drupal installer requires that the %default-file file not be modified in any way from the original download.', [
2017 '@drupal' => drupal_install_profile_distribution_name(),
2018 '%default-file' => $default_file
2019 ]),
2020 ];
2021 }
2022 // Otherwise, if $file does not exist yet, we can try to copy
2023 // $default_file to create it.
2024 elseif (!$exists) {
2025 $copied = drupal_verify_install_file($site_path, FILE_EXIST | FILE_WRITABLE, 'dir') && @copy($default_file, $file);
2026 if ($copied) {
2027 // If the new $file file has the same owner as $default_file this means
2028 // $default_file is owned by the webserver user. This is an inherent
2029 // security weakness because it allows a malicious webserver process to
2030 // append arbitrary PHP code and then execute it. However, it is also a
2031 // common configuration on shared hosting, and there is nothing Drupal
2032 // can do to prevent it. In this situation, having $file also owned by
2033 // the webserver does not introduce any additional security risk, so we
2034 // keep the file in place. Additionally, this situation also occurs when
2035 // the test runner is being run be different user than the webserver.
2036 if (fileowner($default_file) === fileowner($file) || DRUPAL_TEST_IN_CHILD_SITE) {
2037 $readable = drupal_verify_install_file($file, FILE_READABLE);
2038 $writable = drupal_verify_install_file($file, FILE_WRITABLE);
2039 $exists = TRUE;
2040 }
2041 // If $file and $default_file have different owners, this probably means
2042 // the server is set up "securely" (with the webserver running as its
2043 // own user, distinct from the user who owns all the Drupal PHP files),
2044 // although with either a group or world writable sites directory.
2045 // Keeping $file owned by the webserver would therefore introduce a
2046 // security risk. It would also cause a usability problem, since site
2047 // owners who do not have root access to the file system would be unable
2048 // to edit their settings file later on. We therefore must delete the
2049 // file we just created and force the administrator to log on to the
2050 // server and create it manually.
2051 else {
2052 $deleted = @drupal_unlink($file);
2053 // We expect deleting the file to be successful (since we just
2054 // created it ourselves above), but if it fails somehow, we set a
2055 // variable so we can display a one-time error message to the
2056 // administrator at the bottom of the requirements list. We also try
2057 // to make the file writable, to eliminate any conflicting error
2058 // messages in the requirements list.
2059 $exists = !$deleted;
2060 if ($exists) {
2061 $settings_file_ownership_error = TRUE;
2062 $readable = drupal_verify_install_file($file, FILE_READABLE);
2063 $writable = drupal_verify_install_file($file, FILE_WRITABLE);
2064 }
2065 }
2066 }
2067 }
2068
2069 // If the $file does not exist, throw an error.
2070 if (!$exists) {
2071 $requirements["$file file exists"] = [
2072 'title' => $default_file_info['title'],
2073 'value' => t('The %file does not exist.', ['%file' => $default_file_info['title']]),
2074 'severity' => REQUIREMENT_ERROR,
2075 'description' => t('The @drupal installer requires that you create a %file as part of the installation process. Copy the %default_file file to %file. More details about installing Drupal are available in <a href=":install_txt">INSTALL.txt</a>.', [
2076 '@drupal' => drupal_install_profile_distribution_name(),
2077 '%file' => $file,
2078 '%default_file' => $default_file,
2079 ':install_txt' => base_path() . 'core/INSTALL.txt'
2080 ]),
2081 ];
2082 }
2083 else {
2084 $requirements["$file file exists"] = [
2085 'title' => $default_file_info['title'],
2086 'value' => t('The %file exists.', ['%file' => $file]),
2087 ];
2088 // If the $file is not readable, throw an error.
2089 if (!$readable) {
2090 $requirements["$file file readable"] = [
2091 'title' => $default_file_info['title'],
2092 'value' => t('The %file is not readable.', ['%file' => $default_file_info['title']]),
2093 'severity' => REQUIREMENT_ERROR,
2094 'description' => t('@drupal requires read permissions to %file at all times. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', [
2095 '@drupal' => drupal_install_profile_distribution_name(),
2096 '%file' => $file,
2097 ':handbook_url' => 'https://www.drupal.org/server-permissions'
2098 ]),
2099 ];
2100 }
2101 // If the $file is not writable, throw an error.
2102 if (!$writable) {
2103 $requirements["$file file writeable"] = [
2104 'title' => $default_file_info['title'],
2105 'value' => t('The %file is not writable.', ['%file' => $default_file_info['title']]),
2106 'severity' => REQUIREMENT_ERROR,
2107 'description' => t('The @drupal installer requires write permissions to %file during the installation process. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', [
2108 '@drupal' => drupal_install_profile_distribution_name(),
2109 '%file' => $file,
2110 ':handbook_url' => 'https://www.drupal.org/server-permissions'
2111 ]),
2112 ];
2113 }
2114 else {
2115 $requirements["$file file"] = [
2116 'title' => $default_file_info['title'],
2117 'value' => t('The @file is writable.', ['@file' => $default_file_info['title']]),
2118 ];
2119 }
2120 if (!empty($settings_file_ownership_error)) {
2121 $requirements["$file file ownership"] = [
2122 'title' => $default_file_info['title'],
2123 'value' => t('The @file is owned by the web server.', ['@file' => $default_file_info['title']]),
2124 'severity' => REQUIREMENT_ERROR,
2125 'description' => t('The @drupal installer failed to create a %file file with proper file ownership. Log on to your web server, remove the existing %file file, and create a new one by copying the %default_file file to %file. More details about installing Drupal are available in <a href=":install_txt">INSTALL.txt</a>. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', [
2126 '@drupal' => drupal_install_profile_distribution_name(),
2127 '%file' => $file,
2128 '%default_file' => $default_file,
2129 ':install_txt' => base_path() . 'core/INSTALL.txt',
2130 ':handbook_url' => 'https://www.drupal.org/server-permissions'
2131 ]),
2132 ];
2133 }
2134 }
2135 }
2136 return $requirements;
2137 }
2138
2139 /**
2140 * Displays installation requirements.
2141 *
2142 * @param array $install_state
2143 * An array of information about the current installation state.
2144 * @param array $requirements
2145 * An array of requirements, in the same format as is returned by
2146 * hook_requirements().
2147 *
2148 * @return
2149 * A themed status report, or an exception if there are requirement errors.
2150 * If there are only requirement warnings, a themed status report is shown
2151 * initially, but the user is allowed to bypass it by providing 'continue=1'
2152 * in the URL. Otherwise, no output is returned, so that the next task can be
2153 * run in the same page request.
2154 *
2155 * @throws \Drupal\Core\Installer\Exception\InstallerException
2156 */
2157 function install_display_requirements($install_state, $requirements) {
2158 // Check the severity of the requirements reported.
2159 $severity = drupal_requirements_severity($requirements);
2160
2161 // If there are errors, always display them. If there are only warnings, skip
2162 // them if the user has provided a URL parameter acknowledging the warnings
2163 // and indicating a desire to continue anyway. See drupal_requirements_url().
2164 if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
2165 if ($install_state['interactive']) {
2166 $build['report']['#type'] = 'status_report';
2167 $build['report']['#requirements'] = $requirements;
2168 if ($severity == REQUIREMENT_WARNING) {
2169 $build['#title'] = t('Requirements review');
2170 $build['#suffix'] = t('Check the messages and <a href=":retry">retry</a>, or you may choose to <a href=":cont">continue anyway</a>.', [':retry' => drupal_requirements_url(REQUIREMENT_ERROR), ':cont' => drupal_requirements_url($severity)]);
2171 }
2172 else {
2173 $build['#title'] = t('Requirements problem');
2174 $build['#suffix'] = t('Check the messages and <a href=":url">try again</a>.', [':url' => drupal_requirements_url($severity)]);
2175 }
2176 return $build;
2177 }
2178 else {
2179 // Throw an exception showing any unmet requirements.
2180 $failures = [];
2181 foreach ($requirements as $requirement) {
2182 // Skip warnings altogether for non-interactive installations; these
2183 // proceed in a single request so there is no good opportunity (and no
2184 // good method) to warn the user anyway.
2185 if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
2186 $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
2187 }
2188 }
2189 if (!empty($failures)) {
2190 throw new InstallerException(implode("\n\n", $failures));
2191 }
2192 }
2193 }
2194 }
2195
2196 /**
2197 * Installation task; writes profile to settings.php if possible.
2198 *
2199 * @param array $install_state
2200 * An array of information about the current installation state.
2201 *
2202 * @see _install_select_profile()
2203 *
2204 * @throws \Drupal\Core\Installer\Exception\InstallProfileMismatchException
2205 *
2206 * @deprecated in Drupal 8.3.0 and will be removed before Drupal 9.0.0. The
2207 * install profile is written to core.extension.
2208 */
2209 function install_write_profile($install_state) {
2210 // Only need to write to settings.php if it is possible. The primary storage
2211 // for the install profile is the core.extension configuration.
2212 $settings_path = \Drupal::service('site.path') . '/settings.php';
2213 if (is_writable($settings_path)) {
2214 // Remember the profile which was used.
2215 $settings['settings']['install_profile'] = (object) [
2216 'value' => $install_state['parameters']['profile'],
2217 'required' => TRUE,
2218 ];
2219 drupal_rewrite_settings($settings);
2220 }
2221 elseif (($settings_profile = Settings::get('install_profile')) && $settings_profile !== $install_state['parameters']['profile']) {
2222 throw new InstallProfileMismatchException($install_state['parameters']['profile'], $settings_profile, $settings_path, \Drupal::translation());
2223 }
2224 }