[ Index ]

PHP Cross Reference of Documentation Drupal

title

Body

[close]

/ -> update.php (source)

   1  <?php
   2  
   3  /**
   4   * Root directory of Drupal installation.
   5   */
   6  define('DRUPAL_ROOT', getcwd());
   7  
   8  /**
   9   * @file
  10   * Administrative page for handling updates from one Drupal version to another.
  11   *
  12   * Point your browser to "http://www.example.com/update.php" and follow the
  13   * instructions.
  14   *
  15   * If you are not logged in using either the site maintenance account or an
  16   * account with the "Administer software updates" permission, you will need to
  17   * modify the access check statement inside your settings.php file. After
  18   * finishing the upgrade, be sure to open settings.php again, and change it
  19   * back to its original state!
  20   */
  21  
  22  /**
  23   * Global flag indicating that update.php is being run.
  24   *
  25   * When this flag is set, various operations do not take place, such as invoking
  26   * hook_init() and hook_exit(), css/js preprocessing, and translation.
  27   */
  28  define('MAINTENANCE_MODE', 'update');
  29  
  30  function update_selection_page() {
  31    drupal_set_title('Drupal database update');
  32    $elements = drupal_get_form('update_script_selection_form');
  33    $output = drupal_render($elements);
  34  
  35    update_task_list('select');
  36  
  37    return $output;
  38  }
  39  
  40  function update_script_selection_form($form, &$form_state) {
  41    $count = 0;
  42    $incompatible_count = 0;
  43    $form['start'] = array(
  44      '#tree' => TRUE,
  45      '#type' => 'fieldset',
  46      '#collapsed' => TRUE,
  47      '#collapsible' => TRUE,
  48    );
  49  
  50    // Ensure system.module's updates appear first.
  51    $form['start']['system'] = array();
  52  
  53    $updates = update_get_update_list();
  54    $starting_updates = array();
  55    $incompatible_updates_exist = FALSE;
  56    foreach ($updates as $module => $update) {
  57      if (!isset($update['start'])) {
  58        $form['start'][$module] = array(
  59          '#type' => 'item',
  60          '#title' => $module . ' module',
  61          '#markup'  => $update['warning'],
  62          '#prefix' => '<div class="messages warning">',
  63          '#suffix' => '</div>',
  64        );
  65        $incompatible_updates_exist = TRUE;
  66        continue;
  67      }
  68      if (!empty($update['pending'])) {
  69        $starting_updates[$module] = $update['start'];
  70        $form['start'][$module] = array(
  71          '#type' => 'hidden',
  72          '#value' => $update['start'],
  73        );
  74        $form['start'][$module . '_updates'] = array(
  75          '#theme' => 'item_list',
  76          '#items' => $update['pending'],
  77          '#title' => $module . ' module',
  78        );
  79      }
  80      if (isset($update['pending'])) {
  81        $count = $count + count($update['pending']);
  82      }
  83    }
  84  
  85    // Find and label any incompatible updates.
  86    foreach (update_resolve_dependencies($starting_updates) as $function => $data) {
  87      if (!$data['allowed']) {
  88        $incompatible_updates_exist = TRUE;
  89        $incompatible_count++;
  90        $module_update_key = $data['module'] . '_updates';
  91        if (isset($form['start'][$module_update_key]['#items'][$data['number']])) {
  92          $text = $data['missing_dependencies'] ? 'This update will been skipped due to the following missing dependencies: <em>' . implode(', ', $data['missing_dependencies']) . '</em>' : "This update will be skipped due to an error in the module's code.";
  93          $form['start'][$module_update_key]['#items'][$data['number']] .= '<div class="warning">' . $text . '</div>';
  94        }
  95        // Move the module containing this update to the top of the list.
  96        $form['start'] = array($module_update_key => $form['start'][$module_update_key]) + $form['start'];
  97      }
  98    }
  99  
 100    // Warn the user if any updates were incompatible.
 101    if ($incompatible_updates_exist) {
 102      drupal_set_message('Some of the pending updates cannot be applied because their dependencies were not met.', 'warning');
 103    }
 104  
 105    if (empty($count)) {
 106      drupal_set_message(t('No pending updates.'));
 107      unset($form);
 108      $form['links'] = array(
 109        '#markup' => theme('item_list', array('items' => update_helpful_links())),
 110      );
 111  
 112      // No updates to run, so caches won't get flushed later.  Clear them now.
 113      drupal_flush_all_caches();
 114    }
 115    else {
 116      $form['help'] = array(
 117        '#markup' => '<p>The version of Drupal you are updating from has been automatically detected.</p>',
 118        '#weight' => -5,
 119      );
 120      if ($incompatible_count) {
 121        $form['start']['#title'] = format_plural(
 122          $count,
 123          '1 pending update (@number_applied to be applied, @number_incompatible skipped)',
 124          '@count pending updates (@number_applied to be applied, @number_incompatible skipped)',
 125          array('@number_applied' => $count - $incompatible_count, '@number_incompatible' => $incompatible_count)
 126        );
 127      }
 128      else {
 129        $form['start']['#title'] = format_plural($count, '1 pending update', '@count pending updates');
 130      }
 131      $form['has_js'] = array(
 132        '#type' => 'hidden',
 133        '#default_value' => FALSE,
 134      );
 135      $form['actions'] = array('#type' => 'actions');
 136      $form['actions']['submit'] = array(
 137        '#type' => 'submit',
 138        '#value' => 'Apply pending updates',
 139      );
 140    }
 141    return $form;
 142  }
 143  
 144  function update_helpful_links() {
 145    // NOTE: we can't use l() here because the URL would point to
 146    // 'update.php?q=admin'.
 147    $links[] = '<a href="' . base_path() . '">Front page</a>';
 148    if (user_access('access administration pages')) {
 149      $links[] = '<a href="' . base_path() . '?q=admin">Administration pages</a>';
 150    }
 151    return $links;
 152  }
 153  
 154  function update_results_page() {
 155    drupal_set_title('Drupal database update');
 156    $links = update_helpful_links();
 157  
 158    update_task_list();
 159    // Report end result.
 160    if (module_exists('dblog') && user_access('access site reports')) {
 161      $log_message = ' All errors have been <a href="' . base_path() . '?q=admin/reports/dblog">logged</a>.';
 162    }
 163    else {
 164      $log_message = ' All errors have been logged.';
 165    }
 166  
 167    if ($_SESSION['update_success']) {
 168      $output = '<p>Updates were attempted. If you see no failures below, you may proceed happily back to your <a href="' . base_path() . '">site</a>. Otherwise, you may need to update your database manually.' . $log_message . '</p>';
 169    }
 170    else {
 171      list($module, $version) = array_pop(reset($_SESSION['updates_remaining']));
 172      $output = '<p class="error">The update process was aborted prematurely while running <strong>update #' . $version . ' in ' . $module . '.module</strong>.' . $log_message;
 173      if (module_exists('dblog')) {
 174        $output .= ' You may need to check the <code>watchdog</code> database table manually.';
 175      }
 176      $output .= '</p>';
 177    }
 178  
 179    if (!empty($GLOBALS['update_free_access'])) {
 180      $output .= "<p><strong>Reminder: don't forget to set the <code>\$update_free_access</code> value in your <code>settings.php</code> file back to <code>FALSE</code>.</strong></p>";
 181    }
 182  
 183    $output .= theme('item_list', array('items' => $links));
 184  
 185    // Output a list of queries executed.
 186    if (!empty($_SESSION['update_results'])) {
 187      $all_messages = '';
 188      foreach ($_SESSION['update_results'] as $module => $updates) {
 189        if ($module != '#abort') {
 190          $module_has_message = FALSE;
 191          $query_messages = '';
 192          foreach ($updates as $number => $queries) {
 193            $messages = array();
 194            foreach ($queries as $query) {
 195              // If there is no message for this update, don't show anything.
 196              if (empty($query['query'])) {
 197                continue;
 198              }
 199  
 200              if ($query['success']) {
 201                $messages[] = '<li class="success">' . $query['query'] . '</li>';
 202              }
 203              else {
 204                $messages[] = '<li class="failure"><strong>Failed:</strong> ' . $query['query'] . '</li>';
 205              }
 206            }
 207  
 208            if ($messages) {
 209              $module_has_message = TRUE;
 210              $query_messages .= '<h4>Update #' . $number . "</h4>\n";
 211              $query_messages .= '<ul>' . implode("\n", $messages) . "</ul>\n";
 212            }
 213          }
 214  
 215          // If there were any messages in the queries then prefix them with the
 216          // module name and add it to the global message list.
 217          if ($module_has_message) {
 218            $all_messages .= '<h3>' . $module . " module</h3>\n" . $query_messages;
 219          }
 220        }
 221      }
 222      if ($all_messages) {
 223        $output .= '<div id="update-results"><h2>The following updates returned messages</h2>';
 224        $output .= $all_messages;
 225        $output .= '</div>';
 226      }
 227    }
 228    unset($_SESSION['update_results']);
 229    unset($_SESSION['update_success']);
 230  
 231    return $output;
 232  }
 233  
 234  function update_info_page() {
 235    // Change query-strings on css/js files to enforce reload for all users.
 236    _drupal_flush_css_js();
 237    // Flush the cache of all data for the update status module.
 238    if (db_table_exists('cache_update')) {
 239      cache_clear_all('*', 'cache_update', TRUE);
 240    }
 241  
 242    update_task_list('info');
 243    drupal_set_title('Drupal database update');
 244    $token = drupal_get_token('update');
 245    $output = '<p>Use this utility to update your database whenever a new release of Drupal or a module is installed.</p><p>For more detailed information, see the <a href="http://drupal.org/upgrade">upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>';
 246    $output .= "<ol>\n";
 247    $output .= "<li><strong>Back up your database</strong>. This process will change your database values and in case of emergency you may need to revert to a backup.</li>\n";
 248    $output .= "<li><strong>Back up your code</strong>. Hint: when backing up module code, do not leave that backup in the 'modules' or 'sites/*/modules' directories as this may confuse Drupal's auto-discovery mechanism.</li>\n";
 249    $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
 250    $output .= "<li>Install your new files in the appropriate location, as described in the handbook.</li>\n";
 251    $output .= "</ol>\n";
 252    $output .= "<p>When you have performed the steps above, you may proceed.</p>\n";
 253    $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token)));
 254    $output .= '<form method="post" action="' . $form_action . '"><p><input type="submit" value="Continue" class="form-submit" /></p></form>';
 255    $output .= "\n";
 256    return $output;
 257  }
 258  
 259  function update_access_denied_page() {
 260    drupal_add_http_header('Status', '403 Forbidden');
 261    watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
 262    drupal_set_title('Access denied');
 263    return '<p>Access denied. You are not authorized to access this page. Log in using either an account with the <em>administer software updates</em> permission or the site maintenance account (the account you created during installation). If you cannot log in, you will have to edit <code>settings.php</code> to bypass this access check. To do this:</p>
 264  <ol>
 265   <li>With a text editor find the settings.php file on your system. From the main Drupal directory that you installed all the files into, go to <code>sites/your_site_name</code> if such directory exists, or else to <code>sites/default</code> which applies otherwise.</li>
 266   <li>There is a line inside your settings.php file that says <code>$update_free_access = FALSE;</code>. Change it to <code>$update_free_access = TRUE;</code>.</li>
 267   <li>As soon as the update.php script is done, you must change the settings.php file back to its original form with <code>$update_free_access = FALSE;</code>.</li>
 268   <li>To avoid having this problem in the future, remember to log in to your website using either an account with the <em>administer software updates</em> permission or the site maintenance account (the account you created during installation) before you backup your database at the beginning of the update process.</li>
 269  </ol>';
 270  }
 271  
 272  /**
 273   * Determines if the current user is allowed to run update.php.
 274   *
 275   * @return
 276   *   TRUE if the current user should be granted access, or FALSE otherwise.
 277   */
 278  function update_access_allowed() {
 279    global $update_free_access, $user;
 280  
 281    // Allow the global variable in settings.php to override the access check.
 282    if (!empty($update_free_access)) {
 283      return TRUE;
 284    }
 285    // Calls to user_access() might fail during the Drupal 6 to 7 update process,
 286    // so we fall back on requiring that the user be logged in as user #1.
 287    try {
 288      require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'user') . '/user.module';
 289      return user_access('administer software updates');
 290    }
 291    catch (Exception $e) {
 292      return ($user->uid == 1);
 293    }
 294  }
 295  
 296  /**
 297   * Add the update task list to the current page.
 298   */
 299  function update_task_list($active = NULL) {
 300    // Default list of tasks.
 301    $tasks = array(
 302      'requirements' => 'Verify requirements',
 303      'info' => 'Overview',
 304      'select' => 'Review updates',
 305      'run' => 'Run updates',
 306      'finished' => 'Review log',
 307    );
 308  
 309    drupal_add_region_content('sidebar_first', theme('task_list', array('items' => $tasks, 'active' => $active)));
 310  }
 311  
 312  /**
 313   * Returns (and optionally stores) extra requirements that only apply during
 314   * particular parts of the update.php process.
 315   */
 316  function update_extra_requirements($requirements = NULL) {
 317    static $extra_requirements = array();
 318    if (isset($requirements)) {
 319      $extra_requirements += $requirements;
 320    }
 321    return $extra_requirements;
 322  }
 323  
 324  /**
 325   * Check update requirements and report any errors or (optionally) warnings.
 326   *
 327   * @param $skip_warnings
 328   *   (optional) If set to TRUE, requirement warnings will be ignored, and a
 329   *   report will only be issued if there are requirement errors. Defaults to
 330   *   FALSE.
 331   */
 332  function update_check_requirements($skip_warnings = FALSE) {
 333    // Check requirements of all loaded modules.
 334    $requirements = module_invoke_all('requirements', 'update');
 335    $requirements += update_extra_requirements();
 336    $severity = drupal_requirements_severity($requirements);
 337  
 338    // If there are errors, always display them. If there are only warnings, skip
 339    // them if the caller has indicated they should be skipped.
 340    if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && !$skip_warnings)) {
 341      update_task_list('requirements');
 342      drupal_set_title('Requirements problem');
 343      $status_report = theme('status_report', array('requirements' => $requirements));
 344      $status_report .= 'Check the error messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
 345      print theme('update_page', array('content' => $status_report));
 346      exit();
 347    }
 348  }
 349  
 350  // Some unavoidable errors happen because the database is not yet up-to-date.
 351  // Our custom error handler is not yet installed, so we just suppress them.
 352  ini_set('display_errors', FALSE);
 353  
 354  // We prepare a minimal bootstrap for the update requirements check to avoid
 355  // reaching the PHP memory limit.
 356  require_once  DRUPAL_ROOT . '/includes/bootstrap.inc';
 357  require_once  DRUPAL_ROOT . '/includes/update.inc';
 358  require_once  DRUPAL_ROOT . '/includes/common.inc';
 359  require_once  DRUPAL_ROOT . '/includes/file.inc';
 360  require_once  DRUPAL_ROOT . '/includes/entity.inc';
 361  require_once  DRUPAL_ROOT . '/includes/unicode.inc';
 362  update_prepare_d7_bootstrap();
 363  
 364  // Temporarily disable configurable timezones so the upgrade process uses the
 365  // site-wide timezone. This prevents a PHP notice during session initlization
 366  // and before offsets have been converted in user_update_7002().
 367  $configurable_timezones = variable_get('configurable_timezones', 1);
 368  $conf['configurable_timezones'] = 0;
 369  
 370  // Determine if the current user has access to run update.php.
 371  drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
 372  
 373  // Reset configurable timezones.
 374  $conf['configurable_timezones'] = $configurable_timezones;
 375  
 376  // Only allow the requirements check to proceed if the current user has access
 377  // to run updates (since it may expose sensitive information about the site's
 378  // configuration).
 379  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
 380  if (empty($op) && update_access_allowed()) {
 381    require_once  DRUPAL_ROOT . '/includes/install.inc';
 382    require_once  DRUPAL_ROOT . '/modules/system/system.install';
 383  
 384    // Load module basics.
 385    include_once  DRUPAL_ROOT . '/includes/module.inc';
 386    $module_list['system']['filename'] = 'modules/system/system.module';
 387    module_list(TRUE, FALSE, FALSE, $module_list);
 388    drupal_load('module', 'system');
 389  
 390    // Reset the module_implements() cache so that any new hook implementations
 391    // in updated code are picked up.
 392    module_implements('', FALSE, TRUE);
 393  
 394    // Set up $language, since the installer components require it.
 395    drupal_language_initialize();
 396  
 397    // Set up theme system for the maintenance page.
 398    drupal_maintenance_theme();
 399  
 400    // Check the update requirements for Drupal. Only report on errors at this
 401    // stage, since the real requirements check happens further down.
 402    update_check_requirements(TRUE);
 403  
 404    // Redirect to the update information page if all requirements were met.
 405    install_goto('update.php?op=info');
 406  }
 407  
 408  // update_fix_d7_requirements() needs to run before bootstrapping beyond path.
 409  // So bootstrap to DRUPAL_BOOTSTRAP_LANGUAGE then include unicode.inc.
 410  
 411  drupal_bootstrap(DRUPAL_BOOTSTRAP_LANGUAGE);
 412  include_once  DRUPAL_ROOT . '/includes/unicode.inc';
 413  
 414  update_fix_d7_requirements();
 415  
 416  // Now proceed with a full bootstrap.
 417  
 418  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
 419  drupal_maintenance_theme();
 420  
 421  // Turn error reporting back on. From now on, only fatal errors (which are
 422  // not passed through the error handler) will cause a message to be printed.
 423  ini_set('display_errors', TRUE);
 424  
 425  // Only proceed with updates if the user is allowed to run them.
 426  if (update_access_allowed()) {
 427  
 428    include_once  DRUPAL_ROOT . '/includes/install.inc';
 429    include_once  DRUPAL_ROOT . '/includes/batch.inc';
 430    drupal_load_updates();
 431  
 432    update_fix_compatibility();
 433  
 434    // Check the update requirements for all modules. If there are warnings, but
 435    // no errors, skip reporting them if the user has provided a URL parameter
 436    // acknowledging the warnings and indicating a desire to continue anyway. See
 437    // drupal_requirements_url().
 438    $skip_warnings = !empty($_GET['continue']);
 439    update_check_requirements($skip_warnings);
 440  
 441    $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
 442    switch ($op) {
 443      // update.php ops.
 444  
 445      case 'selection':
 446        if (isset($_GET['token']) && $_GET['token'] == drupal_get_token('update')) {
 447          $output = update_selection_page();
 448          break;
 449        }
 450  
 451      case 'Apply pending updates':
 452        if (isset($_GET['token']) && $_GET['token'] == drupal_get_token('update')) {
 453          // Generate absolute URLs for the batch processing (using $base_root),
 454          // since the batch API will pass them to url() which does not handle
 455          // update.php correctly by default.
 456          $batch_url = $base_root . drupal_current_script_url();
 457          $redirect_url = $base_root . drupal_current_script_url(array('op' => 'results'));
 458          update_batch($_POST['start'], $redirect_url, $batch_url);
 459          break;
 460        }
 461  
 462      case 'info':
 463        $output = update_info_page();
 464        break;
 465  
 466      case 'results':
 467        $output = update_results_page();
 468        break;
 469  
 470      // Regular batch ops : defer to batch processing API.
 471      default:
 472        update_task_list('run');
 473        $output = _batch_page();
 474        break;
 475    }
 476  }
 477  else {
 478    $output = update_access_denied_page();
 479  }
 480  if (isset($output) && $output) {
 481    // Explicitly start a session so that the update.php token will be accepted.
 482    drupal_session_start();
 483    // We defer the display of messages until all updates are done.
 484    $progress_page = ($batch = batch_get()) && isset($batch['running']);
 485    print theme('update_page', array('content' => $output, 'show_messages' => !$progress_page));
 486  }


Développeurs Drupal & Développement mobile Montréal
Generated: Thu Feb 21 17:10:26 2013 Cross-referenced by PHPXref 0.7.1