install.inc

  1. 7.x drupal-7.x/includes/install.inc
  2. 7.x drupal-7.x/includes/database/mysql/install.inc
  3. 7.x drupal-7.x/includes/database/pgsql/install.inc
  4. 7.x drupal-7.x/includes/database/sqlite/install.inc
  5. 6.x drupal-6.x/includes/install.inc
  • API functions for installing modules and themes.

File

drupal-7.x/includes/install.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API functions for installing modules and themes.
  5. */
  6. /**
  7. * Indicates that a module has not been installed yet.
  8. */
  9. define('SCHEMA_UNINSTALLED', -1);
  10. /**
  11. * Indicates that a module has been installed.
  12. */
  13. define('SCHEMA_INSTALLED', 0);
  14. /**
  15. * Requirement severity -- Informational message only.
  16. */
  17. define('REQUIREMENT_INFO', -1);
  18. /**
  19. * Requirement severity -- Requirement successfully met.
  20. */
  21. define('REQUIREMENT_OK', 0);
  22. /**
  23. * Requirement severity -- Warning condition; proceed but flag warning.
  24. */
  25. define('REQUIREMENT_WARNING', 1);
  26. /**
  27. * Requirement severity -- Error condition; abort installation.
  28. */
  29. define('REQUIREMENT_ERROR', 2);
  30. /**
  31. * File permission check -- File exists.
  32. */
  33. define('FILE_EXIST', 1);
  34. /**
  35. * File permission check -- File is readable.
  36. */
  37. define('FILE_READABLE', 2);
  38. /**
  39. * File permission check -- File is writable.
  40. */
  41. define('FILE_WRITABLE', 4);
  42. /**
  43. * File permission check -- File is executable.
  44. */
  45. define('FILE_EXECUTABLE', 8);
  46. /**
  47. * File permission check -- File does not exist.
  48. */
  49. define('FILE_NOT_EXIST', 16);
  50. /**
  51. * File permission check -- File is not readable.
  52. */
  53. define('FILE_NOT_READABLE', 32);
  54. /**
  55. * File permission check -- File is not writable.
  56. */
  57. define('FILE_NOT_WRITABLE', 64);
  58. /**
  59. * File permission check -- File is not executable.
  60. */
  61. define('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. * Returns an array of available schema versions for a module.
  74. *
  75. * @param $module
  76. * A module name.
  77. * @return
  78. * If the module has updates, an array of available updates sorted by version.
  79. * Otherwise, FALSE.
  80. */
  81. function drupal_get_schema_versions($module) {
  82. $updates = &drupal_static(__FUNCTION__, NULL);
  83. if (!isset($updates[$module])) {
  84. $updates = array();
  85. foreach (module_list() as $loaded_module) {
  86. $updates[$loaded_module] = array();
  87. }
  88. // Prepare regular expression to match all possible defined hook_update_N().
  89. $regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
  90. $functions = get_defined_functions();
  91. // Narrow this down to functions ending with an integer, since all
  92. // hook_update_N() functions end this way, and there are other
  93. // possible functions which match '_update_'. We use preg_grep() here
  94. // instead of foreaching through all defined functions, since the loop
  95. // through all PHP functions can take significant page execution time
  96. // and this function is called on every administrative page via
  97. // system_requirements().
  98. foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  99. // If this function is a module update function, add it to the list of
  100. // module updates.
  101. if (preg_match($regexp, $function, $matches)) {
  102. $updates[$matches['module']][] = $matches['version'];
  103. }
  104. }
  105. // Ensure that updates are applied in numerical order.
  106. foreach ($updates as &$module_updates) {
  107. sort($module_updates, SORT_NUMERIC);
  108. }
  109. }
  110. return empty($updates[$module]) ? FALSE : $updates[$module];
  111. }
  112. /**
  113. * Returns the currently installed schema version for a module.
  114. *
  115. * @param $module
  116. * A module name.
  117. * @param $reset
  118. * Set to TRUE after modifying the system table.
  119. * @param $array
  120. * Set to TRUE if you want to get information about all modules in the
  121. * system.
  122. * @return
  123. * The currently installed schema version, or SCHEMA_UNINSTALLED if the
  124. * module is not installed.
  125. */
  126. function drupal_get_installed_schema_version($module, $reset = FALSE, $array = FALSE) {
  127. static $versions = array();
  128. if ($reset) {
  129. $versions = array();
  130. }
  131. if (!$versions) {
  132. $versions = array();
  133. $result = db_query("SELECT name, schema_version FROM {system} WHERE type = :type", array(':type' => 'module'));
  134. foreach ($result as $row) {
  135. $versions[$row->name] = $row->schema_version;
  136. }
  137. }
  138. if ($array) {
  139. return $versions;
  140. }
  141. else {
  142. return isset($versions[$module]) ? $versions[$module] : SCHEMA_UNINSTALLED;
  143. }
  144. }
  145. /**
  146. * Update the installed version information for a module.
  147. *
  148. * @param $module
  149. * A module name.
  150. * @param $version
  151. * The new schema version.
  152. */
  153. function drupal_set_installed_schema_version($module, $version) {
  154. db_update('system')
  155. ->fields(array('schema_version' => $version))
  156. ->condition('name', $module)
  157. ->execute();
  158. // Reset the static cache of module schema versions.
  159. drupal_get_installed_schema_version(NULL, TRUE);
  160. }
  161. /**
  162. * Loads the installation profile, extracting its defined distribution name.
  163. *
  164. * @return
  165. * The distribution name defined in the profile's .info file. Defaults to
  166. * "Drupal" if none is explicitly provided by the installation profile.
  167. *
  168. * @see install_profile_info()
  169. */
  170. function drupal_install_profile_distribution_name() {
  171. // During installation, the profile information is stored in the global
  172. // installation state (it might not be saved anywhere yet).
  173. if (drupal_installation_attempted()) {
  174. global $install_state;
  175. return $install_state['profile_info']['distribution_name'];
  176. }
  177. // At all other times, we load the profile via standard methods.
  178. else {
  179. $profile = drupal_get_profile();
  180. $info = system_get_info('module', $profile);
  181. return $info['distribution_name'];
  182. }
  183. }
  184. /**
  185. * Detects the base URL using the PHP $_SERVER variables.
  186. *
  187. * @param $file
  188. * The name of the file calling this function so we can strip it out of
  189. * the URI when generating the base_url.
  190. *
  191. * @return
  192. * The auto-detected $base_url that should be configured in settings.php
  193. */
  194. function drupal_detect_baseurl($file = 'install.php') {
  195. $proto = $_SERVER['HTTPS'] ? 'https://' : 'http://';
  196. $host = $_SERVER['SERVER_NAME'];
  197. $port = ($_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT']);
  198. $uri = preg_replace("/\?.*/", '', $_SERVER['REQUEST_URI']);
  199. $dir = str_replace("/$file", '', $uri);
  200. return "$proto$host$port$dir";
  201. }
  202. /**
  203. * Detects all supported databases that are compiled into PHP.
  204. *
  205. * @return
  206. * An array of database types compiled into PHP.
  207. */
  208. function drupal_detect_database_types() {
  209. $databases = drupal_get_database_types();
  210. foreach ($databases as $driver => $installer) {
  211. $databases[$driver] = $installer->name();
  212. }
  213. return $databases;
  214. }
  215. /**
  216. * Returns all supported database installer objects that are compiled into PHP.
  217. *
  218. * @return
  219. * An array of database installer objects compiled into PHP.
  220. */
  221. function drupal_get_database_types() {
  222. $databases = array();
  223. // We define a driver as a directory in /includes/database that in turn
  224. // contains a database.inc file. That allows us to drop in additional drivers
  225. // without modifying the installer.
  226. // Because we have no registry yet, we need to also include the install.inc
  227. // file for the driver explicitly.
  228. require_once DRUPAL_ROOT . '/includes/database/database.inc';
  229. foreach (file_scan_directory(DRUPAL_ROOT . '/includes/database', '/^[a-z]*$/i', array('recurse' => FALSE)) as $file) {
  230. if (file_exists($file->uri . '/database.inc') && file_exists($file->uri . '/install.inc')) {
  231. $drivers[$file->filename] = $file->uri;
  232. }
  233. }
  234. foreach ($drivers as $driver => $file) {
  235. $installer = db_installer_object($driver);
  236. if ($installer->installable()) {
  237. $databases[$driver] = $installer;
  238. }
  239. }
  240. // Usability: unconditionally put the MySQL driver on top.
  241. if (isset($databases['mysql'])) {
  242. $mysql_database = $databases['mysql'];
  243. unset($databases['mysql']);
  244. $databases = array('mysql' => $mysql_database) + $databases;
  245. }
  246. return $databases;
  247. }
  248. /**
  249. * Database installer structure.
  250. *
  251. * Defines basic Drupal requirements for databases.
  252. */
  253. abstract class DatabaseTasks {
  254. /**
  255. * Structure that describes each task to run.
  256. *
  257. * @var array
  258. *
  259. * Each value of the tasks array is an associative array defining the function
  260. * to call (optional) and any arguments to be passed to the function.
  261. */
  262. protected $tasks = array(
  263. array(
  264. 'function' => 'checkEngineVersion',
  265. 'arguments' => array(),
  266. ),
  267. array(
  268. 'arguments' => array(
  269. 'CREATE TABLE {drupal_install_test} (id int NULL)',
  270. 'Drupal can use CREATE TABLE database commands.',
  271. 'Failed to <strong>CREATE</strong> a test table on your database server with the command %query. The server reports the following message: %error.<p>Are you sure the configured username has the necessary permissions to create tables in the database?</p>',
  272. TRUE,
  273. ),
  274. ),
  275. array(
  276. 'arguments' => array(
  277. 'INSERT INTO {drupal_install_test} (id) VALUES (1)',
  278. 'Drupal can use INSERT database commands.',
  279. 'Failed to <strong>INSERT</strong> a value into a test table on your database server. We tried inserting a value with the command %query and the server reported the following error: %error.',
  280. ),
  281. ),
  282. array(
  283. 'arguments' => array(
  284. 'UPDATE {drupal_install_test} SET id = 2',
  285. 'Drupal can use UPDATE database commands.',
  286. 'Failed to <strong>UPDATE</strong> a value in a test table on your database server. We tried updating a value with the command %query and the server reported the following error: %error.',
  287. ),
  288. ),
  289. array(
  290. 'arguments' => array(
  291. 'DELETE FROM {drupal_install_test}',
  292. 'Drupal can use DELETE database commands.',
  293. 'Failed to <strong>DELETE</strong> a value from a test table on your database server. We tried deleting a value with the command %query and the server reported the following error: %error.',
  294. ),
  295. ),
  296. array(
  297. 'arguments' => array(
  298. 'DROP TABLE {drupal_install_test}',
  299. 'Drupal can use DROP TABLE database commands.',
  300. 'Failed to <strong>DROP</strong> a test table from your database server. We tried dropping a table with the command %query and the server reported the following error %error.',
  301. ),
  302. ),
  303. );
  304. /**
  305. * Results from tasks.
  306. *
  307. * @var array
  308. */
  309. protected $results = array();
  310. /**
  311. * Ensure the PDO driver is supported by the version of PHP in use.
  312. */
  313. protected function hasPdoDriver() {
  314. return in_array($this->pdoDriver, PDO::getAvailableDrivers());
  315. }
  316. /**
  317. * Assert test as failed.
  318. */
  319. protected function fail($message) {
  320. $this->results[$message] = FALSE;
  321. }
  322. /**
  323. * Assert test as a pass.
  324. */
  325. protected function pass($message) {
  326. $this->results[$message] = TRUE;
  327. }
  328. /**
  329. * Check whether Drupal is installable on the database.
  330. */
  331. public function installable() {
  332. return $this->hasPdoDriver() && empty($this->error);
  333. }
  334. /**
  335. * Return the human-readable name of the driver.
  336. */
  337. abstract public function name();
  338. /**
  339. * Return the minimum required version of the engine.
  340. *
  341. * @return
  342. * A version string. If not NULL, it will be checked against the version
  343. * reported by the Database engine using version_compare().
  344. */
  345. public function minimumVersion() {
  346. return NULL;
  347. }
  348. /**
  349. * Run database tasks and tests to see if Drupal can run on the database.
  350. */
  351. public function runTasks() {
  352. // We need to establish a connection before we can run tests.
  353. if ($this->connect()) {
  354. foreach ($this->tasks as $task) {
  355. if (!isset($task['function'])) {
  356. $task['function'] = 'runTestQuery';
  357. }
  358. if (method_exists($this, $task['function'])) {
  359. // Returning false is fatal. No other tasks can run.
  360. if (FALSE === call_user_func_array(array($this, $task['function']), $task['arguments'])) {
  361. break;
  362. }
  363. }
  364. else {
  365. throw new DatabaseTaskException(st("Failed to run all tasks against the database server. The task %task wasn't found.", array('%task' => $task['function'])));
  366. }
  367. }
  368. }
  369. // Check for failed results and compile message
  370. $message = '';
  371. foreach ($this->results as $result => $success) {
  372. if (!$success) {
  373. $message .= '<p class="error">' . $result . '</p>';
  374. }
  375. }
  376. if (!empty($message)) {
  377. $message = '<p>In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the <a href="http://drupal.org/getting-started/install">installation handbook</a>. If you are unsure what any of this means you should probably contact your hosting provider.</p>' . $message;
  378. throw new DatabaseTaskException($message);
  379. }
  380. }
  381. /**
  382. * Check if we can connect to the database.
  383. */
  384. protected function connect() {
  385. try {
  386. // This doesn't actually test the connection.
  387. db_set_active();
  388. // Now actually do a check.
  389. Database::getConnection();
  390. $this->pass('Drupal can CONNECT to the database ok.');
  391. }
  392. catch (Exception $e) {
  393. $this->fail(st('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage())));
  394. return FALSE;
  395. }
  396. return TRUE;
  397. }
  398. /**
  399. * Run SQL tests to ensure the database can execute commands with the current user.
  400. */
  401. protected function runTestQuery($query, $pass, $fail, $fatal = FALSE) {
  402. try {
  403. db_query($query);
  404. $this->pass(st($pass));
  405. }
  406. catch (Exception $e) {
  407. $this->fail(st($fail, array('%query' => $query, '%error' => $e->getMessage(), '%name' => $this->name())));
  408. return !$fatal;
  409. }
  410. }
  411. /**
  412. * Check the engine version.
  413. */
  414. protected function checkEngineVersion() {
  415. if ($this->minimumVersion() && version_compare(Database::getConnection()->version(), $this->minimumVersion(), '<')) {
  416. $this->fail(st("The database version %version is less than the minimum required version %minimum_version.", array('%version' => Database::getConnection()->version(), '%minimum_version' => $this->minimumVersion())));
  417. }
  418. }
  419. /**
  420. * Return driver specific configuration options.
  421. *
  422. * @param $database
  423. * An array of driver specific configuration options.
  424. *
  425. * @return
  426. * The options form array.
  427. */
  428. public function getFormOptions($database) {
  429. $form['database'] = array(
  430. '#type' => 'textfield',
  431. '#title' => st('Database name'),
  432. '#default_value' => empty($database['database']) ? '' : $database['database'],
  433. '#size' => 45,
  434. '#required' => TRUE,
  435. '#description' => st('The name of the database your @drupal data will be stored in. It must exist on your server before @drupal can be installed.', array('@drupal' => drupal_install_profile_distribution_name())),
  436. );
  437. $form['username'] = array(
  438. '#type' => 'textfield',
  439. '#title' => st('Database username'),
  440. '#default_value' => empty($database['username']) ? '' : $database['username'],
  441. '#required' => TRUE,
  442. '#size' => 45,
  443. );
  444. $form['password'] = array(
  445. '#type' => 'password',
  446. '#title' => st('Database password'),
  447. '#default_value' => empty($database['password']) ? '' : $database['password'],
  448. '#required' => FALSE,
  449. '#size' => 45,
  450. );
  451. $form['advanced_options'] = array(
  452. '#type' => 'fieldset',
  453. '#title' => st('Advanced options'),
  454. '#collapsible' => TRUE,
  455. '#collapsed' => TRUE,
  456. '#description' => st("These options are only necessary for some sites. If you're not sure what you should enter here, leave the default settings or check with your hosting provider."),
  457. '#weight' => 10,
  458. );
  459. $profile = drupal_get_profile();
  460. $db_prefix = ($profile == 'standard') ? 'drupal_' : $profile . '_';
  461. $form['advanced_options']['db_prefix'] = array(
  462. '#type' => 'textfield',
  463. '#title' => st('Table prefix'),
  464. '#default_value' => '',
  465. '#size' => 45,
  466. '#description' => st('If more than one application will be sharing this database, enter a table prefix such as %prefix for your @drupal site here.', array('@drupal' => drupal_install_profile_distribution_name(), '%prefix' => $db_prefix)),
  467. '#weight' => 10,
  468. );
  469. $form['advanced_options']['host'] = array(
  470. '#type' => 'textfield',
  471. '#title' => st('Database host'),
  472. '#default_value' => empty($database['host']) ? 'localhost' : $database['host'],
  473. '#size' => 45,
  474. // Hostnames can be 255 characters long.
  475. '#maxlength' => 255,
  476. '#required' => TRUE,
  477. '#description' => st('If your database is located on a different server, change this.'),
  478. );
  479. $form['advanced_options']['port'] = array(
  480. '#type' => 'textfield',
  481. '#title' => st('Database port'),
  482. '#default_value' => empty($database['port']) ? '' : $database['port'],
  483. '#size' => 45,
  484. // The maximum port number is 65536, 5 digits.
  485. '#maxlength' => 5,
  486. '#description' => st('If your database server is listening to a non-standard port, enter its number.'),
  487. );
  488. return $form;
  489. }
  490. /**
  491. * Validates driver specific configuration settings.
  492. *
  493. * Checks to ensure correct basic database settings and that a proper
  494. * connection to the database can be established.
  495. *
  496. * @param $database
  497. * An array of driver specific configuration options.
  498. *
  499. * @return
  500. * An array of driver configuration errors, keyed by form element name.
  501. */
  502. public function validateDatabaseSettings($database) {
  503. $errors = array();
  504. // Verify the table prefix.
  505. if (!empty($database['prefix']) && is_string($database['prefix']) && !preg_match('/^[A-Za-z0-9_.]+$/', $database['prefix'])) {
  506. $errors[$database['driver'] . '][advanced_options][db_prefix'] = st('The database table prefix you have entered, %prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%prefix' => $database['prefix']));
  507. }
  508. // Verify the database port.
  509. if (!empty($database['port']) && !is_numeric($database['port'])) {
  510. $errors[$database['driver'] . '][advanced_options][port'] = st('Database port must be a number.');
  511. }
  512. return $errors;
  513. }
  514. }
  515. /**
  516. * Exception thrown if the database installer fails.
  517. */
  518. class DatabaseTaskException extends Exception {
  519. }
  520. /**
  521. * Replaces values in settings.php with values in the submitted array.
  522. *
  523. * @param $settings
  524. * An array of settings that need to be updated.
  525. */
  526. function drupal_rewrite_settings($settings = array(), $prefix = '') {
  527. $default_settings = 'sites/default/default.settings.php';
  528. drupal_static_reset('conf_path');
  529. $settings_file = conf_path(FALSE) . '/' . $prefix . 'settings.php';
  530. // Build list of setting names and insert the values into the global namespace.
  531. $keys = array();
  532. foreach ($settings as $setting => $data) {
  533. $GLOBALS[$setting] = $data['value'];
  534. $keys[] = $setting;
  535. }
  536. $buffer = NULL;
  537. $first = TRUE;
  538. if ($fp = fopen(DRUPAL_ROOT . '/' . $default_settings, 'r')) {
  539. // Step line by line through settings.php.
  540. while (!feof($fp)) {
  541. $line = fgets($fp);
  542. if ($first && substr($line, 0, 5) != '<?php') {
  543. $buffer = "<?php\n\n";
  544. }
  545. $first = FALSE;
  546. // Check for constants.
  547. if (substr($line, 0, 7) == 'define(') {
  548. preg_match('/define\(\s*[\'"]([A-Z_-]+)[\'"]\s*,(.*?)\);/', $line, $variable);
  549. if (in_array($variable[1], $keys)) {
  550. $setting = $settings[$variable[1]];
  551. $buffer .= str_replace($variable[2], " '" . $setting['value'] . "'", $line);
  552. unset($settings[$variable[1]]);
  553. unset($settings[$variable[2]]);
  554. }
  555. else {
  556. $buffer .= $line;
  557. }
  558. }
  559. // Check for variables.
  560. elseif (substr($line, 0, 1) == '$') {
  561. preg_match('/\$([^ ]*) /', $line, $variable);
  562. if (in_array($variable[1], $keys)) {
  563. // Write new value to settings.php in the following format:
  564. // $'setting' = 'value'; // 'comment'
  565. $setting = $settings[$variable[1]];
  566. $buffer .= '$' . $variable[1] . " = " . var_export($setting['value'], TRUE) . ";" . (!empty($setting['comment']) ? ' // ' . $setting['comment'] . "\n" : "\n");
  567. unset($settings[$variable[1]]);
  568. }
  569. else {
  570. $buffer .= $line;
  571. }
  572. }
  573. else {
  574. $buffer .= $line;
  575. }
  576. }
  577. fclose($fp);
  578. // Add required settings that were missing from settings.php.
  579. foreach ($settings as $setting => $data) {
  580. if ($data['required']) {
  581. $buffer .= "\$$setting = " . var_export($data['value'], TRUE) . ";\n";
  582. }
  583. }
  584. $fp = fopen(DRUPAL_ROOT . '/' . $settings_file, 'w');
  585. if ($fp && fwrite($fp, $buffer) === FALSE) {
  586. throw new Exception(st('Failed to modify %settings. Verify the file permissions.', array('%settings' => $settings_file)));
  587. }
  588. }
  589. else {
  590. throw new Exception(st('Failed to open %settings. Verify the file permissions.', array('%settings' => $default_settings)));
  591. }
  592. }
  593. /**
  594. * Verifies an installation profile for installation.
  595. *
  596. * @param $install_state
  597. * An array of information about the current installation state.
  598. *
  599. * @return
  600. * The list of modules to install.
  601. */
  602. function drupal_verify_profile($install_state) {
  603. $profile = $install_state['parameters']['profile'];
  604. $locale = $install_state['parameters']['locale'];
  605. include_once DRUPAL_ROOT . '/includes/file.inc';
  606. include_once DRUPAL_ROOT . '/includes/common.inc';
  607. $profile_file = DRUPAL_ROOT . "/profiles/$profile/$profile.profile";
  608. if (!isset($profile) || !file_exists($profile_file)) {
  609. throw new Exception(install_no_profile_error());
  610. }
  611. $info = $install_state['profile_info'];
  612. // Get a list of modules that exist in Drupal's assorted subdirectories.
  613. $present_modules = array();
  614. foreach (drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.module$/', 'modules', 'name', 0) as $present_module) {
  615. $present_modules[] = $present_module->name;
  616. }
  617. // The installation profile is also a module, which needs to be installed
  618. // after all the other dependencies have been installed.
  619. $present_modules[] = drupal_get_profile();
  620. // Verify that all of the profile's required modules are present.
  621. $missing_modules = array_diff($info['dependencies'], $present_modules);
  622. $requirements = array();
  623. if (count($missing_modules)) {
  624. $modules = array();
  625. foreach ($missing_modules as $module) {
  626. $modules[] = '<span class="admin-missing">' . drupal_ucfirst($module) . '</span>';
  627. }
  628. $requirements['required_modules'] = array(
  629. 'title' => st('Required modules'),
  630. 'value' => st('Required modules not found.'),
  631. 'severity' => REQUIREMENT_ERROR,
  632. 'description' => st('The following modules are required but were not found. Move them into the appropriate modules subdirectory, such as <em>sites/all/modules</em>. Missing modules: !modules', array('!modules' => implode(', ', $modules))),
  633. );
  634. }
  635. return $requirements;
  636. }
  637. /**
  638. * Installs the system module.
  639. *
  640. * Separated from the installation of other modules so core system
  641. * functions can be made available while other modules are installed.
  642. */
  643. function drupal_install_system() {
  644. $system_path = drupal_get_path('module', 'system');
  645. require_once DRUPAL_ROOT . '/' . $system_path . '/system.install';
  646. module_invoke('system', 'install');
  647. $system_versions = drupal_get_schema_versions('system');
  648. $system_version = $system_versions ? max($system_versions) : SCHEMA_INSTALLED;
  649. db_insert('system')
  650. ->fields(array('filename', 'name', 'type', 'owner', 'status', 'schema_version', 'bootstrap'))
  651. ->values(array(
  652. 'filename' => $system_path . '/system.module',
  653. 'name' => 'system',
  654. 'type' => 'module',
  655. 'owner' => '',
  656. 'status' => 1,
  657. 'schema_version' => $system_version,
  658. 'bootstrap' => 0,
  659. ))
  660. ->execute();
  661. system_rebuild_module_data();
  662. }
  663. /**
  664. * Uninstalls a given list of disabled modules.
  665. *
  666. * @param array $module_list
  667. * The modules to uninstall. It is the caller's responsibility to ensure that
  668. * all modules in this list have already been disabled before this function
  669. * is called.
  670. * @param bool $uninstall_dependents
  671. * (optional) If TRUE, the function will check that all modules which depend
  672. * on the passed-in module list either are already uninstalled or contained in
  673. * the list, and it will ensure that the modules are uninstalled in the
  674. * correct order. This incurs a significant performance cost, so use FALSE if
  675. * you know $module_list is already complete and in the correct order.
  676. * Defaults to TRUE.
  677. *
  678. * @return bool
  679. * Returns TRUE if the operation succeeds or FALSE if it aborts due to an
  680. * unsafe condition, namely, $uninstall_dependents is TRUE and a module in
  681. * $module_list has dependents which are not already uninstalled and not also
  682. * included in $module_list).
  683. *
  684. * @see module_disable()
  685. */
  686. function drupal_uninstall_modules($module_list = array(), $uninstall_dependents = TRUE) {
  687. if ($uninstall_dependents) {
  688. // Get all module data so we can find dependents and sort.
  689. $module_data = system_rebuild_module_data();
  690. // Create an associative array with weights as values.
  691. $module_list = array_flip(array_values($module_list));
  692. $profile = drupal_get_profile();
  693. while (list($module) = each($module_list)) {
  694. if (!isset($module_data[$module]) || drupal_get_installed_schema_version($module) == SCHEMA_UNINSTALLED) {
  695. // This module doesn't exist or is already uninstalled. Skip it.
  696. unset($module_list[$module]);
  697. continue;
  698. }
  699. $module_list[$module] = $module_data[$module]->sort;
  700. // If the module has any dependents which are not already uninstalled and
  701. // not included in the passed-in list, abort. It is not safe to uninstall
  702. // them automatically because uninstalling a module is a destructive
  703. // operation.
  704. foreach (array_keys($module_data[$module]->required_by) as $dependent) {
  705. if (!isset($module_list[$dependent]) && drupal_get_installed_schema_version($dependent) != SCHEMA_UNINSTALLED && $dependent != $profile) {
  706. return FALSE;
  707. }
  708. }
  709. }
  710. // Sort the module list by pre-calculated weights.
  711. asort($module_list);
  712. $module_list = array_keys($module_list);
  713. }
  714. foreach ($module_list as $module) {
  715. // Uninstall the module.
  716. module_load_install($module);
  717. module_invoke($module, 'uninstall');
  718. drupal_uninstall_schema($module);
  719. watchdog('system', '%module module uninstalled.', array('%module' => $module), WATCHDOG_INFO);
  720. drupal_set_installed_schema_version($module, SCHEMA_UNINSTALLED);
  721. }
  722. if (!empty($module_list)) {
  723. // Let other modules react.
  724. module_invoke_all('modules_uninstalled', $module_list);
  725. }
  726. return TRUE;
  727. }
  728. /**
  729. * Verifies the state of the specified file.
  730. *
  731. * @param $file
  732. * The file to check for.
  733. * @param $mask
  734. * An optional bitmask created from various FILE_* constants.
  735. * @param $type
  736. * The type of file. Can be file (default), dir, or link.
  737. *
  738. * @return
  739. * TRUE on success or FALSE on failure. A message is set for the latter.
  740. */
  741. function drupal_verify_install_file($file, $mask = NULL, $type = 'file') {
  742. $return = TRUE;
  743. // Check for files that shouldn't be there.
  744. if (isset($mask) && ($mask & FILE_NOT_EXIST) && file_exists($file)) {
  745. return FALSE;
  746. }
  747. // Verify that the file is the type of file it is supposed to be.
  748. if (isset($type) && file_exists($file)) {
  749. $check = 'is_' . $type;
  750. if (!function_exists($check) || !$check($file)) {
  751. $return = FALSE;
  752. }
  753. }
  754. // Verify file permissions.
  755. if (isset($mask)) {
  756. $masks = array(FILE_EXIST, FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
  757. foreach ($masks as $current_mask) {
  758. if ($mask & $current_mask) {
  759. switch ($current_mask) {
  760. case FILE_EXIST:
  761. if (!file_exists($file)) {
  762. if ($type == 'dir') {
  763. drupal_install_mkdir($file, $mask);
  764. }
  765. if (!file_exists($file)) {
  766. $return = FALSE;
  767. }
  768. }
  769. break;
  770. case FILE_READABLE:
  771. if (!is_readable($file) && !drupal_install_fix_file($file, $mask)) {
  772. $return = FALSE;
  773. }
  774. break;
  775. case FILE_WRITABLE:
  776. if (!is_writable($file) && !drupal_install_fix_file($file, $mask)) {
  777. $return = FALSE;
  778. }
  779. break;
  780. case FILE_EXECUTABLE:
  781. if (!is_executable($file) && !drupal_install_fix_file($file, $mask)) {
  782. $return = FALSE;
  783. }
  784. break;
  785. case FILE_NOT_READABLE:
  786. if (is_readable($file) && !drupal_install_fix_file($file, $mask)) {
  787. $return = FALSE;
  788. }
  789. break;
  790. case FILE_NOT_WRITABLE:
  791. if (is_writable($file) && !drupal_install_fix_file($file, $mask)) {
  792. $return = FALSE;
  793. }
  794. break;
  795. case FILE_NOT_EXECUTABLE:
  796. if (is_executable($file) && !drupal_install_fix_file($file, $mask)) {
  797. $return = FALSE;
  798. }
  799. break;
  800. }
  801. }
  802. }
  803. }
  804. return $return;
  805. }
  806. /**
  807. * Creates a directory with the specified permissions.
  808. *
  809. * @param $file
  810. * The name of the directory to create;
  811. * @param $mask
  812. * The permissions of the directory to create.
  813. * @param $message
  814. * (optional) Whether to output messages. Defaults to TRUE.
  815. *
  816. * @return
  817. * TRUE/FALSE whether or not the directory was successfully created.
  818. */
  819. function drupal_install_mkdir($file, $mask, $message = TRUE) {
  820. $mod = 0;
  821. $masks = array(FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
  822. foreach ($masks as $m) {
  823. if ($mask & $m) {
  824. switch ($m) {
  825. case FILE_READABLE:
  826. $mod |= 0444;
  827. break;
  828. case FILE_WRITABLE:
  829. $mod |= 0222;
  830. break;
  831. case FILE_EXECUTABLE:
  832. $mod |= 0111;
  833. break;
  834. }
  835. }
  836. }
  837. if (@drupal_mkdir($file, $mod)) {
  838. return TRUE;
  839. }
  840. else {
  841. return FALSE;
  842. }
  843. }
  844. /**
  845. * Attempts to fix file permissions.
  846. *
  847. * The general approach here is that, because we do not know the security
  848. * setup of the webserver, we apply our permission changes to all three
  849. * digits of the file permission (i.e. user, group and all).
  850. *
  851. * To ensure that the values behave as expected (and numbers don't carry
  852. * from one digit to the next) we do the calculation on the octal value
  853. * using bitwise operations. This lets us remove, for example, 0222 from
  854. * 0700 and get the correct value of 0500.
  855. *
  856. * @param $file
  857. * The name of the file with permissions to fix.
  858. * @param $mask
  859. * The desired permissions for the file.
  860. * @param $message
  861. * (optional) Whether to output messages. Defaults to TRUE.
  862. *
  863. * @return
  864. * TRUE/FALSE whether or not we were able to fix the file's permissions.
  865. */
  866. function drupal_install_fix_file($file, $mask, $message = TRUE) {
  867. // If $file does not exist, fileperms() issues a PHP warning.
  868. if (!file_exists($file)) {
  869. return FALSE;
  870. }
  871. $mod = fileperms($file) & 0777;
  872. $masks = array(FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
  873. // FILE_READABLE, FILE_WRITABLE, and FILE_EXECUTABLE permission strings
  874. // can theoretically be 0400, 0200, and 0100 respectively, but to be safe
  875. // we set all three access types in case the administrator intends to
  876. // change the owner of settings.php after installation.
  877. foreach ($masks as $m) {
  878. if ($mask & $m) {
  879. switch ($m) {
  880. case FILE_READABLE:
  881. if (!is_readable($file)) {
  882. $mod |= 0444;
  883. }
  884. break;
  885. case FILE_WRITABLE:
  886. if (!is_writable($file)) {
  887. $mod |= 0222;
  888. }
  889. break;
  890. case FILE_EXECUTABLE:
  891. if (!is_executable($file)) {
  892. $mod |= 0111;
  893. }
  894. break;
  895. case FILE_NOT_READABLE:
  896. if (is_readable($file)) {
  897. $mod &= ~0444;
  898. }
  899. break;
  900. case FILE_NOT_WRITABLE:
  901. if (is_writable($file)) {
  902. $mod &= ~0222;
  903. }
  904. break;
  905. case FILE_NOT_EXECUTABLE:
  906. if (is_executable($file)) {
  907. $mod &= ~0111;
  908. }
  909. break;
  910. }
  911. }
  912. }
  913. // chmod() will work if the web server is running as owner of the file.
  914. // If PHP safe_mode is enabled the currently executing script must also
  915. // have the same owner.
  916. if (@chmod($file, $mod)) {
  917. return TRUE;
  918. }
  919. else {
  920. return FALSE;
  921. }
  922. }
  923. /**
  924. * Sends the user to a different installer page.
  925. *
  926. * This issues an on-site HTTP redirect. Messages (and errors) are erased.
  927. *
  928. * @param $path
  929. * An installer path.
  930. */
  931. function install_goto($path) {
  932. global $base_url;
  933. include_once DRUPAL_ROOT . '/includes/common.inc';
  934. header('Location: ' . $base_url . '/' . $path);
  935. header('Cache-Control: no-cache'); // Not a permanent redirect.
  936. drupal_exit();
  937. }
  938. /**
  939. * Returns the URL of the current script, with modified query parameters.
  940. *
  941. * This function can be called by low-level scripts (such as install.php and
  942. * update.php) and returns the URL of the current script. Existing query
  943. * parameters are preserved by default, but new ones can optionally be merged
  944. * in.
  945. *
  946. * This function is used when the script must maintain certain query parameters
  947. * over multiple page requests in order to work correctly. In such cases (for
  948. * example, update.php, which requires the 'continue=1' parameter to remain in
  949. * the URL throughout the update process if there are any requirement warnings
  950. * that need to be bypassed), using this function to generate the URL for links
  951. * to the next steps of the script ensures that the links will work correctly.
  952. *
  953. * @param $query
  954. * (optional) An array of query parameters to merge in to the existing ones.
  955. *
  956. * @return
  957. * The URL of the current script, with query parameters modified by the
  958. * passed-in $query. The URL is not sanitized, so it still needs to be run
  959. * through check_url() if it will be used as an HTML attribute value.
  960. *
  961. * @see drupal_requirements_url()
  962. */
  963. function drupal_current_script_url($query = array()) {
  964. $uri = $_SERVER['SCRIPT_NAME'];
  965. $query = array_merge(drupal_get_query_parameters(), $query);
  966. if (!empty($query)) {
  967. $uri .= '?' . drupal_http_build_query($query);
  968. }
  969. return $uri;
  970. }
  971. /**
  972. * Returns a URL for proceeding to the next page after a requirements problem.
  973. *
  974. * This function can be called by low-level scripts (such as install.php and
  975. * update.php) and returns a URL that can be used to attempt to proceed to the
  976. * next step of the script.
  977. *
  978. * @param $severity
  979. * The severity of the requirements problem, as returned by
  980. * drupal_requirements_severity().
  981. *
  982. * @return
  983. * A URL for attempting to proceed to the next step of the script. The URL is
  984. * not sanitized, so it still needs to be run through check_url() if it will
  985. * be used as an HTML attribute value.
  986. *
  987. * @see drupal_current_script_url()
  988. */
  989. function drupal_requirements_url($severity) {
  990. $query = array();
  991. // If there are no errors, only warnings, append 'continue=1' to the URL so
  992. // the user can bypass this screen on the next page load.
  993. if ($severity == REQUIREMENT_WARNING) {
  994. $query['continue'] = 1;
  995. }
  996. return drupal_current_script_url($query);
  997. }
  998. /**
  999. * Translates a string when some systems are not available.
  1000. *
  1001. * Used during the install process, when database, theme, and localization
  1002. * system is possibly not yet available.
  1003. *
  1004. * Use t() if your code will never run during the Drupal installation phase.
  1005. * Use st() if your code will only run during installation and never any other
  1006. * time. Use get_t() if your code could run in either circumstance.
  1007. *
  1008. * @see t()
  1009. * @see get_t()
  1010. * @ingroup sanitization
  1011. */
  1012. function st($string, array $args = array(), array $options = array()) {
  1013. static $locale_strings = NULL;
  1014. global $install_state;
  1015. if (empty($options['context'])) {
  1016. $options['context'] = '';
  1017. }
  1018. if (!isset($locale_strings)) {
  1019. $locale_strings = array();
  1020. if (isset($install_state['parameters']['profile']) && isset($install_state['parameters']['locale'])) {
  1021. // If the given locale was selected, there should be at least one .po file
  1022. // with its name ending in {$install_state['parameters']['locale']}.po
  1023. // This might or might not be the entire filename. It is also possible
  1024. // that multiple files end with the same extension, even if unlikely.
  1025. $po_files = file_scan_directory('./profiles/' . $install_state['parameters']['profile'] . '/translations', '/'. $install_state['parameters']['locale'] .'\.po$/', array('recurse' => FALSE));
  1026. if (count($po_files)) {
  1027. require_once DRUPAL_ROOT . '/includes/locale.inc';
  1028. foreach ($po_files as $po_file) {
  1029. _locale_import_read_po('mem-store', $po_file);
  1030. }
  1031. $locale_strings = _locale_import_one_string('mem-report');
  1032. }
  1033. }
  1034. }
  1035. // Transform arguments before inserting them
  1036. foreach ($args as $key => $value) {
  1037. switch ($key[0]) {
  1038. // Escaped only
  1039. case '@':
  1040. $args[$key] = check_plain($value);
  1041. break;
  1042. // Escaped and placeholder
  1043. case '%':
  1044. default:
  1045. $args[$key] = '<em>' . check_plain($value) . '</em>';
  1046. break;
  1047. // Pass-through
  1048. case '!':
  1049. }
  1050. }
  1051. return strtr((!empty($locale_strings[$options['context']][$string]) ? $locale_strings[$options['context']][$string] : $string), $args);
  1052. }
  1053. /**
  1054. * Checks an installation profile's requirements.
  1055. *
  1056. * @param $profile
  1057. * Name of installation profile to check.
  1058. * @return
  1059. * Array of the installation profile's requirements.
  1060. */
  1061. function drupal_check_profile($profile) {
  1062. include_once DRUPAL_ROOT . '/includes/file.inc';
  1063. $profile_file = DRUPAL_ROOT . "/profiles/$profile/$profile.profile";
  1064. if (!isset($profile) || !file_exists($profile_file)) {
  1065. throw new Exception(install_no_profile_error());
  1066. }
  1067. $info = install_profile_info($profile);
  1068. // Collect requirement testing results.
  1069. $requirements = array();
  1070. foreach ($info['dependencies'] as $module) {
  1071. module_load_install($module);
  1072. $function = $module . '_requirements';
  1073. if (function_exists($function)) {
  1074. $requirements = array_merge($requirements, $function('install'));
  1075. }
  1076. }
  1077. return $requirements;
  1078. }
  1079. /**
  1080. * Extracts the highest severity from the requirements array.
  1081. *
  1082. * @param $requirements
  1083. * An array of requirements, in the same format as is returned by
  1084. * hook_requirements().
  1085. *
  1086. * @return
  1087. * The highest severity in the array.
  1088. */
  1089. function drupal_requirements_severity(&$requirements) {
  1090. $severity = REQUIREMENT_OK;
  1091. foreach ($requirements as $requirement) {
  1092. if (isset($requirement['severity'])) {
  1093. $severity = max($severity, $requirement['severity']);
  1094. }
  1095. }
  1096. return $severity;
  1097. }
  1098. /**
  1099. * Checks a module's requirements.
  1100. *
  1101. * @param $module
  1102. * Machine name of module to check.
  1103. *
  1104. * @return
  1105. * TRUE or FALSE, depending on whether the requirements are met.
  1106. */
  1107. function drupal_check_module($module) {
  1108. module_load_install($module);
  1109. if (module_hook($module, 'requirements')) {
  1110. // Check requirements
  1111. $requirements = module_invoke($module, 'requirements', 'install');
  1112. if (is_array($requirements) && drupal_requirements_severity($requirements) == REQUIREMENT_ERROR) {
  1113. // Print any error messages
  1114. foreach ($requirements as $requirement) {
  1115. if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
  1116. $message = $requirement['description'];
  1117. if (isset($requirement['value']) && $requirement['value']) {
  1118. $message .= ' (' . t('Currently using !item !version', array('!item' => $requirement['title'], '!version' => $requirement['value'])) . ')';
  1119. }
  1120. drupal_set_message($message, 'error');
  1121. }
  1122. }
  1123. return FALSE;
  1124. }
  1125. }
  1126. return TRUE;
  1127. }
  1128. /**
  1129. * Retrieves information about an installation profile from its .info file.
  1130. *
  1131. * The information stored in a profile .info file is similar to that stored in
  1132. * a normal Drupal module .info file. For example:
  1133. * - name: The real name of the installation profile for display purposes.
  1134. * - description: A brief description of the profile.
  1135. * - dependencies: An array of shortnames of other modules that this install
  1136. * profile requires.
  1137. *
  1138. * Additional, less commonly-used information that can appear in a profile.info
  1139. * file but not in a normal Drupal module .info file includes:
  1140. * - distribution_name: The name of the Drupal distribution that is being
  1141. * installed, to be shown throughout the installation process. Defaults to
  1142. * 'Drupal'.
  1143. * - exclusive: If the install profile is intended to be the only eligible
  1144. * choice in a distribution, setting exclusive = TRUE will auto-select it
  1145. * during installation, and the install profile selection screen will be
  1146. * skipped. If more than one profile is found where exclusive = TRUE then
  1147. * this property will have no effect and the profile selection screen will
  1148. * be shown as normal with all available profiles shown.
  1149. *
  1150. * Note that this function does an expensive file system scan to get info file
  1151. * information for dependencies. If you only need information from the info
  1152. * file itself, use system_get_info().
  1153. *
  1154. * Example of .info file:
  1155. * @code
  1156. * name = Minimal
  1157. * description = Start fresh, with only a few modules enabled.
  1158. * dependencies[] = block
  1159. * dependencies[] = dblog
  1160. * @endcode
  1161. *
  1162. * @param $profile
  1163. * Name of profile.
  1164. * @param $locale
  1165. * Name of locale used (if any).
  1166. *
  1167. * @return
  1168. * The info array.
  1169. */
  1170. function install_profile_info($profile, $locale = 'en') {
  1171. $cache = &drupal_static(__FUNCTION__, array());
  1172. if (!isset($cache[$profile])) {
  1173. // Set defaults for module info.
  1174. $defaults = array(
  1175. 'dependencies' => array(),
  1176. 'description' => '',
  1177. 'distribution_name' => 'Drupal',
  1178. 'version' => NULL,
  1179. 'hidden' => FALSE,
  1180. 'php' => DRUPAL_MINIMUM_PHP,
  1181. );
  1182. $info = drupal_parse_info_file("profiles/$profile/$profile.info") + $defaults;
  1183. $info['dependencies'] = array_unique(array_merge(
  1184. drupal_required_modules(),
  1185. $info['dependencies'],
  1186. ($locale != 'en' && !empty($locale) ? array('locale') : array()))
  1187. );
  1188. // drupal_required_modules() includes the current profile as a dependency.
  1189. // Since a module can't depend on itself we remove that element of the array.
  1190. array_shift($info['dependencies']);
  1191. $cache[$profile] = $info;
  1192. }
  1193. return $cache[$profile];
  1194. }
  1195. /**
  1196. * Ensures the environment for a Drupal database on a predefined connection.
  1197. *
  1198. * This will run tasks that check that Drupal can perform all of the functions
  1199. * on a database, that Drupal needs. Tasks include simple checks like CREATE
  1200. * TABLE to database specific functions like stored procedures and client
  1201. * encoding.
  1202. */
  1203. function db_run_tasks($driver) {
  1204. db_installer_object($driver)->runTasks();
  1205. return TRUE;
  1206. }
  1207. /**
  1208. * Returns a database installer object.
  1209. *
  1210. * @param $driver
  1211. * The name of the driver.
  1212. */
  1213. function db_installer_object($driver) {
  1214. Database::loadDriverFile($driver, array('install.inc'));
  1215. $task_class = 'DatabaseTasks_' . $driver;
  1216. return new $task_class();
  1217. }