6eb8c120056937127bb69ca174beffe567414dad
[yaffs-website] / web / core / modules / system / system.install
1 <?php
2
3 /**
4  * @file
5  * Install, update and uninstall functions for the system module.
6  */
7
8 use Drupal\Component\Utility\Crypt;
9 use Drupal\Component\Utility\Environment;
10 use Drupal\Component\FileSystem\FileSystem;
11 use Drupal\Component\Utility\OpCodeCache;
12 use Drupal\Component\Utility\Unicode;
13 use Drupal\Core\Cache\Cache;
14 use Drupal\Core\Path\AliasStorage;
15 use Drupal\Core\Url;
16 use Drupal\Core\Database\Database;
17 use Drupal\Core\Entity\ContentEntityTypeInterface;
18 use Drupal\Core\Entity\EntityTypeInterface;
19 use Drupal\Core\Entity\FieldableEntityInterface;
20 use Drupal\Core\DrupalKernel;
21 use Drupal\Core\Field\BaseFieldDefinition;
22 use Drupal\Core\Site\Settings;
23 use Drupal\Core\StreamWrapper\PrivateStream;
24 use Drupal\Core\StreamWrapper\PublicStream;
25 use Drupal\system\SystemRequirements;
26 use Symfony\Component\HttpFoundation\Request;
27
28 /**
29  * Implements hook_requirements().
30  */
31 function system_requirements($phase) {
32   global $install_state;
33   $requirements = [];
34
35   // Report Drupal version
36   if ($phase == 'runtime') {
37     $requirements['drupal'] = [
38       'title' => t('Drupal'),
39       'value' => \Drupal::VERSION,
40       'severity' => REQUIREMENT_INFO,
41       'weight' => -10,
42     ];
43
44     // Display the currently active installation profile, if the site
45     // is not running the default installation profile.
46     $profile = drupal_get_profile();
47     if ($profile != 'standard') {
48       $info = system_get_info('module', $profile);
49       $requirements['install_profile'] = [
50         'title' => t('Installation profile'),
51         'value' => t('%profile_name (%profile-%version)', [
52           '%profile_name' => $info['name'],
53           '%profile' => $profile,
54           '%version' => $info['version'],
55         ]),
56         'severity' => REQUIREMENT_INFO,
57         'weight' => -9,
58       ];
59     }
60
61     // Warn if any experimental modules are installed.
62     $experimental = [];
63     $enabled_modules = \Drupal::moduleHandler()->getModuleList();
64     foreach ($enabled_modules as $module => $data) {
65       $info = system_get_info('module', $module);
66       if (isset($info['package']) && $info['package'] === 'Core (Experimental)') {
67         $experimental[$module] = $info['name'];
68       }
69     }
70     if (!empty($experimental)) {
71       $requirements['experimental'] = [
72         'title' => t('Experimental modules enabled'),
73         '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), ':url' => 'https://www.drupal.org/core/experimental']),
74         'severity' => REQUIREMENT_WARNING,
75       ];
76     }
77   }
78
79   // Web server information.
80   $request_object = \Drupal::request();
81   $software = $request_object->server->get('SERVER_SOFTWARE');
82   $requirements['webserver'] = [
83     'title' => t('Web server'),
84     'value' => $software,
85   ];
86
87   // Tests clean URL support.
88   if ($phase == 'install' && $install_state['interactive'] && !$request_object->query->has('rewrite') && strpos($software, 'Apache') !== FALSE) {
89     // If the Apache rewrite module is not enabled, Apache version must be >=
90     // 2.2.16 because of the FallbackResource directive in the root .htaccess
91     // file. Since the Apache version reported by the server is dependent on the
92     // ServerTokens setting in httpd.conf, we may not be able to determine if a
93     // given config is valid. Thus we are unable to use version_compare() as we
94     // need have three possible outcomes: the version of Apache is greater than
95     // 2.2.16, is less than 2.2.16, or cannot be determined accurately. In the
96     // first case, we encourage the use of mod_rewrite; in the second case, we
97     // raise an error regarding the minimum Apache version; in the third case,
98     // we raise a warning that the current version of Apache may not be
99     // supported.
100     $rewrite_warning = FALSE;
101     $rewrite_error = FALSE;
102     $apache_version_string = 'Apache';
103
104     // Determine the Apache version number: major, minor and revision.
105     if (preg_match('/Apache\/(\d+)\.?(\d+)?\.?(\d+)?/', $software, $matches)) {
106       $apache_version_string = $matches[0];
107
108       // Major version number
109       if ($matches[1] < 2) {
110         $rewrite_error = TRUE;
111       }
112       elseif ($matches[1] == 2) {
113         if (!isset($matches[2])) {
114           $rewrite_warning = TRUE;
115         }
116         elseif ($matches[2] < 2) {
117           $rewrite_error = TRUE;
118         }
119         elseif ($matches[2] == 2) {
120           if (!isset($matches[3])) {
121             $rewrite_warning = TRUE;
122           }
123           elseif ($matches[3] < 16) {
124             $rewrite_error = TRUE;
125           }
126         }
127       }
128     }
129     else {
130       $rewrite_warning = TRUE;
131     }
132
133     if ($rewrite_warning) {
134       $requirements['apache_version'] = [
135         'title' => t('Apache version'),
136         'value' => $apache_version_string,
137         'severity' => REQUIREMENT_WARNING,
138         '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]),
139       ];
140     }
141
142     if ($rewrite_error) {
143       $requirements['Apache version'] = [
144         'title' => t('Apache version'),
145         'value' => $apache_version_string,
146         'severity' => REQUIREMENT_ERROR,
147         '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' => 'http://drupal.org/node/15365']),
148       ];
149     }
150
151     if (!$rewrite_error && !$rewrite_warning) {
152       $requirements['rewrite_module'] = [
153         'title' => t('Clean URLs'),
154         'value' => t('Disabled'),
155         'severity' => REQUIREMENT_WARNING,
156         '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' => 'http://drupal.org/node/15365']),
157       ];
158     }
159   }
160
161   // Verify the user is running a supported PHP version.
162   // If the site is running a recommended version of PHP, just display it
163   // as an informational message on the status report. This will be overridden
164   // with an error or warning if the site is running older PHP versions for
165   // which Drupal has already or will soon drop support.
166   $phpversion = $phpversion_label = phpversion();
167   if (function_exists('phpinfo')) {
168     if ($phase === 'runtime') {
169       $phpversion_label = t('@phpversion (<a href=":url">more information</a>)', ['@phpversion' => $phpversion, ':url' => (new Url('system.php'))->toString()]);
170     }
171     $requirements['php'] = [
172       'title' => t('PHP'),
173       'value' => $phpversion_label,
174     ];
175   }
176   else {
177     // @todo Revisit whether this description makes sense in
178     //   https://www.drupal.org/project/drupal/issues/2927318.
179     $requirements['php'] = [
180       'title' => t('PHP'),
181       'value' => $phpversion_label,
182       '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']),
183       'severity' => REQUIREMENT_INFO,
184     ];
185   }
186
187   if (version_compare($phpversion, DRUPAL_MINIMUM_PHP) < 0) {
188     $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version.', ['%version' => DRUPAL_MINIMUM_PHP]);
189     $requirements['php']['severity'] = REQUIREMENT_ERROR;
190     // If PHP is old, it's not safe to continue with the requirements check.
191     return $requirements;
192   }
193   if ((version_compare($phpversion, DRUPAL_RECOMMENDED_PHP) < 0) && ($phase === 'install' || $phase === 'runtime')) {
194     // Warn if still on PHP 5. If at least PHP 7.0, relax from "warning" to
195     // "info", and show it at runtime only, to not scare users while installing.
196     if (version_compare($phpversion, '7.0') < 0) {
197       $requirements['php']['description'] = t('Drupal will drop support for this version on March 6, 2019. Upgrade to PHP version %recommended or higher to ensure your site can receive updates and remain secure. 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']);
198       $requirements['php']['severity'] = REQUIREMENT_WARNING;
199     }
200     else {
201       if ($phase === 'runtime') {
202         $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']);
203         $requirements['php']['severity'] = REQUIREMENT_INFO;
204       }
205     }
206   }
207
208   // Suggest to update to at least 5.5.21 or 5.6.5 for disabling multiple
209   // statements.
210   if (($phase === 'install' || \Drupal::database()->driver() === 'mysql') && !SystemRequirements::phpVersionWithPdoDisallowMultipleStatements($phpversion)) {
211     $requirements['php_multiple_statement'] = [
212       'title' => t('PHP (multiple statement disabling)'),
213       'value' => $phpversion_label,
214       'description' => t('PHP versions higher than 5.6.5 or 5.5.21 provide built-in SQL injection protection for mysql databases. It is recommended to update.'),
215       'severity' => REQUIREMENT_INFO,
216     ];
217   }
218
219   // Test for PHP extensions.
220   $requirements['php_extensions'] = [
221     'title' => t('PHP extensions'),
222   ];
223
224   $missing_extensions = [];
225   $required_extensions = [
226     'date',
227     'dom',
228     'filter',
229     'gd',
230     'hash',
231     'json',
232     'pcre',
233     'pdo',
234     'session',
235     'SimpleXML',
236     'SPL',
237     'tokenizer',
238     'xml',
239   ];
240   foreach ($required_extensions as $extension) {
241     if (!extension_loaded($extension)) {
242       $missing_extensions[] = $extension;
243     }
244   }
245
246   if (!empty($missing_extensions)) {
247     $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):', [
248       ':system_requirements' => 'https://www.drupal.org/requirements',
249     ]);
250
251     // We use twig inline_template to avoid twig's autoescape.
252     $description = [
253       '#type' => 'inline_template',
254       '#template' => '{{ description }}{{ missing_extensions }}',
255       '#context' => [
256         'description' => $description,
257         'missing_extensions' => [
258           '#theme' => 'item_list',
259           '#items' => $missing_extensions,
260         ],
261       ],
262     ];
263
264     $requirements['php_extensions']['value'] = t('Disabled');
265     $requirements['php_extensions']['severity'] = REQUIREMENT_ERROR;
266     $requirements['php_extensions']['description'] = $description;
267   }
268   else {
269     $requirements['php_extensions']['value'] = t('Enabled');
270   }
271
272   if ($phase == 'install' || $phase == 'runtime') {
273     // Check to see if OPcache is installed.
274     if (!OpCodeCache::isEnabled()) {
275       $requirements['php_opcache'] = [
276         'value' => t('Not enabled'),
277         'severity' => REQUIREMENT_WARNING,
278         '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.'),
279       ];
280     }
281     else {
282       $requirements['php_opcache']['value'] = t('Enabled');
283     }
284     $requirements['php_opcache']['title'] = t('PHP OPcode caching');
285   }
286
287   if ($phase != 'update') {
288     // Test whether we have a good source of random bytes.
289     $requirements['php_random_bytes'] = [
290       'title' => t('Random number generation'),
291     ];
292     try {
293       $bytes = random_bytes(10);
294       if (strlen($bytes) != 10) {
295         throw new \Exception(t('Tried to generate 10 random bytes, generated @count', ['@count' => strlen($bytes)]));
296       }
297       $requirements['php_random_bytes']['value'] = t('Successful');
298     }
299     catch (\Exception $e) {
300       // If /dev/urandom is not available on a UNIX-like system, check whether
301       // open_basedir restrictions are the cause.
302       $open_basedir_blocks_urandom = FALSE;
303       if (DIRECTORY_SEPARATOR === '/' && !@is_readable('/dev/urandom')) {
304         $open_basedir = ini_get('open_basedir');
305         if ($open_basedir) {
306           $open_basedir_paths = explode(PATH_SEPARATOR, $open_basedir);
307           $open_basedir_blocks_urandom = !array_intersect(['/dev', '/dev/', '/dev/urandom'], $open_basedir_paths);
308         }
309       }
310       $args = [
311         ':drupal-php' => 'https://www.drupal.org/docs/7/system-requirements/php#csprng',
312         '%exception_message' => $e->getMessage(),
313       ];
314       if ($open_basedir_blocks_urandom) {
315         $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);
316       }
317       else {
318         $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);
319       }
320       $requirements['php_random_bytes']['value'] = t('Less secure');
321       $requirements['php_random_bytes']['severity'] = REQUIREMENT_ERROR;
322     }
323   }
324
325   if ($phase == 'install' || $phase == 'update') {
326     // Test for PDO (database).
327     $requirements['database_extensions'] = [
328       'title' => t('Database support'),
329     ];
330
331     // Make sure PDO is available.
332     $database_ok = extension_loaded('pdo');
333     if (!$database_ok) {
334       $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.', [
335         ':link' => 'https://www.drupal.org/requirements/pdo',
336       ]);
337     }
338     else {
339       // Make sure at least one supported database driver exists.
340       $drivers = drupal_detect_database_types();
341       if (empty($drivers)) {
342         $database_ok = FALSE;
343         $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>.', [
344           ':drupal-databases' => 'https://www.drupal.org/requirements/database',
345         ]);
346       }
347       // Make sure the native PDO extension is available, not the older PEAR
348       // version. (See install_verify_pdo() for details.)
349       if (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
350         $database_ok = FALSE;
351         $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.', [
352           ':link' => 'https://www.drupal.org/requirements/pdo#pecl',
353         ]);
354       }
355     }
356
357     if (!$database_ok) {
358       $requirements['database_extensions']['value'] = t('Disabled');
359       $requirements['database_extensions']['severity'] = REQUIREMENT_ERROR;
360       $requirements['database_extensions']['description'] = $pdo_message;
361     }
362     else {
363       $requirements['database_extensions']['value'] = t('Enabled');
364     }
365   }
366   else {
367     // Database information.
368     $class = Database::getConnection()->getDriverClass('Install\\Tasks');
369     $tasks = new $class();
370     $requirements['database_system'] = [
371       'title' => t('Database system'),
372       'value' => $tasks->name(),
373     ];
374     $requirements['database_system_version'] = [
375       'title' => t('Database system version'),
376       'value' => Database::getConnection()->version(),
377     ];
378   }
379
380   // Test PHP memory_limit
381   $memory_limit = ini_get('memory_limit');
382   $requirements['php_memory_limit'] = [
383     'title' => t('PHP memory limit'),
384     'value' => $memory_limit == -1 ? t('-1 (Unlimited)') : $memory_limit,
385   ];
386
387   if (!Environment::checkMemoryLimit(DRUPAL_MINIMUM_PHP_MEMORY_LIMIT, $memory_limit)) {
388     $description = [];
389     if ($phase == 'install') {
390       $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]);
391     }
392     elseif ($phase == 'update') {
393       $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]);
394     }
395     elseif ($phase == 'runtime') {
396       $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]);
397     }
398
399     if (!empty($description['phase'])) {
400       if ($php_ini_path = get_cfg_var('cfg_file_path')) {
401         $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]);
402       }
403       else {
404         $description['memory'] = t('Contact your system administrator or hosting provider for assistance with increasing your PHP memory limit.');
405       }
406
407       $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']);
408
409       $description = [
410         '#type' => 'inline_template',
411         '#template' => '{{ description_phase }} {{ description_memory }} {{ handbook }}',
412         '#context' => [
413           'description_phase' => $description['phase'],
414           'description_memory' => $description['memory'],
415           'handbook' => $handbook_link,
416         ],
417       ];
418
419       $requirements['php_memory_limit']['description'] = $description;
420       $requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
421     }
422   }
423
424   // Test configuration files and directory for writability.
425   if ($phase == 'runtime') {
426     $conf_errors = [];
427     // Find the site path. Kernel service is not always available at this point,
428     // but is preferred, when available.
429     if (\Drupal::hasService('kernel')) {
430       $site_path = \Drupal::service('site.path');
431     }
432     else {
433       $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
434     }
435     // Allow system administrators to disable permissions hardening for the site
436     // directory. This allows additional files in the site directory to be
437     // updated when they are managed in a version control system.
438     if (Settings::get('skip_permissions_hardening')) {
439       $error_value = t('Protection disabled');
440       // If permissions hardening is disabled, then only show a warning for a
441       // writable file, as a reminder, rather than an error.
442       $file_protection_severity = REQUIREMENT_WARNING;
443     }
444     else {
445       $error_value = t('Not protected');
446       // In normal operation, writable files or directories are an error.
447       $file_protection_severity = REQUIREMENT_ERROR;
448       if (!drupal_verify_install_file($site_path, FILE_NOT_WRITABLE, 'dir')) {
449         $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]);
450       }
451     }
452     foreach (['settings.php', 'settings.local.php', 'services.yml'] as $conf_file) {
453       $full_path = $site_path . '/' . $conf_file;
454       if (file_exists($full_path) && !drupal_verify_install_file($full_path, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE, 'file', !Settings::get('skip_permissions_hardening'))) {
455         $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]);
456       }
457     }
458     if (!empty($conf_errors)) {
459       if (count($conf_errors) == 1) {
460         $description = $conf_errors[0];
461       }
462       else {
463         // We use twig inline_template to avoid double escaping.
464         $description = [
465           '#type' => 'inline_template',
466           '#template' => '{{ configuration_error_list }}',
467           '#context' => [
468             'configuration_error_list' => [
469               '#theme' => 'item_list',
470               '#items' => $conf_errors,
471             ],
472           ],
473         ];
474       }
475       $requirements['configuration_files'] = [
476         'value' => $error_value,
477         'severity' => $file_protection_severity,
478         'description' => $description,
479       ];
480     }
481     else {
482       $requirements['configuration_files'] = [
483         'value' => t('Protected'),
484       ];
485     }
486     $requirements['configuration_files']['title'] = t('Configuration files');
487   }
488
489   // Test the contents of the .htaccess files.
490   if ($phase == 'runtime') {
491     // Try to write the .htaccess files first, to prevent false alarms in case
492     // (for example) the /tmp directory was wiped.
493     file_ensure_htaccess();
494     $file_system = \Drupal::service('file_system');
495     $htaccess_files['public://.htaccess'] = [
496       'title' => t('Public files directory'),
497       'directory' => $file_system->realpath('public://'),
498     ];
499     if (PrivateStream::basePath()) {
500       $htaccess_files['private://.htaccess'] = [
501         'title' => t('Private files directory'),
502         'directory' => $file_system->realpath('private://'),
503       ];
504     }
505     $htaccess_files['temporary://.htaccess'] = [
506       'title' => t('Temporary files directory'),
507       'directory' => $file_system->realpath('temporary://'),
508     ];
509     foreach ($htaccess_files as $htaccess_file => $info) {
510       // Check for the string which was added to the recommended .htaccess file
511       // in the latest security update.
512       if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
513         $url = 'https://www.drupal.org/SA-CORE-2013-003';
514         $requirements[$htaccess_file] = [
515           'title' => $info['title'],
516           'value' => t('Not fully protected'),
517           'severity' => REQUIREMENT_ERROR,
518           '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' => $info['directory']]),
519         ];
520       }
521     }
522   }
523
524   // Report cron status.
525   if ($phase == 'runtime') {
526     $cron_config = \Drupal::config('system.cron');
527     // Cron warning threshold defaults to two days.
528     $threshold_warning = $cron_config->get('threshold.requirements_warning');
529     // Cron error threshold defaults to two weeks.
530     $threshold_error = $cron_config->get('threshold.requirements_error');
531
532     // Determine when cron last ran.
533     $cron_last = \Drupal::state()->get('system.cron_last');
534     if (!is_numeric($cron_last)) {
535       $cron_last = \Drupal::state()->get('install_time', 0);
536     }
537
538     // Determine severity based on time since cron last ran.
539     $severity = REQUIREMENT_INFO;
540     if (REQUEST_TIME - $cron_last > $threshold_error) {
541       $severity = REQUIREMENT_ERROR;
542     }
543     elseif (REQUEST_TIME - $cron_last > $threshold_warning) {
544       $severity = REQUIREMENT_WARNING;
545     }
546
547     // Set summary and description based on values determined above.
548     $summary = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
549
550     $requirements['cron'] = [
551       'title' => t('Cron maintenance tasks'),
552       'severity' => $severity,
553       'value' => $summary,
554     ];
555     if ($severity != REQUIREMENT_INFO) {
556       $requirements['cron']['description'][] = [
557         [
558           '#markup' => t('Cron has not run recently.'),
559           '#suffix' => ' ',
560         ],
561         [
562           '#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']),
563           '#suffix' => ' ',
564         ],
565       ];
566     }
567     $requirements['cron']['description'][] = [
568       [
569         '#type' => 'link',
570         '#prefix' => '(',
571         '#title' => t('more information'),
572         '#suffix' => ')',
573         '#url' => Url::fromRoute('system.cron_settings'),
574       ],
575       [
576         '#prefix' => '<span class="cron-description__run-cron">',
577         '#suffix' => '</span>',
578         '#type' => 'link',
579         '#title' => t('Run cron'),
580         '#url' => Url::fromRoute('system.run_cron'),
581       ],
582     ];
583   }
584   if ($phase != 'install') {
585     $filesystem_config = \Drupal::config('system.file');
586     $directories = [
587       PublicStream::basePath(),
588       // By default no private files directory is configured. For private files
589       // to be secure the admin needs to provide a path outside the webroot.
590       PrivateStream::basePath(),
591       file_directory_temp(),
592     ];
593   }
594
595   // During an install we need to make assumptions about the file system
596   // unless overrides are provided in settings.php.
597   if ($phase == 'install') {
598     $directories = [];
599     if ($file_public_path = Settings::get('file_public_path')) {
600       $directories[] = $file_public_path;
601     }
602     else {
603       // If we are installing Drupal, the settings.php file might not exist yet
604       // in the intended site directory, so don't require it.
605       $request = Request::createFromGlobals();
606       $site_path = DrupalKernel::findSitePath($request);
607       $directories[] = $site_path . '/files';
608     }
609     if ($file_private_path = Settings::get('file_private_path')) {
610       $directories[] = $file_private_path;
611     }
612     if (!empty($GLOBALS['config']['system.file']['path']['temporary'])) {
613       $directories[] = $GLOBALS['config']['system.file']['path']['temporary'];
614     }
615     else {
616       // If the temporary directory is not overridden use an appropriate
617       // temporary path for the system.
618       $directories[] = FileSystem::getOsTemporaryDirectory();
619     }
620   }
621
622   // Check the config directory if it is defined in settings.php. If it isn't
623   // defined, the installer will create a valid config directory later, but
624   // during runtime we must always display an error.
625   if (!empty($GLOBALS['config_directories'])) {
626     foreach (array_keys(array_filter($GLOBALS['config_directories'])) as $type) {
627       $directory = config_get_config_directory($type);
628       // If we're installing Drupal try and create the config sync directory.
629       if (!is_dir($directory) && $phase == 'install') {
630         file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
631       }
632       if (!is_dir($directory)) {
633         if ($phase == 'install') {
634           $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' => $directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']);
635         }
636         else {
637           $description = t('The directory %directory does not exist.', ['%directory' => $directory]);
638         }
639         $requirements['config directory ' . $type] = [
640           'title' => t('Configuration directory: %type', ['%type' => $type]),
641           'description' => $description,
642           'severity' => REQUIREMENT_ERROR,
643         ];
644       }
645     }
646   }
647   if ($phase != 'install' && (empty($GLOBALS['config_directories']) || empty($GLOBALS['config_directories'][CONFIG_SYNC_DIRECTORY]))) {
648     $requirements['config directories'] = [
649       'title' => t('Configuration directories'),
650       'value' => t('Not present'),
651       'description' => t('Your %file file must define the $config_directories variable as an array containing the names of directories in which configuration files can be found. It must contain a %sync_key key.', ['%file' => $site_path . '/settings.php', '%sync_key' => CONFIG_SYNC_DIRECTORY]),
652       'severity' => REQUIREMENT_ERROR,
653     ];
654   }
655
656   $requirements['file system'] = [
657     'title' => t('File system'),
658   ];
659
660   $error = '';
661   // For installer, create the directories if possible.
662   foreach ($directories as $directory) {
663     if (!$directory) {
664       continue;
665     }
666     if ($phase == 'install') {
667       file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
668     }
669     $is_writable = is_writable($directory);
670     $is_directory = is_dir($directory);
671     if (!$is_writable || !$is_directory) {
672       $description = '';
673       $requirements['file system']['value'] = t('Not writable');
674       if (!$is_directory) {
675         $error = t('The directory %directory does not exist.', ['%directory' => $directory]);
676       }
677       else {
678         $error = t('The directory %directory is not writable.', ['%directory' => $directory]);
679       }
680       // The files directory requirement check is done only during install and runtime.
681       if ($phase == 'runtime') {
682         $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' => \Drupal::url('system.file_system_settings')]);
683       }
684       elseif ($phase == 'install') {
685         // For the installer UI, we need different wording. 'value' will
686         // be treated as version, so provide none there.
687         $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']);
688         $requirements['file system']['value'] = '';
689       }
690       if (!empty($description)) {
691         $description = [
692           '#type' => 'inline_template',
693           '#template' => '{{ error }} {{ description }}',
694           '#context' => [
695             'error' => $error,
696             'description' => $description,
697           ],
698         ];
699         $requirements['file system']['description'] = $description;
700         $requirements['file system']['severity'] = REQUIREMENT_ERROR;
701       }
702     }
703     else {
704       // This function can be called before the config_cache table has been
705       // created.
706       if ($phase == 'install' || file_default_scheme() == 'public') {
707         $requirements['file system']['value'] = t('Writable (<em>public</em> download method)');
708       }
709       else {
710         $requirements['file system']['value'] = t('Writable (<em>private</em> download method)');
711       }
712     }
713   }
714
715   // See if updates are available in update.php.
716   if ($phase == 'runtime') {
717     $requirements['update'] = [
718       'title' => t('Database updates'),
719       'value' => t('Up to date'),
720     ];
721
722     // Check installed modules.
723     $has_pending_updates = FALSE;
724     foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) {
725       $updates = drupal_get_schema_versions($module);
726       if ($updates !== FALSE) {
727         $default = drupal_get_installed_schema_version($module);
728         if (max($updates) > $default) {
729           $has_pending_updates = TRUE;
730           break;
731         }
732       }
733     }
734     if (!$has_pending_updates) {
735       /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
736       $post_update_registry = \Drupal::service('update.post_update_registry');
737       $missing_post_update_functions = $post_update_registry->getPendingUpdateFunctions();
738       if (!empty($missing_post_update_functions)) {
739         $has_pending_updates = TRUE;
740       }
741     }
742
743     if ($has_pending_updates) {
744       $requirements['update']['severity'] = REQUIREMENT_ERROR;
745       $requirements['update']['value'] = t('Out of date');
746       $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' => \Drupal::url('system.db_update')]);
747     }
748
749     $requirements['entity_update'] = [
750       'title' => t('Entity/field definitions'),
751       'value' => t('Up to date'),
752     ];
753     // Verify that no entity updates are pending.
754     if ($change_list = \Drupal::entityDefinitionUpdateManager()->getChangeSummary()) {
755       $build = [];
756       foreach ($change_list as $entity_type_id => $changes) {
757         $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
758         $build[] = [
759           '#theme' => 'item_list',
760           '#title' => $entity_type->getLabel(),
761           '#items' => $changes,
762         ];
763       }
764
765       $entity_update_issues = \Drupal::service('renderer')->renderPlain($build);
766       $requirements['entity_update']['severity'] = REQUIREMENT_ERROR;
767       $requirements['entity_update']['value'] = t('Mismatched entity and/or field definitions');
768       $requirements['entity_update']['description'] = t('The following changes were detected in the entity type and field definitions. @updates', ['@updates' => $entity_update_issues]);
769     }
770   }
771
772   // Verify the update.php access setting
773   if ($phase == 'runtime') {
774     if (Settings::get('update_free_access')) {
775       $requirements['update access'] = [
776         'value' => t('Not protected'),
777         'severity' => REQUIREMENT_ERROR,
778         '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\']']),
779       ];
780     }
781     else {
782       $requirements['update access'] = [
783         'value' => t('Protected'),
784       ];
785     }
786     $requirements['update access']['title'] = t('Access to update.php');
787   }
788
789   // Display an error if a newly introduced dependency in a module is not resolved.
790   if ($phase == 'update') {
791     $profile = drupal_get_profile();
792     $files = system_rebuild_module_data();
793     foreach ($files as $module => $file) {
794       // Ignore disabled modules and installation profiles.
795       if (!$file->status || $module == $profile) {
796         continue;
797       }
798       // Check the module's PHP version.
799       $name = $file->info['name'];
800       $php = $file->info['php'];
801       if (version_compare($php, PHP_VERSION, '>')) {
802         $requirements['php']['description'] .= t('@name requires at least PHP @version.', ['@name' => $name, '@version' => $php]);
803         $requirements['php']['severity'] = REQUIREMENT_ERROR;
804       }
805       // Check the module's required modules.
806       foreach ($file->requires as $requirement) {
807         $required_module = $requirement['name'];
808         // Check if the module exists.
809         if (!isset($files[$required_module])) {
810           $requirements["$module-$required_module"] = [
811             'title' => t('Unresolved dependency'),
812             'description' => t('@name requires this module.', ['@name' => $name]),
813             'value' => t('@required_name (Missing)', ['@required_name' => $required_module]),
814             'severity' => REQUIREMENT_ERROR,
815           ];
816           continue;
817         }
818         // Check for an incompatible version.
819         $required_file = $files[$required_module];
820         $required_name = $required_file->info['name'];
821         $version = str_replace(\Drupal::CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
822         $compatibility = drupal_check_incompatibility($requirement, $version);
823         if ($compatibility) {
824           $compatibility = rtrim(substr($compatibility, 2), ')');
825           $requirements["$module-$required_module"] = [
826             'title' => t('Unresolved dependency'),
827             'description' => t('@name requires this module and version. Currently using @required_name version @version', ['@name' => $name, '@required_name' => $required_name, '@version' => $version]),
828             'value' => t('@required_name (Version @compatibility required)', ['@required_name' => $required_name, '@compatibility' => $compatibility]),
829             'severity' => REQUIREMENT_ERROR,
830           ];
831           continue;
832         }
833       }
834     }
835   }
836
837   // Returns Unicode library status and errors.
838   $libraries = [
839     Unicode::STATUS_SINGLEBYTE => t('Standard PHP'),
840     Unicode::STATUS_MULTIBYTE => t('PHP Mbstring Extension'),
841     Unicode::STATUS_ERROR => t('Error'),
842   ];
843   $severities = [
844     Unicode::STATUS_SINGLEBYTE => REQUIREMENT_WARNING,
845     Unicode::STATUS_MULTIBYTE => NULL,
846     Unicode::STATUS_ERROR => REQUIREMENT_ERROR,
847   ];
848   $failed_check = Unicode::check();
849   $library = Unicode::getStatus();
850
851   $requirements['unicode'] = [
852     'title' => t('Unicode library'),
853     'value' => $libraries[$library],
854     'severity' => $severities[$library],
855   ];
856   switch ($failed_check) {
857     case 'mb_strlen':
858       $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.');
859       break;
860
861     case 'mbstring.func_overload':
862       $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.');
863       break;
864
865     case 'mbstring.encoding_translation':
866       $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.');
867       break;
868
869     case 'mbstring.http_input':
870       $requirements['unicode']['description'] = t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_input</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
871       break;
872
873     case 'mbstring.http_output':
874       $requirements['unicode']['description'] = t('Multibyte string output conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_output</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
875       break;
876   }
877
878   if ($phase == 'runtime') {
879     // Check for update status module.
880     if (!\Drupal::moduleHandler()->moduleExists('update')) {
881       $requirements['update status'] = [
882         'value' => t('Not enabled'),
883         'severity' => REQUIREMENT_WARNING,
884         '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>.', [
885           ':update' => 'https://www.drupal.org/documentation/modules/update',
886           ':module' => \Drupal::url('system.modules_list'),
887         ]),
888       ];
889     }
890     else {
891       $requirements['update status'] = [
892         'value' => t('Enabled'),
893       ];
894     }
895     $requirements['update status']['title'] = t('Update notifications');
896
897     if (Settings::get('rebuild_access')) {
898       $requirements['rebuild access'] = [
899         'title' => t('Rebuild access'),
900         'value' => t('Enabled'),
901         'severity' => REQUIREMENT_ERROR,
902         '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.'),
903       ];
904     }
905   }
906
907   // See if trusted hostnames have been configured, and warn the user if they
908   // are not set.
909   if ($phase == 'runtime') {
910     $trusted_host_patterns = Settings::get('trusted_host_patterns');
911     if (empty($trusted_host_patterns)) {
912       $requirements['trusted_host_patterns'] = [
913         'title' => t('Trusted Host Settings'),
914         'value' => t('Not enabled'),
915         '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/node/1992030']),
916         'severity' => REQUIREMENT_ERROR,
917       ];
918     }
919     else {
920       $requirements['trusted_host_patterns'] = [
921         'title' => t('Trusted Host Settings'),
922         'value' => t('Enabled'),
923         'description' => t('The trusted_host_patterns setting is set to allow %trusted_host_patterns', ['%trusted_host_patterns' => implode(', ', $trusted_host_patterns)]),
924       ];
925     }
926   }
927
928   // Check xdebug.max_nesting_level, as some pages will not work if it is too
929   // low.
930   if (extension_loaded('xdebug')) {
931     // Setting this value to 256 was considered adequate on Xdebug 2.3
932     // (see http://bugs.xdebug.org/bug_view_page.php?bug_id=00001100)
933     $minimum_nesting_level = 256;
934     $current_nesting_level = ini_get('xdebug.max_nesting_level');
935
936     if ($current_nesting_level < $minimum_nesting_level) {
937       $requirements['xdebug_max_nesting_level'] = [
938         'title' => t('Xdebug settings'),
939         'value' => t('xdebug.max_nesting_level is set to %value.', ['%value' => $current_nesting_level]),
940         '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]),
941         'severity' => REQUIREMENT_ERROR,
942       ];
943     }
944   }
945
946   // Warning for httpoxy on IIS with affected PHP versions
947   // @see https://www.drupal.org/node/2783079
948   if (strpos($software, 'Microsoft-IIS') !== FALSE
949     && (
950     version_compare(PHP_VERSION, '5.5.38', '<')
951     || (version_compare(PHP_VERSION, '5.6.0', '>=') && version_compare(PHP_VERSION, '5.6.24', '<'))
952     || (version_compare(PHP_VERSION, '7.0.0', '>=') && version_compare(PHP_VERSION, '7.0.9', '<'))
953     )) {
954     $dom = new \DOMDocument('1.0', 'UTF-8');
955     $webconfig = file_get_contents('web.config');
956     // If you are here the web.config file must - of course - be well formed.
957     // But the PHP DOM component will throw warnings on some XML compliant
958     // stuff, so silently parse the configuration file.
959     @$dom->loadHTML($webconfig);
960     $httpoxy_rewrite = FALSE;
961     foreach ($dom->getElementsByTagName('rule') as $rule) {
962       foreach ($rule->attributes as $attr) {
963         if (@$attr->name == 'name' && @$attr->nodeValue == 'Erase HTTP_PROXY') {
964           $httpoxy_rewrite = TRUE;
965           break 2;
966         }
967       }
968     }
969     if (!$httpoxy_rewrite) {
970       $requirements['iis_httpoxy_protection'] = [
971         'title' => t('IIS httpoxy protection'),
972         'value' => t('Your PHP runtime version is affected by the httpoxy vulnerability.'),
973         'description' => t('Either update your PHP runtime version or uncomment the "Erase HTTP_PROXY" rule in your web.config file and add HTTP_PROXY to the allowed headers list. See more details in the <a href=":link">security advisory</a>.', [':link' => 'https://www.drupal.org/SA-CORE-2016-003']),
974         'severity' => REQUIREMENT_ERROR,
975       ];
976     }
977   }
978
979   // Installations on Windows can run into limitations with MAX_PATH if the
980   // Drupal root directory is too deep in the filesystem. Generally this shows
981   // up in cached Twig templates and other public files with long directory or
982   // file names. There is no definite root directory depth below which Drupal is
983   // guaranteed to function correctly on Windows. Since problems are likely
984   // with more than 100 characters in the Drupal root path, show an error.
985   if (substr(PHP_OS, 0, 3) == 'WIN') {
986     $depth = strlen(realpath(DRUPAL_ROOT . '/' . PublicStream::basePath()));
987     if ($depth > 120) {
988       $requirements['max_path_on_windows'] = [
989         'title' => t('Windows installation depth'),
990         'description' => t('The public files directory path is %depth characters. Paths longer than 120 characters will cause problems on Windows.', ['%depth' => $depth]),
991         'severity' => REQUIREMENT_ERROR,
992       ];
993     }
994   }
995   // Check to see if dates will be limited to 1901-2038.
996   if (PHP_INT_SIZE <= 4) {
997     $requirements['limited_date_range'] = [
998       'title' => t('Limited date range'),
999       'value' => t('Your PHP installation has a limited date range.'),
1000       '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']),
1001       'severity' => REQUIREMENT_WARNING,
1002     ];
1003   }
1004
1005   // During installs from configuration don't support install profiles that
1006   // implement hook_install.
1007   if ($phase == 'install' && !empty($install_state['config_install_path'])) {
1008     $install_hook = $install_state['parameters']['profile'] . '_install';
1009     if (function_exists($install_hook)) {
1010       $requirements['config_install'] = [
1011         'title' => t('Configuration install'),
1012         'value' => $install_state['parameters']['profile'],
1013         'description' => t('The selected profile has a hook_install() implementation and therefore can not be installed from configuration.'),
1014         'severity' => REQUIREMENT_ERROR,
1015       ];
1016     }
1017   }
1018
1019   if ($phase === 'runtime') {
1020     $settings = Settings::getAll();
1021     if (array_key_exists('install_profile', $settings)) {
1022       // The following message is only informational because not all site owners
1023       // have access to edit their settings.php as it may be controlled by their
1024       // hosting provider.
1025       $requirements['install_profile_in_settings'] = [
1026         'title' => t('Install profile in settings'),
1027         'value' => t("Drupal 8 no longer uses the \$settings['install_profile'] value in settings.php and it can be removed."),
1028         'severity' => REQUIREMENT_INFO,
1029       ];
1030     }
1031   }
1032
1033   return $requirements;
1034 }
1035
1036 /**
1037  * Implements hook_install().
1038  */
1039 function system_install() {
1040   // Populate the cron key state variable.
1041   $cron_key = Crypt::randomBytesBase64(55);
1042   \Drupal::state()->set('system.cron_key', $cron_key);
1043
1044   // Populate the site UUID and default name (if not set).
1045   $site = \Drupal::configFactory()->getEditable('system.site');
1046   $site->set('uuid', \Drupal::service('uuid')->generate());
1047   if (!$site->get('name')) {
1048     $site->set('name', 'Drupal');
1049   }
1050   $site->save(TRUE);
1051 }
1052
1053 /**
1054  * Implements hook_schema().
1055  */
1056 function system_schema() {
1057   $schema['key_value'] = [
1058     'description' => 'Generic key-value storage table. See the state system for an example.',
1059     'fields' => [
1060       'collection' => [
1061         'description' => 'A named collection of key and value pairs.',
1062         'type' => 'varchar_ascii',
1063         'length' => 128,
1064         'not null' => TRUE,
1065         'default' => '',
1066       ],
1067       'name' => [
1068         'description' => 'The key of the key-value pair. As KEY is a SQL reserved keyword, name was chosen instead.',
1069         'type' => 'varchar_ascii',
1070         'length' => 128,
1071         'not null' => TRUE,
1072         'default' => '',
1073       ],
1074       'value' => [
1075         'description' => 'The value.',
1076         'type' => 'blob',
1077         'not null' => TRUE,
1078         'size' => 'big',
1079       ],
1080     ],
1081     'primary key' => ['collection', 'name'],
1082   ];
1083
1084   $schema['key_value_expire'] = [
1085     'description' => 'Generic key/value storage table with an expiration.',
1086     'fields' => [
1087       'collection' => [
1088         'description' => 'A named collection of key and value pairs.',
1089         'type' => 'varchar_ascii',
1090         'length' => 128,
1091         'not null' => TRUE,
1092         'default' => '',
1093       ],
1094       'name' => [
1095         // KEY is an SQL reserved word, so use 'name' as the key's field name.
1096         'description' => 'The key of the key/value pair.',
1097         'type' => 'varchar_ascii',
1098         'length' => 128,
1099         'not null' => TRUE,
1100         'default' => '',
1101       ],
1102       'value' => [
1103         'description' => 'The value of the key/value pair.',
1104         'type' => 'blob',
1105         'not null' => TRUE,
1106         'size' => 'big',
1107       ],
1108       'expire' => [
1109         'description' => 'The time since Unix epoch in seconds when this item expires. Defaults to the maximum possible time.',
1110         'type' => 'int',
1111         'not null' => TRUE,
1112         'default' => 2147483647,
1113       ],
1114     ],
1115     'primary key' => ['collection', 'name'],
1116     'indexes' => [
1117       'all' => ['name', 'collection', 'expire'],
1118       'expire' => ['expire'],
1119     ],
1120   ];
1121
1122   $schema['sequences'] = [
1123     'description' => 'Stores IDs.',
1124     'fields' => [
1125       'value' => [
1126         'description' => 'The value of the sequence.',
1127         'type' => 'serial',
1128         'unsigned' => TRUE,
1129         'not null' => TRUE,
1130       ],
1131      ],
1132     'primary key' => ['value'],
1133   ];
1134
1135   $schema['sessions'] = [
1136     'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
1137     'fields' => [
1138       'uid' => [
1139         'description' => 'The {users}.uid corresponding to a session, or 0 for anonymous user.',
1140         'type' => 'int',
1141         'unsigned' => TRUE,
1142         'not null' => TRUE,
1143       ],
1144       'sid' => [
1145         'description' => "A session ID (hashed). The value is generated by Drupal's session handlers.",
1146         'type' => 'varchar_ascii',
1147         'length' => 128,
1148         'not null' => TRUE,
1149       ],
1150       'hostname' => [
1151         'description' => 'The IP address that last used this session ID (sid).',
1152         'type' => 'varchar_ascii',
1153         'length' => 128,
1154         'not null' => TRUE,
1155         'default' => '',
1156       ],
1157       'timestamp' => [
1158         'description' => 'The Unix timestamp when this session last requested a page. Old records are purged by PHP automatically.',
1159         'type' => 'int',
1160         'not null' => TRUE,
1161         'default' => 0,
1162       ],
1163       'session' => [
1164         '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.',
1165         'type' => 'blob',
1166         'not null' => FALSE,
1167         'size' => 'big',
1168       ],
1169     ],
1170     'primary key' => [
1171       'sid',
1172     ],
1173     'indexes' => [
1174       'timestamp' => ['timestamp'],
1175       'uid' => ['uid'],
1176     ],
1177     'foreign keys' => [
1178       'session_user' => [
1179         'table' => 'users',
1180         'columns' => ['uid' => 'uid'],
1181       ],
1182     ],
1183   ];
1184
1185   // Create the url_alias table. The alias_storage service can auto-create its
1186   // table, but this relies on exceptions being thrown. These exceptions will be
1187   // thrown every request until an alias is created.
1188   $schema['url_alias'] = AliasStorage::schemaDefinition();
1189
1190   return $schema;
1191 }
1192
1193 /**
1194  * Change two fields on the default menu link storage to be serialized data.
1195  */
1196 function system_update_8001(&$sandbox = NULL) {
1197   $database = \Drupal::database();
1198   $schema = $database->schema();
1199   if ($schema->tableExists('menu_tree')) {
1200
1201     if (!isset($sandbox['current'])) {
1202       // Converting directly to blob can cause problems with reading out and
1203       // serializing the string data later on postgres, so rename the existing
1204       // columns and create replacement ones to hold the serialized objects.
1205       $old_fields = [
1206         'title' => [
1207           'description' => 'The text displayed for the link.',
1208           'type' => 'varchar',
1209           'length' => 255,
1210           'not null' => TRUE,
1211           'default' => '',
1212         ],
1213         'description' => [
1214           'description' => 'The description of this link - used for admin pages and title attribute.',
1215           'type' => 'text',
1216           'not null' => FALSE,
1217         ],
1218       ];
1219       foreach ($old_fields as $name => $spec) {
1220         $schema->changeField('menu_tree', $name, 'system_update_8001_' . $name, $spec);
1221       }
1222       $spec = [
1223         'description' => 'The title for the link. May be a serialized TranslatableMarkup.',
1224         'type' => 'blob',
1225         'size' => 'big',
1226         'not null' => FALSE,
1227         'serialize' => TRUE,
1228       ];
1229       $schema->addField('menu_tree', 'title', $spec);
1230       $spec = [
1231         'description' => 'The description of this link - used for admin pages and title attribute.',
1232         'type' => 'blob',
1233         'size' => 'big',
1234         'not null' => FALSE,
1235         'serialize' => TRUE,
1236       ];
1237       $schema->addField('menu_tree', 'description', $spec);
1238
1239       $sandbox['current'] = 0;
1240       $sandbox['max'] = $database->query('SELECT COUNT(mlid) FROM {menu_tree}')
1241         ->fetchField();
1242     }
1243
1244     $menu_links = $database->queryRange('SELECT mlid, system_update_8001_title AS title, system_update_8001_description AS description FROM {menu_tree} ORDER BY mlid ASC', $sandbox['current'], $sandbox['current'] + 50)
1245       ->fetchAllAssoc('mlid');
1246
1247     foreach ($menu_links as $menu_link) {
1248       $menu_link = (array) $menu_link;
1249       // Convert title and description to serialized strings.
1250       $menu_link['title'] = serialize($menu_link['title']);
1251       $menu_link['description'] = serialize($menu_link['description']);
1252
1253       $database->update('menu_tree')
1254         ->fields($menu_link)
1255         ->condition('mlid', $menu_link['mlid'])
1256         ->execute();
1257
1258       $sandbox['current']++;
1259     }
1260
1261     $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['current'] / $sandbox['max']);
1262
1263     if ($sandbox['#finished'] >= 1) {
1264       // Drop unnecessary fields from {menu_tree}.
1265       $schema->dropField('menu_tree', 'system_update_8001_title');
1266       $schema->dropField('menu_tree', 'title_arguments');
1267       $schema->dropField('menu_tree', 'title_context');
1268       $schema->dropField('menu_tree', 'system_update_8001_description');
1269     }
1270     return t('Menu links converted');
1271   }
1272   else {
1273     return t('Menu link conversion skipped, because the {menu_tree} table did not exist yet.');
1274   }
1275 }
1276
1277 /**
1278  * Removes the system.filter configuration.
1279  */
1280 function system_update_8002() {
1281   \Drupal::configFactory()->getEditable('system.filter')->delete();
1282   return t('The system.filter configuration has been moved to a container parameter, see default.services.yml for more information.');
1283 }
1284
1285 /**
1286  * Change the index on the {router} table.
1287  */
1288 function system_update_8003() {
1289   $database = \Drupal::database();
1290   $database->schema()->dropIndex('router', 'pattern_outline_fit');
1291   $database->schema()->addIndex(
1292     'router',
1293     'pattern_outline_parts',
1294     ['pattern_outline', 'number_parts'],
1295     [
1296       'fields' => [
1297         'pattern_outline' => [
1298           'description' => 'The pattern',
1299           'type' => 'varchar',
1300           'length' => 255,
1301           'not null' => TRUE,
1302           'default' => '',
1303         ],
1304         'number_parts' => [
1305           'description' => 'Number of parts in this router path.',
1306           'type' => 'int',
1307           'not null' => TRUE,
1308           'default' => 0,
1309           'size' => 'small',
1310         ],
1311       ],
1312     ]
1313   );
1314 }
1315
1316 /**
1317  * Add a (id, default_langcode, langcode) composite index to entities.
1318  */
1319 function system_update_8004() {
1320   // \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema was changed in
1321   // https://www.drupal.org/node/2261669 to include a (id, default_langcode,
1322   // langcode) compound index, but this update function wasn't added until
1323   // https://www.drupal.org/node/2542748. Regenerate the related schemas to
1324   // ensure they match the currently expected status.
1325   $manager = \Drupal::entityDefinitionUpdateManager();
1326   foreach (array_keys(\Drupal::entityManager()
1327     ->getDefinitions()) as $entity_type_id) {
1328     // Only update the entity type if it already exists. This condition is
1329     // needed in case new entity types are introduced after this update.
1330     if ($entity_type = $manager->getEntityType($entity_type_id)) {
1331       $manager->updateEntityType($entity_type);
1332     }
1333   }
1334 }
1335
1336 /**
1337  * Place local actions and tasks blocks in every theme.
1338  */
1339 function system_update_8005() {
1340   // When block module is not installed, there is nothing that could be done
1341   // except showing a warning.
1342   if (!\Drupal::moduleHandler()->moduleExists('block')) {
1343     return t('Block module is not enabled so local actions and tasks which have been converted to blocks, are not visible anymore.');
1344   }
1345   $config_factory = \Drupal::configFactory();
1346   /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
1347   $theme_handler = \Drupal::service('theme_handler');
1348   $custom_themes_installed = FALSE;
1349   $message = NULL;
1350   $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
1351
1352   $local_actions_default_settings = [
1353     'plugin' => 'local_actions_block',
1354     'region' => 'content',
1355     'settings.label' => 'Primary admin actions',
1356     'settings.label_display' => 0,
1357     'settings.cache.max_age' => 0,
1358     'visibility' => [],
1359     'weight' => 0,
1360     'langcode' => $langcode,
1361   ];
1362   $tabs_default_settings = [
1363     'plugin' => 'local_tasks_block',
1364     'region' => 'content',
1365     'settings.label' => 'Tabs',
1366     'settings.label_display' => 0,
1367     'settings.cache.max_age' => 0,
1368     'visibility' => [],
1369     'weight' => 0,
1370     'langcode' => $langcode,
1371   ];
1372   foreach ($theme_handler->listInfo() as $theme) {
1373     $theme_name = $theme->getName();
1374     switch ($theme_name) {
1375       case 'bartik':
1376         $name = 'block.block.bartik_local_actions';
1377         $values = [
1378           'id' => 'bartik_local_actions',
1379           'weight' => -1,
1380         ] + $local_actions_default_settings;
1381         _system_update_create_block($name, $theme_name, $values);
1382
1383         $name = 'block.block.bartik_local_tasks';
1384         $values = [
1385           'id' => 'bartik_local_tasks',
1386           'weight' => -7,
1387         ] + $tabs_default_settings;
1388         _system_update_create_block($name, $theme_name, $values);
1389
1390         // Help region has been removed so all the blocks inside has to be moved
1391         // to content region.
1392         $weight = -6;
1393         $blocks = [];
1394         foreach ($config_factory->listAll('block.block.') as $block_config) {
1395           $block = $config_factory->getEditable($block_config);
1396           if ($block->get('theme') == 'bartik' && $block->get('region') == 'help') {
1397             $blocks[] = $block;
1398           }
1399         }
1400         // Sort blocks by block weight.
1401         uasort($blocks, function ($a, $b) {
1402           return $a->get('weight') - $b->get('weight');
1403         });
1404         // Move blocks to content region and set them in right order by their
1405         // weight.
1406         foreach ($blocks as $block) {
1407           $block->set('region', 'content');
1408           $block->set('weight', $weight++);
1409           $block->save();
1410         }
1411         break;
1412
1413       case 'seven':
1414         $name = 'block.block.seven_local_actions';
1415         $values = [
1416           'id' => 'seven_local_actions',
1417           'weight' => -10,
1418         ] + $local_actions_default_settings;
1419         _system_update_create_block($name, $theme_name, $values);
1420
1421         $name = 'block.block.seven_primary_local_tasks';
1422         $values = [
1423           'region' => 'header',
1424           'id' => 'seven_primary_local_tasks',
1425           'settings.label' => 'Primary tabs',
1426           'settings.primary' => TRUE,
1427           'settings.secondary' => FALSE,
1428         ] + $tabs_default_settings;
1429         _system_update_create_block($name, $theme_name, $values);
1430
1431         $name = 'block.block.seven_secondary_local_tasks';
1432         $values = [
1433           'region' => 'pre_content',
1434           'id' => 'seven_secondary_local_tasks',
1435           'settings.label' => 'Secondary tabs',
1436           'settings.primary' => FALSE,
1437           'settings.secondary' => TRUE,
1438         ] + $tabs_default_settings;
1439         _system_update_create_block($name, $theme_name, $values);
1440         break;
1441
1442       case 'stark':
1443         $name = 'block.block.stark_local_actions';
1444         $values = [
1445           'id' => 'stark_local_actions',
1446         ] + $local_actions_default_settings;
1447         _system_update_create_block($name, $theme_name, $values);
1448
1449         $name = 'block.block.stark_local_tasks';
1450         $values = [
1451           'id' => 'stark_local_tasks',
1452         ] + $tabs_default_settings;
1453         _system_update_create_block($name, $theme_name, $values);
1454         break;
1455
1456       case 'classy':
1457       case 'stable':
1458         // Don't place any blocks or trigger custom themes installed warning.
1459         break;
1460
1461       default:
1462         $custom_themes_installed = TRUE;
1463         $name = 'block.block.' . $theme_name . '_local_actions';
1464         $values = [
1465           'id' => $theme_name . '_local_actions',
1466           'weight' => -10,
1467         ] + $local_actions_default_settings;
1468         _system_update_create_block($name, $theme_name, $values);
1469
1470         $name = sprintf('block.block.%s_local_tasks', $theme_name);
1471         $values = [
1472           'id' => $theme_name . '_local_tasks',
1473           'weight' => -20,
1474         ] + $tabs_default_settings;
1475         _system_update_create_block($name, $theme_name, $values);
1476         break;
1477     }
1478   }
1479
1480   if ($custom_themes_installed) {
1481     $message = t('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
1482   }
1483
1484   return $message;
1485 }
1486
1487 /**
1488  * Place branding blocks in every theme.
1489  */
1490 function system_update_8006() {
1491   // When block module is not installed, there is nothing that could be done
1492   // except showing a warning.
1493   if (!\Drupal::moduleHandler()->moduleExists('block')) {
1494     return t('Block module is not enabled so site branding elements, which have been converted to a block, are not visible anymore.');
1495   }
1496
1497   /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
1498   $theme_handler = \Drupal::service('theme_handler');
1499   $custom_themes_installed = FALSE;
1500   $message = NULL;
1501   $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
1502
1503   $site_branding_default_settings = [
1504     'plugin' => 'system_branding_block',
1505     'region' => 'content',
1506     'settings.label' => 'Site branding',
1507     'settings.label_display' => 0,
1508     'visibility' => [],
1509     'weight' => 0,
1510     'langcode' => $langcode,
1511   ];
1512   foreach ($theme_handler->listInfo() as $theme) {
1513     $theme_name = $theme->getName();
1514     switch ($theme_name) {
1515       case 'bartik':
1516         $name = 'block.block.bartik_branding';
1517         $values = [
1518             'id' => 'bartik_branding',
1519             'region' => 'header',
1520           ] + $site_branding_default_settings;
1521         _system_update_create_block($name, $theme_name, $values);
1522         break;
1523
1524       case 'stark':
1525         $name = 'block.block.stark_branding';
1526         $values = [
1527             'id' => 'stark_branding',
1528             'region' => 'header',
1529           ] + $site_branding_default_settings;
1530         _system_update_create_block($name, $theme_name, $values);
1531         break;
1532
1533       case 'seven':
1534       case 'classy':
1535       case 'stable':
1536         // Don't place any blocks or trigger custom themes installed warning.
1537         break;
1538       default:
1539         $custom_themes_installed = TRUE;
1540         $name = sprintf('block.block.%s_branding', $theme_name);
1541         $values = [
1542             'id' => sprintf('%s_branding', $theme_name),
1543             'region' => 'content',
1544             'weight' => '-50',
1545           ] + $site_branding_default_settings;
1546         _system_update_create_block($name, $theme_name, $values);
1547         break;
1548     }
1549   }
1550
1551   if ($custom_themes_installed) {
1552     $message = t('Because your site has custom theme(s) installed, we had to set the branding block into the content region. Please manually review the block configuration and remove the site name, slogan, and logo variables from your templates.');
1553   }
1554
1555   return $message;
1556 }
1557
1558 /**
1559  * Helper function to create block configuration objects for an update.
1560  *
1561  * @param string $name
1562  *   The name of the config object.
1563  * @param string $theme_name
1564  *   The name of the theme the block is associated with.
1565  * @param array $values
1566  *   The block config values.
1567  */
1568 function _system_update_create_block($name, $theme_name, array $values) {
1569   if (!\Drupal::service('config.storage')->exists($name)) {
1570     $block = \Drupal::configFactory()->getEditable($name);
1571     $values['uuid'] = \Drupal::service('uuid')->generate();
1572     $values['theme'] = $theme_name;
1573     $values['dependencies.theme'] = [$theme_name];
1574     foreach ($values as $key => $value) {
1575       $block->set($key, $value);
1576     }
1577     $block->save();
1578   }
1579 }
1580
1581 /**
1582  * Set langcode fields to be ASCII-only.
1583  */
1584 function system_update_8007() {
1585   $database = \Drupal::database();
1586   $database_schema = $database->schema();
1587   $entity_types = \Drupal::entityManager()->getDefinitions();
1588
1589   $schema = \Drupal::keyValue('entity.storage_schema.sql')->getAll();
1590   $schema_copy = $schema;
1591   foreach ($schema as $item_name => $item) {
1592     list($entity_type_id, ,) = explode('.', $item_name);
1593     if (!isset($entity_types[$entity_type_id])) {
1594       continue;
1595     }
1596     foreach ($item as $table_name => $table_schema) {
1597       foreach ($table_schema as $schema_key => $schema_data) {
1598         if ($schema_key == 'fields') {
1599           foreach ($schema_data as $field_name => $field_data) {
1600             foreach ($field_data as $field_data_property => $field_data_value) {
1601               // Langcode fields have the property 'is_ascii' set, instead
1602               // they should have set the type to 'varchar_ascii'.
1603               if ($field_data_property == 'is_ascii') {
1604                 unset($schema_copy[$item_name][$table_name]['fields'][$field_name]['is_ascii']);
1605                 $schema_copy[$item_name][$table_name]['fields'][$field_name]['type'] = 'varchar_ascii';
1606                 if ($database->driver() == 'mysql') {
1607                   $database_schema->changeField($table_name, $field_name, $field_name, $schema_copy[$item_name][$table_name]['fields'][$field_name]);
1608                 }
1609               }
1610             }
1611           }
1612         }
1613       }
1614     }
1615   }
1616   \Drupal::keyValue('entity.storage_schema.sql')->setMultiple($schema_copy);
1617
1618   $definitions = \Drupal::keyValue('entity.definitions.installed')->getAll();
1619   $definitions_copy = $definitions;
1620   foreach ($definitions as $item_name => $item_value) {
1621     $suffix = '.field_storage_definitions';
1622     if (substr($item_name, -strlen($suffix)) == $suffix) {
1623       foreach ($item_value as $field_name => $field_definition) {
1624         $reflection = new \ReflectionObject($field_definition);
1625         $schema_property = $reflection->getProperty('schema');
1626         $schema_property->setAccessible(TRUE);
1627         $schema = $schema_property->getValue($field_definition);
1628         if (isset($schema['columns']['value']['is_ascii'])) {
1629           $schema['columns']['value']['type'] = 'varchar_ascii';
1630           unset($schema['columns']['value']['is_ascii']);
1631         }
1632         $schema_property->setValue($field_definition, $schema);
1633         $schema_property->setAccessible(FALSE);
1634         $definitions_copy[$item_name][$field_name] = $field_definition;
1635       }
1636     }
1637   }
1638   \Drupal::keyValue('entity.definitions.installed')->setMultiple($definitions_copy);
1639 }
1640
1641 /**
1642  * Purge field schema data for uninstalled entity types.
1643  */
1644 function system_update_8008() {
1645   $entity_types = \Drupal::entityManager()->getDefinitions();
1646   /** @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface $schema */
1647   $schema = \Drupal::keyValue('entity.storage_schema.sql');
1648   foreach ($schema->getAll() as $key => $item) {
1649     list($entity_type_id, ,) = explode('.', $key);
1650     if (!isset($entity_types[$entity_type_id])) {
1651       $schema->delete($key);
1652     }
1653   }
1654 }
1655
1656 /**
1657  * Add allowed attributes to existing html filters.
1658  */
1659 function system_update_8009() {
1660   $default_mapping = [
1661     '<a>' => '<a href hreflang>',
1662     '<blockquote>' => '<blockquote cite>',
1663     '<ol>' => '<ol start type>',
1664     '<ul>' => '<ul type>',
1665     '<img>' => '<img src alt height width>',
1666     '<h2>' => '<h2 id>',
1667     '<h3>' => '<h3 id>',
1668     '<h4>' => '<h4 id>',
1669     '<h5>' => '<h5 id>',
1670     '<h6>' => '<h6 id>',
1671   ];
1672   $config_factory = \Drupal::configFactory();
1673   foreach ($config_factory->listAll('filter.format') as $name) {
1674     $allowed_html_mapping = $default_mapping;
1675     $config = $config_factory->getEditable($name);
1676     // The image alignment filter needs the data-align attribute.
1677     $align_enabled = $config->get('filters.filter_align.status');
1678     if ($align_enabled) {
1679       $allowed_html_mapping['<img>'] = str_replace('>', ' data-align>', $allowed_html_mapping['<img>']);
1680     }
1681     // The image caption filter needs the data-caption attribute.
1682     $caption_enabled = $config->get('filters.filter_caption.status');
1683     if ($caption_enabled) {
1684       $allowed_html_mapping['<img>'] = str_replace('>', ' data-caption>', $allowed_html_mapping['<img>']);
1685     }
1686     $allowed_html = $config->get('filters.filter_html.settings.allowed_html');
1687     if (!empty($allowed_html)) {
1688       $allowed_html = strtr($allowed_html, $allowed_html_mapping);
1689       $config->set('filters.filter_html.settings.allowed_html', $allowed_html);
1690       $config->save();
1691     }
1692   }
1693 }
1694
1695 /**
1696  * Place page title blocks in every theme.
1697  */
1698 function system_update_8010() {
1699   // When block module is not installed, there is nothing that could be done
1700   // except showing a warning.
1701   if (!\Drupal::moduleHandler()->moduleExists('block')) {
1702     return t('Block module is not enabled. The page title has been converted to a block, but default page title markup will still display at the top of the main content area.');
1703   }
1704
1705   /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
1706   $theme_handler = \Drupal::service('theme_handler');
1707   $custom_themes_installed = FALSE;
1708   $message = NULL;
1709   $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
1710
1711   $page_title_default_settings = [
1712     'plugin' => 'page_title_block',
1713     'region' => 'content',
1714     'settings.label' => 'Page title',
1715     'settings.label_display' => 0,
1716     'visibility' => [],
1717     'weight' => -50,
1718     'langcode' => $langcode,
1719   ];
1720   foreach ($theme_handler->listInfo() as $theme) {
1721     $theme_name = $theme->getName();
1722     switch ($theme_name) {
1723       case 'bartik':
1724         $name = 'block.block.bartik_page_title';
1725         $values = [
1726           'id' => 'bartik_page_title',
1727         ] + $page_title_default_settings;
1728         _system_update_create_block($name, $theme_name, $values);
1729         break;
1730
1731       case 'stark':
1732         $name = 'block.block.stark_page_title';
1733         $values = [
1734           'id' => 'stark_page_title',
1735           'region' => 'content',
1736         ] + $page_title_default_settings;
1737         _system_update_create_block($name, $theme_name, $values);
1738         break;
1739
1740       case 'seven':
1741         $name = 'block.block.seven_page_title';
1742         $values = [
1743           'id' => 'seven_page_title',
1744           'region' => 'header',
1745         ] + $page_title_default_settings;
1746         _system_update_create_block($name, $theme_name, $values);
1747         break;
1748
1749       case 'classy':
1750         $name = 'block.block.classy_page_title';
1751         $values = [
1752           'id' => 'classy_page_title',
1753           'region' => 'content',
1754         ] + $page_title_default_settings;
1755         _system_update_create_block($name, $theme_name, $values);
1756         break;
1757
1758       default:
1759         $custom_themes_installed = TRUE;
1760         $name = sprintf('block.block.%s_page_title', $theme_name);
1761         $values = [
1762           'id' => sprintf('%s_page_title', $theme_name),
1763           'region' => 'content',
1764           'weight' => '-50',
1765         ] + $page_title_default_settings;
1766         _system_update_create_block($name, $theme_name, $values);
1767         break;
1768     }
1769   }
1770
1771   if ($custom_themes_installed) {
1772     $message = t('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page templates.');
1773   }
1774
1775   return $message;
1776 }
1777
1778 /**
1779  * Add secondary local tasks block to Seven (fixes system_update_8005).
1780  */
1781 function system_update_8011() {
1782   $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
1783   $theme_name = 'seven';
1784   $name = 'block.block.seven_secondary_local_tasks';
1785   $values = [
1786       'plugin' => 'local_tasks_block',
1787       'region' => 'pre_content',
1788       'id' => 'seven_secondary_local_tasks',
1789       'settings.label' => 'Secondary tabs',
1790       'settings.label_display' => 0,
1791       'settings.primary' => FALSE,
1792       'settings.secondary' => TRUE,
1793       'visibility' => [],
1794       'weight' => 0,
1795       'langcode' => $langcode,
1796     ];
1797   _system_update_create_block($name, $theme_name, $values);
1798 }
1799
1800 /**
1801  * Enable automated cron module and move the config into it.
1802  */
1803 function system_update_8013() {
1804   $config_factory = \Drupal::configFactory();
1805   $system_cron_config = $config_factory->getEditable('system.cron');
1806   if ($autorun = $system_cron_config->get('threshold.autorun')) {
1807     // Install 'automated_cron' module.
1808     \Drupal::service('module_installer')->install(['automated_cron'], FALSE);
1809
1810     // Copy 'autorun' value into the new module's 'interval' setting.
1811     $config_factory->getEditable('automated_cron.settings')
1812       ->set('interval', $autorun)
1813       ->save(TRUE);
1814   }
1815
1816   // Remove the 'autorun' key in system module config.
1817   $system_cron_config
1818     ->clear('threshold.autorun')
1819     ->save(TRUE);
1820 }
1821
1822 /**
1823  * Install the Stable base theme if needed.
1824  */
1825 function system_update_8014() {
1826   $theme_handler = \Drupal::service('theme_handler');
1827   if ($theme_handler->themeExists('stable')) {
1828     return;
1829   }
1830   $theme_handler->refreshInfo();
1831   foreach ($theme_handler->listInfo() as $theme) {
1832     // We first check that a base theme is set because if it's set to false then
1833     // it's unset in \Drupal\Core\Extension\ThemeHandler::rebuildThemeData().
1834     if (isset($theme->info['base theme']) && $theme->info['base theme'] == 'stable') {
1835       $theme_handler->install(['stable']);
1836       return;
1837     }
1838   }
1839 }
1840
1841 /**
1842  * Fix configuration overrides to not override non existing keys.
1843  */
1844 function system_update_8200(&$sandbox) {
1845   $config_factory = \Drupal::configFactory();
1846   if (!array_key_exists('config_names', $sandbox)) {
1847     $sandbox['config_names'] = $config_factory->listAll();
1848     $sandbox['max'] = count($sandbox['config_names']);
1849   }
1850
1851   // Get a list of 50 to work on at a time.
1852   $config_names_to_process = array_slice($sandbox['config_names'], 0, 50);
1853   // Preload in a single query.
1854   $config_factory->loadMultiple($config_names_to_process);
1855   foreach ($config_names_to_process as $config_name) {
1856     $config_factory->getEditable($config_name)->save();
1857   }
1858
1859   // Update the list of names to process.
1860   $sandbox['config_names'] = array_diff($sandbox['config_names'], $config_names_to_process);
1861   $sandbox['#finished'] = empty($sandbox['config_names']) ? 1 : ($sandbox['max'] - count($sandbox['config_names'])) / $sandbox['max'];
1862 }
1863
1864 /**
1865  * Clear caches due to behavior change in DefaultPluginManager.
1866  */
1867 function system_update_8201() {
1868   // Empty update to cause a cache rebuild.
1869
1870   // Use hook_post_update_NAME() instead to clear the cache.
1871   // The use of hook_update_N() to clear the cache has been deprecated
1872   // see https://www.drupal.org/node/2960601 for more details.
1873 }
1874
1875 /**
1876  * Clear caches due to behavior change in MachineName element.
1877  */
1878 function system_update_8202() {
1879   // Empty update to cause a cache rebuild.
1880
1881   // Use hook_post_update_NAME() instead to clear the cache.The use
1882   // of hook_update_N to clear the cache has been deprecated see
1883   // https://www.drupal.org/node/2960601 for more details.
1884 }
1885
1886 /**
1887  * Add detailed cron logging configuration.
1888  */
1889 function system_update_8300() {
1890   \Drupal::configFactory()->getEditable('system.cron')
1891     ->set('logging', 1)
1892     ->save(TRUE);
1893 }
1894
1895 /**
1896  * Add install profile to core.extension configuration.
1897  */
1898 function system_update_8301() {
1899   \Drupal::configFactory()->getEditable('core.extension')
1900     ->set('profile', \Drupal::installProfile())
1901     ->save();
1902 }
1903
1904 /**
1905  * Move revision metadata fields to the revision table.
1906  */
1907 function system_update_8400(&$sandbox) {
1908   // Due to the fields from RevisionLogEntityTrait not being explicitly
1909   // mentioned in the storage they might have been installed wrongly in the base
1910   // table for revisionable untranslatable entities and in the data and revision
1911   // data tables for revisionable and translatable entities.
1912   $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
1913   $database = \Drupal::database();
1914   $database_schema = $database->schema();
1915
1916   if (!isset($sandbox['current'])) {
1917     // This must be the first run. Initialize the sandbox.
1918     $sandbox['current'] = 0;
1919
1920     $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($entity_definition_update_manager) {
1921       if ($entity_type = $entity_definition_update_manager->getEntityType($entity_type->id())) {
1922         return is_subclass_of($entity_type->getClass(), FieldableEntityInterface::class) && ($entity_type instanceof ContentEntityTypeInterface) && $entity_type->isRevisionable();
1923       }
1924       return FALSE;
1925     });
1926     $sandbox['entity_type_ids'] = array_keys($definitions);
1927     $sandbox['max'] = count($sandbox['entity_type_ids']);
1928   }
1929
1930   $current_entity_type_key = $sandbox['current'];
1931   for ($i = $current_entity_type_key; ($i < $current_entity_type_key + 1) && ($i < $sandbox['max']); $i++) {
1932     $entity_type_id = $sandbox['entity_type_ids'][$i];
1933     /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
1934     $entity_type = $entity_definition_update_manager->getEntityType($entity_type_id);
1935
1936     $base_fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
1937     $revision_metadata_fields = $entity_type->getRevisionMetadataKeys();
1938     $fields_to_update = array_intersect_key($base_fields, array_flip($revision_metadata_fields));
1939
1940     if (!empty($fields_to_update)) {
1941       // Initialize the entity table names.
1942       // @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout()
1943       $base_table = $entity_type->getBaseTable() ?: $entity_type_id;
1944       $data_table = $entity_type->getDataTable() ?: $entity_type_id . '_field_data';
1945       $revision_table = $entity_type->getRevisionTable() ?: $entity_type_id . '_revision';
1946       $revision_data_table = $entity_type->getRevisionDataTable() ?: $entity_type_id . '_field_revision';
1947       $revision_field = $entity_type->getKey('revision');
1948
1949       // No data needs to be migrated if the entity type is not translatable.
1950       if ($entity_type->isTranslatable()) {
1951         if (!isset($sandbox[$entity_type_id])) {
1952           // This must be the first run for this entity type. Initialize the
1953           // sub-sandbox for it.
1954
1955           // Calculate the number of revisions to process.
1956           $count = \Drupal::entityQuery($entity_type_id)
1957             ->allRevisions()
1958             ->count()
1959             ->accessCheck(FALSE)
1960             ->execute();
1961
1962           $sandbox[$entity_type_id]['current'] = 0;
1963           $sandbox[$entity_type_id]['max'] = $count;
1964         }
1965         // Define the step size.
1966         $steps = Settings::get('entity_update_batch_size', 50);
1967
1968         // Collect the revision IDs to process.
1969         $revisions = \Drupal::entityQuery($entity_type_id)
1970           ->allRevisions()
1971           ->range($sandbox[$entity_type_id]['current'], $sandbox[$entity_type_id]['current'] + $steps)
1972           ->sort($revision_field, 'ASC')
1973           ->accessCheck(FALSE)
1974           ->execute();
1975         $revisions = array_keys($revisions);
1976
1977         foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
1978           // If the revision metadata field is present in the data and the
1979           // revision data table, install its definition again with the updated
1980           // storage code in order for the field to be installed in the
1981           // revision table. Afterwards, copy over the field values and remove
1982           // the field from the data and the revision data tables.
1983           if ($database_schema->fieldExists($data_table, $revision_metadata_field_name) && $database_schema->fieldExists($revision_data_table, $revision_metadata_field_name)) {
1984             // Install the field in the revision table.
1985             if (!isset($sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name])) {
1986               $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
1987               $sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name] = TRUE;
1988             }
1989
1990             // Apply the field value from the revision data table to the
1991             // revision table.
1992             foreach ($revisions as $rev_id) {
1993               $field_value = $database->select($revision_data_table, 't')
1994                 ->fields('t', [$revision_metadata_field_name])
1995                 ->condition($revision_field, $rev_id)
1996                 ->execute()
1997                 ->fetchField();
1998               $database->update($revision_table)
1999                 ->condition($revision_field, $rev_id)
2000                 ->fields([$revision_metadata_field_name => $field_value])
2001                 ->execute();
2002             }
2003           }
2004         }
2005
2006         $sandbox[$entity_type_id]['current'] += count($revisions);
2007         $sandbox[$entity_type_id]['finished'] = ($sandbox[$entity_type_id]['current'] == $sandbox[$entity_type_id]['max']) || empty($revisions);
2008
2009         if ($sandbox[$entity_type_id]['finished']) {
2010           foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
2011             // Drop the field from the data and revision data tables.
2012             $database_schema->dropField($data_table, $revision_metadata_field_name);
2013             $database_schema->dropField($revision_data_table, $revision_metadata_field_name);
2014           }
2015           $sandbox['current']++;
2016         }
2017       }
2018       else {
2019         foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
2020           if ($database_schema->fieldExists($base_table, $revision_metadata_field_name)) {
2021             // Install the field in the revision table.
2022             $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
2023             // Drop the field from the base table.
2024             $database_schema->dropField($base_table, $revision_metadata_field_name);
2025           }
2026         }
2027         $sandbox['current']++;
2028       }
2029     }
2030     else {
2031       $sandbox['current']++;
2032     }
2033
2034   }
2035
2036   $sandbox['#finished'] = $sandbox['current'] == $sandbox['max'];
2037 }
2038
2039 /**
2040  * Remove response.gzip (and response) from system module configuration.
2041  */
2042 function system_update_8401() {
2043   \Drupal::configFactory()->getEditable('system.performance')
2044     ->clear('response.gzip')
2045     ->clear('response')
2046     ->save();
2047 }
2048
2049 /**
2050  * Add the 'revision_translation_affected' field to all entity types.
2051  */
2052 function system_update_8402() {
2053   $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
2054
2055   // Clear the cached entity type definitions so we get the new
2056   // 'revision_translation_affected' entity key.
2057   \Drupal::entityTypeManager()->clearCachedDefinitions();
2058
2059   // Get a list of revisionable and translatable entity types.
2060   /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
2061   $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
2062     if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
2063       return $entity_type->isRevisionable() && $entity_type->isTranslatable();
2064     }
2065     return FALSE;
2066   });
2067
2068   foreach ($definitions as $entity_type_id => $entity_type) {
2069     $field_name = $entity_type->getKey('revision_translation_affected');
2070     // Install the 'revision_translation_affected' field if needed.
2071     if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
2072       $storage_definition = BaseFieldDefinition::create('boolean')
2073         ->setLabel(t('Revision translation affected'))
2074         ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
2075         ->setReadOnly(TRUE)
2076         ->setRevisionable(TRUE)
2077         ->setTranslatable(TRUE)
2078         // Mark all pre-existing revisions as affected in order to be consistent
2079         // with the previous API return value: if the field was not defined the
2080         // value returned was always TRUE.
2081         ->setInitialValue(TRUE);
2082
2083       $definition_update_manager
2084         ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
2085     }
2086   }
2087 }
2088
2089 /**
2090  * Delete all cache_* tables. They are recreated on demand with the new schema.
2091  */
2092 function system_update_8403() {
2093   foreach (Cache::getBins() as $bin => $cache_backend) {
2094     // Try to delete the table regardless of which cache backend is handling it.
2095     // This is to ensure the new schema is used if the configuration for the
2096     // backend class is changed after the update hook runs.
2097     $table_name = "cache_$bin";
2098     $schema = Database::getConnection()->schema();
2099     if ($schema->tableExists($table_name)) {
2100       $schema->dropTable($table_name);
2101     }
2102   }
2103 }
2104
2105 /**
2106  * Add the 'revision_default' field to all relevant entity types.
2107  */
2108 function system_update_8501() {
2109   $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
2110
2111   // Clear the cached entity type definitions so we get the new
2112   // 'revision_default' revision metadata key.
2113   \Drupal::entityTypeManager()->clearCachedDefinitions();
2114
2115   // Get a list of revisionable entity types.
2116   /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
2117   $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
2118     if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
2119       return $entity_type->isRevisionable();
2120     }
2121     return FALSE;
2122   });
2123
2124   // Install the 'revision_default' field.
2125   foreach ($definitions as $entity_type_id => $entity_type) {
2126     $field_name = $entity_type->getRevisionMetadataKey('revision_default');
2127     // Install the 'revision_default' field if needed.
2128     if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
2129       // Make sure the new "revision_default" revision metadata key is available
2130       // also to code using the latest installed definition.
2131       $installed_entity_type = $definition_update_manager->getEntityType($entity_type_id);
2132       $revision_metadata_keys = $installed_entity_type->get('revision_metadata_keys');
2133
2134       if (!isset($revision_metadata_keys['revision_default'])) {
2135         // Update the property holding the required revision metadata keys,
2136         // which is used by the BC layer for retrieving the revision metadata
2137         // keys.
2138         // @see \Drupal\Core\Entity\ContentEntityType::getRevisionMetadataKeys().
2139         $required_revision_metadata_keys = $installed_entity_type->get('requiredRevisionMetadataKeys');
2140         $required_revision_metadata_keys['revision_default'] = $field_name;
2141         $installed_entity_type->set('requiredRevisionMetadataKeys', $required_revision_metadata_keys);
2142
2143         // Update the revision metadata keys to add the new required revision
2144         // metadata key "revision_default".
2145         $revision_metadata_keys['revision_default'] = $required_revision_metadata_keys['revision_default'];
2146         $installed_entity_type->set('revision_metadata_keys', $revision_metadata_keys);
2147
2148         $definition_update_manager->updateEntityType($installed_entity_type);
2149       }
2150
2151       $storage_definition = BaseFieldDefinition::create('boolean')
2152         ->setLabel(t('Default revision'))
2153         ->setDescription(t('A flag indicating whether this was a default revision when it was saved.'))
2154         ->setStorageRequired(TRUE)
2155         ->setTranslatable(FALSE)
2156         ->setRevisionable(TRUE)
2157         // We cannot tell whether existing revisions were default or not when
2158         // they were created, but since we did not support creating non-default
2159         // revisions in any core stable UI so far, we default to TRUE.
2160         ->setInitialValue(TRUE);
2161
2162       $definition_update_manager
2163         ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
2164     }
2165     else {
2166       $variables = ['@entity_type_label' => $entity_type->getLabel()];
2167       if ($field_name === 'revision_default') {
2168         \Drupal::logger('system')->error('An existing "Default revision" field was found for the @entity_type_label entity type, but no "revision_default" revision metadata key was found in its definition.', $variables);
2169       }
2170       else {
2171         \Drupal::logger('system')->error('An existing "Default revision" field was found for the @entity_type_label entity type.', $variables);
2172       }
2173     }
2174   }
2175 }