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