<?php

/**
 * @file
 * Install, update and uninstall functions for the system module.
 */

/**
 * Implements hook_requirements().
 */
function system_requirements($phase) {
  global $base_url;
  $requirements = array();
  // Ensure translations don't break during installation.
  $t = get_t();

  // Report Drupal version
  if ($phase == 'runtime') {
    $requirements['drupal'] = array(
      'title' => $t('Drupal'),
      'value' => VERSION,
      'severity' => REQUIREMENT_INFO,
      'weight' => -10,
    );

    // Display the currently active installation profile, if the site
    // is not running the default installation profile.
    $profile = drupal_get_profile();
    if ($profile != 'standard') {
      $info = system_get_info('module', $profile);
      $requirements['install_profile'] = array(
        'title' => $t('Install profile'),
        'value' => $t('%profile_name (%profile-%version)', array(
          '%profile_name' => $info['name'],
          '%profile' => $profile,
          '%version' => $info['version']
        )),
        'severity' => REQUIREMENT_INFO,
        'weight' => -9
      );
    }
  }
  if (isset($GLOBALS['install_state']['profile_info'])) {
    $profile_info = $GLOBALS['install_state']['profile_info'];
  }
  else {
    if (!isset($profile)) {
      $profile = drupal_get_profile();
    }
    $profile_info = install_profile_info($profile);
  }

  // Web server information.
  $software = $_SERVER['SERVER_SOFTWARE'];
  $requirements['webserver'] = array(
    'title' => $t('Web server'),
    'value' => $software,
  );

  // Test PHP version and show link to phpinfo() if it's available
  $phpversion = phpversion();
  if (function_exists('phpinfo')) {
    $requirements['php'] = array(
      'title' => $t('PHP'),
      'value' => ($phase == 'runtime') ? $phpversion .' ('. l($t('more information'), 'admin/reports/status/php') .')' : $phpversion,
    );
  }
  else {
    $requirements['php'] = array(
      'title' => $t('PHP'),
      'value' => $phpversion,
      'description' => $t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, <a href="@phpinfo">Enabling and disabling phpinfo()</a> handbook page.', array('@phpinfo' => 'http://drupal.org/node/243993')),
      'severity' => REQUIREMENT_INFO,
    );
  }

  if (version_compare($phpversion, $profile_info['php']) < 0) {
    $requirements['php']['description'] = $t('Your PHP installation is too old. Drupal requires at least PHP %version.', array('%version' => $profile_info['php']));
    $requirements['php']['severity'] = REQUIREMENT_ERROR;
    // If PHP is old, it's not safe to continue with the requirements check.
    return $requirements;
  }
  // Check that htmlspecialchars() is secure if the site is running any PHP
  // version older than 5.2.5. We don't simply require 5.2.5, because Ubuntu
  // 8.04 ships with PHP 5.2.4, but includes the necessary security patch.
  elseif (version_compare($phpversion, '5.2.5') < 0 && strlen(@htmlspecialchars(chr(0xC0) . chr(0xAF), ENT_QUOTES, 'UTF-8'))) {
    $requirements['php']['description'] = $t('Your PHP installation is too old. Drupal requires at least PHP 5.2.5, or PHP @version with the htmlspecialchars security patch backported.', array('@version' => DRUPAL_MINIMUM_PHP));
    $requirements['php']['severity'] = REQUIREMENT_ERROR;
    // If PHP is old, it's not safe to continue with the requirements check.
    return $requirements;
  }

  // Test PHP register_globals setting.
  $requirements['php_register_globals'] = array(
    'title' => $t('PHP register globals'),
  );
  $register_globals = trim(ini_get('register_globals'));
  // Unfortunately, ini_get() may return many different values, and we can't
  // be certain which values mean 'on', so we instead check for 'not off'
  // since we never want to tell the user that their site is secure
  // (register_globals off), when it is in fact on. We can only guarantee
  // register_globals is off if the value returned is 'off', '', or 0.
  if (!empty($register_globals) && strtolower($register_globals) != 'off') {
    $requirements['php_register_globals']['description'] = $t('<em>register_globals</em> is enabled. Drupal requires this configuration directive to be disabled. Your site may not be secure when <em>register_globals</em> is enabled. The PHP manual has instructions for <a href="http://php.net/configuration.changes">how to change configuration settings</a>.');
    $requirements['php_register_globals']['severity'] = REQUIREMENT_ERROR;
    $requirements['php_register_globals']['value'] = $t("Enabled ('@value')", array('@value' => $register_globals));
  }
  else {
    $requirements['php_register_globals']['value'] = $t('Disabled');
  }

  // Test for PHP extensions.
  $requirements['php_extensions'] = array(
    'title' => $t('PHP extensions'),
  );

  $missing_extensions = array();
  $required_extensions = array(
    'date',
    'dom',
    'filter',
    'gd',
    'hash',
    'json',
    'pcre',
    'pdo',
    'session',
    'SimpleXML',
    'SPL',
    'xml',
  );
  foreach ($required_extensions as $extension) {
    if (!extension_loaded($extension)) {
      $missing_extensions[] = $extension;
    }
  }

  if (!empty($missing_extensions)) {
    $description = $t('Drupal requires you to enable the PHP extensions in the following list (see the <a href="@system_requirements">system requirements page</a> for more information):', array(
      '@system_requirements' => 'http://drupal.org/requirements',
    ));

    $description .= theme('item_list', array('items' => $missing_extensions));

    $requirements['php_extensions']['value'] = $t('Disabled');
    $requirements['php_extensions']['severity'] = REQUIREMENT_ERROR;
    $requirements['php_extensions']['description'] = $description;
  }
  else {
    $requirements['php_extensions']['value'] = $t('Enabled');
  }

  if ($phase == 'install' || $phase == 'update') {
    // Test for PDO (database).
    $requirements['database_extensions'] = array(
      'title' => $t('Database support'),
    );

    // Make sure PDO is available.
    $database_ok = extension_loaded('pdo');
    if (!$database_ok) {
      $pdo_message = $t('Your web server does not appear to support PDO (PHP Data Objects). Ask your hosting provider if they support the native PDO extension. See the <a href="@link">system requirements</a> page for more information.', array(
        '@link' => 'http://drupal.org/requirements/pdo',
      ));
    }
    else {
      // Make sure at least one supported database driver exists.
      $drivers = drupal_detect_database_types();
      if (empty($drivers)) {
        $database_ok = FALSE;
        $pdo_message = $t('Your web server does not appear to support any common PDO database extensions. Check with your hosting provider to see if they support PDO (PHP Data Objects) and offer any databases that <a href="@drupal-databases">Drupal supports</a>.', array(
          '@drupal-databases' => 'http://drupal.org/node/270#database',
        ));
      }
      // Make sure the native PDO extension is available, not the older PEAR
      // version. (See install_verify_pdo() for details.)
      if (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
        $database_ok = FALSE;
        $pdo_message = $t('Your web server seems to have the wrong version of PDO installed. Drupal 7 requires the PDO extension from PHP core. This system has the older PECL version. See the <a href="@link">system requirements</a> page for more information.', array(
          '@link' => 'http://drupal.org/requirements/pdo#pecl',
        ));
      }
    }

    if (!$database_ok) {
      $requirements['database_extensions']['value'] = $t('Disabled');
      $requirements['database_extensions']['severity'] = REQUIREMENT_ERROR;
      $requirements['database_extensions']['description'] = $pdo_message;
    }
    else {
      $requirements['database_extensions']['value'] = $t('Enabled');
    }
  }
  else {
    // Database information.
    $class = 'DatabaseTasks_' . Database::getConnection()->driver();
    $tasks = new $class();
    $requirements['database_system'] = array(
      'title' => $t('Database system'),
      'value' => $tasks->name(),
    );
    $requirements['database_system_version'] = array(
      'title' => $t('Database system version'),
      'value' => Database::getConnection()->version(),
    );
  }

  // Test database-specific multi-byte UTF-8 related requirements.
  $charset_requirements = _system_check_db_utf8mb4_requirements($phase);
  if (!empty($charset_requirements)) {
    $requirements['database_charset'] = $charset_requirements;
  }

  // Test PHP memory_limit
  $memory_limit = ini_get('memory_limit');
  $requirements['php_memory_limit'] = array(
    'title' => $t('PHP memory limit'),
    'value' => $memory_limit == -1 ? t('-1 (Unlimited)') : $memory_limit,
  );

  if (!drupal_check_memory_limit($profile_info['php_memory_limit'], $memory_limit)) {
    $description = '';
    if ($phase == 'install') {
      $description = $t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the installation process.', array('%memory_minimum_limit' => $profile_info['php_memory_limit']));
    }
    elseif ($phase == 'update') {
      $description = $t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the update process.', array('%memory_minimum_limit' => $profile_info['php_memory_limit']));
    }
    elseif ($phase == 'runtime') {
      $description = $t('Depending on your configuration, Drupal can run with a %memory_limit PHP memory limit. However, a %memory_minimum_limit PHP memory limit or above is recommended, especially if your site uses additional custom or contributed modules.', array('%memory_limit' => $memory_limit, '%memory_minimum_limit' => $profile_info['php_memory_limit']));
    }

    if (!empty($description)) {
      if ($php_ini_path = get_cfg_var('cfg_file_path')) {
        $description .= ' ' . $t('Increase the memory limit by editing the memory_limit parameter in the file %configuration-file and then restart your web server (or contact your system administrator or hosting provider for assistance).', array('%configuration-file' => $php_ini_path));
      }
      else {
        $description .= ' ' . $t('Contact your system administrator or hosting provider for assistance with increasing your PHP memory limit.');
      }

      $requirements['php_memory_limit']['description'] = $description . ' ' . $t('See the <a href="@url">Drupal requirements</a> for more information.', array('@url' => 'http://drupal.org/requirements'));
      $requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
    }
  }

  // Test settings.php file writability
  if ($phase == 'runtime') {
    $conf_dir = drupal_verify_install_file(conf_path(), FILE_NOT_WRITABLE, 'dir');
    $conf_file = drupal_verify_install_file(conf_path() . '/settings.php', FILE_EXIST|FILE_READABLE|FILE_NOT_WRITABLE);
    if (!$conf_dir || !$conf_file) {
      $requirements['settings.php'] = array(
        'value' => $t('Not protected'),
        'severity' => REQUIREMENT_ERROR,
        'description' => '',
      );
      if (!$conf_dir) {
        $requirements['settings.php']['description'] .= $t('The directory %file is not protected from modifications and poses a security risk. You must change the directory\'s permissions to be non-writable. ', array('%file' => conf_path()));
      }
      if (!$conf_file) {
        $requirements['settings.php']['description'] .= $t('The file %file is not protected from modifications and poses a security risk. You must change the file\'s permissions to be non-writable.', array('%file' => conf_path() . '/settings.php'));
      }
    }
    else {
      $requirements['settings.php'] = array(
        'value' => $t('Protected'),
      );
    }
    $requirements['settings.php']['title'] = $t('Configuration file');
  }

  // Test the contents of the .htaccess files.
  if ($phase == 'runtime') {
    // Try to write the .htaccess files first, to prevent false alarms in case
    // (for example) the /tmp directory was wiped.
    file_ensure_htaccess();
    $htaccess_files['public://.htaccess'] = array(
      'title' => $t('Public files directory'),
      'directory' => variable_get('file_public_path', conf_path() . '/files'),
    );
    if ($private_files_directory = variable_get('file_private_path')) {
      $htaccess_files['private://.htaccess'] = array(
        'title' => $t('Private files directory'),
        'directory' => $private_files_directory,
      );
    }
    $htaccess_files['temporary://.htaccess'] = array(
      'title' => $t('Temporary files directory'),
      'directory' => variable_get('file_temporary_path', file_directory_temp()),
    );
    foreach ($htaccess_files as $htaccess_file => $info) {
      // Check for the string which was added to the recommended .htaccess file
      // in the latest security update.
      if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
        $requirements[$htaccess_file] = array(
          'title' => $info['title'],
          'value' => $t('Not fully protected'),
          'severity' => REQUIREMENT_ERROR,
          'description' => $t('See <a href="@url">@url</a> for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', array('@url' => 'http://drupal.org/SA-CORE-2013-003', '%directory' => $info['directory'])),
        );
      }
    }
  }

  // Report cron status.
  if ($phase == 'runtime') {
    // Cron warning threshold defaults to two days.
    $threshold_warning = variable_get('cron_threshold_warning', 172800);
    // Cron error threshold defaults to two weeks.
    $threshold_error = variable_get('cron_threshold_error', 1209600);
    // Cron configuration help text.
    $help = $t('For more information, see the online handbook entry for <a href="@cron-handbook">configuring cron jobs</a>.', array('@cron-handbook' => 'http://drupal.org/cron'));

    // Determine when cron last ran.
    $cron_last = variable_get('cron_last');
    if (!is_numeric($cron_last)) {
      $cron_last = variable_get('install_time', 0);
    }

    // Determine severity based on time since cron last ran.
    $severity = REQUIREMENT_OK;
    if (REQUEST_TIME - $cron_last > $threshold_error) {
      $severity = REQUIREMENT_ERROR;
    }
    elseif (REQUEST_TIME - $cron_last > $threshold_warning) {
      $severity = REQUIREMENT_WARNING;
    }

    // Set summary and description based on values determined above.
    $summary = $t('Last run !time ago', array('!time' => format_interval(REQUEST_TIME - $cron_last)));
    $description = '';
    if ($severity != REQUIREMENT_OK) {
      $description = $t('Cron has not run recently.') . ' ' . $help;
    }

    $description .= ' ' . $t('You can <a href="@cron">run cron manually</a>.', array('@cron' => url('admin/reports/status/run-cron')));
    $description .= '<br />' . $t('To run cron from outside the site, go to <a href="!cron">!cron</a>', array('!cron' => url($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))))));

    $requirements['cron'] = array(
      'title' => $t('Cron maintenance tasks'),
      'severity' => $severity,
      'value' => $summary,
      'description' => $description
    );
  }

  // Test files directories.
  $directories = array(
    variable_get('file_public_path', conf_path() . '/files'),
    // By default no private files directory is configured. For private files
    // to be secure the admin needs to provide a path outside the webroot.
    variable_get('file_private_path', FALSE),
  );

  // Do not check for the temporary files directory during installation
  // unless it has been set in settings.php. In this case the user has
  // no alternative but to fix the directory if it is not writable.
  if ($phase == 'install') {
    $directories[] = variable_get('file_temporary_path', FALSE);
  }
  else {
    $directories[] = variable_get('file_temporary_path', file_directory_temp());
  }

  $requirements['file system'] = array(
    'title' => $t('File system'),
  );

  $error = '';
  // For installer, create the directories if possible.
  foreach ($directories as $directory) {
    if (!$directory) {
      continue;
    }
    if ($phase == 'install') {
      file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    }
    $is_writable = is_writable($directory);
    $is_directory = is_dir($directory);
    if (!$is_writable || !$is_directory) {
      $description = '';
      $requirements['file system']['value'] = $t('Not writable');
      if (!$is_directory) {
        $error .= $t('The directory %directory does not exist.', array('%directory' => $directory)) . ' ';
      }
      else {
        $error .= $t('The directory %directory is not writable.', array('%directory' => $directory)) . ' ';
      }
      // The files directory requirement check is done only during install and runtime.
      if ($phase == 'runtime') {
        $description = $error . $t('You may need to set the correct directory at the <a href="@admin-file-system">file system settings page</a> or change the current directory\'s permissions so that it is writable.', array('@admin-file-system' => url('admin/config/media/file-system')));
      }
      elseif ($phase == 'install') {
        // For the installer UI, we need different wording. 'value' will
        // be treated as version, so provide none there.
        $description = $error . $t('An automated attempt to create this directory failed, possibly due to a permissions problem. 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 INSTALL.txt or the <a href="@handbook_url">online handbook</a>.', array('@handbook_url' => 'http://drupal.org/server-permissions'));
        $requirements['file system']['value'] = '';
      }
      if (!empty($description)) {
        $requirements['file system']['description'] = $description;
        $requirements['file system']['severity'] = REQUIREMENT_ERROR;
      }
    }
    else {
      if (file_default_scheme() == 'public') {
        $requirements['file system']['value'] = $t('Writable (<em>public</em> download method)');
      }
      else {
        $requirements['file system']['value'] = $t('Writable (<em>private</em> download method)');
      }
    }
  }

  // See if updates are available in update.php.
  if ($phase == 'runtime') {
    $requirements['update'] = array(
      'title' => $t('Database updates'),
      'severity' => REQUIREMENT_OK,
      'value' => $t('Up to date'),
    );

    // Check installed modules.
    foreach (module_list() as $module) {
      $updates = drupal_get_schema_versions($module);
      if ($updates !== FALSE) {
        $default = drupal_get_installed_schema_version($module);
        if (max($updates) > $default) {
          $requirements['update']['severity'] = REQUIREMENT_ERROR;
          $requirements['update']['value'] = $t('Out of date');
          $requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the <a href="@update">database update script</a> immediately.', array('@update' => base_path() . 'update.php'));
          break;
        }
      }
    }
  }

  // Verify the update.php access setting
  if ($phase == 'runtime') {
    if (!empty($GLOBALS['update_free_access'])) {
      $requirements['update access'] = array(
        'value' => $t('Not protected'),
        'severity' => REQUIREMENT_ERROR,
        'description' => $t('The update.php script is accessible to everyone without authentication check, which is a security risk. You must change the $update_free_access value in your settings.php back to FALSE.'),
      );
    }
    else {
      $requirements['update access'] = array(
        'value' => $t('Protected'),
      );
    }
    $requirements['update access']['title'] = $t('Access to update.php');
  }

  // Display an error if a newly introduced dependency in a module is not resolved.
  if ($phase == 'update') {
    $profile = drupal_get_profile();
    $files = system_rebuild_module_data();
    foreach ($files as $module => $file) {
      // Ignore disabled modules and installation profiles.
      if (!$file->status || $module == $profile) {
        continue;
      }
      // Check the module's PHP version.
      $name = $file->info['name'];
      $php = $file->info['php'];
      if (version_compare($php, PHP_VERSION, '>')) {
        $requirements['php']['description'] .= $t('@name requires at least PHP @version.', array('@name' => $name, '@version' => $php));
        $requirements['php']['severity'] = REQUIREMENT_ERROR;
      }
      // Check the module's required modules.
      foreach ($file->requires as $requirement) {
        $required_module = $requirement['name'];
        // Check if the module exists.
        if (!isset($files[$required_module])) {
          $requirements["$module-$required_module"] = array(
            'title' => $t('Unresolved dependency'),
            'description' => $t('@name requires this module.', array('@name' => $name)),
            'value' => t('@required_name (Missing)', array('@required_name' => $required_module)),
            'severity' => REQUIREMENT_ERROR,
          );
          continue;
        }
        // Check for an incompatible version.
        $required_file = $files[$required_module];
        $required_name = $required_file->info['name'];
        $version = str_replace(DRUPAL_CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
        $compatibility = drupal_check_incompatibility($requirement, $version);
        if ($compatibility) {
          $compatibility = rtrim(substr($compatibility, 2), ')');
          $requirements["$module-$required_module"] = array(
            'title' => $t('Unresolved dependency'),
            'description' => $t('@name requires this module and version. Currently using @required_name version @version', array('@name' => $name, '@required_name' => $required_name, '@version' => $version)),
            'value' => t('@required_name (Version @compatibility required)', array('@required_name' => $required_name, '@compatibility' => $compatibility)),
            'severity' => REQUIREMENT_ERROR,
          );
          continue;
        }
      }
    }
  }

  // Test Unicode library
  include_once DRUPAL_ROOT . '/includes/unicode.inc';
  $requirements = array_merge($requirements, unicode_requirements());

  if ($phase == 'runtime') {
    // Check for update status module.
    if (!module_exists('update')) {
      $requirements['update status'] = array(
        'value' => $t('Not enabled'),
        'severity' => REQUIREMENT_WARNING,
        'description' => $t('Update notifications are not enabled. It is <strong>highly recommended</strong> that you enable the update manager module from the <a href="@module">module administration page</a> in order to stay up-to-date on new releases. For more information, <a href="@update">Update status handbook page</a>.', array('@update' => 'http://drupal.org/documentation/modules/update', '@module' => url('admin/modules'))),
      );
    }
    else {
      $requirements['update status'] = array(
        'value' => $t('Enabled'),
      );
    }
    $requirements['update status']['title'] = $t('Update notifications');

    // Check that Drupal can issue HTTP requests.
    if (variable_get('drupal_http_request_fails', TRUE) && !system_check_http_request()) {
      $requirements['http requests'] = array(
        'title' => $t('HTTP request status'),
        'value' => $t('Fails'),
        'severity' => REQUIREMENT_ERROR,
        'description' => $t('Your system or network configuration does not allow Drupal to access web pages, resulting in reduced functionality. This could be due to your webserver configuration or PHP settings, and should be resolved in order to download information about available updates, fetch aggregator feeds, sign in via OpenID, or use other network-dependent services. If you are certain that Drupal can access web pages but you are still seeing this message, you may add <code>$conf[\'drupal_http_request_fails\'] = FALSE;</code> to the bottom of your settings.php file.'),
      );
    }
  }

  return $requirements;
}

