comparison core/includes/install.inc @ 0:c75dbcec494b

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