install.inc 31.5 KB
Newer Older
1 2
<?php

3 4 5 6 7
 /**
 * @file
 * API functions for installing modules and themes.
 */

8
use Drupal\Core\Database\Database;
9
use Drupal\Core\DrupalKernel;
10
use Drupal\locale\Gettext;
11

12 13 14
/**
 * Requirement severity -- Informational message only.
 */
15
const REQUIREMENT_INFO = -1;
16 17 18 19

/**
 * Requirement severity -- Requirement successfully met.
 */
20
const REQUIREMENT_OK = 0;
21 22 23 24

/**
 * Requirement severity -- Warning condition; proceed but flag warning.
 */
25
const REQUIREMENT_WARNING = 1;
26 27 28 29

/**
 * Requirement severity -- Error condition; abort installation.
 */
30
const REQUIREMENT_ERROR = 2;
31

32 33 34
/**
 * File permission check -- File exists.
 */
35
const FILE_EXIST = 1;
36 37 38 39

/**
 * File permission check -- File is readable.
 */
40
const FILE_READABLE = 2;
41 42 43 44

/**
 * File permission check -- File is writable.
 */
45
const FILE_WRITABLE = 4;
46 47 48 49

/**
 * File permission check -- File is executable.
 */
50
const FILE_EXECUTABLE = 8;
51 52 53 54

/**
 * File permission check -- File does not exist.
 */
55
const FILE_NOT_EXIST = 16;
56 57 58 59

/**
 * File permission check -- File is not readable.
 */
60
const FILE_NOT_READABLE = 32;
61 62 63 64

/**
 * File permission check -- File is not writable.
 */
65
const FILE_NOT_WRITABLE = 64;
66 67 68 69

/**
 * File permission check -- File is not executable.
 */
70
const FILE_NOT_EXECUTABLE = 128;
71

72
/**
73
 * Loads .install files for installed modules to initialize the update system.
74 75
 */
function drupal_load_updates() {
76 77 78 79
  foreach (drupal_get_installed_schema_version(NULL, FALSE, TRUE) as $module => $schema_version) {
    if ($schema_version > -1) {
      module_load_install($module);
    }
80 81 82
  }
}

83
/**
84
 * Loads the installation profile, extracting its defined distribution name.
85 86
 *
 * @return
87
 *   The distribution name defined in the profile's .info file. Defaults to
88
 *   "Drupal" if none is explicitly provided by the installation profile.
89 90
 *
 * @see install_profile_info()
91
 */
92
function drupal_install_profile_distribution_name() {
93 94 95 96 97 98 99 100 101
  // During installation, the profile information is stored in the global
  // installation state (it might not be saved anywhere yet).
  if (drupal_installation_attempted()) {
    global $install_state;
    return $install_state['profile_info']['distribution_name'];
  }
  // At all other times, we load the profile via standard methods.
  else {
    $profile = drupal_get_profile();
102
    $info = system_get_info('module', $profile);
103 104
    return $info['distribution_name'];
  }
105 106 107
}

/**
108
 * Detects all supported databases that are compiled into PHP.
109 110 111 112 113
 *
 * @return
 *  An array of database types compiled into PHP.
 */
function drupal_detect_database_types() {
114 115 116 117 118 119 120 121 122 123
  $databases = drupal_get_database_types();

  foreach ($databases as $driver => $installer) {
    $databases[$driver] = $installer->name();
  }

  return $databases;
}

/**
124
 * Returns all supported database installer objects that are compiled into PHP.
125 126 127 128 129
 *
 * @return
 *  An array of database installer objects compiled into PHP.
 */
