install.inc 39 KB

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