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