function drupal_get_database_types() {
130
  $databases = array();
131
  $drivers = array();
132

133
  // We define a driver as a directory in /core/includes/database that in turn
134
  // contains a database.inc file. That allows us to drop in additional drivers
135
  // without modifying the installer.
136
  require_once DRUPAL_ROOT . '/core/includes/database.inc';
137
  foreach (file_scan_directory(DRUPAL_ROOT . '/core/lib/Drupal/Core/Database/Driver', '/^[a-z]*$/i', array('recurse' => FALSE)) as $file) {
138
    if (file_exists($file->uri . '/Install/Tasks.php')) {
139 140
      $drivers[$file->filename] = $file->uri;
    }
141 142 143
  }

  foreach ($drivers as $driver => $file) {
144
    $installer = db_installer_object($driver);
145
    if ($installer->installable()) {
146
      $databases[$driver] = $installer;
147 148
    }
  }
149

150
  // Usability: unconditionally put the MySQL driver on top.
151 152 153 154 155
  if (isset($databases['mysql'])) {
    $mysql_database = $databases['mysql'];
    unset($databases['mysql']);
    $databases = array('mysql' => $mysql_database) + $databases;
  }
156

157 158 159
  return $databases;
}

160
/**
161
 * Replaces values in settings.php with values in the submitted array.
162 163 164 165
 *
 * @param $settings
 *   An array of settings that need to be updated.
 */
166
function drupal_rewrite_settings($settings = array()) {
167
  drupal_static_reset('conf_path');
168
  $settings_file = conf_path(FALSE) . '/settings.php';
169 170 171 172 173 174 175 176 177

  // Build list of setting names and insert the values into the global namespace.
  $keys = array();
  foreach ($settings as $setting => $data) {
    $GLOBALS[$setting] = $data['value'];
    $keys[] = $setting;
  }

  $buffer = NULL;
178 179 180 181 182 183 184 185 186 187 188 189 190 191
  $contents = file_get_contents(DRUPAL_ROOT . '/' . $settings_file);
  if ($contents !== FALSE) {
    // Step through each token in settings.php and replace any variables that
    // are in the passed-in array.
    $replacing_variable = FALSE;
    foreach (token_get_all($contents) as $token) {
      // Strip off the leading "$" before comparing the variable name.
      if (is_array($token) && $token[0] == T_VARIABLE && ($variable_name = substr($token[1], 1)) && in_array($variable_name, $keys)) {
        // Write the new value to settings.php in the following format:
        //    $[setting] = '[value]'; // [comment]
        $setting = $settings[$variable_name];
        $buffer .= '$' . $variable_name . ' = ' . var_export($setting['value'], TRUE) . ';';
        if (!empty($setting['comment'])) {
          $buffer .= ' // ' . $setting['comment'];
192
        }
193 194
        unset($settings[$variable_name]);
        $replacing_variable = TRUE;
195
      }
196 197 198 199 200
      else {
        // Write a regular token (that is not part of a variable we're
        // replacing) to settings.php directly.
        if (!$replacing_variable) {
          $buffer .= is_array($token) ? $token[1] : $token;
201
        }
202 203 204 205
        // When we hit a semicolon, we are done with the code that defines the
        // variable that is being replaced.
        if ($token == ';') {
          $replacing_variable = FALSE;
206 207 208 209 210 211
        }
      }
    }

    // Add required settings that were missing from settings.php.
    foreach ($settings as $setting => $data) {
212
      if (!empty($data['required'])) {
213
        $buffer .= "\$$setting = " . var_export($data['value'], TRUE) . ";\n";
214 215 216
      }
    }

217 218
    // Write the new settings file.
    if (file_put_contents(DRUPAL_ROOT . '/' . $settings_file, $buffer) === FALSE) {
219
      throw new Exception(st('Failed to modify %settings. Verify the file permissions.', array('%settings' => $settings_file)));
220 221 222
    }
  }
  else {
223
    throw new Exception(st('Failed to open %settings. Verify the file permissions.', array('%settings' => $settings_file)));
224 225 226
  }
}

227 228 229 230 231 232
/**
 * Creates the config directory and ensures it is operational.
 *
 * @see install_settings_form_submit()
 * @see update_prepare_d8_bootstrap()
 */
