1<?php
2
3/**
4 * @file
5 * Install, update and uninstall functions for the system module.
6 */
7
8use Drupal\Component\FileSystem\FileSystem as FileSystemComponent;
9use Drupal\Component\Utility\Bytes;
10use Drupal\Component\Utility\Crypt;
11use Drupal\Component\Utility\Environment;
12use Drupal\Component\Utility\OpCodeCache;
13use Drupal\Component\Utility\Unicode;
14use Drupal\Core\Database\Database;
15use Drupal\Core\DrupalKernel;
16use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
17use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
18use Drupal\Core\File\FileSystemInterface;
19use Drupal\Core\Link;
20use Drupal\Core\Site\Settings;
21use Drupal\Core\StreamWrapper\PrivateStream;
22use Drupal\Core\StreamWrapper\PublicStream;
23use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
24use Drupal\Core\StringTranslation\TranslatableMarkup;
25use Drupal\Core\Url;
26use GuzzleHttp\Exception\TransferException;
27use Symfony\Component\HttpFoundation\Request;
28
29/**
30 * Implements hook_requirements().
31 */
32function system_requirements($phase) {
33  global $install_state;
34  // Reset the extension lists.
35  \Drupal::service('extension.list.module')->reset();
36  \Drupal::service('extension.list.theme')->reset();
37  $requirements = [];
38
39  // Report Drupal version
40  if ($phase == 'runtime') {
41    $requirements['drupal'] = [
42      'title' => t('Drupal'),
43      'value' => \Drupal::VERSION,
44      'severity' => REQUIREMENT_INFO,
45      'weight' => -10,
46    ];
47
48    // Display the currently active installation profile, if the site
49    // is not running the default installation profile.
50    $profile = \Drupal::installProfile();
51    if ($profile != 'standard') {
52      $info = \Drupal::service('extension.list.module')->getExtensionInfo($profile);
53      $requirements['install_profile'] = [
54        'title' => t('Installation profile'),
55        'value' => t('%profile_name (%profile-%version)', [
56          '%profile_name' => $info['name'],
57          '%profile' => $profile,
58          '%version' => $info['version'],
59        ]),
60        'severity' => REQUIREMENT_INFO,
61        'weight' => -9,
62      ];
63    }
64
65    // Warn if any experimental modules are installed.
66    $experimental_modules = [];
67    $enabled_modules = \Drupal::moduleHandler()->getModuleList();
68    foreach ($enabled_modules as $module => $data) {
69      $info = \Drupal::service('extension.list.module')->getExtensionInfo($module);
70      if (isset($info['package']) && $info['package'] === 'Core (Experimental)') {
71        $experimental_modules[$module] = $info['name'];
72      }
73    }
74    if (!empty($experimental_modules)) {
75      $requirements['experimental_modules'] = [
76        'title' => t('Experimental modules enabled'),
77        'value' => t('Experimental modules found: %module_list. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', ['%module_list' => implode(', ', $experimental_modules), ':url' => 'https://www.drupal.org/core/experimental']),
78        'severity' => REQUIREMENT_WARNING,
79      ];
80    }
81    // Warn if any experimental themes are installed.
82    $experimental_themes = [];
83    $installed_themes = \Drupal::service('theme_handler')->listInfo();
84    foreach ($installed_themes as $theme => $data) {
85      if (isset($data->info['experimental']) && $data->info['experimental']) {
86        $experimental_themes[$theme] = $data->info['name'];
87      }
88    }
89    if (!empty($experimental_themes)) {
90      $requirements['experimental_themes'] = [
91        'title' => t('Experimental themes enabled'),
92        'value' => t('Experimental themes found: %theme_list. Experimental themes are provided for testing purposes only. Use at your own risk.', ['%theme_list' => implode(', ', $experimental_themes)]),
93        'severity' => REQUIREMENT_WARNING,
94      ];
95    }
96    _system_advisories_requirements($requirements);
97  }
98
99  // Web server information.
100  $request_object = \Drupal::request();
101  $software = $request_object->server->get('SERVER_SOFTWARE');
102  $requirements['webserver'] = [
103    'title' => t('Web server'),
104    'value' => $software,
105  ];
106
107  // Tests clean URL support.
108  if ($phase == 'install' && $install_state['interactive'] && !$request_object->query->has('rewrite') && strpos($software, 'Apache') !== FALSE) {
109    // If the Apache rewrite module is not enabled, Apache version must be >=
110    // 2.2.16 because of the FallbackResource directive in the root .htaccess
111    // file. Since the Apache version reported by the server is dependent on the
112    // ServerTokens setting in httpd.conf, we may not be able to determine if a
113    // given config is valid. Thus we are unable to use version_compare() as we
114    // need have three possible outcomes: the version of Apache is greater than
115    // 2.2.16, is less than 2.2.16, or cannot be determined accurately. In the
116    // first case, we encourage the use of mod_rewrite; in the second case, we
117    // raise an error regarding the minimum Apache version; in the third case,
118    // we raise a warning that the current version of Apache may not be
119    // supported.
120    $rewrite_warning = FALSE;
121    $rewrite_error = FALSE;
122    $apache_version_string = 'Apache';
123
124    // Determine the Apache version number: major, minor and revision.
125    if (preg_match('/Apache\/(\d+)\.?(\d+)?\.?(\d+)?/', $software, $matches)) {
126      $apache_version_string = $matches[0];
127
128      // Major version number
129      if ($matches[1] < 2) {
130        $rewrite_error = TRUE;
131      }
132      elseif ($matches[1] == 2) {
133        if (!isset($matches[2])) {
134          $rewrite_warning = TRUE;
135        }
136        elseif ($matches[2] < 2) {
137          $rewrite_error = TRUE;
138        }
139        elseif ($matches[2] == 2) {
140          if (!isset($matches[3])) {
141            $rewrite_warning = TRUE;
142          }
143          elseif ($matches[3] < 16) {
144            $rewrite_error = TRUE;
145          }
146        }
147      }
148    }
149    else {
150      $rewrite_warning = TRUE;
151    }
152
153    if ($rewrite_warning) {
154      $requirements['apache_version'] = [
155        'title' => t('Apache version'),
156        'value' => $apache_version_string,
157        'severity' => REQUIREMENT_WARNING,
158        'description' => t('Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately determine the version of Apache running on this server. The reported value is @reported, to run Drupal without mod_rewrite, a minimum version of 2.2.16 is needed.', ['@reported' => $apache_version_string]),
159      ];
160    }
161
162    if ($rewrite_error) {
163      $requirements['Apache version'] = [
164        'title' => t('Apache version'),
165        'value' => $apache_version_string,
166        'severity' => REQUIREMENT_ERROR,
167        'description' => t('The minimum version of Apache needed to run Drupal without mod_rewrite enabled is 2.2.16. See the <a href=":link">enabling clean URLs</a> page for more information on mod_rewrite.', [':link' => 'https://www.drupal.org/docs/8/clean-urls-in-drupal-8']),
168      ];
169    }
170
171    if (!$rewrite_error && !$rewrite_warning) {
172      $requirements['rewrite_module'] = [
173        'title' => t('Clean URLs'),
174        'value' => t('Disabled'),
175        'severity' => REQUIREMENT_WARNING,
176        'description' => t('Your server is capable of using clean URLs, but it is not enabled. Using clean URLs gives an improved user experience and is recommended. <a href=":link">Enable clean URLs</a>', [':link' => 'https://www.drupal.org/docs/8/clean-urls-in-drupal-8']),
177      ];
178    }
179  }
180
181  // Verify the user is running a supported PHP version.
182  // If the site is running a recommended version of PHP, just display it
183  // as an informational message on the status report. This will be overridden
184  // with an error or warning if the site is running older PHP versions for
185  // which Drupal has already or will soon drop support.
186  $phpversion = $phpversion_label = phpversion();
187  if (function_exists('phpinfo')) {
188    if ($phase === 'runtime') {
189      $phpversion_label = t('@phpversion (<a href=":url">more information</a>)', ['@phpversion' => $phpversion, ':url' => (new Url('system.php'))->toString()]);
190    }
191    $requirements['php'] = [
192      'title' => t('PHP'),
193      'value' => $phpversion_label,
194    ];
195  }
196  else {
197    // @todo Revisit whether this description makes sense in
198    //   https://www.drupal.org/project/drupal/issues/2927318.
199    $requirements['php'] = [
200      'title' => t('PHP'),
201      'value' => $phpversion_label,
202      'description' => t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, <a href=":phpinfo">Enabling and disabling phpinfo()</a> handbook page.', [':phpinfo' => 'https://www.drupal.org/node/243993']),
203      'severity' => REQUIREMENT_INFO,
204    ];
205  }
206
207  // Check if the PHP version is below what Drupal supports.
208  if (version_compare($phpversion, \Drupal::MINIMUM_SUPPORTED_PHP) < 0) {
209    $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version. It is recommended to upgrade to PHP version %recommended or higher for the best ongoing support. See <a href="http://php.net/supported-versions.php">PHP\'s version support documentation</a> and the <a href=":php_requirements">Environment requirements of Drupal 9</a> page for more information.',
210      [
211        '%version' => \Drupal::MINIMUM_SUPPORTED_PHP,
212        '%recommended' => \Drupal::RECOMMENDED_PHP,
213        ':php_requirements' => 'https://www.drupal.org/docs/9/how-drupal-9-is-made-and-what-is-included/environment-requirements-of-drupal-9#s-php-version-requirement',
214      ]
215    );
216    $requirements['php']['severity'] = REQUIREMENT_ERROR;
217
218    // If the PHP version is also below the absolute minimum allowed, it's not
219    // safe to continue with the requirements check.
220    if (version_compare($phpversion, \Drupal::MINIMUM_PHP) < 0) {
221      return $requirements;
222    }
223    // Otherwise downgrade the error to a warning during updates. Even if there
224    // are some problems with the site's PHP version, it's still better for the
225    // site to keep its Drupal codebase up to date.
226    elseif ($phase === 'update') {
227      $requirements['php']['severity'] = REQUIREMENT_WARNING;
228    }
229    // Since we allow sites with unsupported PHP versions to still run Drupal
230    // updates, we also need to be able to run tests with those PHP versions,
231    // which requires the ability to install test sites. Not all tests are
232    // required to pass on these PHP versions, but we want to monitor which
233    // ones do and don't.
234    elseif ($phase === 'install' && drupal_valid_test_ua()) {
235      $requirements['php']['severity'] = REQUIREMENT_INFO;
236    }
237  }
238  // For PHP versions that are still supported but no longer recommended,
239  // inform users of what's recommended, allowing them to take action before it
240  // becomes urgent.
241  elseif ($phase === 'runtime' && version_compare($phpversion, \Drupal::RECOMMENDED_PHP) < 0) {
242    $requirements['php']['description'] = t('It is recommended to upgrade to PHP version %recommended or higher for the best ongoing support.  See <a href="http://php.net/supported-versions.php">PHP\'s version support documentation</a> and the <a href=":php_requirements">Drupal 8 PHP requirements handbook page</a> for more information.', ['%recommended' => \Drupal::RECOMMENDED_PHP, ':php_requirements' => 'https://www.drupal.org/docs/8/system-requirements/php']);
243    $requirements['php']['severity'] = REQUIREMENT_INFO;
244  }
245
246  // Test for PHP extensions.
247  $requirements['php_extensions'] = [
248    'title' => t('PHP extensions'),
249  ];
250
251  $missing_extensions = [];
252  $required_extensions = [
253    'date',
254    'dom',
255    'filter',
256    'gd',
257    'hash',
258    'json',
259    'pcre',
260    'pdo',
261    'session',
262    'SimpleXML',
263    'SPL',
264    'tokenizer',
265    'xml',
266  ];
267  foreach ($required_extensions as $extension) {
268    if (!extension_loaded($extension)) {
269      $missing_extensions[] = $extension;
270    }
271  }
272
273  if (!empty($missing_extensions)) {
274    $description = t('Drupal requires you to enable the PHP extensions in the following list (see the <a href=":system_requirements">system requirements page</a> for more information):', [
275      ':system_requirements' => 'https://www.drupal.org/docs/system-requirements',
276    ]);
277
278    // We use twig inline_template to avoid twig's autoescape.
279    $description = [
280      '#type' => 'inline_template',
281      '#template' => '{{ description }}{{ missing_extensions }}',
282      '#context' => [
283        'description' => $description,
284        'missing_extensions' => [
285          '#theme' => 'item_list',
286          '#items' => $missing_extensions,
287        ],
288      ],
289    ];
290
291    $requirements['php_extensions']['value'] = t('Disabled');
292    $requirements['php_extensions']['severity'] = REQUIREMENT_ERROR;
293    $requirements['php_extensions']['description'] = $description;
294  }
295  else {
296    $requirements['php_extensions']['value'] = t('Enabled');
297  }
298
299  if ($phase == 'install' || $phase == 'runtime') {
300    // Check to see if OPcache is installed.
301    if (!OpCodeCache::isEnabled()) {
302      $requirements['php_opcache'] = [
303        'value' => t('Not enabled'),
304        'severity' => REQUIREMENT_WARNING,
305        'description' => t('PHP OPcode caching can improve your site\'s performance considerably. It is <strong>highly recommended</strong> to have <a href="http://php.net/manual/opcache.installation.php" target="_blank">OPcache</a> installed on your server.'),
306      ];
307    }
308    else {
309      $requirements['php_opcache']['value'] = t('Enabled');
310    }
311    $requirements['php_opcache']['title'] = t('PHP OPcode caching');
312  }
313
314  // Check to see if APCu is installed and configured correctly.
315  if ($phase == 'runtime' && PHP_SAPI != 'cli') {
316    $requirements['php_apcu']['title'] = t('PHP APCu caching');
317    if (extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN)) {
318      $memory_info = apcu_sma_info(TRUE);
319      $apcu_actual_size = format_size($memory_info['seg_size']);
320      $apcu_recommended_size = '32 MB';
321      $requirements['php_apcu']['value'] = t('Enabled (@size)', ['@size' => $apcu_actual_size]);
322      if (Bytes::toNumber($apcu_actual_size) < Bytes::toNumber($apcu_recommended_size)) {
323        $requirements['php_apcu']['severity'] = REQUIREMENT_WARNING;
324        $requirements['php_apcu']['description'] = t('Depending on your configuration, Drupal can run with a @apcu_size APCu limit. However, a @apcu_default_size APCu limit (the default) or above is recommended, especially if your site uses additional custom or contributed modules.', [
325          '@apcu_size' => $apcu_actual_size,
326          '@apcu_default_size' => $apcu_recommended_size,
327        ]);
328      }
329      else {
330        $memory_available = $memory_info['avail_mem'] / $memory_info['seg_size'];
331        if ($memory_available < 0.1) {
332          $requirements['php_apcu']['severity'] = REQUIREMENT_ERROR;
333        }
334        elseif ($memory_available < 0.25) {
335          $requirements['php_apcu']['severity'] = REQUIREMENT_WARNING;
336        }
337        else {
338          $requirements['php_apcu']['severity'] = REQUIREMENT_OK;
339        }
340        $requirements['php_apcu']['description'] = t('Memory available: @available.', [
341          '@available' => format_size($memory_info['avail_mem']),
342        ]);
343      }
344    }
345    else {
346      $requirements['php_apcu'] += [
347        'value' => t('Not enabled'),
348        'severity' => REQUIREMENT_INFO,
349        'description' => t('PHP APCu caching can improve your site\'s performance considerably. It is <strong>highly recommended</strong> to have <a href="https://www.php.net/manual/apcu.installation.php" target="_blank">APCu</a> installed on your server.'),
350      ];
351    }
352  }
353
354  if ($phase != 'update') {
355    // Test whether we have a good source of random bytes.
356    $requirements['php_random_bytes'] = [
357      'title' => t('Random number generation'),
358    ];
359    try {
360      $bytes = random_bytes(10);
361      if (strlen($bytes) != 10) {
362        throw new \Exception("Tried to generate 10 random bytes, generated '" . strlen($bytes) . "'");
363      }
364      $requirements['php_random_bytes']['value'] = t('Successful');
365    }
366    catch (\Exception $e) {
367      // If /dev/urandom is not available on a UNIX-like system, check whether
368      // open_basedir restrictions are the cause.
369      $open_basedir_blocks_urandom = FALSE;
370      if (DIRECTORY_SEPARATOR === '/' && !@is_readable('/dev/urandom')) {
371        $open_basedir = ini_get('open_basedir');
372        if ($open_basedir) {
373          $open_basedir_paths = explode(PATH_SEPARATOR, $open_basedir);
374          $open_basedir_blocks_urandom = !array_intersect(['/dev', '/dev/', '/dev/urandom'], $open_basedir_paths);
375        }
376      }
377      $args = [
378        ':drupal-php' => 'https://www.drupal.org/docs/8/system-requirements/php-requirements',
379        '%exception_message' => $e->getMessage(),
380      ];
381      if ($open_basedir_blocks_urandom) {
382        $requirements['php_random_bytes']['description'] = t('Drupal is unable to generate highly randomized numbers, which means certain security features like password reset URLs are not as secure as they should be. Instead, only a slow, less-secure fallback generator is available. The most likely cause is that open_basedir restrictions are in effect and /dev/urandom is not on the whitelist. See the <a href=":drupal-php">system requirements</a> page for more information. %exception_message', $args);
383      }
384      else {
385        $requirements['php_random_bytes']['description'] = t('Drupal is unable to generate highly randomized numbers, which means certain security features like password reset URLs are not as secure as they should be. Instead, only a slow, less-secure fallback generator is available. See the <a href=":drupal-php">system requirements</a> page for more information. %exception_message', $args);
386      }
387      $requirements['php_random_bytes']['value'] = t('Less secure');
388      $requirements['php_random_bytes']['severity'] = REQUIREMENT_ERROR;
389    }
390  }
391
392  if ($phase == 'install' || $phase == 'update') {
393    // Test for PDO (database).
394    $requirements['database_extensions'] = [
395      'title' => t('Database support'),
396    ];
397
398    // Make sure PDO is available.
399    $database_ok = extension_loaded('pdo');
400    if (!$database_ok) {
401      $pdo_message = t('Your web server does not appear to support PDO (PHP Data Objects). Ask your hosting provider if they support the native PDO extension. See the <a href=":link">system requirements</a> page for more information.', [
402        ':link' => 'https://www.drupal.org/docs/system-requirements/php-requirements#database',
403      ]);
404    }
405    else {
406      // Make sure at least one supported database driver exists.
407      $drivers = drupal_detect_database_types();
408      if (empty($drivers)) {
409        $database_ok = FALSE;
410        $pdo_message = t('Your web server does not appear to support any common PDO database extensions. Check with your hosting provider to see if they support PDO (PHP Data Objects) and offer any databases that <a href=":drupal-databases">Drupal supports</a>.', [
411          ':drupal-databases' => 'https://www.drupal.org/docs/system-requirements/database-server-requirements',
412        ]);
413      }
414      // Make sure the native PDO extension is available, not the older PEAR
415      // version. (See install_verify_pdo() for details.)
416      if (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
417        $database_ok = FALSE;
418        $pdo_message = t('Your web server seems to have the wrong version of PDO installed. Drupal requires the PDO extension from PHP core. This system has the older PECL version. See the <a href=":link">system requirements</a> page for more information.', [
419          ':link' => 'https://www.drupal.org/docs/system-requirements/php-requirements#database',
420        ]);
421      }
422    }
423
424    if (!$database_ok) {
425      $requirements['database_extensions']['value'] = t('Disabled');
426      $requirements['database_extensions']['severity'] = REQUIREMENT_ERROR;
427      $requirements['database_extensions']['description'] = $pdo_message;
428    }
429    else {
430      $requirements['database_extensions']['value'] = t('Enabled');
431    }
432  }
433
434  if ($phase === 'runtime' || $phase === 'update') {
435    // Database information.
436    $class = Database::getConnection()->getDriverClass('Install\\Tasks');
437    /** @var \Drupal\Core\Database\Install\Tasks $tasks */
438    $tasks = new $class();
439    $requirements['database_system'] = [
440      'title' => t('Database system'),
441      'value' => $tasks->name(),
442    ];
443    $requirements['database_system_version'] = [
444      'title' => t('Database system version'),
445      'value' => Database::getConnection()->version(),
446    ];
447
448    $errors = $tasks->engineVersionRequirementsCheck();
449    $error_count = count($errors);
450    if ($error_count > 0) {
451      $error_message = [
452        '#theme' => 'item_list',
453        '#items' => $errors,
454        // Use the comma-list style to display a single error without bullets.
455        '#context' => ['list_style' => $error_count === 1 ? 'comma-list' : ''],
456      ];
457      $requirements['database_system_version']['severity'] = REQUIREMENT_ERROR;
458      $requirements['database_system_version']['description'] = $error_message;
459    }
460  }
461
462  // Test PHP memory_limit
463  $memory_limit = ini_get('memory_limit');
464  $requirements['php_memory_limit'] = [
465    'title' => t('PHP memory limit'),
466    'value' => $memory_limit == -1 ? t('-1 (Unlimited)') : $memory_limit,
467  ];
468
469  if (!Environment::checkMemoryLimit(\Drupal::MINIMUM_PHP_MEMORY_LIMIT, $memory_limit)) {
470    $description = [];
471    if ($phase == 'install') {
472      $description['phase'] = t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the installation process.', ['%memory_minimum_limit' => \Drupal::MINIMUM_PHP_MEMORY_LIMIT]);
473    }
474    elseif ($phase == 'update') {
475      $description['phase'] = t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the update process.', ['%memory_minimum_limit' => \Drupal::MINIMUM_PHP_MEMORY_LIMIT]);
476    }
477    elseif ($phase == 'runtime') {
478      $description['phase'] = t('Depending on your configuration, Drupal can run with a %memory_limit PHP memory limit. However, a %memory_minimum_limit PHP memory limit or above is recommended, especially if your site uses additional custom or contributed modules.', ['%memory_limit' => $memory_limit, '%memory_minimum_limit' => \Drupal::MINIMUM_PHP_MEMORY_LIMIT]);
479    }
480
481    if (!empty($description['phase'])) {
482      if ($php_ini_path = get_cfg_var('cfg_file_path')) {
483        $description['memory'] = t('Increase the memory limit by editing the memory_limit parameter in the file %configuration-file and then restart your web server (or contact your system administrator or hosting provider for assistance).', ['%configuration-file' => $php_ini_path]);
484      }
485      else {
486        $description['memory'] = t('Contact your system administrator or hosting provider for assistance with increasing your PHP memory limit.');
487      }
488
489      $handbook_link = t('For more information, see the online handbook entry for <a href=":memory-limit">increasing the PHP memory limit</a>.', [':memory-limit' => 'https://www.drupal.org/node/207036']);
490
491      $description = [
492        '#type' => 'inline_template',
493        '#template' => '{{ description_phase }} {{ description_memory }} {{ handbook }}',
494        '#context' => [
495          'description_phase' => $description['phase'],
496          'description_memory' => $description['memory'],
497          'handbook' => $handbook_link,
498        ],
499      ];
500
501      $requirements['php_memory_limit']['description'] = $description;
502      $requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
503    }
504  }
505
506  // Test configuration files and directory for writability.
507  if ($phase == 'runtime') {
508    $conf_errors = [];
509    // Find the site path. Kernel service is not always available at this point,
510    // but is preferred, when available.
511    if (\Drupal::hasService('kernel')) {
512      $site_path = \Drupal::getContainer()->getParameter('site.path');
513    }
514    else {
515      $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
516    }
517    // Allow system administrators to disable permissions hardening for the site
518    // directory. This allows additional files in the site directory to be
519    // updated when they are managed in a version control system.
520    if (Settings::get('skip_permissions_hardening')) {
521      $error_value = t('Protection disabled');
522      // If permissions hardening is disabled, then only show a warning for a
523      // writable file, as a reminder, rather than an error.
524      $file_protection_severity = REQUIREMENT_WARNING;
525    }
526    else {
527      $error_value = t('Not protected');
528      // In normal operation, writable files or directories are an error.
529      $file_protection_severity = REQUIREMENT_ERROR;
530      if (!drupal_verify_install_file($site_path, FILE_NOT_WRITABLE, 'dir')) {
531        $conf_errors[] = t("The directory %file is not protected from modifications and poses a security risk. You must change the directory's permissions to be non-writable.", ['%file' => $site_path]);
532      }
533    }
534    foreach (['settings.php', 'settings.local.php', 'services.yml'] as $conf_file) {
535      $full_path = $site_path . '/' . $conf_file;
536      if (file_exists($full_path) && !drupal_verify_install_file($full_path, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE, 'file', !Settings::get('skip_permissions_hardening'))) {
537        $conf_errors[] = t("The file %file is not protected from modifications and poses a security risk. You must change the file's permissions to be non-writable.", ['%file' => $full_path]);
538      }
539    }
540    if (!empty($conf_errors)) {
541      if (count($conf_errors) == 1) {
542        $description = $conf_errors[0];
543      }
544      else {
545        // We use twig inline_template to avoid double escaping.
546        $description = [
547          '#type' => 'inline_template',
548          '#template' => '{{ configuration_error_list }}',
549          '#context' => [
550            'configuration_error_list' => [
551              '#theme' => 'item_list',
552              '#items' => $conf_errors,
553            ],
554          ],
555        ];
556      }
557      $requirements['configuration_files'] = [
558        'value' => $error_value,
559        'severity' => $file_protection_severity,
560        'description' => $description,
561      ];
562    }
563    else {
564      $requirements['configuration_files'] = [
565        'value' => t('Protected'),
566      ];
567    }
568    $requirements['configuration_files']['title'] = t('Configuration files');
569  }
570
571  // Test the contents of the .htaccess files.
572  if ($phase == 'runtime') {
573    // Try to write the .htaccess files first, to prevent false alarms in case
574    // (for example) the /tmp directory was wiped.
575    /** @var \Drupal\Core\File\HtaccessWriterInterface $htaccessWriter */
576    $htaccessWriter = \Drupal::service("file.htaccess_writer");
577    $htaccessWriter->ensure();
578    foreach ($htaccessWriter->defaultProtectedDirs() as $protected_dir) {
579      $htaccess_file = $protected_dir->getPath() . '/.htaccess';
580      // Check for the string which was added to the recommended .htaccess file
581      // in the latest security update.
582      if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
583        $url = 'https://www.drupal.org/SA-CORE-2013-003';
584        $requirements[$htaccess_file] = [
585          'title' => new TranslatableMarkup($protected_dir->getTitle()),
586          'value' => t('Not fully protected'),
587          'severity' => REQUIREMENT_ERROR,
588          'description' => t('See <a href=":url">@url</a> for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', [':url' => $url, '@url' => $url, '%directory' => $protected_dir->getPath()]),
589        ];
590      }
591    }
592  }
593
594  // Report cron status.
595  if ($phase == 'runtime') {
596    $cron_config = \Drupal::config('system.cron');
597    // Cron warning threshold defaults to two days.
598    $threshold_warning = $cron_config->get('threshold.requirements_warning');
599    // Cron error threshold defaults to two weeks.
600    $threshold_error = $cron_config->get('threshold.requirements_error');
601
602    // Determine when cron last ran.
603    $cron_last = \Drupal::state()->get('system.cron_last');
604    if (!is_numeric($cron_last)) {
605      $cron_last = \Drupal::state()->get('install_time', 0);
606    }
607
608    // Determine severity based on time since cron last ran.
609    $severity = REQUIREMENT_INFO;
610    if (REQUEST_TIME - $cron_last > $threshold_error) {
611      $severity = REQUIREMENT_ERROR;
612    }
613    elseif (REQUEST_TIME - $cron_last > $threshold_warning) {
614      $severity = REQUIREMENT_WARNING;
615    }
616
617    // Set summary and description based on values determined above.
618    $summary = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
619
620    $requirements['cron'] = [
621      'title' => t('Cron maintenance tasks'),
622      'severity' => $severity,
623      'value' => $summary,
624    ];
625    if ($severity != REQUIREMENT_INFO) {
626      $requirements['cron']['description'][] = [
627        [
628          '#markup' => t('Cron has not run recently.'),
629          '#suffix' => ' ',
630        ],
631        [
632          '#markup' => t('For more information, see the online handbook entry for <a href=":cron-handbook">configuring cron jobs</a>.', [':cron-handbook' => 'https://www.drupal.org/cron']),
633          '#suffix' => ' ',
634        ],
635      ];
636    }
637    $requirements['cron']['description'][] = [
638      [
639        '#type' => 'link',
640        '#prefix' => '(',
641        '#title' => t('more information'),
642        '#suffix' => ')',
643        '#url' => Url::fromRoute('system.cron_settings'),
644      ],
645      [
646        '#prefix' => '<span class="cron-description__run-cron">',
647        '#suffix' => '</span>',
648        '#type' => 'link',
649        '#title' => t('Run cron'),
650        '#url' => Url::fromRoute('system.run_cron'),
651      ],
652    ];
653  }
654  if ($phase != 'install') {
655    $directories = [
656      PublicStream::basePath(),
657      // By default no private files directory is configured. For private files
658      // to be secure the admin needs to provide a path outside the webroot.
659      PrivateStream::basePath(),
660      \Drupal::service('file_system')->getTempDirectory(),
661    ];
662  }
663
664  // During an install we need to make assumptions about the file system
665  // unless overrides are provided in settings.php.
666  if ($phase == 'install') {
667    $directories = [];
668    if ($file_public_path = Settings::get('file_public_path')) {
669      $directories[] = $file_public_path;
670    }
671    else {
672      // If we are installing Drupal, the settings.php file might not exist yet
673      // in the intended site directory, so don't require it.
674      $request = Request::createFromGlobals();
675      $site_path = DrupalKernel::findSitePath($request);
676      $directories[] = $site_path . '/files';
677    }
678    if ($file_private_path = Settings::get('file_private_path')) {
679      $directories[] = $file_private_path;
680    }
681    if (Settings::get('file_temp_path')) {
682      $directories[] = Settings::get('file_temp_path');
683    }
684    else {
685      // If the temporary directory is not overridden use an appropriate
686      // temporary path for the system.
687      $directories[] = FileSystemComponent::getOsTemporaryDirectory();
688    }
689  }
690
691  // Check the config directory if it is defined in settings.php. If it isn't
692  // defined, the installer will create a valid config directory later, but
693  // during runtime we must always display an error.
694  $config_sync_directory = Settings::get('config_sync_directory');
695  if (!empty($config_sync_directory)) {
696    // If we're installing Drupal try and create the config sync directory.
697    if (!is_dir($config_sync_directory) && $phase == 'install') {
698      \Drupal::service('file_system')->prepareDirectory($config_sync_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
699    }
700    if (!is_dir($config_sync_directory)) {
701      if ($phase == 'install') {
702        $description = t('An automated attempt to create the directory %directory failed, possibly due to a permissions problem. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see INSTALL.txt or the <a href=":handbook_url">online handbook</a>.', ['%directory' => $config_sync_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']);
703      }
704      else {
705        $description = t('The directory %directory does not exist.', ['%directory' => $config_sync_directory]);
706      }
707      $requirements['config sync directory'] = [
708        'title' => t('Configuration sync directory'),
709        'description' => $description,
710        'severity' => REQUIREMENT_ERROR,
711      ];
712    }
713  }
714  if ($phase != 'install' && empty($config_sync_directory)) {
715    $requirements['config sync directory'] = [
716      'title' => t('Configuration sync directory'),
717      'value' => t('Not present'),
718      'description' => t("Your %file file must define the %setting setting as a string containing the directory in which configuration files can be found.", ['%file' => $site_path . '/settings.php', '%setting' => "\$settings['config_sync_directory']"]),
719      'severity' => REQUIREMENT_ERROR,
720    ];
721  }
722
723  $requirements['file system'] = [
724    'title' => t('File system'),
725  ];
726
727  $error = '';
728  // For installer, create the directories if possible.
729  foreach ($directories as $directory) {
730    if (!$directory) {
731      continue;
732    }
733    if ($phase == 'install') {
734      \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
735    }
736    $is_writable = is_writable($directory);
737    $is_directory = is_dir($directory);
738    if (!$is_writable || !$is_directory) {
739      $description = '';
740      $requirements['file system']['value'] = t('Not writable');
741      if (!$is_directory) {
742        $error = t('The directory %directory does not exist.', ['%directory' => $directory]);
743      }
744      else {
745        $error = t('The directory %directory is not writable.', ['%directory' => $directory]);
746      }
747      // The files directory requirement check is done only during install and runtime.
748      if ($phase == 'runtime') {
749        $description = t('You may need to set the correct directory at the <a href=":admin-file-system">file system settings page</a> or change the current directory\'s permissions so that it is writable.', [':admin-file-system' => Url::fromRoute('system.file_system_settings')->toString()]);
750      }
751      elseif ($phase == 'install') {
752        // For the installer UI, we need different wording. 'value' will
753        // be treated as version, so provide none there.
754        $description = t('An automated attempt to create this directory failed, possibly due to a permissions problem. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see INSTALL.txt or the <a href=":handbook_url">online handbook</a>.', [':handbook_url' => 'https://www.drupal.org/server-permissions']);
755        $requirements['file system']['value'] = '';
756      }
757      if (!empty($description)) {
758        $description = [
759          '#type' => 'inline_template',
760          '#template' => '{{ error }} {{ description }}',
761          '#context' => [
762            'error' => $error,
763            'description' => $description,
764          ],
765        ];
766        $requirements['file system']['description'] = $description;
767        $requirements['file system']['severity'] = REQUIREMENT_ERROR;
768      }
769    }
770    else {
771      // This function can be called before the config_cache table has been
772      // created.
773      if ($phase == 'install' || \Drupal::config('system.file')->get('default_scheme') == 'public') {
774        $requirements['file system']['value'] = t('Writable (<em>public</em> download method)');
775      }
776      else {
777        $requirements['file system']['value'] = t('Writable (<em>private</em> download method)');
778      }
779    }
780  }
781
782  // See if updates are available in update.php.
783  if ($phase == 'runtime') {
784    $requirements['update'] = [
785      'title' => t('Database updates'),
786      'value' => t('Up to date'),
787    ];
788
789    // Check installed modules.
790    $has_pending_updates = FALSE;
791    foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) {
792      $updates = drupal_get_schema_versions($module);
793      if ($updates !== FALSE) {
794        $default = drupal_get_installed_schema_version($module);
795        if (max($updates) > $default) {
796          $has_pending_updates = TRUE;
797          break;
798        }
799      }
800    }
801    if (!$has_pending_updates) {
802      /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
803      $post_update_registry = \Drupal::service('update.post_update_registry');
804      $missing_post_update_functions = $post_update_registry->getPendingUpdateFunctions();
805      if (!empty($missing_post_update_functions)) {
806        $has_pending_updates = TRUE;
807      }
808    }
809
810    if ($has_pending_updates) {
811      $requirements['update']['severity'] = REQUIREMENT_ERROR;
812      $requirements['update']['value'] = t('Out of date');
813      $requirements['update']['description'] = t('Some modules have database schema updates to install. You should run the <a href=":update">database update script</a> immediately.', [':update' => Url::fromRoute('system.db_update')->toString()]);
814    }
815
816    $requirements['entity_update'] = [
817      'title' => t('Entity/field definitions'),
818      'value' => t('Up to date'),
819    ];
820    // Verify that no entity updates are pending.
821    if ($change_list = \Drupal::entityDefinitionUpdateManager()->getChangeSummary()) {
822      $build = [];
823      foreach ($change_list as $entity_type_id => $changes) {
824        $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
825        $build[] = [
826          '#theme' => 'item_list',
827          '#title' => $entity_type->getLabel(),
828          '#items' => $changes,
829        ];
830      }
831
832      $entity_update_issues = \Drupal::service('renderer')->renderPlain($build);
833      $requirements['entity_update']['severity'] = REQUIREMENT_ERROR;
834      $requirements['entity_update']['value'] = t('Mismatched entity and/or field definitions');
835      $requirements['entity_update']['description'] = t('The following changes were detected in the entity type and field definitions. @updates', ['@updates' => $entity_update_issues]);
836    }
837  }
838
839  // Verify the update.php access setting
840  if ($phase == 'runtime') {
841    if (Settings::get('update_free_access')) {
842      $requirements['update access'] = [
843        'value' => t('Not protected'),
844        'severity' => REQUIREMENT_ERROR,
845        'description' => t('The update.php script is accessible to everyone without authentication check, which is a security risk. You must change the @settings_name value in your settings.php back to FALSE.', ['@settings_name' => '$settings[\'update_free_access\']']),
846      ];
847    }
848    else {
849      $requirements['update access'] = [
850        'value' => t('Protected'),
851      ];
852    }
853    $requirements['update access']['title'] = t('Access to update.php');
854  }
855
856  // Display an error if a newly introduced dependency in a module is not resolved.
857  if ($phase === 'update' || $phase === 'runtime') {
858    $create_extension_incompatibility_list = function ($extension_names, $description, $title) {
859      // Use an inline twig template to:
860      // - Concatenate two MarkupInterface objects and preserve safeness.
861      // - Use the item_list theme for the extension list.
862      $template = [
863        '#type' => 'inline_template',
864        '#template' => '{{ description }}{{ extensions }}',
865        '#context' => [
866          'extensions' => [
867            '#theme' => 'item_list',
868          ],
869        ],
870      ];
871      $template['#context']['extensions']['#items'] = $extension_names;
872      $template['#context']['description'] = $description;
873      return [
874        'title' => $title,
875        'value' => [
876          'list' => $template,
877          'handbook_link' => [
878            '#markup' => t(
879              'Review the <a href=":url"> suggestions for resolving this incompatibility</a> to repair your installation, and then re-run update.php.',
880              [':url' => 'https://www.drupal.org/docs/8/update/troubleshooting-database-updates']
881            ),
882          ],
883        ],
884        'severity' => REQUIREMENT_ERROR,
885      ];
886    };
887    $profile = \Drupal::installProfile();
888    $files = \Drupal::service('extension.list.module')->getList();
889    $files += \Drupal::service('extension.list.theme')->getList();
890    $core_incompatible_extensions = [];
891    $php_incompatible_extensions = [];
892    foreach ($files as $extension_name => $file) {
893      // Ignore uninstalled extensions and installation profiles.
894      if (!$file->status || $extension_name == $profile) {
895        continue;
896      }
897
898      $name = $file->info['name'];
899      if (!empty($file->info['core_incompatible'])) {
900        $core_incompatible_extensions[$file->info['type']][] = $name;
901      }
902
903      // Check the extension's PHP version.
904      $php = $file->info['php'];
905      if (version_compare($php, PHP_VERSION, '>')) {
906        $php_incompatible_extensions[$file->info['type']][] = $name;
907      }
908
909      // Check the module's required modules.
910      /** @var \Drupal\Core\Extension\Dependency $requirement */
911      foreach ($file->requires as $requirement) {
912        $required_module = $requirement->getName();
913        // Check if the module exists.
914        if (!isset($files[$required_module])) {
915          $requirements["$extension_name-$required_module"] = [
916            'title' => t('Unresolved dependency'),
917            'description' => t('@name requires this module.', ['@name' => $name]),
918            'value' => t('@required_name (Missing)', ['@required_name' => $required_module]),
919            'severity' => REQUIREMENT_ERROR,
920          ];
921          continue;
922        }
923        // Check for an incompatible version.
924        $required_file = $files[$required_module];
925        $required_name = $required_file->info['name'];
926        $version = str_replace(\Drupal::CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
927        if (!$requirement->isCompatible($version)) {
928          $requirements["$extension_name-$required_module"] = [
929            'title' => t('Unresolved dependency'),
930            'description' => t('@name requires this module and version. Currently using @required_name version @version', ['@name' => $name, '@required_name' => $required_name, '@version' => $version]),
931            'value' => t('@required_name (Version @compatibility required)', ['@required_name' => $required_name, '@compatibility' => $requirement->getConstraintString()]),
932            'severity' => REQUIREMENT_ERROR,
933          ];
934          continue;
935        }
936      }
937    }
938    if (!empty($core_incompatible_extensions['module'])) {
939      $requirements['module_core_incompatible'] = $create_extension_incompatibility_list(
940        $core_incompatible_extensions['module'],
941        new PluralTranslatableMarkup(
942          count($core_incompatible_extensions['module']),
943        'The following module is installed, but it is incompatible with Drupal @version:',
944        'The following modules are installed, but they are incompatible with Drupal @version:',
945        ['@version' => \Drupal::VERSION]
946        ),
947        new PluralTranslatableMarkup(
948          count($core_incompatible_extensions['module']),
949          'Incompatible module',
950          'Incompatible modules'
951        )
952      );
953    }
954    if (!empty($core_incompatible_extensions['theme'])) {
955      $requirements['theme_core_incompatible'] = $create_extension_incompatibility_list(
956        $core_incompatible_extensions['theme'],
957        new PluralTranslatableMarkup(
958          count($core_incompatible_extensions['theme']),
959          'The following theme is installed, but it is incompatible with Drupal @version:',
960          'The following themes are installed, but they are incompatible with Drupal @version:',
961          ['@version' => \Drupal::VERSION]
962        ),
963        new PluralTranslatableMarkup(
964          count($core_incompatible_extensions['theme']),
965          'Incompatible theme',
966          'Incompatible themes'
967        )
968      );
969    }
970    if (!empty($php_incompatible_extensions['module'])) {
971      $requirements['module_php_incompatible'] = $create_extension_incompatibility_list(
972        $php_incompatible_extensions['module'],
973        new PluralTranslatableMarkup(
974          count($php_incompatible_extensions['module']),
975          'The following module is installed, but it is incompatible with PHP @version:',
976          'The following modules are installed, but they are incompatible with PHP @version:',
977          ['@version' => phpversion()]
978        ),
979        new PluralTranslatableMarkup(
980          count($php_incompatible_extensions['module']),
981          'Incompatible module',
982          'Incompatible modules'
983        )
984      );
985    }
986    if (!empty($php_incompatible_extensions['theme'])) {
987      $requirements['theme_php_incompatible'] = $create_extension_incompatibility_list(
988        $php_incompatible_extensions['theme'],
989        new PluralTranslatableMarkup(
990          count($php_incompatible_extensions['theme']),
991          'The following theme is installed, but it is incompatible with PHP @version:',
992          'The following themes are installed, but they are incompatible with PHP @version:',
993          ['@version' => phpversion()]
994        ),
995        new PluralTranslatableMarkup(
996          count($php_incompatible_extensions['theme']),
997          'Incompatible theme',
998          'Incompatible themes'
999        )
1000      );
1001    }
1002
1003    // Look for invalid modules.
1004    $extension_config = \Drupal::configFactory()->get('core.extension');
1005    /** @var \Drupal\Core\Extension\ExtensionList $extension_list */
1006    $extension_list = \Drupal::service('extension.list.module');
1007    $is_missing_extension = function ($extension_name) use (&$extension_list) {
1008      return !$extension_list->exists($extension_name);
1009    };
1010
1011    $invalid_modules = array_filter(array_keys($extension_config->get('module')), $is_missing_extension);
1012
1013    if (!empty($invalid_modules)) {
1014      $requirements['invalid_module'] = $create_extension_incompatibility_list(
1015        $invalid_modules,
1016        new PluralTranslatableMarkup(
1017          count($invalid_modules),
1018          'The following module is marked as installed in the core.extension configuration, but it is missing:',
1019          'The following modules are marked as installed in the core.extension configuration, but they are missing:'
1020        ),
1021        new PluralTranslatableMarkup(
1022          count($invalid_modules),
1023          'Missing or invalid module',
1024          'Missing or invalid modules'
1025        )
1026      );
1027    }
1028
1029    // Look for invalid themes.
1030    $extension_list = \Drupal::service('extension.list.theme');
1031    $invalid_themes = array_filter(array_keys($extension_config->get('theme')), $is_missing_extension);
1032    if (!empty($invalid_themes)) {
1033      $requirements['invalid_theme'] = $create_extension_incompatibility_list(
1034        $invalid_themes,
1035        new PluralTranslatableMarkup(
1036          count($invalid_themes),
1037          'The following theme is marked as installed in the core.extension configuration, but it is missing:',
1038          'The following themes are marked as installed in the core.extension configuration, but they are missing:'
1039        ),
1040        new PluralTranslatableMarkup(
1041          count($invalid_themes),
1042          'Missing or invalid theme',
1043          'Missing or invalid themes'
1044        )
1045      );
1046    }
1047  }
1048
1049  // Returns Unicode library status and errors.
1050  $libraries = [
1051    Unicode::STATUS_SINGLEBYTE => t('Standard PHP'),
1052    Unicode::STATUS_MULTIBYTE => t('PHP Mbstring Extension'),
1053    Unicode::STATUS_ERROR => t('Error'),
1054  ];
1055  $severities = [
1056    Unicode::STATUS_SINGLEBYTE => REQUIREMENT_WARNING,
1057    Unicode::STATUS_MULTIBYTE => NULL,
1058    Unicode::STATUS_ERROR => REQUIREMENT_ERROR,
1059  ];
1060  $failed_check = Unicode::check();
1061  $library = Unicode::getStatus();
1062
1063  $requirements['unicode'] = [
1064    'title' => t('Unicode library'),
1065    'value' => $libraries[$library],
1066    'severity' => $severities[$library],
1067  ];
1068  switch ($failed_check) {
1069    case 'mb_strlen':
1070      $requirements['unicode']['description'] = t('Operations on Unicode strings are emulated on a best-effort basis. Install the <a href="http://php.net/mbstring">PHP mbstring extension</a> for improved Unicode support.');
1071      break;
1072
1073    case 'mbstring.func_overload':
1074      $requirements['unicode']['description'] = t('Multibyte string function overloading in PHP is active and must be disabled. Check the php.ini <em>mbstring.func_overload</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
1075      break;
1076
1077    case 'mbstring.encoding_translation':
1078      $requirements['unicode']['description'] = t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.encoding_translation</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
1079      break;
1080  }
1081
1082  if ($phase == 'runtime') {
1083    // Check for update status module.
1084    if (!\Drupal::moduleHandler()->moduleExists('update')) {
1085      $requirements['update status'] = [
1086        'value' => t('Not enabled'),
1087        'severity' => REQUIREMENT_WARNING,
1088        'description' => t('Update notifications are not enabled. It is <strong>highly recommended</strong> that you enable the Update Manager module from the <a href=":module">module administration page</a> in order to stay up-to-date on new releases. For more information, <a href=":update">Update status handbook page</a>.', [
1089          ':update' => 'https://www.drupal.org/documentation/modules/update',
1090          ':module' => Url::fromRoute('system.modules_list')->toString(),
1091        ]),
1092      ];
1093    }
1094    else {
1095      $requirements['update status'] = [
1096        'value' => t('Enabled'),
1097      ];
1098    }
1099    $requirements['update status']['title'] = t('Update notifications');
1100
1101    if (Settings::get('rebuild_access')) {
1102      $requirements['rebuild access'] = [
1103        'title' => t('Rebuild access'),
1104        'value' => t('Enabled'),
1105        'severity' => REQUIREMENT_ERROR,
1106        'description' => t('The rebuild_access setting is enabled in settings.php. It is recommended to have this setting disabled unless you are performing a rebuild.'),
1107      ];
1108    }
1109  }
1110
1111  // See if trusted hostnames have been configured, and warn the user if they
1112  // are not set.
1113  if ($phase == 'runtime') {
1114    $trusted_host_patterns = Settings::get('trusted_host_patterns');
1115    if (empty($trusted_host_patterns)) {
1116      $requirements['trusted_host_patterns'] = [
1117        'title' => t('Trusted Host Settings'),
1118        'value' => t('Not enabled'),
1119        'description' => t('The trusted_host_patterns setting is not configured in settings.php. This can lead to security vulnerabilities. It is <strong>highly recommended</strong> that you configure this. See <a href=":url">Protecting against HTTP HOST Header attacks</a> for more information.', [':url' => 'https://www.drupal.org/docs/8/install/trusted-host-settings']),
1120        'severity' => REQUIREMENT_ERROR,
1121      ];
1122    }
1123    else {
1124      $requirements['trusted_host_patterns'] = [
1125        'title' => t('Trusted Host Settings'),
1126        'value' => t('Enabled'),
1127        'description' => t('The trusted_host_patterns setting is set to allow %trusted_host_patterns', ['%trusted_host_patterns' => implode(', ', $trusted_host_patterns)]),
1128      ];
1129    }
1130  }
1131
1132  // When the database driver is provided by a module, then check that the
1133  // providing module is enabled.
1134  if ($phase === 'runtime' || $phase === 'update') {
1135    $connection = Database::getConnection();
1136    $provider = $connection->getProvider();
1137    if ($provider !== 'core' && !\Drupal::moduleHandler()->moduleExists($provider)) {
1138      $autoload = $connection->getConnectionOptions()['autoload'] ?? '';
1139      if (($pos = strpos($autoload, 'src/Driver/Database/')) !== FALSE) {
1140        $requirements['database_driver_provided_by_module'] = [
1141          'title' => t('Database driver provided by module'),
1142          'value' => t('Not enabled'),
1143          'description' => t('The current database driver is provided by the module: %module. The module is currently not enabled. You should immediately <a href=":enable">enable</a> the module.', ['%module' => $provider, ':enable' => Url::fromRoute('system.modules_list')->toString()]),
1144          'severity' => REQUIREMENT_ERROR,
1145        ];
1146      }
1147    }
1148  }
1149
1150  // Check xdebug.max_nesting_level, as some pages will not work if it is too
1151  // low.
1152  if (extension_loaded('xdebug')) {
1153    // Setting this value to 256 was considered adequate on Xdebug 2.3
1154    // (see http://bugs.xdebug.org/bug_view_page.php?bug_id=00001100)
1155    $minimum_nesting_level = 256;
1156    $current_nesting_level = ini_get('xdebug.max_nesting_level');
1157
1158    if ($current_nesting_level < $minimum_nesting_level) {
1159      $requirements['xdebug_max_nesting_level'] = [
1160        'title' => t('Xdebug settings'),
1161        'value' => t('xdebug.max_nesting_level is set to %value.', ['%value' => $current_nesting_level]),
1162        'description' => t('Set <code>xdebug.max_nesting_level=@level</code> in your PHP configuration as some pages in your Drupal site will not work when this setting is too low.', ['@level' => $minimum_nesting_level]),
1163        'severity' => REQUIREMENT_ERROR,
1164      ];
1165    }
1166  }
1167
1168  // Installations on Windows can run into limitations with MAX_PATH if the
1169  // Drupal root directory is too deep in the filesystem. Generally this shows
1170  // up in cached Twig templates and other public files with long directory or
1171  // file names. There is no definite root directory depth below which Drupal is
1172  // guaranteed to function correctly on Windows. Since problems are likely
1173  // with more than 100 characters in the Drupal root path, show an error.
1174  if (substr(PHP_OS, 0, 3) == 'WIN') {
1175    $depth = strlen(realpath(DRUPAL_ROOT . '/' . PublicStream::basePath()));
1176    if ($depth > 120) {
1177      $requirements['max_path_on_windows'] = [
1178        'title' => t('Windows installation depth'),
1179        'description' => t('The public files directory path is %depth characters. Paths longer than 120 characters will cause problems on Windows.', ['%depth' => $depth]),
1180        'severity' => REQUIREMENT_ERROR,
1181      ];
1182    }
1183  }
1184  // Check to see if dates will be limited to 1901-2038.
1185  if (PHP_INT_SIZE <= 4) {
1186    $requirements['limited_date_range'] = [
1187      'title' => t('Limited date range'),
1188      'value' => t('Your PHP installation has a limited date range.'),
1189      'description' => t('You are running on a system where PHP is compiled or limited to using 32-bit integers. This will limit the range of dates and timestamps to the years 1901-2038. Read about the <a href=":url">limitations of 32-bit PHP</a>.', [':url' => 'https://www.drupal.org/docs/8/system-requirements/limitations-of-32-bit-php']),
1190      'severity' => REQUIREMENT_WARNING,
1191    ];
1192  }
1193
1194  // During installs from configuration don't support install profiles that
1195  // implement hook_install.
1196  if ($phase == 'install' && !empty($install_state['config_install_path'])) {
1197    $install_hook = $install_state['parameters']['profile'] . '_install';
1198    if (function_exists($install_hook)) {
1199      $requirements['config_install'] = [
1200        'title' => t('Configuration install'),
1201        'value' => $install_state['parameters']['profile'],
1202        'description' => t('The selected profile has a hook_install() implementation and therefore can not be installed from configuration.'),
1203        'severity' => REQUIREMENT_ERROR,
1204      ];
1205    }
1206  }
1207
1208  if ($phase === 'runtime') {
1209    $settings = Settings::getAll();
1210    if (array_key_exists('install_profile', $settings)) {
1211      // The following message is only informational because not all site owners
1212      // have access to edit their settings.php as it may be controlled by their
1213      // hosting provider.
1214      $requirements['install_profile_in_settings'] = [
1215        'title' => t('Install profile in settings'),
1216        'value' => t("Drupal 9 no longer uses the \$settings['install_profile'] value in settings.php and it should be removed."),
1217        'severity' => REQUIREMENT_WARNING,
1218      ];
1219    }
1220  }
1221
1222  // Ensure that no module has a current schema version that is lower than the
1223  // one that was last removed.
1224  if ($phase == 'update') {
1225    $module_handler = \Drupal::moduleHandler();
1226    $module_list = [];
1227    foreach ($module_handler->getImplementations('update_last_removed') as $module) {
1228      $last_removed = $module_handler->invoke($module, 'update_last_removed');
1229      if ($last_removed && $last_removed > drupal_get_installed_schema_version($module)) {
1230
1231        /** @var \Drupal\Core\Extension\Extension $module_info */
1232        $module_info = \Drupal::service('extension.list.module')->get($module);
1233        $module_list[$module] = [
1234          'name' => $module_info->info['name'],
1235          'last_removed' => $last_removed,
1236          'installed_version' => drupal_get_installed_schema_version($module),
1237        ];
1238      }
1239    }
1240
1241    // If system or workspaces is in the list then only show a specific message
1242    // for Drupal core.
1243    if (isset($module_list['system']) || isset($module_list['workspaces'])) {
1244      $requirements['system_update_last_removed'] = [
1245        'title' => t('The version of Drupal you are trying to update from is too old'),
1246        'description' => t('Updating to Drupal @current_major is only supported from Drupal version @required_min_version or higher. If you are trying to update from an older version, first update to the latest version of Drupal @previous_major. (<a href=":url">Drupal 9 upgrade guide</a>)', [
1247          '@current_major' => 9,
1248          // Workspaces is special cased due to updates being removed after
1249          // 8.8.0.
1250          '@required_min_version' => isset($module_list['workspaces']) ? '8.8.2' : '8.8.0',
1251          '@previous_major' => 8,
1252          ':url' => 'https://www.drupal.org/docs/9/how-to-prepare-your-drupal-7-or-8-site-for-drupal-9/upgrading-a-drupal-8-site-to-drupal-9',
1253        ]),
1254        'severity' => REQUIREMENT_ERROR,
1255      ];
1256    }
1257    else {
1258      foreach ($module_list as $module => $data) {
1259        $requirements[$module . '_update_last_removed'] = [
1260          'title' => t('Unsupported schema version: @module', ['@module' => $data['name']]),
1261          'description' => t('The installed version of the %module module is too old to update. Update to an intermediate version first (last removed version: @last_removed_version, installed version: @installed_version).', [
1262            '%module' => $data['name'],
1263            '@last_removed_version' => $data['last_removed'],
1264            '@installed_version' => $data['installed_version'],
1265          ]),
1266          'severity' => REQUIREMENT_ERROR,
1267        ];
1268      }
1269    }
1270    // Also check post-updates. Only do this if we're not already showing an
1271    // error for hook_update_N().
1272    if (empty($module_list)) {
1273      $existing_updates = \Drupal::service('keyvalue')->get('post_update')->get('existing_updates', []);
1274      $post_update_registry = \Drupal::service('update.post_update_registry');
1275      $modules = \Drupal::moduleHandler()->getModuleList();
1276      $module_extension_list = \Drupal::service('extension.list.module');
1277      foreach ($modules as $module => $extension) {
1278        $module_info = $module_extension_list->get($module);
1279        $removed_post_updates = $post_update_registry->getRemovedPostUpdates($module);
1280        if ($missing_updates = array_diff(array_keys($removed_post_updates), $existing_updates)) {
1281          $versions = array_unique(array_intersect_key($removed_post_updates, array_flip($missing_updates)));
1282          $description = new PluralTranslatableMarkup(count($versions),
1283            'The installed version of the %module module is too old to update. Update to a version prior to @versions first (missing updates: @missing_updates).',
1284            'The installed version of the %module module is too old to update. Update first to a version prior to all of the following: @versions (missing updates: @missing_updates).',
1285            [
1286              '%module' => $module_info->info['name'],
1287              '@missing_updates' => implode(', ', $missing_updates),
1288              '@versions' => implode(', ', $versions),
1289            ]
1290          );
1291          $requirements[$module . '_post_update_removed'] = [
1292            'title' => t('Missing updates for: @module', ['@module' => $module_info->info['name']]),
1293            'description' => $description,
1294            'severity' => REQUIREMENT_ERROR,
1295          ];
1296        }
1297      }
1298    }
1299  }
1300
1301  return $requirements;
1302}
1303
1304/**
1305 * Implements hook_install().
1306 */
1307function system_install() {
1308  // Populate the cron key state variable.
1309  $cron_key = Crypt::randomBytesBase64(55);
1310  \Drupal::state()->set('system.cron_key', $cron_key);
1311
1312  // Populate the site UUID and default name (if not set).
1313  $site = \Drupal::configFactory()->getEditable('system.site');
1314  $site->set('uuid', \Drupal::service('uuid')->generate());
1315  if (!$site->get('name')) {
1316    $site->set('name', 'Drupal');
1317  }
1318  $site->save(TRUE);
1319
1320  // Populate the dummy query string added to all CSS and JavaScript files.
1321  _drupal_flush_css_js();
1322}
1323
1324/**
1325 * Implements hook_schema().
1326 */
1327function system_schema() {
1328  $schema['sequences'] = [
1329    'description' => 'Stores IDs.',
1330    'fields' => [
1331      'value' => [
1332        'description' => 'The value of the sequence.',
1333        'type' => 'serial',
1334        'unsigned' => TRUE,
1335        'not null' => TRUE,
1336      ],
1337     ],
1338    'primary key' => ['value'],
1339  ];
1340
1341  $schema['sessions'] = [
1342    'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
1343    'fields' => [
1344      'uid' => [
1345        'description' => 'The {users}.uid corresponding to a session, or 0 for anonymous user.',
1346        'type' => 'int',
1347        'unsigned' => TRUE,
1348        'not null' => TRUE,
1349      ],
1350      'sid' => [
1351        'description' => "A session ID (hashed). The value is generated by Drupal's session handlers.",
1352        'type' => 'varchar_ascii',
1353        'length' => 128,
1354        'not null' => TRUE,
1355      ],
1356      'hostname' => [
1357        'description' => 'The IP address that last used this session ID (sid).',
1358        'type' => 'varchar_ascii',
1359        'length' => 128,
1360        'not null' => TRUE,
1361        'default' => '',
1362      ],
1363      'timestamp' => [
1364        'description' => 'The Unix timestamp when this session last requested a page. Old records are purged by PHP automatically.',
1365        'type' => 'int',
1366        'not null' => TRUE,
1367        'default' => 0,
1368      ],
1369      'session' => [
1370        'description' => 'The serialized contents of $_SESSION, an array of name/value pairs that persists across page requests by this session ID. Drupal loads $_SESSION from here at the start of each request and saves it at the end.',
1371        'type' => 'blob',
1372        'not null' => FALSE,
1373        'size' => 'big',
1374      ],
1375    ],
1376    'primary key' => [
1377      'sid',
1378    ],
1379    'indexes' => [
1380      'timestamp' => ['timestamp'],
1381      'uid' => ['uid'],
1382    ],
1383    'foreign keys' => [
1384      'session_user' => [
1385        'table' => 'users',
1386        'columns' => ['uid' => 'uid'],
1387      ],
1388    ],
1389  ];
1390
1391  return $schema;
1392}
1393
1394/**
1395 * Implements hook_update_last_removed().
1396 */
1397function system_update_last_removed() {
1398  return 8805;
1399}
1400
1401/**
1402 * Update the stored schema data for entity identifier fields.
1403 */
1404function system_update_8901() {
1405  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
1406  $entity_type_manager = \Drupal::entityTypeManager();
1407  $installed_storage_schema = \Drupal::keyValue('entity.storage_schema.sql');
1408
1409  foreach ($definition_update_manager->getEntityTypes() as $entity_type_id => $entity_type) {
1410    // Ensure that we are dealing with a non-deleted entity type that uses the
1411    // default SQL storage.
1412    if (!$entity_type_manager->hasDefinition($entity_type_id)) {
1413      continue;
1414    }
1415
1416    $storage = $entity_type_manager->getStorage($entity_type_id);
1417    if (!$storage instanceof SqlContentEntityStorage) {
1418      continue;
1419    }
1420
1421    foreach (['id', 'revision'] as $key) {
1422      if (!$entity_type->hasKey($key)) {
1423        continue;
1424      }
1425
1426      $field_name = $entity_type->getKey($key);
1427      $field_storage_definition = $definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id);
1428      if (!$field_storage_definition) {
1429        continue;
1430      }
1431      if ($field_storage_definition->getType() !== 'integer') {
1432        continue;
1433      }
1434
1435      // Retrieve the storage schema in order to use its own method for updating
1436      // the identifier schema - ::processIdentifierSchema(). This is needed
1437      // because some storage schemas might not use serial identifiers.
1438      // @see \Drupal\user\UserStorageSchema::processIdentifierSchema()
1439      $ref_get_storage_schema = new \ReflectionMethod($storage, 'getStorageSchema');
1440      $ref_get_storage_schema->setAccessible(TRUE);
1441      $storage_schema = $ref_get_storage_schema->invoke($storage);
1442
1443      if ($storage_schema instanceof SqlContentEntityStorageSchema) {
1444        $field_schema_data = $installed_storage_schema->get($entity_type_id . '.field_schema_data.' . $field_storage_definition->getName(), []);
1445        $table = $key === 'id' ? $entity_type->getBaseTable() : $entity_type->getRevisionTable();
1446
1447        $ref_process_identifier_schema = new \ReflectionMethod($storage_schema, 'processIdentifierSchema');
1448        $ref_process_identifier_schema->setAccessible(TRUE);
1449        $ref_process_identifier_schema->invokeArgs($storage_schema, [&$field_schema_data[$table], $field_name]);
1450
1451        $installed_storage_schema->set($entity_type_id . '.field_schema_data.' . $field_storage_definition->getName(), $field_schema_data);
1452      }
1453    }
1454  }
1455}
1456
1457/**
1458 * Display requirements from security advisories.
1459 *
1460 * @param array[] $requirements
1461 *   The requirements array as specified in hook_requirements().
1462 */
1463function _system_advisories_requirements(array &$requirements): void {
1464  if (!\Drupal::config('system.advisories')->get('enabled')) {
1465    return;
1466  }
1467
1468  /** @var \Drupal\system\SecurityAdvisories\SecurityAdvisoriesFetcher $fetcher */
1469  $fetcher = \Drupal::service('system.sa_fetcher');
1470  try {
1471    $advisories = $fetcher->getSecurityAdvisories(TRUE, 5);
1472  }
1473  catch (TransferException $exception) {
1474    $requirements['system_advisories']['title'] = t('Critical security announcements');
1475    $requirements['system_advisories']['severity'] = REQUIREMENT_WARNING;
1476    $requirements['system_advisories']['description'] = ['#theme' => 'system_security_advisories_fetch_error_message'];
1477    watchdog_exception('system', $exception, 'Failed to retrieve security advisory data.');
1478    return;
1479  }
1480
1481  if (!empty($advisories)) {
1482    $advisory_links = [];
1483    $severity = REQUIREMENT_WARNING;
1484    foreach ($advisories as $advisory) {
1485      if (!$advisory->isPsa()) {
1486        $severity = REQUIREMENT_ERROR;
1487      }
1488      $advisory_links[] = new Link($advisory->getTitle(), Url::fromUri($advisory->getUrl()));
1489    }
1490    $requirements['system_advisories']['title'] = t('Critical security announcements');
1491    $requirements['system_advisories']['severity'] = $severity;
1492    $requirements['system_advisories']['description'] = [
1493      'list' => [
1494        '#theme' => 'item_list',
1495        '#items' => $advisory_links,
1496      ],
1497    ];
1498    if (\Drupal::moduleHandler()->moduleExists('help')) {
1499      $requirements['system_advisories']['description']['help_link'] = Link::createFromRoute(
1500        'What are critical security announcements?',
1501        'help.page', ['name' => 'system'],
1502        ['fragment' => 'security-advisories']
1503      )->toRenderable();
1504    }
1505  }
1506}
1507