install.inc 42 KB

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