233 234
function drupal_install_config_directories() {
  global $config_directories;
235 236 237

  // Add a randomized config directory name to settings.php, unless it was
  // manually defined in the existing already.
238
  if (empty($config_directories)) {
239
    $config_directories_hash = drupal_hash_base64(drupal_random_bytes(55));
240 241
    $settings['config_directories'] = array(
      'value' => array(
242
        CONFIG_ACTIVE_DIRECTORY => array(
243
          'path' => 'config_' . $config_directories_hash . '/active',
244 245
        ),
        CONFIG_STAGING_DIRECTORY => array(
246
          'path' => 'config_' . $config_directories_hash . '/staging',
247
        ),
248
      ),
249 250 251 252 253 254
      'required' => TRUE,
    );
    // Rewrite settings.php, which also sets the value as global variable.
    drupal_rewrite_settings($settings);
  }

255
  // Ensure the config directories exist or can be created, and are writable.
256
  foreach (array(CONFIG_ACTIVE_DIRECTORY, CONFIG_STAGING_DIRECTORY) as $config_type) {
257 258 259 260 261 262
    // This should never fail, since if the config directory was specified in
    // settings.php it will have already been created and verified earlier, and
    // if it wasn't specified in settings.php, it is created here inside the
    // public files directory, which has already been verified to be writable
    // itself. But if it somehow fails anyway, the installation cannot proceed.
    // Bail out using a similar error message as in system_requirements().
263 264 265 266 267 268
    if (!install_ensure_config_directory($config_type)) {
      throw new Exception(st('The directory %directory could not be created or could not be made writable. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see the <a href="@handbook_url">online handbook</a>.', array(
        '%directory' => config_get_config_directory($config_type),
        '@handbook_url' => 'http://drupal.org/server-permissions',
      )));
    }
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

    // Put a README.txt into each config directory. This is required so that
    // they can later be added to git. Since these directories are auto-
    // created, we have to write out the README rather than just adding it
    // to the drupal core repo.
    switch ($config_type) {
      case CONFIG_ACTIVE_DIRECTORY:
        $text = 'This directory contains the active configuration for your Drupal site. To move this configuration between environments, contents from this directory should be placed in the staging directory on the target server. To make this configuration active, see admin/config/development/sync on the target server.';
        break;
      case CONFIG_STAGING_DIRECTORY:
        $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, see admin/config/development/sync.';
        break;
    }
    $text .=  ' For information about deploying configuration between servers, see http://drupal.org/documentation/administer/config';
    file_put_contents(config_get_config_directory($config_type) . '/README.txt', $text);
284 285 286
  }
}

287
/**
288
 * Checks whether a config directory exists and is writable.
289
 *
290
 * This partially duplicates install_ensure_config_directory(), but is required
291 292
 * since the installer would create the config directory too early in the
 * installation process otherwise (e.g., when only visiting install.php when
293 294
 * there is a settings.php already, but not actually executing the
 * installation).
295 296 297 298 299 300 301 302 303 304 305 306 307
 *
 * @param string $type
 *   Type of config directory to return. Drupal core provides 'active' and
 *   'staging'.
 *
 * @return bool
 *   TRUE if the config directory exists and is writable.
 */
function install_verify_config_directory($type) {
  global $config_directories;
  if (!isset($config_directories[$type])) {
    return FALSE;
  }
308 309 310 311 312 313 314 315 316 317
  // config_get_config_directory() throws an exception when the passed $type
  // does not exist in $config_directories. This can happen if there is a
  // prepared settings.php that defines $config_directories already.
  try {
    $config_directory = config_get_config_directory($type);
    if (is_dir($config_directory) && is_writable($config_directory)) {
      return TRUE;
    }
  }
  catch (\Exception $e) {
318 319 320 321
  }
  return FALSE;
}

322 323
/**
 * Ensures that the config directory exists and is writable, or can be made so.
324 325 326 327 328 329 330
 *
 * @param string $type
 *   Type of config directory to return. Drupal core provides 'active' and
 *   'staging'.
 *
 * @return bool
 *   TRUE if the config directory exists and is writable.
331
 */
