Pull merge.
[yaffs-website] / web / core / includes / install.inc
1 <?php
2
3 /**
4  * @file
5  * API functions for installing modules and themes.
6  */
7
8 use Drupal\Component\Utility\Unicode;
9 use Symfony\Component\HttpFoundation\RedirectResponse;
10 use Drupal\Component\Utility\Crypt;
11 use Drupal\Component\Utility\OpCodeCache;
12 use Drupal\Component\Utility\UrlHelper;
13 use Drupal\Core\Extension\ExtensionDiscovery;
14 use Drupal\Core\Extension\ModuleHandler;
15 use Drupal\Core\Site\Settings;
16
17 /**
18  * Requirement severity -- Informational message only.
19  */
20 const REQUIREMENT_INFO = -1;
21
22 /**
23  * Requirement severity -- Requirement successfully met.
24  */
25 const REQUIREMENT_OK = 0;
26
27 /**
28  * Requirement severity -- Warning condition; proceed but flag warning.
29  */
30 const REQUIREMENT_WARNING = 1;
31
32 /**
33  * Requirement severity -- Error condition; abort installation.
34  */
35 const REQUIREMENT_ERROR = 2;
36
37 /**
38  * File permission check -- File exists.
39  */
40 const FILE_EXIST = 1;
41
42 /**
43  * File permission check -- File is readable.
44  */
45 const FILE_READABLE = 2;
46
47 /**
48  * File permission check -- File is writable.
49  */
50 const FILE_WRITABLE = 4;
51
52 /**
53  * File permission check -- File is executable.
54  */
55 const FILE_EXECUTABLE = 8;
56
57 /**
58  * File permission check -- File does not exist.
59  */
60 const FILE_NOT_EXIST = 16;
61
62 /**
63  * File permission check -- File is not readable.
64  */
65 const FILE_NOT_READABLE = 32;
66
67 /**
68  * File permission check -- File is not writable.
69  */
70 const FILE_NOT_WRITABLE = 64;
71
72 /**
73  * File permission check -- File is not executable.
74  */
75 const FILE_NOT_EXECUTABLE = 128;
76
77 /**
78  * Loads .install files for installed modules to initialize the update system.
79  */
80 function drupal_load_updates() {
81   foreach (drupal_get_installed_schema_version(NULL, FALSE, TRUE) as $module => $schema_version) {
82     if ($schema_version > -1) {
83       module_load_install($module);
84     }
85   }
86 }
87
88 /**
89  * Loads the installation profile, extracting its defined distribution name.
90  *
91  * @return
92  *   The distribution name defined in the profile's .info.yml file. Defaults to
93  *   "Drupal" if none is explicitly provided by the installation profile.
94  *
95  * @see install_profile_info()
96  */
97 function drupal_install_profile_distribution_name() {
98   // During installation, the profile information is stored in the global
99   // installation state (it might not be saved anywhere yet).
100   $info = [];
101   if (drupal_installation_attempted()) {
102     global $install_state;
103     if (isset($install_state['profile_info'])) {
104       $info = $install_state['profile_info'];
105     }
106   }
107   // At all other times, we load the profile via standard methods.
108   else {
109     $profile = drupal_get_profile();
110     $info = system_get_info('module', $profile);
111   }
112   return isset($info['distribution']['name']) ? $info['distribution']['name'] : 'Drupal';
113 }
114
115 /**
116  * Loads the installation profile, extracting its defined version.
117  *
118  * @return string
119  *   Distribution version defined in the profile's .info.yml file.
120  *   Defaults to \Drupal::VERSION if no version is explicitly provided by the
121  *   installation profile.
122  *
123  * @see install_profile_info()
124  */
125 function drupal_install_profile_distribution_version() {
126   // During installation, the profile information is stored in the global
127   // installation state (it might not be saved anywhere yet).
128   if (drupal_installation_attempted()) {
129     global $install_state;
130     return isset($install_state['profile_info']['version']) ? $install_state['profile_info']['version'] : \Drupal::VERSION;
131   }
132   // At all other times, we load the profile via standard methods.
133   else {
134     $profile = drupal_get_profile();
135     $info = system_get_info('module', $profile);
136     return $info['version'];
137   }
138 }
139
140 /**
141  * Detects all supported databases that are compiled into PHP.
142  *
143  * @return
144  *   An array of database types compiled into PHP.
145  */
146 function drupal_detect_database_types() {
147   $databases = drupal_get_database_types();
148
149   foreach ($databases as $driver => $installer) {
150     $databases[$driver] = $installer->name();
151   }
152
153   return $databases;
154 }
155
156 /**
157  * Returns all supported database driver installer objects.
158  *
159  * @return \Drupal\Core\Database\Install\Tasks[]
160  *   An array of available database driver installer objects.
161  */
162 function drupal_get_database_types() {
163   $databases = [];
164   $drivers = [];
165
166   // The internal database driver name is any valid PHP identifier.
167   $mask = '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '$/';
168   $files = file_scan_directory(DRUPAL_ROOT . '/core/lib/Drupal/Core/Database/Driver', $mask, ['recurse' => FALSE]);
169   if (is_dir(DRUPAL_ROOT . '/drivers/lib/Drupal/Driver/Database')) {
170     $files += file_scan_directory(DRUPAL_ROOT . '/drivers/lib/Drupal/Driver/Database/', $mask, ['recurse' => FALSE]);
171   }
172   foreach ($files as $file) {
173     if (file_exists($file->uri . '/Install/Tasks.php')) {
174       $drivers[$file->filename] = $file->uri;
175     }
176   }
177   foreach ($drivers as $driver => $file) {
178     $installer = db_installer_object($driver);
179     if ($installer->installable()) {
180       $databases[$driver] = $installer;
181     }
182   }
183
184   // Usability: unconditionally put the MySQL driver on top.
185   if (isset($databases['mysql'])) {
186     $mysql_database = $databases['mysql'];
187     unset($databases['mysql']);
188     $databases = ['mysql' => $mysql_database] + $databases;
189   }
190
191   return $databases;
192 }
193
194 /**
195  * Replaces values in settings.php with values in the submitted array.
196  *
197  * This function replaces values in place if possible, even for
198  * multidimensional arrays. This way the old settings do not linger,
199  * overridden and also the doxygen on a value remains where it should be.
200  *
201  * @param $settings
202  *   An array of settings that need to be updated. Multidimensional arrays
203  *   are dumped up to a stdClass object. The object can have value, required
204  *   and comment properties.
205  *   @code
206  *   $settings['config_directories'] = array(
207  *     CONFIG_SYNC_DIRECTORY => (object) array(
208  *       'value' => 'config_hash/sync',
209  *       'required' => TRUE,
210  *     ),
211  *   );
212  *   @endcode
213  *   gets dumped as:
214  *   @code
215  *   $config_directories['sync'] = 'config_hash/sync'
216  *   @endcode
217  */
218 function drupal_rewrite_settings($settings = [], $settings_file = NULL) {
219   if (!isset($settings_file)) {
220     $settings_file = \Drupal::service('site.path') . '/settings.php';
221   }
222   // Build list of setting names and insert the values into the global namespace.
223   $variable_names = [];
224   $settings_settings = [];
225   foreach ($settings as $setting => $data) {
226     if ($setting != 'settings') {
227       _drupal_rewrite_settings_global($GLOBALS[$setting], $data);
228     }
229     else {
230       _drupal_rewrite_settings_global($settings_settings, $data);
231     }
232     $variable_names['$' . $setting] = $setting;
233   }
234   $contents = file_get_contents($settings_file);
235   if ($contents !== FALSE) {
236     // Initialize the contents for the settings.php file if it is empty.
237     if (trim($contents) === '') {
238       $contents = "<?php\n";
239     }
240     // Step through each token in settings.php and replace any variables that
241     // are in the passed-in array.
242     $buffer = '';
243     $state = 'default';
244     foreach (token_get_all($contents) as $token) {
245       if (is_array($token)) {
246         list($type, $value) = $token;
247       }
248       else {
249         $type = -1;
250         $value = $token;
251       }
252       // Do not operate on whitespace.
253       if (!in_array($type, [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
254         switch ($state) {
255           case 'default':
256             if ($type === T_VARIABLE && isset($variable_names[$value])) {
257               // This will be necessary to unset the dumped variable.
258               $parent = &$settings;
259               // This is the current index in parent.
260               $index = $variable_names[$value];
261               // This will be necessary for descending into the array.
262               $current = &$parent[$index];
263               $state = 'candidate_left';
264             }
265             break;
266           case 'candidate_left':
267             if ($value == '[') {
268               $state = 'array_index';
269             }
270             if ($value == '=') {
271               $state = 'candidate_right';
272             }
273             break;
274           case 'array_index':
275             if (_drupal_rewrite_settings_is_array_index($type, $value)) {
276               $index = trim($value, '\'"');
277               $state = 'right_bracket';
278             }
279             else {
280               // $a[foo()] or $a[$bar] or something like that.
281               throw new Exception('invalid array index');
282             }
283             break;
284           case 'right_bracket':
285             if ($value == ']') {
286               if (isset($current[$index])) {
287                 // If the new settings has this index, descend into it.
288                 $parent = &$current;
289                 $current = &$parent[$index];
290                 $state = 'candidate_left';
291               }
292               else {
293                 // Otherwise, jump back to the default state.
294                 $state = 'wait_for_semicolon';
295               }
296             }
297             else {
298               // $a[1 + 2].
299               throw new Exception('] expected');
300             }
301             break;
302           case 'candidate_right':
303             if (_drupal_rewrite_settings_is_simple($type, $value)) {
304               $value = _drupal_rewrite_settings_dump_one($current);
305               // Unsetting $current would not affect $settings at all.
306               unset($parent[$index]);
307               // Skip the semicolon because _drupal_rewrite_settings_dump_one() added one.
308               $state = 'semicolon_skip';
309             }
310             else {
311               $state = 'wait_for_semicolon';
312             }
313             break;
314           case 'wait_for_semicolon':
315             if ($value == ';') {
316               $state = 'default';
317             }
318             break;
319           case 'semicolon_skip':
320             if ($value == ';') {
321               $value = '';
322               $state = 'default';
323             }
324             else {
325               // If the expression was $a = 1 + 2; then we replaced 1 and
326               // the + is unexpected.
327               throw new Exception('Unexpected token after replacing value.');
328             }
329             break;
330         }
331       }
332       $buffer .= $value;
333     }
334     foreach ($settings as $name => $setting) {
335       $buffer .= _drupal_rewrite_settings_dump($setting, '$' . $name);
336     }
337
338     // Write the new settings file.
339     if (file_put_contents($settings_file, $buffer) === FALSE) {
340       throw new Exception(t('Failed to modify %settings. Verify the file permissions.', ['%settings' => $settings_file]));
341     }
342     else {
343       // In case any $settings variables were written, import them into the
344       // Settings singleton.
345       if (!empty($settings_settings)) {
346         $old_settings = Settings::getAll();
347         new Settings($settings_settings + $old_settings);
348       }
349       // The existing settings.php file might have been included already. In
350       // case an opcode cache is enabled, the rewritten contents of the file
351       // will not be reflected in this process. Ensure to invalidate the file
352       // in case an opcode cache is enabled.
353       OpCodeCache::invalidate(DRUPAL_ROOT . '/' . $settings_file);
354     }
355   }
356   else {
357     throw new Exception(t('Failed to open %settings. Verify the file permissions.', ['%settings' => $settings_file]));
358   }
359 }
360
361 /**
362  * Helper for drupal_rewrite_settings().
363  *
364  * Checks whether this token represents a scalar or NULL.
365  *
366  * @param int $type
367  *   The token type.
368  * @param string $value
369  *   The value of the token.
370  *
371  * @return bool
372  *   TRUE if this token represents a scalar or NULL.
373  *
374  * @see token_name()
375  */
376 function _drupal_rewrite_settings_is_simple($type, $value) {
377   $is_integer = $type == T_LNUMBER;
378   $is_float = $type == T_DNUMBER;
379   $is_string = $type == T_CONSTANT_ENCAPSED_STRING;
380   $is_boolean_or_null = $type == T_STRING && in_array(strtoupper($value), ['TRUE', 'FALSE', 'NULL']);
381   return $is_integer || $is_float || $is_string || $is_boolean_or_null;
382 }
383
384 /**
385  * Helper for drupal_rewrite_settings().
386  *
387  * Checks whether this token represents a valid array index: a number or a
388  * string.
389  *
390  * @param int $type
391  *   The token type.
392  *
393  * @return bool
394  *   TRUE if this token represents a number or a string.
395  *
396  * @see token_name()
397  */
398 function _drupal_rewrite_settings_is_array_index($type) {
399   $is_integer = $type == T_LNUMBER;
400   $is_float = $type == T_DNUMBER;
401   $is_string = $type == T_CONSTANT_ENCAPSED_STRING;
402   return $is_integer || $is_float || $is_string;
403 }
404
405 /**
406  * Helper for drupal_rewrite_settings().
407  *
408  * Makes the new settings global.
409  *
410  * @param array|null $ref
411  *   A reference to a nested index in $GLOBALS.
412  * @param array|object $variable
413  *   The nested value of the setting being copied.
414  */
415 function _drupal_rewrite_settings_global(&$ref, $variable) {
416   if (is_object($variable)) {
417     $ref = $variable->value;
418   }
419   else {
420     foreach ($variable as $k => $v) {
421       _drupal_rewrite_settings_global($ref[$k], $v);
422     }
423   }
424 }
425
426 /**
427  * Helper for drupal_rewrite_settings().
428  *
429  * Dump the relevant value properties.
430  *
431  * @param array|object $variable
432  *   The container for variable values.
433  * @param string $variable_name
434  *   Name of variable.
435  * @return string
436  *   A string containing valid PHP code of the variable suitable for placing
437  *   into settings.php.
438  */
439 function _drupal_rewrite_settings_dump($variable, $variable_name) {
440   $return = '';
441   if (is_object($variable)) {
442     if (!empty($variable->required)) {
443       $return .= _drupal_rewrite_settings_dump_one($variable, "$variable_name = ", "\n");
444     }
445   }
446   else {
447     foreach ($variable as $k => $v) {
448       $return .= _drupal_rewrite_settings_dump($v, $variable_name . "['" . $k . "']");
449     }
450   }
451   return $return;
452 }
453
454 /**
455  * Helper for drupal_rewrite_settings().
456  *
457  * Dump the value of a value property and adds the comment if it exists.
458  *
459  * @param object $variable
460  *   A stdClass object with at least a value property.
461  * @param string $prefix
462  *   A string to prepend to the variable's value.
463  * @param string $suffix
464  *   A string to append to the variable's value.
465  * @return string
466  *   A string containing valid PHP code of the variable suitable for placing
467  *   into settings.php.
468  */
469 function _drupal_rewrite_settings_dump_one(\stdClass $variable, $prefix = '', $suffix = '') {
470   $return = $prefix . var_export($variable->value, TRUE) . ';';
471   if (!empty($variable->comment)) {
472     $return .= ' // ' . $variable->comment;
473   }
474   $return .= $suffix;
475   return $return;
476 }
477
478 /**
479  * Creates the config directory and ensures it is operational.
480  *
481  * @see install_settings_form_submit()
482  * @see update_prepare_d8_bootstrap()
483  */
484 function drupal_install_config_directories() {
485   global $config_directories, $install_state;
486
487   // If settings.php does not contain a config sync directory name we need to
488   // configure one.
489   if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
490     if (empty($install_state['config_install_path'])) {
491       // Add a randomized config directory name to settings.php
492       $config_directories[CONFIG_SYNC_DIRECTORY] = \Drupal::service('site.path') . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
493     }
494     else {
495       // Install profiles can contain a config sync directory. If they do,
496       // 'config_install_path' is a path to the directory.
497       $config_directories[CONFIG_SYNC_DIRECTORY] = $install_state['config_install_path'];
498     }
499     $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) [
500       'value' => $config_directories[CONFIG_SYNC_DIRECTORY],
501       'required' => TRUE,
502     ];
503     // Rewrite settings.php, which also sets the value as global variable.
504     drupal_rewrite_settings($settings);
505   }
506
507   // This should never fail, since if the config directory was specified in
508   // settings.php it will have already been created and verified earlier, and
509   // if it wasn't specified in settings.php, it is created here inside the
510   // public files directory, which has already been verified to be writable
511   // itself. But if it somehow fails anyway, the installation cannot proceed.
512   // Bail out using a similar error message as in system_requirements().
513   if (!file_prepare_directory($config_directories[CONFIG_SYNC_DIRECTORY], FILE_CREATE_DIRECTORY)
514     && !file_exists($config_directories[CONFIG_SYNC_DIRECTORY])) {
515     throw new Exception(t('The directory %directory could not be created. To proceed with the installation, either create the directory or ensure that the installer has the permissions to create it automatically. For more information, see the <a href=":handbook_url">online handbook</a>.', [
516       '%directory' => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
517       ':handbook_url' => 'https://www.drupal.org/server-permissions',
518     ]));
519   }
520   elseif (is_writable($config_directories[CONFIG_SYNC_DIRECTORY])) {
521     // Put a README.txt into the sync config directory. This is required so that
522     // they can later be added to git. Since this directory is auto-created, we
523     // have to write out the README rather than just adding it to the drupal core
524     // repo.
525     $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
526     file_put_contents(config_get_config_directory(CONFIG_SYNC_DIRECTORY) . '/README.txt', $text);
527   }
528 }
529
530 /**
531  * Ensures that the config directory exists and is writable, or can be made so.
532  *
533  * @param string $type
534  *   Type of config directory to return. Drupal core provides 'sync'.
535  *
536  * @return bool
537  *   TRUE if the config directory exists and is writable.
538  *
539  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.x. Use
540  *   config_get_config_directory() and file_prepare_directory() instead.
541  *
542  * @see https://www.drupal.org/node/2501187
543  */
544 function install_ensure_config_directory($type) {
545   @trigger_error('install_ensure_config_directory() is deprecated in Drupal 8.1.0 and will be removed before Drupal 9.0.0. Use config_get_config_directory() and file_prepare_directory() instead. See https://www.drupal.org/node/2501187.', E_USER_DEPRECATED);
546   // The config directory must be defined in settings.php.
547   global $config_directories;
548   if (!isset($config_directories[$type])) {
549     return FALSE;
550   }
551   // The logic here is similar to that used by system_requirements() for other
552   // directories that the installer creates.
553   else {
554     $config_directory = config_get_config_directory($type);
555     return file_prepare_directory($config_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
556   }
557 }
558
559 /**
560  * Verifies that all dependencies are met for a given installation profile.
561  *
562  * @param $install_state
563  *   An array of information about the current installation state.
564  *
565  * @return
566  *   The list of modules to install.
567  */
568 function drupal_verify_profile($install_state) {
569   $profile = $install_state['parameters']['profile'];
570   $info = $install_state['profile_info'];
571
572   // Get the list of available modules for the selected installation profile.
573   $listing = new ExtensionDiscovery(\Drupal::root());
574   $present_modules = [];
575   foreach ($listing->scan('module') as $present_module) {
576     $present_modules[] = $present_module->getName();
577   }
578
579   // The installation profile is also a module, which needs to be installed
580   // after all the other dependencies have been installed.
581   $present_modules[] = $profile;
582
583   // Verify that all of the profile's required modules are present.
584   $missing_modules = array_diff($info['install'], $present_modules);
585
586   $requirements = [];
587
588   if ($missing_modules) {
589     $build = [
590       '#theme' => 'item_list',
591       '#context' => ['list_style' => 'comma-list'],
592     ];
593
594     foreach ($missing_modules as $module) {
595       $build['#items'][] = ['#markup' => '<span class="admin-missing">' . Unicode::ucfirst($module) . '</span>'];
596     }
597
598     $modules_list = \Drupal::service('renderer')->renderPlain($build);
599     $requirements['required_modules'] = [
600       'title' => t('Required modules'),
601       'value' => t('Required modules not found.'),
602       'severity' => REQUIREMENT_ERROR,
603       'description' => t('The following modules are required but were not found. Move them into the appropriate modules subdirectory, such as <em>/modules</em>. Missing modules: @modules', ['@modules' => $modules_list]),
604     ];
605   }
606   return $requirements;
607 }
608
609 /**
610  * Installs the system module.
611  *
612  * Separated from the installation of other modules so core system
613  * functions can be made available while other modules are installed.
614  *
615  * @param array $install_state
616  *   An array of information about the current installation state. This is used
617  *   to set the default language.
618  */
619 function drupal_install_system($install_state) {
620   // Remove the service provider of the early installer.
621   unset($GLOBALS['conf']['container_service_providers']['InstallerServiceProvider']);
622   // Add the normal installer service provider.
623   $GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\NormalInstallerServiceProvider';
624
625   $request = \Drupal::request();
626   // Reboot into a full production environment to continue the installation.
627   /** @var \Drupal\Core\Installer\InstallerKernel $kernel */
628   $kernel = \Drupal::service('kernel');
629   $kernel->shutdown();
630   // Have installer rebuild from the disk, rather then building from scratch.
631   $kernel->rebuildContainer(FALSE);
632   $kernel->prepareLegacyRequest($request);
633
634   // Before having installed the system module and being able to do a module
635   // rebuild, prime the \Drupal\Core\Extension\ModuleExtensionList static cache
636   // with the module's location.
637   // @todo Try to install system as any other module, see
638   //   https://www.drupal.org/node/2719315.
639   \Drupal::service('extension.list.module')->setPathname('system', 'core/modules/system/system.info.yml');
640
641   // Install base system configuration.
642   \Drupal::service('config.installer')->installDefaultConfig('core', 'core');
643
644   // Store the installation profile in configuration to populate the
645   // 'install_profile' container parameter.
646   \Drupal::configFactory()->getEditable('core.extension')
647     ->set('profile', $install_state['parameters']['profile'])
648     ->save();
649
650   // Install System module and rebuild the newly available routes.
651   $kernel->getContainer()->get('module_installer')->install(['system'], FALSE);
652   \Drupal::service('router.builder')->rebuild();
653
654   // Ensure default language is saved.
655   if (isset($install_state['parameters']['langcode'])) {
656     \Drupal::configFactory()->getEditable('system.site')
657       ->set('langcode', (string) $install_state['parameters']['langcode'])
658       ->set('default_langcode', (string) $install_state['parameters']['langcode'])
659       ->save(TRUE);
660   }
661 }
662
663 /**
664  * Verifies the state of the specified file.
665  *
666  * @param $file
667  *   The file to check for.
668  * @param $mask
669  *   An optional bitmask created from various FILE_* constants.
670  * @param $type
671  *   The type of file. Can be file (default), dir, or link.
672  * @param bool $autofix
673  *   (optional) Determines whether to attempt fixing the permissions according
674  *   to the provided $mask. Defaults to TRUE.
675  *
676  * @return
677  *   TRUE on success or FALSE on failure. A message is set for the latter.
678  */
679 function drupal_verify_install_file($file, $mask = NULL, $type = 'file', $autofix = TRUE) {
680   $return = TRUE;
681   // Check for files that shouldn't be there.
682   if (isset($mask) && ($mask & FILE_NOT_EXIST) && file_exists($file)) {
683     return FALSE;
684   }
685   // Verify that the file is the type of file it is supposed to be.
686   if (isset($type) && file_exists($file)) {
687     $check = 'is_' . $type;
688     if (!function_exists($check) || !$check($file)) {
689       $return = FALSE;
690     }
691   }
692
693   // Verify file permissions.
694   if (isset($mask)) {
695     $masks = [FILE_EXIST, FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE];
696     foreach ($masks as $current_mask) {
697       if ($mask & $current_mask) {
698         switch ($current_mask) {
699           case FILE_EXIST:
700             if (!file_exists($file)) {
701               if ($type == 'dir' && $autofix) {
702                 drupal_install_mkdir($file, $mask);
703               }
704               if (!file_exists($file)) {
705                 $return = FALSE;
706               }
707             }
708             break;
709           case FILE_READABLE:
710             if (!is_readable($file)) {
711               $return = FALSE;
712             }
713             break;
714           case FILE_WRITABLE:
715             if (!is_writable($file)) {
716               $return = FALSE;
717             }
718             break;
719           case FILE_EXECUTABLE:
720             if (!is_executable($file)) {
721               $return = FALSE;
722             }
723             break;
724           case FILE_NOT_READABLE:
725             if (is_readable($file)) {
726               $return = FALSE;
727             }
728             break;
729           case FILE_NOT_WRITABLE:
730             if (is_writable($file)) {
731               $return = FALSE;
732             }
733             break;
734           case FILE_NOT_EXECUTABLE:
735             if (is_executable($file)) {
736               $return = FALSE;
737             }
738             break;
739         }
740       }
741     }
742   }
743   if (!$return && $autofix) {
744     return drupal_install_fix_file($file, $mask);
745   }
746   return $return;
747 }
748
749 /**
750  * Creates a directory with the specified permissions.
751  *
752  * @param $file
753  *   The name of the directory to create;
754  * @param $mask
755  *   The permissions of the directory to create.
756  * @param $message
757  *   (optional) Whether to output messages. Defaults to TRUE.
758  *
759  * @return
760  *   TRUE/FALSE whether or not the directory was successfully created.
761  */
762 function drupal_install_mkdir($file, $mask, $message = TRUE) {
763   $mod = 0;
764   $masks = [FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE];
765   foreach ($masks as $m) {
766     if ($mask & $m) {
767       switch ($m) {
768         case FILE_READABLE:
769           $mod |= 0444;
770           break;
771         case FILE_WRITABLE:
772           $mod |= 0222;
773           break;
774         case FILE_EXECUTABLE:
775           $mod |= 0111;
776           break;
777       }
778     }
779   }
780
781   if (@drupal_mkdir($file, $mod)) {
782     return TRUE;
783   }
784   else {
785     return FALSE;
786   }
787 }
788
789 /**
790  * Attempts to fix file permissions.
791  *
792  * The general approach here is that, because we do not know the security
793  * setup of the webserver, we apply our permission changes to all three
794  * digits of the file permission (i.e. user, group and all).
795  *
796  * To ensure that the values behave as expected (and numbers don't carry
797  * from one digit to the next) we do the calculation on the octal value
798  * using bitwise operations. This lets us remove, for example, 0222 from
799  * 0700 and get the correct value of 0500.
800  *
801  * @param $file
802  *   The name of the file with permissions to fix.
803  * @param $mask
804  *   The desired permissions for the file.
805  * @param $message
806  *   (optional) Whether to output messages. Defaults to TRUE.
807  *
808  * @return
809  *   TRUE/FALSE whether or not we were able to fix the file's permissions.
810  */
811 function drupal_install_fix_file($file, $mask, $message = TRUE) {
812   // If $file does not exist, fileperms() issues a PHP warning.
813   if (!file_exists($file)) {
814     return FALSE;
815   }
816
817   $mod = fileperms($file) & 0777;
818   $masks = [FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE];
819
820   // FILE_READABLE, FILE_WRITABLE, and FILE_EXECUTABLE permission strings
821   // can theoretically be 0400, 0200, and 0100 respectively, but to be safe
822   // we set all three access types in case the administrator intends to
823   // change the owner of settings.php after installation.
824   foreach ($masks as $m) {
825     if ($mask & $m) {
826       switch ($m) {
827         case FILE_READABLE:
828           if (!is_readable($file)) {
829             $mod |= 0444;
830           }
831           break;
832         case FILE_WRITABLE:
833           if (!is_writable($file)) {
834             $mod |= 0222;
835           }
836           break;
837         case FILE_EXECUTABLE:
838           if (!is_executable($file)) {
839             $mod |= 0111;
840           }
841           break;
842         case FILE_NOT_READABLE:
843           if (is_readable($file)) {
844             $mod &= ~0444;
845           }
846           break;
847         case FILE_NOT_WRITABLE:
848           if (is_writable($file)) {
849             $mod &= ~0222;
850           }
851           break;
852         case FILE_NOT_EXECUTABLE:
853           if (is_executable($file)) {
854             $mod &= ~0111;
855           }
856           break;
857       }
858     }
859   }
860
861   // chmod() will work if the web server is running as owner of the file.
862   if (@chmod($file, $mod)) {
863     return TRUE;
864   }
865   else {
866     return FALSE;
867   }
868 }
869
870 /**
871  * Sends the user to a different installer page.
872  *
873  * This issues an on-site HTTP redirect. Messages (and errors) are erased.
874  *
875  * @param $path
876  *   An installer path.
877  */
878 function install_goto($path) {
879   global $base_url;
880   $headers = [
881     // Not a permanent redirect.
882     'Cache-Control' => 'no-cache',
883   ];
884   $response = new RedirectResponse($base_url . '/' . $path, 302, $headers);
885   $response->send();
886 }
887
888 /**
889  * Returns the URL of the current script, with modified query parameters.
890  *
891  * This function can be called by low-level scripts (such as install.php and
892  * update.php) and returns the URL of the current script. Existing query
893  * parameters are preserved by default, but new ones can optionally be merged
894  * in.
895  *
896  * This function is used when the script must maintain certain query parameters
897  * over multiple page requests in order to work correctly. In such cases (for
898  * example, update.php, which requires the 'continue=1' parameter to remain in
899  * the URL throughout the update process if there are any requirement warnings
900  * that need to be bypassed), using this function to generate the URL for links
901  * to the next steps of the script ensures that the links will work correctly.
902  *
903  * @param $query
904  *   (optional) An array of query parameters to merge in to the existing ones.
905  *
906  * @return
907  *   The URL of the current script, with query parameters modified by the
908  *   passed-in $query. The URL is not sanitized, so it still needs to be run
909  *   through \Drupal\Component\Utility\UrlHelper::filterBadProtocol() if it will be
910  *   used as an HTML attribute value.
911  *
912  * @see drupal_requirements_url()
913  * @see Drupal\Component\Utility\UrlHelper::filterBadProtocol()
914  */
915 function drupal_current_script_url($query = []) {
916   $uri = $_SERVER['SCRIPT_NAME'];
917   $query = array_merge(UrlHelper::filterQueryParameters(\Drupal::request()->query->all()), $query);
918   if (!empty($query)) {
919     $uri .= '?' . UrlHelper::buildQuery($query);
920   }
921   return $uri;
922 }
923
924 /**
925  * Returns a URL for proceeding to the next page after a requirements problem.
926  *
927  * This function can be called by low-level scripts (such as install.php and
928  * update.php) and returns a URL that can be used to attempt to proceed to the
929  * next step of the script.
930  *
931  * @param $severity
932  *   The severity of the requirements problem, as returned by
933  *   drupal_requirements_severity().
934  *
935  * @return
936  *   A URL for attempting to proceed to the next step of the script. The URL is
937  *   not sanitized, so it still needs to be run through
938  *   \Drupal\Component\Utility\UrlHelper::filterBadProtocol() if it will be used
939  *   as an HTML attribute value.
940  *
941  * @see drupal_current_script_url()
942  * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
943  */
944 function drupal_requirements_url($severity) {
945   $query = [];
946   // If there are no errors, only warnings, append 'continue=1' to the URL so
947   // the user can bypass this screen on the next page load.
948   if ($severity == REQUIREMENT_WARNING) {
949     $query['continue'] = 1;
950   }
951   return drupal_current_script_url($query);
952 }
953
954 /**
955  * Checks an installation profile's requirements.
956  *
957  * @param string $profile
958  *   Name of installation profile to check.
959  *
960  * @return array
961  *   Array of the installation profile's requirements.
962  */
963 function drupal_check_profile($profile) {
964   $info = install_profile_info($profile);
965   // Collect requirement testing results.
966   $requirements = [];
967   // Performs an ExtensionDiscovery scan as the system module is unavailable and
968   // we don't yet know where all the modules are located.
969   // @todo Remove as part of https://www.drupal.org/node/2186491
970   $drupal_root = \Drupal::root();
971   $module_list = (new ExtensionDiscovery($drupal_root))->scan('module');
972
973   foreach ($info['install'] as $module) {
974     // If the module is in the module list we know it exists and we can continue
975     // including and registering it.
976     // @see \Drupal\Core\Extension\ExtensionDiscovery::scanDirectory()
977     if (isset($module_list[$module])) {
978       $function = $module . '_requirements';
979       $module_path = $module_list[$module]->getPath();
980       $install_file = "$drupal_root/$module_path/$module.install";
981
982       if (is_file($install_file)) {
983         require_once $install_file;
984       }
985
986       drupal_classloader_register($module, $module_path);
987
988       if (function_exists($function)) {
989         $requirements = array_merge($requirements, $function('install'));
990       }
991     }
992   }
993
994   // Add the profile requirements.
995   $function = $profile . '_requirements';
996   if (function_exists($function)) {
997     $requirements = array_merge($requirements, $function('install'));
998   }
999
1000   return $requirements;
1001 }
1002
1003 /**
1004  * Extracts the highest severity from the requirements array.
1005  *
1006  * @param $requirements
1007  *   An array of requirements, in the same format as is returned by
1008  *   hook_requirements().
1009  *
1010  * @return
1011  *   The highest severity in the array.
1012  */
1013 function drupal_requirements_severity(&$requirements) {
1014   $severity = REQUIREMENT_OK;
1015   foreach ($requirements as $requirement) {
1016     if (isset($requirement['severity'])) {
1017       $severity = max($severity, $requirement['severity']);
1018     }
1019   }
1020   return $severity;
1021 }
1022
1023 /**
1024  * Checks a module's requirements.
1025  *
1026  * @param $module
1027  *   Machine name of module to check.
1028  *
1029  * @return
1030  *   TRUE or FALSE, depending on whether the requirements are met.
1031  */
1032 function drupal_check_module($module) {
1033   module_load_install($module);
1034   // Check requirements
1035   $requirements = \Drupal::moduleHandler()->invoke($module, 'requirements', ['install']);
1036   if (is_array($requirements) && drupal_requirements_severity($requirements) == REQUIREMENT_ERROR) {
1037     // Print any error messages
1038     foreach ($requirements as $requirement) {
1039       if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
1040         $message = $requirement['description'];
1041         if (isset($requirement['value']) && $requirement['value']) {
1042           $message = t('@requirements_message (Currently using @item version @version)', ['@requirements_message' => $requirement['description'], '@item' => $requirement['title'], '@version' => $requirement['value']]);
1043         }
1044         \Drupal::messenger()->addError($message);
1045       }
1046     }
1047     return FALSE;
1048   }
1049   return TRUE;
1050 }
1051
1052 /**
1053  * Retrieves information about an installation profile from its .info.yml file.
1054  *
1055  * The information stored in a profile .info.yml file is similar to that stored
1056  * in a normal Drupal module .info.yml file. For example:
1057  * - name: The real name of the installation profile for display purposes.
1058  * - description: A brief description of the profile.
1059  * - dependencies: An array of shortnames of other modules that this install
1060  *   profile requires.
1061  * - install: An array of shortname of other modules to install that are not
1062  *   required by this install profile.
1063  *
1064  * Additional, less commonly-used information that can appear in a
1065  * profile.info.yml file but not in a normal Drupal module .info.yml file
1066  * includes:
1067  *
1068  * - distribution: Existence of this key denotes that the installation profile
1069  *   is intended to be the only eligible choice in a distribution and will be
1070  *   auto-selected during installation, whereas the installation profile
1071  *   selection screen will be skipped. If more than one distribution profile is
1072  *   found then the first one discovered will be selected.
1073  *   The following subproperties may be set:
1074  *   - name: The name of the distribution that is being installed, to be shown
1075  *     throughout the installation process. If omitted,
1076  *     drupal_install_profile_distribution_name() defaults to 'Drupal'.
1077  *   - install: Optional parameters to override the installer:
1078  *     - theme: The machine name of a theme to use in the installer instead of
1079  *       Drupal's default installer theme.
1080  *     - finish_url: A destination to visit after the installation of the
1081  *       distribution is finished
1082  *
1083  * Note that this function does an expensive file system scan to get info file
1084  * information for dependencies. If you only need information from the info
1085  * file itself, use system_get_info().
1086  *
1087  * Example of .info.yml file:
1088  * @code
1089  *    name: Minimal
1090  *    description: Start fresh, with only a few modules enabled.
1091  *    install:
1092  *      - block
1093  *      - dblog
1094  * @endcode
1095  *
1096  * @param $profile
1097  *   Name of profile.
1098  * @param $langcode
1099  *   Language code (if any).
1100  *
1101  * @return
1102  *   The info array.
1103  */
1104 function install_profile_info($profile, $langcode = 'en') {
1105   $cache = &drupal_static(__FUNCTION__, []);
1106
1107   if (!isset($cache[$profile][$langcode])) {
1108     // Set defaults for module info.
1109     $defaults = [
1110       'dependencies' => [],
1111       'install' => [],
1112       'themes' => ['stark'],
1113       'description' => '',
1114       'version' => NULL,
1115       'hidden' => FALSE,
1116       'php' => DRUPAL_MINIMUM_PHP,
1117       'config_install_path' => NULL,
1118     ];
1119     $profile_path = drupal_get_path('profile', $profile);
1120     $info = \Drupal::service('info_parser')->parse("$profile_path/$profile.info.yml");
1121     $info += $defaults;
1122
1123     // Convert dependencies in [project:module] format.
1124     $info['dependencies'] = array_map(function ($dependency) {
1125       return ModuleHandler::parseDependency($dependency)['name'];
1126     }, $info['dependencies']);
1127
1128     // Convert install key in [project:module] format.
1129     $info['install'] = array_map(function ($dependency) {
1130       return ModuleHandler::parseDependency($dependency)['name'];
1131     }, $info['install']);
1132
1133     // drupal_required_modules() includes the current profile as a dependency.
1134     // Remove that dependency, since a module cannot depend on itself.
1135     $required = array_diff(drupal_required_modules(), [$profile]);
1136
1137     $locale = !empty($langcode) && $langcode != 'en' ? ['locale'] : [];
1138
1139     // Merge dependencies, required modules and locale into install list and
1140     // remove any duplicates.
1141     $info['install'] = array_unique(array_merge($info['install'], $required, $info['dependencies'], $locale));
1142
1143     // If the profile has a config/sync directory use that to install drupal.
1144     if (is_dir($profile_path . '/config/sync')) {
1145       $info['config_install_path'] = $profile_path . '/config/sync';
1146     }
1147     $cache[$profile][$langcode] = $info;
1148   }
1149   return $cache[$profile][$langcode];
1150 }
1151
1152 /**
1153  * Returns a database installer object.
1154  *
1155  * @param $driver
1156  *   The name of the driver.
1157  *
1158  * @return \Drupal\Core\Database\Install\Tasks
1159  *   A class defining the requirements and tasks for installing the database.
1160  */
1161 function db_installer_object($driver) {
1162   // We cannot use Database::getConnection->getDriverClass() here, because
1163   // the connection object is not yet functional.
1164   $task_class = "Drupal\\Core\\Database\\Driver\\{$driver}\\Install\\Tasks";
1165   if (class_exists($task_class)) {
1166     return new $task_class();
1167   }
1168   else {
1169     $task_class = "Drupal\\Driver\\Database\\{$driver}\\Install\\Tasks";
1170     return new $task_class();
1171   }
1172 }