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