332
function install_ensure_config_directory($type) {
333
  // The config directory must be defined in settings.php.
334 335
  global $config_directories;
  if (!isset($config_directories[$type])) {
336 337 338 339 340
    return FALSE;
  }
  // The logic here is similar to that used by system_requirements() for other
  // directories that the installer creates.
  else {
341
    $config_directory = config_get_config_directory($type);
342 343 344 345
    return file_prepare_directory($config_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  }
}

346
/**
347
 * Verifies that all dependencies are met for a given installation profile.
348
 *
349 350
 * @param $install_state
 *   An array of information about the current installation state.
351
 *
Steven Wittens's avatar
Steven Wittens committed
352 353
 * @return
 *   The list of modules to install.
354
 */
355
function drupal_verify_profile($install_state) {
356 357
  include_once DRUPAL_ROOT . '/core/includes/file.inc';
  include_once DRUPAL_ROOT . '/core/includes/common.inc';
358

359 360
  $profile = $install_state['parameters']['profile'];
  $profile_file = $install_state['profiles'][$profile]->uri;
361 362

  if (!isset($profile) || !file_exists($profile_file)) {
363
    throw new Exception(install_no_profile_error());
364
  }
365
  $info = $install_state['profile_info'];
366

367 368
  // Get a list of modules that exist in Drupal's assorted subdirectories.
  $present_modules = array();
369
  foreach (drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.module$/', 'modules') as $present_module) {
370 371 372
    $present_modules[] = $present_module->name;
  }

373 374
  // The installation profile is also a module, which needs to be installed
  // after all the other dependencies have been installed.
375 376
  $present_modules[] = drupal_get_profile();

377
  // Verify that all of the profile's required modules are present.
378
  $missing_modules = array_diff($info['dependencies'], $present_modules);
379 380

  $requirements = array();
381

382
  if (count($missing_modules)) {
383
    $modules = array();
384
    foreach ($missing_modules as $module) {
385
      $modules[] = '<span class="admin-missing">' . drupal_ucfirst($module) . '</span>';
Steven Wittens's avatar
Steven Wittens committed
386
    }
387 388 389 390
    $requirements['required_modules'] = array(
      'title'       => st('Required modules'),
      'value'       => st('Required modules not found.'),
      'severity'    => REQUIREMENT_ERROR,
391
      'description' => st('The following modules are required but were not found. Move them into the appropriate modules subdirectory, such as <em>/modules</em>. Missing modules: !modules', array('!modules' => implode(', ', $modules))),
392
    );
Steven Wittens's avatar
Steven Wittens committed
393
  }
394
  return $requirements;
Steven Wittens's avatar
Steven Wittens committed
395
}
396

397
/**
398
 * Installs the system module.
399 400 401 402 403
 *
 * Separated from the installation of other modules so core system
 * functions can be made available while other modules are installed.
 */
function drupal_install_system() {
404 405
  // Create tables.
  drupal_install_schema('system');
406 407 408
  // Immediately boot a kernel to have real services ready.
  $kernel = new DrupalKernel('install', FALSE, drupal_classloader(), FALSE);
  $kernel->boot();
409

410
  $system_path = drupal_get_path('module', 'system');
411
  require_once DRUPAL_ROOT . '/' . $system_path . '/system.install';
Steven Wittens's avatar
Steven Wittens committed
412 413
  $system_versions = drupal_get_schema_versions('system');
  $system_version = $system_versions ? max($system_versions) : SCHEMA_INSTALLED;
414 415 416 417 418 419 420 421 422 423 424 425 426
  drupal_container()
    ->get('keyvalue')
    ->get('system.schema')
    ->set('system', $system_version);

  // System module needs to be enabled and the system/module lists need to be
  // reset first in order to allow config_install_default_config() to invoke
  // config import callbacks.
  // @todo Installation profiles may override the system.module config object.
  config('system.module')
    ->set('enabled.system', 0)
    ->save();

427 428 429 430 431 432 433 434 435
  // Clear out module list and hook implementation statics.
  system_list_reset();
  module_list_reset();
  module_implements_reset();

  // To ensure that the system module can be found by the plugin system, warm
  // the module list cache.
  // @todo Remove this in http://drupal.org/node/1798732.
  module_list();
436
  config_install_default_config('module', 'system');
437 438

  module_invoke('system', 'install');
439 440
}

441
/**
442
 * Verifies the state of the specified file.
443 444 445 446 447 448 449
 *
 * @param $file
 *   The file to check for.
 * @param $mask
 *   An optional bitmask created from various FILE_* constants.
 * @param $type
 *   The type of file. Can be file (default), dir, or link.
450
 *
451
 * @return
452
 *   TRUE on success or FALSE on failure. A message is set for the latter.
453 454 455 456 457 458 459 460 461
 */
function drupal_verify_install_file($file, $mask = NULL, $type = 'file') {
  $return = TRUE;
  // Check for files that shouldn't be there.
  if (isset($mask) && ($mask & FILE_NOT_EXIST) && file_exists($file)) {
    return FALSE;
  }
  // Verify that the file is the type of file it is supposed to be.
  if (isset($type) && file_exists($file)) {
462
    $check = 'is_' . $type;
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    if (!function_exists($check) || !$check($file)) {
      $return = FALSE;
    }
  }

  // Verify file permissions.
  if (isset($mask)) {
    $masks = array(FILE_EXIST, FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
    foreach ($masks as $current_mask) {
      if ($mask & $current_mask) {
        switch ($current_mask) {
          case FILE_EXIST:
            if (!file_exists($file)) {
              if ($type == 'dir') {
                drupal_install_mkdir($file, $mask);
              }
              if (!file_exists($file)) {
                $return = FALSE;
              }
            }
            break;
          case FILE_READABLE:
            if (!is_readable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
          case FILE_WRITABLE:
            if (!is_writable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
          case FILE_EXECUTABLE:
            if (!is_executable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
          case FILE_NOT_READABLE:
            if (is_readable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
          case FILE_NOT_WRITABLE:
            if (is_writable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
          case FILE_NOT_EXECUTABLE:
            if (is_executable($file) && !drupal_install_fix_file($file, $mask)) {
              $return = FALSE;
            }
            break;
        }
      }
    }
  }
  return $return;
}

/**
522
 * Creates a directory with the specified permissions.
523
 *
524
 * @param $file
525
 *  The name of the directory to create;
526
 * @param $mask
527 528 529
 *  The permissions of the directory to create.
 * @param $message
 *  (optional) Whether to output messages. Defaults to TRUE.
530
 *
531 532 533 534 535 536 537 538 539 540
 * @return
 *  TRUE/FALSE whether or not the directory was successfully created.
 */
function drupal_install_mkdir($file, $mask, $message = TRUE) {
  $mod = 0;
  $masks = array(FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
  foreach ($masks as $m) {
    if ($mask & $m) {
      switch ($m) {
        case FILE_READABLE:
541
          $mod |= 0444;
542 543
          break;
        case FILE_WRITABLE:
544
          $mod |= 0222;
545 546
          break;
        case FILE_EXECUTABLE:
547
          $mod |= 0111;
548 549 550 551 552
          break;
      }
    }
  }

553
  if (@drupal_mkdir($file, $mod)) {
554 555 556 557 558 559 560 561
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
562
 * Attempts to fix file permissions.
563
 *
564 565 566 567 568 569 570 571 572
 * The general approach here is that, because we do not know the security
 * setup of the webserver, we apply our permission changes to all three
 * digits of the file permission (i.e. user, group and all).
 *
 * To ensure that the values behave as expected (and numbers don't carry
 * from one digit to the next) we do the calculation on the octal value
 * using bitwise operations. This lets us remove, for example, 0222 from
 * 0700 and get the correct value of 0500.
 *
573 574 575 576 577 578
 * @param $file
 *  The name of the file with permissions to fix.
 * @param $mask
 *  The desired permissions for the file.
 * @param $message
 *  (optional) Whether to output messages. Defaults to TRUE.
579
 *
580 581 582 583
 * @return
 *  TRUE/FALSE whether or not we were able to fix the file's permissions.
 */
function drupal_install_fix_file($file, $mask, $message = TRUE) {
584 585 586 587 588
  // If $file does not exist, fileperms() issues a PHP warning.
  if (!file_exists($file)) {
    return FALSE;
  }

589
  $mod = fileperms($file) & 0777;
590
  $masks = array(FILE_READABLE, FILE_WRITABLE, FILE_EXECUTABLE, FILE_NOT_READABLE, FILE_NOT_WRITABLE, FILE_NOT_EXECUTABLE);
591 592 593 594 595

  // FILE_READABLE, FILE_WRITABLE, and FILE_EXECUTABLE permission strings
  // can theoretically be 0400, 0200, and 0100 respectively, but to be safe
  // we set all three access types in case the administrator intends to
  // change the owner of settings.php after installation.
596 597 598 599 600
  foreach ($masks as $m) {
    if ($mask & $m) {
      switch ($m) {
        case FILE_READABLE:
          if (!is_readable($file)) {
601
            $mod |= 0444;
602 603 604 605
          }
          break;
        case FILE_WRITABLE:
          if (!is_writable($file)) {
606
            $mod |= 0222;
607 608 609 610
          }
          break;
        case FILE_EXECUTABLE:
          if (!is_executable($file)) {
611
            $mod |= 0111;
612 613 614 615
          }
          break;
        case FILE_NOT_READABLE:
          if (is_readable($file)) {
616
            $mod &= ~0444;
617 618 619 620
          }
          break;
        case FILE_NOT_WRITABLE:
          if (is_writable($file)) {
621
            $mod &= ~0222;
622 623 624 625
          }
          break;
        case FILE_NOT_EXECUTABLE:
          if (is_executable($file)) {
626
            $mod &= ~0111;
627 628 629 630 631 632
          }
          break;
      }
    }
  }

633 634 635 636
  // chmod() will work if the web server is running as owner of the file.
  // If PHP safe_mode is enabled the currently executing script must also
  // have the same owner.
  if (@chmod($file, $mod)) {
637 638 639 640 641 642 643
    return TRUE;
  }
  else {
    return FALSE;
  }
}

644
/**
645
 * Sends the user to a different installer page.
646 647
 *
 * This issues an on-site HTTP redirect. Messages (and errors) are erased.
648 649 650 651 652
 *
 * @param $path
 *   An installer path.
 */
function install_goto($path) {
653
  global $base_url;
654
  include_once DRUPAL_ROOT . '/core/includes/common.inc';
655
  header('Location: ' . $base_url . '/' . $path);
656
  header('Cache-Control: no-cache'); // Not a permanent redirect.
657
  drupal_exit();
658 659
}

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
/**
 * Returns the URL of the current script, with modified query parameters.
 *
 * This function can be called by low-level scripts (such as install.php and
 * update.php) and returns the URL of the current script. Existing query
 * parameters are preserved by default, but new ones can optionally be merged
 * in.
 *
 * This function is used when the script must maintain certain query parameters
 * over multiple page requests in order to work correctly. In such cases (for
 * example, update.php, which requires the 'continue=1' parameter to remain in
 * the URL throughout the update process if there are any requirement warnings
 * that need to be bypassed), using this function to generate the URL for links
 * to the next steps of the script ensures that the links will work correctly.
 *
 * @param $query
 *   (optional) An array of query parameters to merge in to the existing ones.
 *
 * @return
 *   The URL of the current script, with query parameters modified by the
 *   passed-in $query. The URL is not sanitized, so it still needs to be run
 *   through check_url() if it will be used as an HTML attribute value.
 *
 * @see drupal_requirements_url()
 */
function drupal_current_script_url($query = array()) {
  $uri = $_SERVER['SCRIPT_NAME'];
  $query = array_merge(drupal_get_query_parameters(), $query);
  if (!empty($query)) {
    $uri .= '?' . drupal_http_build_query($query);
  }
  return $uri;
}

/**
 * Returns a URL for proceeding to the next page after a requirements problem.
 *
 * This function can be called by low-level scripts (such as install.php and
 * update.php) and returns a URL that can be used to attempt to proceed to the
 * next step of the script.
 *
 * @param $severity
 *   The severity of the requirements problem, as returned by
 *   drupal_requirements_severity().
 *
 * @return
 *   A URL for attempting to proceed to the next step of the script. The URL is
 *   not sanitized, so it still needs to be run through check_url() if it will
 *   be used as an HTML attribute value.
 *
 * @see drupal_current_script_url()
 */
function drupal_requirements_url($severity) {
  $query = array();
  // If there are no errors, only warnings, append 'continue=1' to the URL so
  // the user can bypass this screen on the next page load.
  if ($severity == REQUIREMENT_WARNING) {
    $query['continue'] = 1;
  }
  return drupal_current_script_url($query);
}

722
/**
723
 * Translates a string when some systems are not available.
724 725
 *
 * Used during the install process, when database, theme, and localization
726
 * system is possibly not yet available.
727
 *
728 729 730 731
 * Use t() if your code will never run during the Drupal installation phase.
 * Use st() if your code will only run during installation and never any other
 * time. Use get_t() if your code could run in either circumstance.
 *
732
 * @see t()
733
 * @see get_t()
734
 * @ingroup sanitization
735
 */
736
function st($string, array $args = array(), array $options = array()) {
737
  static $strings = NULL;
738
  global $install_state;
drumm's avatar
drumm committed
739

740 741 742 743
  if (empty($options['context'])) {
    $options['context'] = '';
  }

744 745
  if (!isset($strings)) {
    $strings = array();
746
    if (isset($install_state['parameters']['langcode'])) {
747 748
      // If the given langcode was selected, there should be at least one .po
      // file with its name in the pattern drupal-$version.$langcode.po.
749
      // This might or might not be the entire filename. It is also possible
750
      // that multiple files end with the same suffix, even if unlikely.
751 752
      $files = install_find_translation_files($install_state['parameters']['langcode']);
      if (!empty($files)) {
753 754 755
        // Register locale classes with the classloader. Locale module is not
        // yet enabled at this stage, so this is not happening automatically.
        drupal_classloader_register('locale', drupal_get_path('module', 'locale'));
756
        $strings = Gettext::filesToArray($install_state['parameters']['langcode'], $files);
757
      }
758
    }
drumm's avatar
drumm committed
759 760
  }

761
  require_once DRUPAL_ROOT . '/core/includes/theme.inc';
762
  // Transform arguments before inserting them
763
  foreach ($args as $key => $value) {
764 765 766 767 768 769 770 771
    switch ($key[0]) {
      // Escaped only
      case '@':
        $args[$key] = check_plain($value);
        break;
      // Escaped and placeholder
      case '%':
      default:
772
        $args[$key] = '<em>' . check_plain($value) . '</em>';
773 774 775 776
        break;
      // Pass-through
      case '!':
    }
777
  }
778
  return strtr((!empty($strings[$options['context']][$string]) ? $strings[$options['context']][$string] : $string), $args);
779
}
780 781

/**
782
 * Checks an installation profile's requirements.
783
 *
784
 * @param string $profile
785
 *   Name of installation profile to check.
786 787 788 789
 * @param array $install_state
 *   The current state in the install process.
 *
 * @return array
790
 *   Array of the installation profile's requirements.
791
 */
792
function drupal_check_profile($profile, array $install_state) {
793
  include_once DRUPAL_ROOT . '/core/includes/file.inc';
794

795
  $profile_file = $install_state['profiles'][$profile]->uri;
796 797

  if (!isset($profile) || !file_exists($profile_file)) {
798
    throw new Exception(install_no_profile_error());
799 800
  }

801
  $info = install_profile_info($profile);
802

803
  // Collect requirement testing results.
804
  $requirements = array();
805 806 807
  foreach ($info['dependencies'] as $module) {
    module_load_install($module);
    $function = $module . '_requirements';
808 809
    if (function_exists($function)) {
      $requirements = array_merge($requirements, $function('install'));
810
    }
811 812 813 814 815
  }
  return $requirements;
}

/**
816
 * Extracts the highest severity from the requirements array.
817 818
 *
 * @param $requirements
819
 *   An array of requirements, in the same format as is returned by
820
 *   hook_requirements().
821
 *
822 823
 * @return
 *   The highest severity in the array.
824 825 826 827 828 829 830 831 832 833 834 835
 */
function drupal_requirements_severity(&$requirements) {
  $severity = REQUIREMENT_OK;
  foreach ($requirements as $requirement) {
    if (isset($requirement['severity'])) {
      $severity = max($severity, $requirement['severity']);
    }
  }
  return $severity;
}

/**
836
 * Checks a module's requirements.
837 838 839
 *
 * @param $module
 *   Machine name of module to check.
840
 *
841
 * @return
842
 *   TRUE or FALSE, depending on whether the requirements are met.
843 844
 */
function drupal_check_module($module) {
845 846
  module_load_install($module);
  if (module_hook($module, 'requirements')) {
847 848 849 850 851 852
    // Check requirements
    $requirements = module_invoke($module, 'requirements', 'install');
    if (is_array($requirements) && drupal_requirements_severity($requirements) == REQUIREMENT_ERROR) {
      // Print any error messages
      foreach ($requirements as $requirement) {
        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
853 854
          $message = $requirement['description'];
          if (isset($requirement['value']) && $requirement['value']) {
855
            $message .= ' (' . t('Currently using !item !version', array('!item' => $requirement['title'], '!version' => $requirement['value'])) . ')';
856 857
          }
          drupal_set_message($message, 'error');
858 859 860 861 862 863 864
        }
      }
      return FALSE;
    }
  }
  return TRUE;
}
865 866

/**
867
 * Retrieves information about an installation profile from its .info file.
868
 *
869 870
 * The information stored in a profile .info file is similar to that stored in
 * a normal Drupal module .info file. For example:
871
 * - name: The real name of the installation profile for display purposes.
872
 * - description: A brief description of the profile.
873 874
 * - dependencies: An array of shortnames of other modules that this install
 *   profile requires.
875
 *
876 877 878 879 880
 * Additional, less commonly-used information that can appear in a profile.info
 * file but not in a normal Drupal module .info file includes:
 * - distribution_name: The name of the Drupal distribution that is being
 *   installed, to be shown throughout the installation process. Defaults to
 *   'Drupal'.
881 882 883 884 885 886
 * - exclusive: If the install profile is intended to be the only eligible
 *   choice in a distribution, setting exclusive = TRUE will auto-select it
 *   during installation, and the install profile selection screen will be
 *   skipped. If more than one profile is found where exclusive = TRUE then
 *   this property will have no effect and the profile selection screen will
 *   be shown as normal with all available profiles shown.
887
 *
888 889 890 891
 * Note that this function does an expensive file system scan to get info file
 * information for dependencies. If you only need information from the info
 * file itself, use system_get_info().
 *
892
 * Example of .info file:
893
 * @code
894 895
 *    name = Minimal
 *    description = Start fresh, with only a few modules enabled.
896 897
 *    dependencies[] = block
 *    dependencies[] = dblog
898
 * @endcode
899
 *
900
 * @param $profile
901
 *   Name of profile.
902 903
 * @param $langcode
 *   Language code (if any).
904
 *
905 906
 * @return
 *   The info array.
907
 */
908
function install_profile_info($profile, $langcode = 'en') {
909 910 911 912 913 914 915
  $cache = &drupal_static(__FUNCTION__, array());

  if (!isset($cache[$profile])) {
    // Set defaults for module info.
    $defaults = array(
      'dependencies' => array(),
      'description' => '',
916
      'distribution_name' => 'Drupal',
917
      'version' => NULL,
918
      'hidden' => FALSE,
919 920
      'php' => DRUPAL_MINIMUM_PHP,
    );
921 922 923
    $profile_file = drupal_get_path('profile', $profile) . "/$profile.info";
    $info = drupal_parse_info_file($profile_file);
    $info += $defaults;
924
    $info['dependencies'] = array_unique(array_merge(
925 926
      drupal_required_modules(),
      $info['dependencies'],
927
      ($langcode != 'en' && !empty($langcode) ? array('locale') : array()))
928
    );
929 930 931 932 933

    // drupal_required_modules() includes the current profile as a dependency.
    // Since a module can't depend on itself we remove that element of the array.
    array_shift($info['dependencies']);

934 935 936
    $cache[$profile] = $info;
  }
  return $cache[$profile];
937 938
}

939 940 941 942 943
/**
 * Ensures the environment for a Drupal database on a predefined connection.
 *
 * This will run tasks that check that Drupal can perform all of the functions
 * on a database, that Drupal needs. Tasks include simple checks like CREATE
944
 * TABLE to database specific functions like stored procedures and client
945 946 947
 * encoding.
 */
function db_run_tasks($driver) {
948
  db_installer_object($driver)->runTasks();
949
  return TRUE;
950
}
951 952 953 954 955 956 957 958

/**
 * Returns a database installer object.
 *
 * @param $driver
 *   The name of the driver.
 */
function db_installer_object($driver) {
959 960
  // We cannot use Database::getConnection->getDriverClass() here,