/**
 * Checks whether the requirements for multi-byte UTF-8 support are met.
 *
 * @param string $phase
 *   The hook_requirements() stage.
 *
 * @return array
 *   A requirements array with the result of the charset check.
 */
function _system_check_db_utf8mb4_requirements($phase) {
  global $install_state;
  // In the requirements check of the installer, skip the utf8mb4 check unless
  // the database connection info has been preconfigured by hand with valid
  // information before running the installer, as otherwise we cannot get a
  // valid database connection object.
  if (isset($install_state['settings_verified']) && !$install_state['settings_verified']) {
    return array();
  }

  $connection = Database::getConnection();
  $t = get_t();
  $requirements['title'] = $t('Database 4 byte UTF-8 support');

  $utf8mb4_configurable = $connection->utf8mb4IsConfigurable();
  $utf8mb4_active = $connection->utf8mb4IsActive();
  $utf8mb4_supported = $connection->utf8mb4IsSupported();
  $driver = $connection->driver();
  $documentation_url = 'https://www.drupal.org/node/2754539';

  if ($utf8mb4_active) {
    if ($utf8mb4_supported) {
      if ($phase != 'install' && $utf8mb4_configurable && !variable_get('drupal_all_databases_are_utf8mb4', FALSE)) {
        // Supported, active, and configurable, but not all database tables
        // have been converted yet.
        $requirements['value'] = $t('Enabled, but database tables need conversion');
        $requirements['description'] = $t('Please convert all database tables to utf8mb4 prior to enabling it in settings.php. See the <a href="@url">documentation on adding 4 byte UTF-8 support</a> for more information.', array('@url' => $documentation_url));
        $requirements['severity'] = REQUIREMENT_ERROR;
      }
      else {
        // Supported, active.
        $requirements['value'] = $t('Enabled');
        $requirements['description'] = $t('4 byte UTF-8 for @driver is enabled.', array('@driver' => $driver));
        $requirements['severity'] = REQUIREMENT_OK;
      }
    }
    else {
      // Not supported, active.
      $requirements['value'] = $t('Not supported');
      $requirements['description'] = $t('4 byte UTF-8 for @driver is activated, but not supported on your system. Please turn this off in settings.php, or ensure that all database-related requirements are met. See the <a href="@url">documentation on adding 4 byte UTF-8 support</a> for more information.', array('@driver' => $driver, '@url' => $documentation_url));
      $requirements['severity'] = REQUIREMENT_ERROR;
    }
  }
  else {
    if ($utf8mb4_supported) {
      // Supported, not active.
      $requirements['value'] = $t('Not enabled');
      $requirements['description'] = $t('4 byte UTF-8 for @driver is not activated, but it is supported on your system. It is recommended that you enable this to allow 4-byte UTF-8 input such as emojis, Asian symbols and mathematical symbols to be stored correctly. See the <a href="@url">documentation on adding 4 byte UTF-8 support</a> for more information.', array('@driver' => $driver, '@url' => $documentation_url));
      $requirements['severity'] = REQUIREMENT_INFO;
    }
    else {
      // Not supported, not active.
      $requirements['value'] = $t('Disabled');
      $requirements['description'] = $t('4 byte UTF-8 for @driver is disabled. See the <a href="@url">documentation on adding 4 byte UTF-8 support</a> for more information.', array('@driver' => $driver, '@url' => $documentation_url));
      $requirements['severity'] = REQUIREMENT_INFO;
    }
  }
  return $requirements;
}

/**
 * Implements hook_install().
 */
function system_install() {
  // Create tables.
  drupal_install_schema('system');
  $versions = drupal_get_schema_versions('system');
  $version = $versions ? max($versions) : SCHEMA_INSTALLED;
  drupal_set_installed_schema_version('system', $version);

  // Clear out module list and hook implementation statics before calling
  // system_rebuild_theme_data().
  module_list(TRUE);
  module_implements('', FALSE, TRUE);

  // Ensure the schema versions are not based on a previous module list.
  drupal_static_reset('drupal_get_schema_versions');

  // Load system theme data appropriately.
  system_rebuild_theme_data();

  // Enable the default theme.
  variable_set('theme_default', 'bartik');
  db_update('system')
    ->fields(array('status' => 1))
    ->condition('type', 'theme')
    ->condition('name', 'bartik')
    ->execute();

  // Populate the cron key variable.
  $cron_key = drupal_random_key();
  variable_set('cron_key', $cron_key);
}

/**
 * Implements hook_schema().
 */
function system_schema() {
  // NOTE: {variable} needs to be created before all other tables, as
  // some database drivers, e.g. Oracle and DB2, will require variable_get()
  // and variable_set() for overcoming some database specific limitations.
  $schema['variable'] = array(
    'description' => 'Named variable/value pairs created by Drupal core or any other module or theme. All variables are cached in memory at the start of every Drupal request so developers should not be careless about what is stored here.',
    'fields' => array(
      'name' => array(
        'description' => 'The name of the variable.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'value' => array(
        'description' => 'The value of the variable.',
        'type' => 'blob',
        'not null' => TRUE,
        'size' => 'big',
        'translatable' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );

  $schema['actions'] = array(
    'description' => 'Stores action information.',
    'fields' => array(
      'aid' => array(
        'description' => 'Primary Key: Unique actions ID.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '0',
      ),
      'type' => array(
        'description' => 'The object that that action acts on (node, user, comment, system or custom types.)',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'callback' => array(
        'description' => 'The callback function that executes when the action runs.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'parameters' => array(
        'description' => 'Parameters to be passed to the callback function.',
        'type' => 'blob',
        'not null' => TRUE,
        'size' => 'big',
      ),
      'label' => array(
        'description' => 'Label of the action.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '0',
      ),
    ),
    'primary key' => array('aid'),
  );

  $schema['batch'] = array(
    'description' => 'Stores details about batches (processes that run in multiple HTTP requests).',
    'fields' => array(
      'bid' => array(
        'description' => 'Primary Key: Unique batch ID.',
        // This is not a serial column, to allow both progressive and
        // non-progressive batches. See batch_process().
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'token' => array(
        'description' => "A string token generated against the current user's session id and the batch id, used to ensure that only the user who submitted the batch can effectively access it.",
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
      ),
      'timestamp' => array(
        'description' => 'A Unix timestamp indicating when this batch was submitted for processing. Stale batches are purged at cron time.',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'batch' => array(
        'description' => 'A serialized array containing the processing data for the batch.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
    ),
    'primary key' => array('bid'),
    'indexes' => array(
      'token' => array('token'),
    ),
  );

  $schema['blocked_ips'] = array(
    'description' => 'Stores blocked IP addresses.',
    'fields' => array(
       'iid' => array(
        'description' => 'Primary Key: unique ID for IP addresses.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'ip' => array(
        'description' => 'IP address',
        'type' => 'varchar',
        'length' => 40,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'blocked_ip' => array('ip'),
    ),
    'primary key' => array('iid'),
  );

  $schema['cache'] = array(
    'description' => 'Generic cache table for caching things not separated out into their own tables. Contributed modules may also use this to store cached items.',
    'fields' => array(
      'cid' => array(
        'description' => 'Primary Key: Unique cache ID.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'data' => array(
        'description' => 'A collection of data to cache.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
      'expire' => array(
        'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'created' => array(
        'description' => 'A Unix timestamp indicating when the cache entry was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'serialized' => array(
        'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
        'type' => 'int',
        'size' => 'small',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'expire' => array('expire'),
    ),
    'primary key' => array('cid'),
  );
  $schema['cache_bootstrap'] = $schema['cache'];
  $schema['cache_bootstrap']['description'] = 'Cache table for data required to bootstrap Drupal, may be routed to a shared memory cache.';
  $schema['cache_form'] = $schema['cache'];
  $schema['cache_form']['description'] = 'Cache table for the form system to store recently built forms and their storage data, to be used in subsequent page requests.';
  $schema['cache_page'] = $schema['cache'];
  $schema['cache_page']['description'] = 'Cache table used to store compressed pages for anonymous users, if page caching is enabled.';
  $schema['cache_menu'] = $schema['cache'];
  $schema['cache_menu']['description'] = 'Cache table for the menu system to store router information as well as generated link trees for various menu/page/user combinations.';
  $schema['cache_path'] = $schema['cache'];
  $schema['cache_path']['description'] = 'Cache table for path alias lookup.';

  $schema['date_format_type'] = array(
    'description' => 'Stores configured date format types.',
    'fields' => array(
      'type' => array(
        'description' => 'The date format type, e.g. medium.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'The human readable name of the format type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'locked' => array(
        'description' => 'Whether or not this is a system provided format.',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 0,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('type'),
    'indexes' => array(
      'title' => array('title'),
    ),
  );

  // This table's name is plural as some versions of MySQL can't create a
  // table named 'date_format'.
  $schema['date_formats'] = array(
    'description' => 'Stores configured date formats.',
    'fields' => array(
      'dfid' => array(
        'description' => 'The date format identifier.',
        'type' => 'serial',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
      'format' => array(
        'description' => 'The date format string.',
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'binary' => TRUE,
      ),
      'type' => array(
        'description' => 'The date format type, e.g. medium.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
      ),
      'locked' => array(
        'description' => 'Whether or not this format can be modified.',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 0,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('dfid'),
    'unique keys' => array('formats' => array('format', 'type')),
  );

  $schema['date_format_locale'] = array(
    'description' => 'Stores configured date formats for each locale.',
    'fields' => array(
      'format' => array(
        'description' => 'The date format string.',
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'binary' => TRUE,
      ),
      'type' => array(
        'description' => 'The date format type, e.g. medium.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
      ),
      'language' => array(
        'description' => 'A {languages}.language for this format to be used with.',
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('type', 'language'),
  );

  $schema['file_managed'] = array(
    'description' => 'Stores information for uploaded files.',
    'fields' => array(
      'fid' => array(
        'description' => 'File ID.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'The {users}.uid of the user who is associated with the file.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'filename' => array(
        'description' => 'Name of the file with no path components. This may differ from the basename of the URI if the file is renamed to avoid overwriting an existing file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'uri' => array(
        'description' => 'The URI to access the file (either local or remote).',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'binary' => TRUE,
      ),
      'filemime' => array(
        'description' => "The file's MIME type.",
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'filesize' => array(
        'description' => 'The size of the file in bytes.',
        'type' => 'int',
        'size' => 'big',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'status' => array(
        'description' => 'A field indicating the status of the file. Two status are defined in core: temporary (0) and permanent (1). Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during a cron run.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
      ),
      'timestamp' => array(
        'description' => 'UNIX timestamp for when the file was added.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'uid' => array('uid'),
      'status' => array('status'),
      'timestamp' => array('timestamp'),
    ),
    'unique keys' => array(
      'uri' => array('uri'),
    ),
    'primary key' => array('fid'),
    'foreign keys' => array(
      'file_owner' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  $schema['file_usage'] = array(
    'description' => 'Track where a file is used.',
    'fields' => array(
      'fid' => array(
        'description' => 'File ID.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'module' => array(
        'description' => 'The name of the module that is using the file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'type' => array(
        'description' => 'The name of the object type in which the file is used.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'id' => array(
        'description' => 'The primary key of the object using the file.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'count' => array(
        'description' => 'The number of times this file is used by this object.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('fid', 'type', 'id', 'module'),
    'indexes' => array(
      'type_id' => array('type', 'id'),
      'fid_count' => array('fid', 'count'),
      'fid_module' => array('fid', 'module'),
    ),
  );

  $schema['flood'] = array(
    'description' => 'Flood controls the threshold of events, such as the number of contact attempts.',
    'fields' => array(
      'fid' => array(
        'description' => 'Unique flood event ID.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'event' => array(
        'description' => 'Name of event (e.g. contact).',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'identifier' => array(
        'description' => 'Identifier of the visitor, such as an IP address or hostname.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'timestamp' => array(
        'description' => 'Timestamp of the event.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'expiration' => array(
        'description' => 'Expiration timestamp. Expired events are purged on cron run.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('fid'),
    'indexes' => array(
      'allow' => array('event', 'identifier', 'timestamp'),
      'purge' => array('expiration'),
    ),
  );

  $schema['menu_router'] = array(
    'description' => 'Maps paths to various callbacks (access, page and title)',
    'fields' => array(
      'path' => array(
        'description' => 'Primary Key: the Drupal path this entry describes',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'load_functions' => array(
        'description' => 'A serialized array of function names (like node_load) to be called to load an object corresponding to a part of the current path.',
        'type' => 'blob',
        'not null' => TRUE,
      ),
      'to_arg_functions' => array(
        'description' => 'A serialized array of function names (like user_uid_optional_to_arg) to be called to replace a part of the router path with another string.',
        'type' => 'blob',
        'not null' => TRUE,
      ),
      'access_callback' => array(
        'description' => 'The callback which determines the access to this router path. Defaults to user_access.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'access_arguments' => array(
        'description' => 'A serialized array of arguments for the access callback.',
        'type' => 'blob',
        'not null' => FALSE,
      ),
      'page_callback' => array(
        'description' => 'The name of the function that renders the page.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'page_arguments' => array(
        'description' => 'A serialized array of arguments for the page callback.',
        'type' => 'blob',
        'not null' => FALSE,
      ),
      'delivery_callback' => array(
        'description' => 'The name of the function that sends the result of the page_callback function to the browser.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'fit' => array(
        'description' => 'A numeric representation of how specific the path is.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'number_parts' => array(
        'description' => 'Number of parts in this router path.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'context' => array(
        'description' => 'Only for local tasks (tabs) - the context of a local task to control its placement.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'tab_parent' => array(
        'description' => 'Only for local tasks (tabs) - the router path of the parent page (which may also be a local task).',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'tab_root' => array(
        'description' => 'Router path of the closest non-tab parent page. For pages that are not local tasks, this will be the same as the path.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'title' => array(
        'description' => 'The title for the current page, or the title for the tab if this is a local task.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'title_callback' => array(
        'description' => 'A function which will alter the title. Defaults to t()',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'title_arguments' => array(
        'description' => 'A serialized array of arguments for the title callback. If empty, the title will be used as the sole argument for the title callback.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'theme_callback' => array(
        'description' => 'A function which returns the name of the theme that will be used to render this page. If left empty, the default theme will be used.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'theme_arguments' => array(
        'description' => 'A serialized array of arguments for the theme callback.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'type' => array(
        'description' => 'Numeric representation of the type of the menu item, like MENU_LOCAL_TASK.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'description' => array(
        'description' => 'A description of this item.',
        'type' => 'text',
        'not null' => TRUE,
      ),
      'position' => array(
        'description' => 'The position of the block (left or right) on the system administration page for this item.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'weight' => array(
        'description' => 'Weight of the element. Lighter weights are higher up, heavier weights go down.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'include_file' => array(
        'description' => 'The file to include for this element, usually the page callback function lives in this file.',
        'type' => 'text',
        'size' => 'medium',
      ),
    ),
    'indexes' => array(
      'fit' => array('fit'),
      'tab_parent' => array(array('tab_parent', 64), 'weight', 'title'),
      'tab_root_weight_title' => array(array('tab_root', 64), 'weight', 'title'),
    ),
    'primary key' => array('path'),
  );

  $schema['menu_links'] = array(
    'description' => 'Contains the individual links within a menu.',
    'fields' => array(
     'menu_name' => array(
        'description' => "The menu name. All links with the same menu name (such as 'navigation') are part of the same menu.",
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'mlid' => array(
        'description' => 'The menu link ID (mlid) is the integer primary key.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'plid' => array(
        'description' => 'The parent link ID (plid) is the mlid of the link above in the hierarchy, or zero if the link is at the top level in its menu.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'link_path' => array(
        'description' => 'The Drupal path or external path this link points to.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'router_path' => array(
        'description' => 'For links corresponding to a Drupal path (external = 0), this connects the link to a {menu_router}.path for joins.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'link_title' => array(
      'description' => 'The text displayed for the link, which may be modified by a title callback stored in {menu_router}.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'translatable' => TRUE,
      ),
      'options' => array(
        'description' => 'A serialized array of options to be passed to the url() or l() function, such as a query string or HTML attributes.',
        'type' => 'blob',
        'not null' => FALSE,
        'translatable' => TRUE,
      ),
      'module' => array(
        'description' => 'The name of the module that generated this link.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => 'system',
      ),
      'hidden' => array(
        'description' => 'A flag for whether the link should be rendered in menus. (1 = a disabled menu item that may be shown on admin screens, -1 = a menu callback, 0 = a normal, visible link)',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'external' => array(
        'description' => 'A flag to indicate if the link points to a full URL starting with a protocol, like http:// (1 = external, 0 = internal).',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'has_children' => array(
        'description' => 'Flag indicating whether any links have this link as a parent (1 = children exist, 0 = no children).',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'expanded' => array(
        'description' => 'Flag for whether this link should be rendered as expanded in menus - expanded links always have their child links displayed, instead of only when the link is in the active trail (1 = expanded, 0 = not expanded)',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'weight' => array(
        'description' => 'Link weight among links in the same menu at the same depth.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'depth' => array(
        'description' => 'The depth relative to the top level. A link with plid == 0 will have depth == 1.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'customized' => array(
        'description' => 'A flag to indicate that the user has manually created or edited the link (1 = customized, 0 = not customized).',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
      'p1' => array(
        'description' => 'The first mlid in the materialized path. If N = depth, then pN must equal the mlid. If depth > 1 then p(N-1) must equal the plid. All pX where X > depth must equal zero. The columns p1 .. p9 are also called the parents.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p2' => array(
        'description' => 'The second mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p3' => array(
        'description' => 'The third mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p4' => array(
        'description' => 'The fourth mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p5' => array(
        'description' => 'The fifth mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p6' => array(
        'description' => 'The sixth mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p7' => array(
        'description' => 'The seventh mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p8' => array(
        'description' => 'The eighth mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'p9' => array(
        'description' => 'The ninth mlid in the materialized path. See p1.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'updated' => array(
        'description' => 'Flag that indicates that this link was generated during the update from Drupal 5.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'small',
      ),
    ),
    'indexes' => array(
      'path_menu' => array(array('link_path', 128), 'menu_name'),
      'menu_plid_expand_child' => array('menu_name', 'plid', 'expanded', 'has_children'),
      'menu_parents' => array('menu_name', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9'),
      'router_path' => array(array('router_path', 128)),
    ),
    'primary key' => array('mlid'),
  );

  $schema['queue'] = array(
    'description' => 'Stores items in queues.',
    'fields' => array(
      'item_id' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique item ID.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The queue name.',
      ),
      'data' => array(
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
        'serialize' => TRUE,
        'description' => 'The arbitrary data for the item.',
      ),
      'expire' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Timestamp when the claim lease expires on the item.',
      ),
      'created' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Timestamp when the item was created.',
      ),
    ),
    'primary key' => array('item_id'),
    'indexes' => array(
      'name_created' => array('name', 'created'),
      'expire' => array('expire'),
    ),
  );

  $schema['registry'] = array(
    'description' => "Each record is a function, class, or interface name and the file it is in.",
    'fields' => array(
      'name'   => array(
        'description' => 'The name of the function, class, or interface.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'type'   => array(
        'description' => 'Either function or class or interface.',
        'type' => 'varchar',
        'length' => 9,
        'not null' => TRUE,
        'default' => '',
      ),
      'filename'   => array(
        'description' => 'Name of the file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'module' => array(
        'description' => 'Name of the module the file belongs to.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''
      ),
      'weight' => array(
        'description' => "The order in which this module's hooks should be invoked relative to other modules. Equal-weighted modules are ordered by name.",
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('name', 'type'),
    'indexes' => array(
      'hook' => array('type', 'weight', 'module'),
    ),
  );

  $schema['registry_file'] = array(
    'description' => "Files parsed to build the registry.",
    'fields' => array(
      'filename'   => array(
        'description' => 'Path to the file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'hash'  => array(
        'description' => "sha-256 hash of the file's contents when last parsed.",
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('filename'),
  );

  $schema['semaphore'] = array(
    'description' => 'Table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached.',
    'fields' => array(
      'name' => array(
        'description' => 'Primary Key: Unique name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''
      ),
      'value' => array(
        'description' => 'A value for the semaphore.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''
      ),
      'expire' => array(
        'description' => 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
        'type' => 'float',
        'size' => 'big',
        'not null' => TRUE
      ),
    ),
    'indexes' => array(
      'value' => array('value'),
      'expire' => array('expire'),
    ),
    'primary key' => array('name'),
  );

  $schema['sequences'] = array(
    'description' => 'Stores IDs.',
    'fields' => array(
      'value' => array(
        'description' => 'The value of the sequence.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
     ),
    'primary key' => array('value'),
  );

  $schema['sessions'] = array(
    'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
    'fields' => array(
      'uid' => array(
        'description' => 'The {users}.uid corresponding to a session, or 0 for anonymous user.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'sid' => array(
        'description' => "A session ID. The value is generated by Drupal's session handlers.",
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
      ),
      'ssid' => array(
        'description' => "Secure session ID. The value is generated by Drupal's session handlers.",
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'hostname' => array(
        'description' => 'The IP address that last used this session ID (sid).',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'timestamp' => array(
        'description' => 'The Unix timestamp when this session last requested a page. Old records are purged by PHP automatically.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'cache' => array(
        'description' => "The time of this user's last post. This is used when the site has specified a minimum_cache_lifetime. See cache_get().",
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'session' => array(
        'description' => 'The serialized contents of $_SESSION, an array of name/value pairs that persists across page requests by this session ID. Drupal loads $_SESSION from here at the start of each request and saves it at the end.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
    ),
    'primary key' => array(
      'sid',
      'ssid',
    ),
    'indexes' => array(
      'timestamp' => array('timestamp'),
      'uid' => array('uid'),
      'ssid' => array('ssid'),
    ),
    'foreign keys' => array(
      'session_user' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  $schema['system'] = array(
    'description' => "A list of all modules, themes, and theme engines that are or have been installed in Drupal's file system.",
    'fields' => array(
      'filename' => array(
        'description' => 'The path of the primary file for this item, relative to the Drupal root; e.g. modules/node/node.module.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'name' => array(
        'description' => 'The name of the item; e.g. node.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'type' => array(
        'description' => 'The type of the item, either module, theme, or theme_engine.',
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
      ),
      'owner' => array(
        'description' => "A theme's 'parent' . Can be either a theme or an engine.",
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'status' => array(
        'description' => 'Boolean indicating whether or not this item is enabled.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'bootstrap' => array(
        'description' => "Boolean indicating whether this module is loaded during Drupal's early bootstrapping phase (e.g. even before the page cache is consulted).",
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'schema_version' => array(
        'description' => "The module's database schema version number. -1 if the module is not installed (its tables do not exist); 0 or the largest N of the module's hook_update_N() function that has either been run or existed when the module was first installed.",
        'type' => 'int',
        'not null' => TRUE,
        'default' => -1,
        'size' => 'small',
      ),
      'weight' => array(
        'description' => "The order in which this module's hooks should be invoked relative to other modules. Equal-weighted modules are ordered by name.",
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'info' => array(
        'description' => "A serialized array containing information from the module's .info file; keys can include name, description, package, version, core, dependencies, and php.",
        'type' => 'blob',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('filename'),
    'indexes' => array(
      'system_list' => array('status', 'bootstrap', 'type', 'weight', 'name'),
      'type_name' => array('type', 'name'),
    ),
  );

  $schema['url_alias'] = array(
    'description' => 'A list of URL aliases for Drupal paths; a user may visit either the source or destination path.',
    'fields' => array(
      'pid' => array(
        'description' => 'A unique path alias identifier.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'source' => array(
        'description' => 'The Drupal path this alias is for; e.g. node/12.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'alias' => array(
        'description' => 'The alias for this path; e.g. title-of-the-story.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'language' => array(
        'description' => "The language this alias is for; if 'und', the alias will be used for unknown languages. Each Drupal path can have an alias for each supported language.",
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'alias_language_pid' => array('alias', 'language', 'pid'),
      'source_language_pid' => array('source', 'language', 'pid'),
    ),
  );

  return $schema;
}

/**
 * The cache schema corresponding to system_update_7054.
 *
 * Drupal 7 adds several new cache tables. Since they all have identical schema
 * this helper function allows them to re-use the same definition, without
 * relying on system_schema(), which may change with future updates.
 */
function system_schema_cache_7054() {
  return array(
    'description' => 'Generic cache table for caching things not separated out into their own tables. Contributed modules may also use this to store cached items.',
    'fields' => array(
      'cid' => array(
        'description' => 'Primary Key: Unique cache ID.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'data' => array(
        'description' => 'A collection of data to cache.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
      'expire' => array(
        'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'created' => array(
        'description' => 'A Unix timestamp indicating when the cache entry was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'serialized' => array(
        'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
        'type' => 'int',
        'size' => 'small',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'expire' => array('expire'),
    ),
    'primary key' => array('cid'),
  );
}


// Updates for core.

function system_update_last_removed() {
  return 6055;
}

/**
 * Implements hook_update_dependencies().
 */
function system_update_dependencies() {
  // system_update_7053() queries the {block} table, so it must run after
  // block_update_7002(), which creates that table.
  $dependencies['system'][7053] = array(
    'block' => 7002,
  );

  // system_update_7061() queries the {node_revision} table, so it must run
  // after node_update_7001(), which renames the {node_revisions} table.
  $dependencies['system'][7061] = array(
    'node' => 7001,
  );

  // system_update_7067() migrates role permissions and therefore must run
  // after the {role} and {role_permission} tables are properly set up, which
  // happens in user_update_7007().
  $dependencies['system'][7067] = array(
    'user' => 7007,
  );

  return $dependencies;
}

/**
 * @defgroup updates-6.x-to-7.x Updates from 6.x to 7.x
 * @{
 * Update functions from 6.x to 7.x.
 */

/**
 * Rename blog and forum permissions to be consistent with other content types.
 */
function system_update_7000() {
  $result = db_query("SELECT rid, perm FROM {permission} ORDER BY rid");
  foreach ($result as $role) {
    $renamed_permission = $role->perm;
    $renamed_permission = preg_replace('/(?<=^|,\ )create\ blog\ entries(?=,|$)/', 'create blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ blog\ entries(?=,|$)/', 'edit own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ blog\ entry(?=,|$)/', 'edit any blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ blog\ entries(?=,|$)/', 'delete own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ blog\ entry(?=,|$)/', 'delete any blog content', $renamed_permission);

    $renamed_permission = preg_replace('/(?<=^|,\ )create\ forum\ topics(?=,|$)/', 'create forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ forum\ topic(?=,|$)/', 'delete any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ forum\ topics(?=,|$)/', 'delete own forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ forum\ topic(?=,|$)/', 'edit any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ forum\ topics(?=,|$)/', 'edit own forum content', $renamed_permission);

    if ($renamed_permission != $role->perm) {
      db_update('permission')
        ->fields(array('perm' => $renamed_permission))
        ->condition('rid', $role->rid)
        ->execute();
    }
  }
}

/**
 * Generate a cron key and save it in the variables table.
 */
function system_update_7001() {
  variable_set('cron_key', drupal_random_key());
}

/**
 * Add a table to store blocked IP addresses.
 */
function system_update_7002() {
  $schema['blocked_ips'] = array(
    'description' => 'Stores blocked IP addresses.',
    'fields' => array(
      'iid' => array(
        'description' => 'Primary Key: unique ID for IP addresses.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'ip' => array(
        'description' => 'IP address',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'blocked_ip' => array('ip'),
    ),
    'primary key' => array('iid'),
  );

  db_create_table('blocked_ips', $schema['blocked_ips']);
}

/**
 * Update {blocked_ips} with valid IP addresses from {access}.
 */
function system_update_7003() {
  $messages = array();
  $type = 'host';
  $result = db_query("SELECT mask FROM {access} WHERE status = :status AND type = :type", array(
    ':status' => 0,
    ':type' => $type,
  ));
  foreach ($result as $blocked) {
    if (filter_var($blocked->mask, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) !== FALSE) {
      db_insert('blocked_ips')
        ->fields(array('ip' => $blocked->mask))
        ->execute();
    }
    else {
      $invalid_host = check_plain($blocked->mask);
      $messages[] = t('The host !host is no longer blocked because it is not a valid IP address.', array('!host' => $invalid_host ));
    }
  }
  if (isset($invalid_host)) {
    drupal_set_message('Drupal no longer supports wildcard IP address blocking. Visitors whose IP addresses match ranges you have previously set using <em>access rules</em> will no longer be blocked from your site when you put the site online. See the <a href="http://drupal.org/node/24302">IP address and referrer blocking Handbook page</a> for alternative methods.', 'warning');
  }
  // Make sure not to block any IP addresses that were specifically allowed by access rules.
  if (!empty($result)) {
    $result = db_query("SELECT mask FROM {access} WHERE status = :status AND type = :type", array(
      ':status' => 1,
      ':type' => $type,
    ));
    $or = db_condition('or');
    foreach ($result as $allowed) {
      $or->condition('ip', $allowed->mask, 'LIKE');
    }
    if (count($or)) {
      db_delete('blocked_ips')
        ->condition($or)
        ->execute();
    }
  }
}

/**
 * Remove hardcoded numeric deltas from all blocks in core.
 */
function system_update_7004(&$sandbox) {
  // Get an array of the renamed block deltas, organized by module.
  $renamed_deltas = array(
    'blog' => array('0' => 'recent'),
    'book' => array('0' => 'navigation'),
    'comment' => array('0' => 'recent'),
    'forum' => array(
      '0' => 'active',
      '1' => 'new',
    ),
    'locale' => array('0' => LANGUAGE_TYPE_INTERFACE),
    'node' => array('0' => 'syndicate'),
    'poll' => array('0' => 'recent'),
    'profile' => array('0' => 'author-information'),
    'search' => array('0' => 'form'),
    'statistics' => array('0' => 'popular'),
    'system' => array('0' => 'powered-by'),
    'user' => array(
      '0' => 'login',
      '1' => 'navigation',
      '2' => 'new',
      '3' => 'online',
    ),
  );

  $moved_deltas = array(
    'user' => array('navigation' => 'system'),
  );

  // Only run this the first time through the batch update.
  if (!isset($sandbox['progress'])) {
    // Rename forum module's block variables.
    $forum_block_num_0 = variable_get('forum_block_num_0');
    if (isset($forum_block_num_0)) {
      variable_set('forum_block_num_active', $forum_block_num_0);
      variable_del('forum_block_num_0');
    }
    $forum_block_num_1 = variable_get('forum_block_num_1');
    if (isset($forum_block_num_1)) {
      variable_set('forum_block_num_new', $forum_block_num_1);
      variable_del('forum_block_num_1');
    }
  }

  update_fix_d7_block_deltas($sandbox, $renamed_deltas, $moved_deltas);

}

/**
 * Remove throttle columns and variables.
 */
function system_update_7005() {
  db_drop_field('blocks', 'throttle');
  db_drop_field('system', 'throttle');
  variable_del('throttle_user');
  variable_del('throttle_anonymous');
  variable_del('throttle_level');
  variable_del('throttle_probability_limiter');
}

/**
 * Convert to new method of storing permissions.
 */
function system_update_7007() {
  // Copy the permissions from the old {permission} table to the new {role_permission} table.
  $messages = array();
  $result = db_query("SELECT rid, perm FROM {permission} ORDER BY rid ASC");
  $query = db_insert('role_permission')->fields(array('rid', 'permission'));
  foreach ($result as $role) {
    foreach (array_unique(explode(', ', $role->perm)) as $perm) {
      $query->values(array(
        'rid' => $role->rid,
        'permission' => $perm,
      ));
    }
    $messages[] = t('Inserted into {role_permission} the permissions for role ID !id', array('!id' => $role->rid));
  }
  $query->execute();
  db_drop_table('permission');

  return implode(', ', $messages);
}

/**
 * Rename the variable for primary links.
 */
function system_update_7009() {
  $current_primary = variable_get('menu_primary_links_source');
  if (isset($current_primary)) {
    variable_set('menu_main_links_source', $current_primary);
    variable_del('menu_primary_links_source');
  }
}

/**
 * Split the 'bypass node access' permission from 'administer nodes'.
 */
function system_update_7011() {
  // Get existing roles that can 'administer nodes'.
  $rids = array();
  $rids = db_query("SELECT rid FROM {role_permission} WHERE permission = :perm", array(':perm' => 'administer nodes'))->fetchCol();
  // None found.
  if (empty($rids)) {
    return;
  }
  $insert = db_insert('role_permission')->fields(array('rid', 'permission'));
  foreach ($rids as $rid) {
    $insert->values(array(
    'rid' => $rid,
    'permission' => 'bypass node access',
    ));
  }
  $insert->execute();
}

/**
 * Convert default time zone offset to default time zone name.
 */
function system_update_7013() {
  $timezone = NULL;
  $timezones = system_time_zones();
  // If the contributed Date module set a default time zone name, use this
  // setting as the default time zone.
  if (($timezone_name = variable_get('date_default_timezone_name')) && isset($timezones[$timezone_name])) {
    $timezone = $timezone_name;
  }
  // If the contributed Event module has set a default site time zone, look up
  // the time zone name and use it as the default time zone.
  if (!$timezone && ($timezone_id = variable_get('date_default_timezone_id', 0))) {
    try {
      $timezone_name = db_query('SELECT name FROM {event_timezones} WHERE timezone = :timezone_id', array(':timezone_id' => $timezone_id))->fetchField();
      if (($timezone_name = str_replace(' ', '_', $timezone_name)) && isset($timezones[$timezone_name])) {
        $timezone = $timezone_name;
      }
    }
    catch (PDOException $e) {
      // Ignore error if event_timezones table does not exist or unexpected
      // schema found.
    }
  }

  // Check to see if timezone was overriden in update_prepare_d7_bootstrap().
  $offset = variable_get('date_temporary_timezone');
  // If not, use the default.
  if (!isset($offset)) {
    $offset = variable_get('date_default_timezone', 0);
  }

  // If the previous default time zone was a non-zero offset, guess the site's
  // intended time zone based on that offset and the server's daylight saving
  // time status.
  if (!$timezone && $offset) {
    $timezone_name = timezone_name_from_abbr('', intval($offset), date('I'));
    if ($timezone_name && isset($timezones[$timezone_name])) {
      $timezone = $timezone_name;
    }
  }
  // Otherwise, the default time zone offset was zero, which is UTC.
  if (!$timezone) {
    $timezone = 'UTC';
  }
  variable_set('date_default_timezone', $timezone);
  drupal_set_message(format_string('The default time zone has been set to %timezone. Check the <a href="@config-url">date and time configuration page</a> to configure it correctly.', array('%timezone' => $timezone, '@config-url' => url('admin/config/regional/settings'))), 'warning');
  // Remove temporary override.
  variable_del('date_temporary_timezone');
}

/**
 * Change the user logout path.
 */
function system_update_7015() {
  db_update('menu_links')
    ->fields(array('link_path' => 'user/logout'))
    ->condition('link_path', 'logout')
    ->execute();
  db_update('menu_links')
    ->fields(array('router_path' => 'user/logout'))
    ->condition('router_path', 'logout')
    ->execute();

  db_update('menu_links')
    ->fields(array(
      'menu_name' => 'user-menu',
      'plid' => 0,
    ))
    ->condition(db_or()
      ->condition('link_path', 'user/logout')
      ->condition('router_path', 'user/logout')
    )
    ->condition('module', 'system')
    ->condition('customized', 0)
    ->execute();
}

/**
 * Remove custom datatype *_unsigned in PostgreSQL.
 */
function system_update_7016() {
  // Only run these queries if the driver used is pgsql.
  if (db_driver() == 'pgsql') {
    $result = db_query("SELECT c.relname AS table, a.attname AS field,
                        pg_catalog.format_type(a.atttypid, a.atttypmod) AS type
                        FROM pg_catalog.pg_attribute a
                        LEFT JOIN pg_class c ON (c.oid =  a.attrelid)
                        WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relkind = 'r'
                        AND pg_catalog.format_type(a.atttypid, a.atttypmod) LIKE '%unsigned%'");
    foreach ($result as $row) {
      switch ($row->type) {
        case 'smallint_unsigned':
          $datatype = 'int';
          break;
        case 'int_unsigned':
        case 'bigint_unsigned':
        default:
          $datatype = 'bigint';
          break;
      }
      db_query('ALTER TABLE ' . $row->table . ' ALTER COLUMN "' . $row->field . '" TYPE ' . $datatype);
      db_query('ALTER TABLE ' . $row->table . ' ADD CHECK ("' . $row->field . '" >= 0)');
    }
    db_query('DROP DOMAIN IF EXISTS smallint_unsigned');
    db_query('DROP DOMAIN IF EXISTS int_unsigned');
    db_query('DROP DOMAIN IF EXISTS bigint_unsigned');
  }
}

/**
 * Change the theme setting 'toggle_node_info' into a per content type variable.
 */
function system_update_7017() {
  // Get the global theme settings.
  $settings = variable_get('theme_settings', array());
  // Get the settings of the default theme.
  $settings = array_merge($settings, variable_get('theme_' . variable_get('theme_default', 'garland') . '_settings', array()));

  $types = _update_7000_node_get_types();
  foreach ($types as $type) {
    if (isset($settings['toggle_node_info_' . $type->type])) {
      variable_set('node_submitted_' . $type->type, $settings['toggle_node_info_' . $type->type]);
    }
  }

  // Unset deprecated 'toggle_node_info' theme settings.
  $theme_settings = variable_get('theme_settings', array());
  foreach ($theme_settings as $setting => $value) {
    if (substr($setting, 0, 16) == 'toggle_node_info') {
      unset($theme_settings[$setting]);
    }
  }
  variable_set('theme_settings', $theme_settings);
}

/**
 * Shorten the {system}.type column and modify indexes.
 */
function system_update_7018() {
  db_drop_index('system', 'modules');
  db_drop_index('system', 'type_name');
  db_change_field('system', 'type', 'type', array('type' => 'varchar', 'length' => 12, 'not null' => TRUE, 'default' => ''));
  db_add_index('system', 'type_name', array('type', 'name'));
}

/**
 * Enable field and field_ui modules.
 */
function system_update_7020() {
  $module_list = array('field_sql_storage', 'field', 'field_ui');
  module_enable($module_list, FALSE);
}

/**
 * Change the PHP for settings permission.
 */
function system_update_7021() {
  db_update('role_permission')
    ->fields(array('permission' => 'use PHP for settings'))
    ->condition('permission', 'use PHP for block visibility')
    ->execute();
}

/**
 * Enable field type modules.
 */
function system_update_7027() {
  $module_list = array('text', 'number', 'list', 'options');
  module_enable($module_list, FALSE);
}

/**
 * Add new 'view own unpublished content' permission for authenticated users.
 * Preserves legacy behavior from Drupal 6.x.
 */
function system_update_7029() {
  db_insert('role_permission')
    ->fields(array(
      'rid' => DRUPAL_AUTHENTICATED_RID,
      'permission' => 'view own unpublished content',
    ))
    ->execute();
}

/**
* Alter field hostname to identifier in the {flood} table.
 */
function system_update_7032() {
  db_drop_index('flood', 'allow');
  db_change_field('flood', 'hostname', 'identifier', array('type' => 'varchar', 'length' => 128, 'not null' => TRUE, 'default' => ''));
  db_add_index('flood', 'allow', array('event', 'identifier', 'timestamp'));
}

/**
 * Move CACHE_AGGRESSIVE to CACHE_NORMAL.
 */
function system_update_7033() {
  if (variable_get('cache') == 2) {
    variable_set('cache', 1);
    return t('Aggressive caching was disabled and replaced with normal caching. Read the page caching section in default.settings.php for more information on how to enable similar functionality.');
  }
}

/**
 * Migrate the file path settings and create the new {file_managed} table.
 */
function system_update_7034() {
  $files_directory = variable_get('file_directory_path', NULL);
  if (variable_get('file_downloads', 1) == 1) {
    // Our default is public, so we don't need to set anything.
    if (!empty($files_directory)) {
      variable_set('file_public_path', $files_directory);
    }
  }
  elseif (variable_get('file_downloads', 1) == 2) {
    variable_set('file_default_scheme', 'private');
    if (!empty($files_directory)) {
      variable_set('file_private_path', $files_directory);
    }
  }
  variable_del('file_downloads');

  $schema['file_managed'] = array(
    'description' => 'Stores information for uploaded files.',
    'fields' => array(
      'fid' => array(
        'description' => 'File ID.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'The {user}.uid of the user who is associated with the file.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'filename' => array(
        'description' => 'Name of the file with no path components. This may differ from the basename of the filepath if the file is renamed to avoid overwriting an existing file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'binary' => TRUE,
      ),
      'uri' => array(
        'description' => 'URI of file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'binary' => TRUE,
      ),
      'filemime' => array(
        'description' => "The file's MIME type.",
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'filesize' => array(
        'description' => 'The size of the file in bytes.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'status' => array(
        'description' => 'A field indicating the status of the file. Two status are defined in core: temporary (0) and permanent (1). Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during a cron run.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
      ),
      'timestamp' => array(
        'description' => 'UNIX timestamp for when the file was added.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'uid' => array('uid'),
      'status' => array('status'),
      'timestamp' => array('timestamp'),
    ),
    'unique keys' => array(
      'uri' => array('uri'),
    ),
    'primary key' => array('fid'),
  );

  db_create_table('file_managed', $schema['file_managed']);
}

/**
 * Split the 'access site in maintenance mode' permission from 'administer site configuration'.
 */
function system_update_7036() {
  // Get existing roles that can 'administer site configuration'.
  $rids = db_query("SELECT rid FROM {role_permission} WHERE permission = :perm", array(':perm' => 'administer site configuration'))->fetchCol();
  // None found.
  if (empty($rids)) {
    return;
  }
  $insert = db_insert('role_permission')->fields(array('rid', 'permission'));
  foreach ($rids as $rid) {
    $insert->values(array(
      'rid' => $rid,
      'permission' => 'access site in maintenance mode',
    ));
  }
  $insert->execute();
}

/**
 * Upgrade the {url_alias} table and create a cache bin for path aliases.
 */
function system_update_7042() {
  // update_fix_d7_requirements() adds 'fake' source and alias columns to
  // allow bootstrap to run without fatal errors. Remove those columns now
  // so that we can rename properly.
  db_drop_field('url_alias', 'source');
  db_drop_field('url_alias', 'alias');

  // Drop indexes.
  db_drop_index('url_alias', 'src_language_pid');
  db_drop_unique_key('url_alias', 'dst_language_pid');
  // Rename the fields, and increase their length to 255 characters.
  db_change_field('url_alias', 'src', 'source', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
  db_change_field('url_alias', 'dst', 'alias', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
  // Add indexes back. We replace the unique key with an index since it never
  // provided any meaningful unique constraint ('pid' is a primary key).
  db_add_index('url_alias', 'source_language_pid', array('source', 'language', 'pid'));
  db_add_index('url_alias', 'alias_language_pid', array('alias', 'language', 'pid'));

  // Now that the URL aliases are correct, we can rebuild the whitelist.
  drupal_path_alias_whitelist_rebuild();
}

/**
 * Drop the actions_aid table.
 */
function system_update_7044() {
  // The current value of the increment has been taken into account when
  // creating the sequences table in update_fix_d7_requirements().
  db_drop_table('actions_aid');
}

/**
 * Add expiration field to the {flood} table.
 */
function system_update_7045() {
  db_add_field('flood', 'expiration', array('description' => 'Expiration timestamp. Expired events are purged on cron run.', 'type' => 'int', 'not null' => TRUE, 'default' => 0));
  db_add_index('flood', 'purge', array('expiration'));
}

/**
 * Switch from the Minnelli theme if it is the default or admin theme.
 */
function system_update_7046() {
  if (variable_get('theme_default') == 'minnelli' || variable_get('admin_theme') == 'minnelli') {
    // Make sure Garland is enabled.
    db_update('system')
      ->fields(array('status' => 1))
      ->condition('type', 'theme')
      ->condition('name', 'garland')
      ->execute();
    if (variable_get('theme_default') != 'garland') {
      // If the default theme isn't Garland, transfer all of Minnelli's old
      // settings to Garland.
      $settings = variable_get('theme_minnelli_settings', array());
      // Set the theme setting width to "fixed" to match Minnelli's old layout.
      $settings['garland_width'] = 'fixed';
      variable_set('theme_garland_settings', $settings);
      // Remove Garland's color files since they won't match Minnelli's.
      foreach (variable_get('color_garland_files', array()) as $file) {
        @drupal_unlink($file);
      }
      if (isset($file) && $file = dirname($file)) {
        @drupal_rmdir($file);
      }
      variable_del('color_garland_palette');
      variable_del('color_garland_stylesheets');
      variable_del('color_garland_logo');
      variable_del('color_garland_files');
      variable_del('color_garland_screenshot');
    }
    if (variable_get('theme_default') == 'minnelli') {
      variable_set('theme_default', 'garland');
    }
    if (variable_get('admin_theme') == 'minnelli') {
      variable_set('admin_theme', 'garland');
    }
  }
}

/**
 * Normalize the front page path variable.
 */
function system_update_7047() {
  variable_set('site_frontpage', drupal_get_normal_path(variable_get('site_frontpage', 'node')));
}

/**
 * Convert path languages from the empty string to LANGUAGE_NONE.
 */
function system_update_7048() {
  db_update('url_alias')
    ->fields(array('language' => LANGUAGE_NONE))
    ->condition('language', '')
    ->execute();
}

/**
 * Rename 'Default' profile to 'Standard.'
 */
function system_update_7049() {
  if (variable_get('install_profile', 'standard') == 'default') {
    variable_set('install_profile', 'standard');
  }
}

/**
 * Change {batch}.id column from serial to regular int.
 */
function system_update_7050() {
  db_change_field('batch', 'bid', 'bid', array('description' => 'Primary Key: Unique batch ID.', 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE));
}

/**
 * make the IP field IPv6 compatible
 */
function system_update_7051() {
  db_change_field('blocked_ips', 'ip', 'ip', array('description' => 'IP address', 'type' => 'varchar', 'length' => 40, 'not null' => TRUE, 'default' => ''));
}

/**
 * Rename file to include_file in {menu_router} table.
 */
function system_update_7052() {
  db_change_field('menu_router', 'file', 'include_file', array('type' => 'text', 'size' => 'medium'));
}

/**
 * Upgrade standard blocks and menus.
 */
function system_update_7053() {
  if (db_table_exists('menu_custom')) {
    // Create the same menus as in menu_install().
    db_insert('menu_custom')
      ->fields(array('menu_name' => 'user-menu', 'title' => 'User Menu', 'description' => "The <em>User</em> menu contains links related to the user's account, as well as the 'Log out' link."))
      ->execute();

    db_insert('menu_custom')
      ->fields(array('menu_name' => 'management', 'title' => 'Management', 'description' => "The <em>Management</em> menu contains links for administrative tasks."))
      ->execute();
  }

  block_flush_caches();

  // Show the new menu blocks along the navigation block.
  $blocks = db_query("SELECT theme, status, region, weight, visibility, pages FROM {block} WHERE module = 'system' AND delta = 'navigation'");
  $deltas = db_or()
    ->condition('delta', 'user-menu')
    ->condition('delta', 'management');

  foreach ($blocks as $block) {
    db_update('block')
      ->fields(array(
        'status' => $block->status,
        'region' => $block->region,
        'weight' => $block->weight,
        'visibility' => $block->visibility,
        'pages' => $block->pages,
      ))
      ->condition('theme', $block->theme)
      ->condition('module', 'system')
      ->condition($deltas)
      ->execute();
  }
}

/**
 * Remove {cache_*}.headers columns.
 */
function system_update_7054() {
  // Update: update_fix_d7_requirements() installs this version for cache_path
  // already, so we don't include it in this particular update. It should be
  // included in later updates though.
  $cache_tables = array(
    'cache' => 'Generic cache table for caching things not separated out into their own tables. Contributed modules may also use this to store cached items.',
    'cache_form' => 'Cache table for the form system to store recently built forms and their storage data, to be used in subsequent page requests.',
    'cache_page' => 'Cache table used to store compressed pages for anonymous users, if page caching is enabled.',
    'cache_menu' => 'Cache table for the menu system to store router information as well as generated link trees for various menu/page/user combinations.',
  );
  $schema = system_schema_cache_7054();
  foreach ($cache_tables as $table => $description) {
    $schema['description'] = $description;
    db_drop_table($table);
    db_create_table($table, $schema);
  }
}

/**
 * Converts fields that store serialized variables from text to blob.
 */
function system_update_7055() {
  $spec = array(
    'description' => 'The value of the variable.',
    'type' => 'blob',
    'not null' => TRUE,
    'size' => 'big',
    'translatable' => TRUE,
  );
  db_change_field('variable', 'value', 'value', $spec);

  $spec = array(
    'description' => 'Parameters to be passed to the callback function.',
    'type' => 'blob',
    'not null' => TRUE,
    'size' => 'big',
  );
  db_change_field('actions', 'parameters', 'parameters', $spec);

  $spec = array(
    'description' => 'A serialized array containing the processing data for the batch.',
    'type' => 'blob',
    'not null' => FALSE,
    'size' => 'big',
  );
  db_change_field('batch', 'batch', 'batch', $spec);

  $spec = array(
    'description' => 'A serialized array of function names (like node_load) to be called to load an object corresponding to a part of the current path.',
    'type' => 'blob',
    'not null' => TRUE,
  );
  db_change_field('menu_router', 'load_functions', 'load_functions', $spec);

  $spec = array(
    'description' => 'A serialized array of function names (like user_uid_optional_to_arg) to be called to replace a part of the router path with another string.',
    'type' => 'blob',
    'not null' => TRUE,
  );
  db_change_field('menu_router', 'to_arg_functions', 'to_arg_functions', $spec);

  $spec = array(
    'description' => 'A serialized array of arguments for the access callback.',
    'type' => 'blob',
    'not null' => FALSE,
  );
  db_change_field('menu_router', 'access_arguments', 'access_arguments', $spec);

  $spec = array(
    'description' => 'A serialized array of arguments for the page callback.',
    'type' => 'blob',
    'not null' => FALSE,
  );
  db_change_field('menu_router', 'page_arguments', 'page_arguments', $spec);

  $spec = array(
    'description' => 'A serialized array of options to be passed to the url() or l() function, such as a query string or HTML attributes.',
    'type' => 'blob',
    'not null' => FALSE,
    'translatable' => TRUE,
  );
  db_change_field('menu_links', 'options', 'options', $spec);

  $spec = array(
    'description' => 'The serialized contents of $_SESSION, an array of name/value pairs that persists across page requests by this session ID. Drupal loads $_SESSION from here at the start of each request and saves it at the end.',
    'type' => 'blob',
    'not null' => FALSE,
    'size' => 'big',
  );
  db_change_field('sessions', 'session', 'session', $spec);

  $spec = array(
    'description' => "A serialized array containing information from the module's .info file; keys can include name, description, package, version, core, dependencies, and php.",
    'type' => 'blob',
    'not null' => FALSE,
  );
  db_change_field('system', 'info', 'info', $spec);
}

/**
 * Increase the size of session-ids.
 */
function system_update_7057() {
  $spec = array(
    'description' => "A session ID. The value is generated by PHP's Session API.",
    'type' => 'varchar',
    'length' => 128,
    'not null' => TRUE,
    'default' => '',
  );
  db_change_field('sessions', 'sid', 'sid', $spec);
}

/**
 * Remove cron semaphore variable.
 */
function system_update_7058() {
  variable_del('cron_semaphore');
}

/**
 * Create the {file_usage} table.
 */
function system_update_7059() {
  $spec = array(
    'description' => 'Track where a file is used.',
    'fields' => array(
      'fid' => array(
        'description' => 'File ID.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'module' => array(
        'description' => 'The name of the module that is using the file.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'type' => array(
        'description' => 'The name of the object type in which the file is used.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'id' => array(
        'description' => 'The primary key of the object using the file.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'count' => array(
        'description' => 'The number of times this file is used by this object.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('fid', 'type', 'id', 'module'),
    'indexes' => array(
      'type_id' => array('type', 'id'),
      'fid_count' => array('fid', 'count'),
      'fid_module' => array('fid', 'module'),
    ),
  );
  db_create_table('file_usage', $spec);
}

/**
 * Create fields in preparation for migrating upload.module to file.module.
 */
function system_update_7060() {
  if (!db_table_exists('upload')) {
    return;
  }

  if (!db_query_range('SELECT 1 FROM {upload}', 0, 1)->fetchField()) {
    // There is nothing to migrate. Delete variables and the empty table. There
    // is no need to create fields that are not going to be used.
    foreach (_update_7000_node_get_types() as $node_type) {
      variable_del('upload_' . $node_type->type);
    }
    db_drop_table('upload');
    return;
  }

  // Check which node types have upload.module attachments enabled.
  $context['types'] = array();
  foreach (_update_7000_node_get_types() as $node_type) {
    if (variable_get('upload_' . $node_type->type, 0)) {
      $context['types'][$node_type->type] = $node_type->type;
    }
  }

  // The {upload} table will be deleted when this update is complete so we
  // want to be careful to migrate all the data, even for node types that
  // may have had attachments disabled after files were uploaded. Look for
  // any other node types referenced by the upload records and add those to
  // the list. The admin can always remove the field later.
  $results = db_query('SELECT DISTINCT type FROM {node} n INNER JOIN {node_revision} nr ON n.nid = nr.nid INNER JOIN {upload} u ON nr.vid = u.vid');
  foreach ($results as $row) {
    if (!isset($context['types'][$row->type])) {
      drupal_set_message(t('The content type %rowtype had uploads disabled but contained uploaded file data. Uploads have been re-enabled to migrate the existing data. You may delete the "File attachments" field in the %rowtype type if this data is not necessary.', array('%rowtype' => $row->type)));
      $context['types'][$row->type] = $row->type;
    }
  }

  // Create a single "upload" field on all the content types that have uploads
  // enabled, then add an instance to each enabled type.
  if (count($context['types']) > 0) {
    module_enable(array('file'));
    $field = array(
      'field_name' => 'upload',
      'type' => 'file',
      'module' => 'file',
      'locked' => FALSE,
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'translatable' => FALSE,
      'settings' => array(
        'display_field' => 1,
        'display_default' => variable_get('upload_list_default', 1),
        'uri_scheme' => file_default_scheme(),
        'default_file' => 0,
      ),
    );

    $upload_size = variable_get('upload_uploadsize_default', 1);
    $instance = array(
      'field_name' => 'upload',
      'entity_type' => 'node',
      'bundle' => NULL,
      'label' => 'File attachments',
      'required' => 0,
      'description' => '',
      'widget' => array(
        'weight' => '1',
        'settings' => array(
          'progress_indicator' => 'throbber',
        ),
        'type' => 'file_generic',
      ),
      'settings' => array(
        'max_filesize' => $upload_size ? ($upload_size . ' MB') : '',
        'file_extensions' => variable_get('upload_extensions_default', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
        'file_directory' => '',
        'description_field' => 1,
      ),
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'file_table',
          'settings' => array(),
          'weight' => 0,
          'module' => 'file',
        ),
        'full' => array(
          'label' => 'hidden',
          'type' => 'file_table',
          'settings' => array(),
          'weight' => 0,
          'module' => 'file',
        ),
        'teaser' => array(
          'label' => 'hidden',
          'type' => 'hidden',
          'settings' => array(),
          'weight' => 0,
          'module' => NULL,
        ),
        'rss' => array(
          'label' => 'hidden',
          'type' => 'file_table',
          'settings' => array(),
          'weight' => 0,
          'module' => 'file',
        ),
      ),
    );

    // Create the field.
    _update_7000_field_create_field($field);

    // Create the instances.
    foreach ($context['types'] as $bundle) {
      $instance['bundle'] = $bundle;
      _update_7000_field_create_instance($field, $instance);
      // Now that the instance is created, we can safely delete any legacy
      // node type information.
      variable_del('upload_' . $bundle);
    }
  }
  else {
    // No uploads or content types with uploads enabled.
    db_drop_table('upload');
  }
}

/**
 * Migrate upload.module data to the newly created file field.
 */
function system_update_7061(&$sandbox) {
  if (!db_table_exists('upload')) {
    return;
  }

  if (!isset($sandbox['progress'])) {
    // Delete stale rows from {upload} where the fid is not in the {files} table.
    db_delete('upload')
      ->notExists(
        db_select('files', 'f')
        ->fields('f', array('fid'))
        ->where('f.fid = {upload}.fid')
      )
      ->execute();

    // Delete stale rows from {upload} where the vid is not in the
    // {node_revision} table. The table has already been renamed in
    // node_update_7001().
    db_delete('upload')
      ->notExists(
        db_select('node_revision', 'nr')
        ->fields('nr', array('vid'))
        ->where('nr.vid = {upload}.vid')
      )
      ->execute();

    // Retrieve a list of node revisions that have uploaded files attached.
    // DISTINCT queries are expensive, especially when paged, so we store the
    // data in its own table for the duration of the update.
    if (!db_table_exists('system_update_7061')) {
      $table = array(
        'description' => t('Stores temporary data for system_update_7061.'),
        'fields' => array('vid' => array('type' => 'int')),
        'primary key' => array('vid'),
      );
      db_create_table('system_update_7061', $table);
    }
    $query = db_select('upload', 'u');
    $query->distinct();
    $query->addField('u','vid');
    db_insert('system_update_7061')
      ->from($query)
      ->execute();

    // Retrieve a list of duplicate files with the same filepath. Only the
    // most-recently uploaded of these will be moved to the new {file_managed}
    // table (and all references will be updated to point to it), since
    // duplicate file URIs are not allowed in Drupal 7.
    // Since the Drupal 6 to 7 upgrade path leaves the {files} table behind
    // after it's done, custom or contributed modules which need to migrate
    // file references of their own can use a similar query to determine the
    // file IDs that duplicate filepaths were mapped to.
    $sandbox['duplicate_filepath_fids_to_use'] = db_query("SELECT filepath, MAX(fid) FROM {files} GROUP BY filepath HAVING COUNT(*) > 1")->fetchAllKeyed();

    // Initialize batch update information.
    $sandbox['progress'] = 0;
    $sandbox['last_vid_processed'] = -1;
    $sandbox['max'] = db_query("SELECT COUNT(*) FROM {system_update_7061}")->fetchField();
  }

  // Determine vids for this batch.
  // Process all files attached to a given revision during the same batch.
  $limit = variable_get('upload_update_batch_size', 100);
  $vids = db_query_range('SELECT vid FROM {system_update_7061} WHERE vid > :lastvid ORDER BY vid', 0, $limit, array(':lastvid' => $sandbox['last_vid_processed']))
    ->fetchCol();

  // Retrieve information on all the files attached to these revisions.
  if (!empty($vids)) {
    $node_revisions = array();
    $result = db_query('SELECT u.fid, u.vid, u.list, u.description, n.nid, n.type, u.weight FROM {upload} u INNER JOIN {node_revision} nr ON u.vid = nr.vid INNER JOIN {node} n ON n.nid = nr.nid WHERE u.vid IN (:vids) ORDER BY u.vid, u.weight, u.fid', array(':vids' => $vids));
    foreach ($result as $record) {
      // For each uploaded file, retrieve the corresponding data from the old
      // files table (since upload doesn't know about the new entry in the
      // file_managed table).
      $file = db_select('files', 'f')
        ->fields('f', array('fid', 'uid', 'filename', 'filepath', 'filemime', 'filesize', 'status', 'timestamp'))
        ->condition('f.fid', $record->fid)
        ->execute()
        ->fetchAssoc();
      if (!$file) {
        continue;
      }

      // If this file has a duplicate filepath, replace it with the
      // most-recently uploaded file that has the same filepath.
      if (isset($sandbox['duplicate_filepath_fids_to_use'][$file['filepath']]) && $record->fid != $sandbox['duplicate_filepath_fids_to_use'][$file['filepath']]) {
        $file = db_select('files', 'f')
          ->fields('f', array('fid', 'uid', 'filename', 'filepath', 'filemime', 'filesize', 'status', 'timestamp'))
          ->condition('f.fid', $sandbox['duplicate_filepath_fids_to_use'][$file['filepath']])
          ->execute()
          ->fetchAssoc();
      }

      // Add in the file information from the upload table.
      $file['description'] = $record->description;
      $file['display'] = $record->list;

      // Create one record for each revision that contains all the uploaded
      // files.
      $node_revisions[$record->vid]['nid'] = $record->nid;
      $node_revisions[$record->vid]['vid'] = $record->vid;
      $node_revisions[$record->vid]['type'] = $record->type;
      $node_revisions[$record->vid]['file'][LANGUAGE_NONE][] = $file;
    }

    // Now that we know which files belong to which revisions, update the
    // files'// database entries, and save a reference to each file in the
    // upload field on their node revisions.
    $basename = variable_get('file_directory_path', conf_path() . '/files');
    $scheme = file_default_scheme() . '://';
    foreach ($node_revisions as $vid => $revision) {
      foreach ($revision['file'][LANGUAGE_NONE] as $delta => $file) {
        // We will convert filepaths to URI using the default scheme
        // and stripping off the existing file directory path.
        $file['uri'] = $scheme . preg_replace('!^' . preg_quote($basename) . '!', '', $file['filepath']);
        // Normalize the URI but don't call file_stream_wrapper_uri_normalize()
        // directly, since that is a higher-level API function which invokes
        // hooks while validating the scheme, and those will not work during
        // the upgrade. Instead, use a simpler version that just assumes the
        // scheme from above is already valid.
        if (($file_uri_scheme = file_uri_scheme($file['uri'])) && ($file_uri_target = file_uri_target($file['uri']))) {
          $file['uri'] = $file_uri_scheme . '://' . $file_uri_target;
        }
        unset($file['filepath']);
        // Insert into the file_managed table.
        // Each fid should only be stored once in file_managed.
        db_merge('file_managed')
          ->key(array(
            'fid' => $file['fid'],
          ))
          ->fields(array(
            'uid' => $file['uid'],
            'filename' => $file['filename'],
            'uri' => $file['uri'],
            'filemime' => $file['filemime'],
            'filesize' => $file['filesize'],
            'status' => $file['status'],
            'timestamp' => $file['timestamp'],
          ))
          ->execute();

        // Add the usage entry for the file.
        $file = (object) $file;
        file_usage_add($file, 'file', 'node', $revision['nid']);

        // Update the node revision's upload file field with the file data.
        $revision['file'][LANGUAGE_NONE][$delta] = array('fid' => $file->fid, 'display' => $file->display, 'description' => $file->description);
      }

      // Write the revision's upload field data into the field_upload tables.
      $node = (object) $revision;
      _update_7000_field_sql_storage_write('node', $node->type, $node->nid, $node->vid, 'upload', $node->file);

      // Update our progress information for the batch update.
      $sandbox['progress']++;
      $sandbox['last_vid_processed'] = $vid;
    }
  }

  // If less than limit node revisions were processed, the update process is
  // finished.
  if (count($vids) < $limit) {
    $finished = TRUE;
  }

  // If there's no max value then there's nothing to update and we're finished.
  if (empty($sandbox['max']) || isset($finished)) {
    db_drop_table('upload');
    db_drop_table('system_update_7061');
    return t('Upload module has been migrated to File module.');
  }
  else {
    // Indicate our current progress to the batch update system.
    $sandbox['#finished'] = $sandbox['progress'] / $sandbox['max'];
  }
}

/**
 * Replace 'system_list' index with 'bootstrap' index on {system}.
 */
function system_update_7062() {
  db_drop_index('system', 'bootstrap');
  db_drop_index('system', 'system_list');
  db_add_index('system', 'system_list', array('status', 'bootstrap', 'type', 'weight', 'name'));
}

/**
 * Delete {menu_links} records for 'type' => MENU_CALLBACK which would not appear in a fresh install.
 */
function system_update_7063() {
  // For router items where 'type' => MENU_CALLBACK, {menu_router}.type is
  // stored as 4 in Drupal 6, and 0 in Drupal 7. Fortunately Drupal 7 doesn't
  // store any types as 4, so delete both.
  $result = db_query('SELECT ml.mlid FROM {menu_links} ml INNER JOIN {menu_router} mr ON ml.router_path = mr.path WHERE ml.module = :system AND ml.customized = 0 AND mr.type IN(:callbacks)', array(':callbacks' => array(0, 4), ':system' => 'system'));
  foreach ($result as $record) {
    db_delete('menu_links')->condition('mlid', $record->mlid)->execute();
  }
}

/**
 * Remove block_callback field from {menu_router}.
 */
function system_update_7064() {
  db_drop_field('menu_router', 'block_callback');
}

/**
 * Remove the default value for sid.
 */
function system_update_7065() {
  $spec = array(
    'description' => "A session ID. The value is generated by Drupal's session handlers.",
    'type' => 'varchar',
    'length' => 128,
    'not null' => TRUE,
  );
  db_drop_primary_key('sessions');
  db_change_field('sessions', 'sid', 'sid', $spec, array('primary key' => array('sid', 'ssid')));
  // Delete any sessions with empty session ID.
  db_delete('sessions')->condition('sid', '')->execute();
}

/**
 * Migrate the 'file_directory_temp' variable.
 */
function system_update_7066() {
  $d6_file_directory_temp = variable_get('file_directory_temp', file_directory_temp());
  variable_set('file_temporary_path', $d6_file_directory_temp);
  variable_del('file_directory_temp');
}

/**
 * Grant administrators permission to view the administration theme.
 */
function system_update_7067() {
  // Users with access to administration pages already see the administration
  // theme in some places (if one is enabled on the site), so we want them to
  // continue seeing it.
  $admin_roles = user_roles(FALSE, 'access administration pages');
  foreach (array_keys($admin_roles) as $rid) {
    _update_7000_user_role_grant_permissions($rid, array('view the administration theme'), 'system');
  }
  // The above check is not guaranteed to reach all administrative users of the
  // site, so if the site is currently using an administration theme, display a
  // message also.
  if (variable_get('admin_theme')) {
    if (empty($admin_roles)) {
      drupal_set_message('The new "View the administration theme" permission is required in order to view your site\'s administration theme. You can grant this permission to your site\'s administrators on the <a href="' . url('admin/people/permissions', array('fragment' => 'module-system')) . '">permissions page</a>.');
    }
    else {
      drupal_set_message('The new "View the administration theme" permission is required in order to view your site\'s administration theme. This permission has been automatically granted to the following roles: <em>' . check_plain(implode(', ', $admin_roles)) . '</em>. You can grant this permission to other roles on the <a href="' . url('admin/people/permissions', array('fragment' => 'module-system')) . '">permissions page</a>.');
    }
  }
}

/**
 * Update {url_alias}.language description.
 */
function system_update_7068() {
  $spec = array(
    'description' => "The language this alias is for; if 'und', the alias will be used for unknown languages. Each Drupal path can have an alias for each supported language.",
    'type' => 'varchar',
    'length' => 12,
    'not null' => TRUE,
    'default' => '',
  );
  db_change_field('url_alias', 'language', 'language', $spec);
}

/**
 * Remove the obsolete 'site_offline' variable.
 *
 * @see update_fix_d7_requirements()
 */
function system_update_7069() {
  variable_del('site_offline');
}

/**
 * @} End of "defgroup updates-6.x-to-7.x".
 * The next series of updates should start at 8000.
 */

/**
 * @defgroup updates-7.x-extra Extra updates for 7.x
 * @{
 * Update functions between 7.x versions.
 */

/**
 * Remove the obsolete 'drupal_badge_color' and 'drupal_badge_size' variables.
 */
function system_update_7070() {
  variable_del('drupal_badge_color');
  variable_del('drupal_badge_size');
}

/**
 * Add index missed during upgrade, and fix field default.
 */
function system_update_7071() {
  db_drop_index('date_format_type', 'title');
  db_add_index('date_format_type', 'title', array('title'));
  db_change_field('registry', 'filename', 'filename', array(
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
  ));
}

/**
 * Remove the obsolete 'site_offline_message' variable.
 *
 * @see update_fix_d7_requirements()
 */
function system_update_7072() {
  variable_del('site_offline_message');
}

/**
 * Add binary to {file_managed}, in case system_update_7034() was run without
 * it.
 */
function system_update_7073() {
  db_change_field('file_managed', 'filename', 'filename', array(
    'description' => 'Name of the file with no path components. This may differ from the basename of the URI if the file is renamed to avoid overwriting an existing file.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
    'binary' => TRUE,
  ));
  db_drop_unique_key('file_managed', 'uri');
  db_change_field('file_managed', 'uri', 'uri', array(
    'description' => 'The URI to access the file (either local or remote).',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
    'binary' => TRUE,
  ));
  db_add_unique_key('file_managed', 'uri', array('uri'));
}

/**
 * This update has been removed and will not run.
 */
function system_update_7074() {
  // This update function previously converted menu_links query strings to
  // arrays. It has been removed for now due to incompatibility with
  // PostgreSQL.
}

/**
 * Convert menu_links query strings into arrays.
 */
function system_update_7076() {
  $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('ml', array('mlid', 'options'));
  foreach ($query->execute() as $menu_link) {
    if (strpos($menu_link['options'], 'query') !== FALSE) {
      $menu_link['options'] = unserialize($menu_link['options']);
      if (isset($menu_link['options']['query']) && is_string($menu_link['options']['query'])) {
        $menu_link['options']['query'] = drupal_get_query_array($menu_link['options']['query']);
        db_update('menu_links')
          ->fields(array(
            'options' => serialize($menu_link['options']),
          ))
          ->condition('mlid', $menu_link['mlid'], '=')
          ->execute();
      }
    }
  }
}

/**
 * Revert {file_managed}.filename changed to a binary column.
 */
function system_update_7077() {
  db_change_field('file_managed', 'filename', 'filename', array(
    'description' => 'Name of the file with no path components. This may differ from the basename of the URI if the file is renamed to avoid overwriting an existing file.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ));
}


/**
 * Add binary to {date_formats}.format.
 */
function system_update_7078() {
  db_drop_unique_key('date_formats', 'formats');
  db_change_field('date_formats', 'format', 'format', array(
    'description' => 'The date format string.',
    'type' => 'varchar',
    'length' => 100,
    'not null' => TRUE,
    'binary' => TRUE,
  ), array('unique keys' => array('formats' => array('format', 'type'))));
}

/**
 * Convert the 'filesize' column in {file_managed} to a bigint.
 */
function system_update_7079() {
  $spec = array(
    'description' => 'The size of the file in bytes.',
    'type' => 'int',
    'size' => 'big',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
  );
  db_change_field('file_managed', 'filesize', 'filesize', $spec);
}

/**
 * Convert the 'format' column in {date_format_locale} to case sensitive varchar.
 */
function system_update_7080() {
  $spec = array(
    'description' => 'The date format string.',
    'type' => 'varchar',
    'length' => 100,
    'not null' => TRUE,
    'binary' => TRUE,
  );
  db_change_field('date_format_locale', 'format', 'format', $spec);
}

/**
 * @} End of "defgroup updates-7.x-extra".
 * The next series of updates should start at 8000.
 */
