update.php 20.5 KB
Newer Older
1
<?php
2 3 4 5 6

/**
 * @file
 * Administrative page for handling updates from one Drupal version to another.
 *
7
 * Point your browser to "http://www.example.com/core/update.php" and follow the
8 9
 * instructions.
 *
10 11 12 13 14
 * If you are not logged in using either the site maintenance account or an
 * account with the "Administer software updates" permission, you will need to
 * modify the access check statement inside your settings.php file. After
 * finishing the upgrade, be sure to open settings.php again, and change it
 * back to its original state!
15
 */
16

17 18
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\DependencyInjection\Reference;
20

21 22 23 24
// Change the directory to the Drupal root.
chdir('..');

/**
25
 * Defines the root directory of the Drupal installation.
26 27 28
 */
define('DRUPAL_ROOT', getcwd());

29
// Exit early if an incompatible PHP version would cause fatal errors.
30 31 32
// The minimum version is specified explicitly, as DRUPAL_MINIMUM_PHP is not
// yet available. It is defined in bootstrap.inc, but it is not possible to
// load that file yet as it would cause a fatal error on older versions of PHP.
33 34
if (version_compare(PHP_VERSION, '5.3.3') < 0) {
  print 'Your PHP installation is too old. Drupal requires at least PHP 5.3.3. See the <a href="http://drupal.org/requirements">system requirements</a> page for more information.';
35 36 37
  exit;
}

38
/**
39 40 41 42
 * Global flag indicating that update.php is being run.
 *
 * When this flag is set, various operations do not take place, such as invoking
 * hook_init() and hook_exit(), css/js preprocessing, and translation.
43 44 45 46
 *
 * This constant is defined using define() instead of const so that PHP
 * versions older than 5.3 can display the proper PHP requirements instead of
 * causing a fatal error.
47
 */
48
define('MAINTENANCE_MODE', 'update');
49

50
/**
51
 * Renders a form with a list of available database updates.
52
 */
53
function update_selection_page() {
54
  drupal_set_title('Drupal database update');
55 56
  $elements = drupal_get_form('update_script_selection_form');
  $output = drupal_render($elements);
57

58 59
  update_task_list('select');

60 61 62
  return $output;
}

63 64 65
/**
 * Form constructor for the list of available database module updates.
 */
66
function update_script_selection_form($form, &$form_state) {
67
  $count = 0;
68
  $incompatible_count = 0;
69
  $form['start'] = array(
70
    '#tree' => TRUE,
71
    '#type' => 'details',
72
    '#collapsed' => TRUE,
73
    '#collapsible' => TRUE,
74
  );
75

76
  // Ensure system.module's updates appear first.
77 78
  $form['start']['system'] = array();

79
  $updates = update_get_update_list();
80 81
  $starting_updates = array();
  $incompatible_updates_exist = FALSE;
82 83 84
  foreach ($updates as $module => $update) {
    if (!isset($update['start'])) {
      $form['start'][$module] = array(
85 86 87 88
        '#type' => 'item',
        '#title' => $module . ' module',
        '#markup'  => $update['warning'],
        '#prefix' => '<div class="messages warning">',
89 90
        '#suffix' => '</div>',
      );
91
      $incompatible_updates_exist = TRUE;
92 93 94
      continue;
    }
    if (!empty($update['pending'])) {
95
      $starting_updates[$module] = $update['start'];
96 97 98 99 100
      $form['start'][$module] = array(
        '#type' => 'hidden',
        '#value' => $update['start'],
      );
      $form['start'][$module . '_updates'] = array(
101 102 103
        '#theme' => 'item_list',
        '#items' => $update['pending'],
        '#title' => $module . ' module',
104 105 106 107
      );
    }
    if (isset($update['pending'])) {
      $count = $count + count($update['pending']);
108 109 110
    }
  }

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  // Find and label any incompatible updates.
  foreach (update_resolve_dependencies($starting_updates) as $function => $data) {
    if (!$data['allowed']) {
      $incompatible_updates_exist = TRUE;
      $incompatible_count++;
      $module_update_key = $data['module'] . '_updates';
      if (isset($form['start'][$module_update_key]['#items'][$data['number']])) {
        $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.";
        $form['start'][$module_update_key]['#items'][$data['number']] .= '<div class="warning">' . $text . '</div>';
      }
      // Move the module containing this update to the top of the list.
      $form['start'] = array($module_update_key => $form['start'][$module_update_key]) + $form['start'];
    }
  }

  // Warn the user if any updates were incompatible.
  if ($incompatible_updates_exist) {
    drupal_set_message('Some of the pending updates cannot be applied because their dependencies were not met.', 'warning');
  }

131
  if (empty($count)) {
132 133 134
    drupal_set_message(t('No pending updates.'));
    unset($form);
    $form['links'] = array(
135 136
      '#theme' => 'links',
      '#links' => update_helpful_links(),
137
    );
138 139 140

    // No updates to run, so caches won't get flushed later.  Clear them now.
    drupal_flush_all_caches();
141 142 143 144 145 146
  }
  else {
    $form['help'] = array(
      '#markup' => '<p>The version of Drupal you are updating from has been automatically detected.</p>',
      '#weight' => -5,
    );
147 148 149 150 151 152 153 154 155 156 157
    if ($incompatible_count) {
      $form['start']['#title'] = format_plural(
        $count,
        '1 pending update (@number_applied to be applied, @number_incompatible skipped)',
        '@count pending updates (@number_applied to be applied, @number_incompatible skipped)',
        array('@number_applied' => $count - $incompatible_count, '@number_incompatible' => $incompatible_count)
      );
    }
    else {
      $form['start']['#title'] = format_plural($count, '1 pending update', '@count pending updates');
    }
158 159
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
160
      '#type' => 'submit',
161
      '#value' => 'Apply pending updates',
162 163
    );
  }
164
  return $form;
165 166
}

167 168 169
/**
 * Provides links to the homepage and administration pages.
 */
170
function update_helpful_links() {
171 172 173 174
  $links['front'] = array(
    'title' => t('Front page'),
    'href' => '<front>',
  );
175
  if (user_access('access administration pages')) {
176 177 178 179
    $links['admin-pages'] = array(
      'title' => t('Administration pages'),
      'href' => 'admin',
    );
180
  }
181 182 183
  return $links;
}

184 185 186
/**
 * Displays results of the update script with any accompanying errors.
 */
187 188
function update_results_page() {
  drupal_set_title('Drupal database update');
189

190
  update_task_list();
191
  // Report end result.
192
  if (module_exists('dblog') && user_access('access site reports')) {
193
    $log_message = ' All errors have been <a href="' . base_path() . '?q=admin/reports/dblog">logged</a>.';
194 195 196 197 198
  }
  else {
    $log_message = ' All errors have been logged.';
  }

199
  if ($_SESSION['update_success']) {
200
    $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>';
201 202
  }
  else {
203 204
    $last = reset($_SESSION['updates_remaining']);
    list($module, $version) = array_pop($last);
205
    $output = '<p class="error">The update process was aborted prematurely while running <strong>update #' . $version . ' in ' . $module . '.module</strong>.' . $log_message;
206 207 208 209
    if (module_exists('dblog')) {
      $output .= ' You may need to check the <code>watchdog</code> database table manually.';
    }
    $output .= '</p>';
210 211
  }

212 213
  if (!empty($GLOBALS['update_free_access'])) {
    $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>";
214
  }
215

216
  $output .= theme('links', array('links' => update_helpful_links()));
217

218
  // Output a list of queries executed.
219
  if (!empty($_SESSION['update_results'])) {
220
    $all_messages = '';
221
    foreach ($_SESSION['update_results'] as $module => $updates) {
222
      if ($module != '#abort') {
223 224
        $module_has_message = FALSE;
        $query_messages = '';
225
        foreach ($updates as $number => $queries) {
226
          $messages = array();
227
          foreach ($queries as $query) {
228 229 230 231
            // If there is no message for this update, don't show anything.
            if (empty($query['query'])) {
              continue;
            }
232

233
            if ($query['success']) {
234
              $messages[] = '<li class="success">' . $query['query'] . '</li>';
235 236
            }
            else {
237
              $messages[] = '<li class="failure"><strong>Failed:</strong> ' . $query['query'] . '</li>';
238
            }
239
          }
240 241

          if ($messages) {
242 243 244
            $module_has_message = TRUE;
            $query_messages .= '<h4>Update #' . $number . "</h4>\n";
            $query_messages .= '<ul>' . implode("\n", $messages) . "</ul>\n";
245 246
          }
        }
247 248 249 250 251 252

        // If there were any messages in the queries then prefix them with the
        // module name and add it to the global message list.
        if ($module_has_message) {
          $all_messages .= '<h3>' . $module . " module</h3>\n" . $query_messages;
        }
253 254
      }
    }
255 256 257 258 259
    if ($all_messages) {
      $output .= '<div id="update-results"><h2>The following updates returned messages</h2>';
      $output .= $all_messages;
      $output .= '</div>';
    }
260
  }
261 262
  unset($_SESSION['update_results']);
  unset($_SESSION['update_success']);
263

264
  return $output;
265 266
}

267 268 269 270 271 272 273 274 275
/**
 * Provides an overview of the Drupal database update.
 *
 * This page provides cautionary suggestions that should happen before
 * proceeding with the update to ensure data integrity.
 *
 * @return
 *   Rendered HTML form.
 */
276
function update_info_page() {
277 278
  // Change query-strings on css/js files to enforce reload for all users.
  _drupal_flush_css_js();
279 280
  // Flush the cache of all data for the update status module.
  if (db_table_exists('cache_update')) {
281
    cache('update')->deleteAll();
282
  }
283

284
  update_task_list('info');
Steven Wittens's avatar
Steven Wittens committed
285
  drupal_set_title('Drupal database update');
286
  $token = drupal_get_token('update');
287
  $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>';
288 289 290
  $output .= "<ol>\n";
  $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";
  $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";
291
  $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
292 293 294
  $output .= "<li>Install your new files in the appropriate location, as described in the handbook.</li>\n";
  $output .= "</ol>\n";
  $output .= "<p>When you have performed the steps above, you may proceed.</p>\n";
295 296
  $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token)));
  $output .= '<form method="post" action="' . $form_action . '"><p><input type="submit" value="Continue" class="form-submit" /></p></form>';
297
  $output .= "\n";
298 299 300
  return $output;
}

301 302 303 304 305 306
/**
 * Renders a 403 access denied page for update.php.
 *
 * @return
 *   Rendered HTML warning with 403 status.
 */
307
function update_access_denied_page() {
308
  drupal_add_http_header('Status', '403 Forbidden');
309
  watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
310
  drupal_set_title('Access denied');
311
  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>
312
<ol>
313 314 315
 <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>
 <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>
 <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>
316
 <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>
317
</ol>';
318
}
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
/**
 * Determines if the current user is allowed to run update.php.
 *
 * @return
 *   TRUE if the current user should be granted access, or FALSE otherwise.
 */
function update_access_allowed() {
  global $update_free_access, $user;

  // Allow the global variable in settings.php to override the access check.
  if (!empty($update_free_access)) {
    return TRUE;
  }
  // Calls to user_access() might fail during the Drupal 6 to 7 update process,
  // so we fall back on requiring that the user be logged in as user #1.
  try {
336
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'user') . '/user.module';
337 338 339 340 341 342 343
    return user_access('administer software updates');
  }
  catch (Exception $e) {
    return ($user->uid == 1);
  }
}

344
/**
345
 * Adds the update task list to the current page.
346 347 348 349
 */
function update_task_list($active = NULL) {
  // Default list of tasks.
  $tasks = array(
350
    'requirements' => 'Verify requirements',
351
    'info' => 'Overview',
352
    'select' => 'Review updates',
353 354 355 356
    'run' => 'Run updates',
    'finished' => 'Review log',
  );

357
  drupal_add_region_content('sidebar_first', theme('task_list', array('items' => $tasks, 'active' => $active)));
358 359
}

360
/**
361
 * Returns and stores extra requirements that apply during the update process.
362
 */
363 364 365 366
function update_extra_requirements($requirements = NULL) {
  static $extra_requirements = array();
  if (isset($requirements)) {
    $extra_requirements += $requirements;
367
  }
368
  return $extra_requirements;
369 370 371
}

/**
372
 * Checks update requirements and reports errors and (optionally) warnings.
373 374 375 376 377
 *
 * @param $skip_warnings
 *   (optional) If set to TRUE, requirement warnings will be ignored, and a
 *   report will only be issued if there are requirement errors. Defaults to
 *   FALSE.
378
 */
379
function update_check_requirements($skip_warnings = FALSE) {
380 381
  // Check requirements of all loaded modules.
  $requirements = module_invoke_all('requirements', 'update');
382 383 384
  $requirements += update_extra_requirements();
  $severity = drupal_requirements_severity($requirements);

385 386 387
  // If there are errors, always display them. If there are only warnings, skip
  // them if the caller has indicated they should be skipped.
  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && !$skip_warnings)) {
388 389
    update_task_list('requirements');
    drupal_set_title('Requirements problem');
390
    $status_report = theme('status_report', array('requirements' => $requirements));
391
    $status_report .= 'Check the messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
392
    print theme('update_page', array('content' => $status_report));
393
    exit();
394
  }
395 396
}

397
// Some unavoidable errors happen because the database is not yet up-to-date.
398
// Our custom error handler is not yet installed, so we just suppress them.
399 400
ini_set('display_errors', FALSE);

401 402
// We prepare a minimal bootstrap for the update requirements check to avoid
// reaching the PHP memory limit.
403 404 405 406 407
require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/core/includes/update.inc';
require_once DRUPAL_ROOT . '/core/includes/common.inc';
require_once DRUPAL_ROOT . '/core/includes/file.inc';
require_once DRUPAL_ROOT . '/core/includes/unicode.inc';
408
require_once DRUPAL_ROOT . '/core/includes/schema.inc';
409
update_prepare_d8_bootstrap();
410

411 412
// Determine if the current user has access to run update.php.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
413

414 415 416 417
// A request object from the HTTPFoundation to tell us about the request.
// @todo These two lines were copied from index.php which has its own todo about
// a change required here. Revisit this when that change has been made.
$request = Request::createFromGlobals();
418 419
drupal_container()
  ->set('request', $request);
420 421 422 423 424 425 426 427 428

// There can be conflicting 'op' parameters because both update and batch use
// this parameter name. We need the 'op' coming from a POST request to trump
// that coming from a GET request.
$op = $request->request->get('op');
if (is_null($op)) {
  $op = $request->query->get('op');
}

429 430 431
// Only allow the requirements check to proceed if the current user has access
// to run updates (since it may expose sensitive information about the site's
// configuration).
432
if (is_null($op) && update_access_allowed()) {
433 434
  require_once DRUPAL_ROOT . '/core/includes/install.inc';
  require_once DRUPAL_ROOT . '/core/modules/system/system.install';
435 436

  // Load module basics.
437 438
  include_once DRUPAL_ROOT . '/core/includes/module.inc';
  $module_list['system']['filename'] = 'core/modules/system/system.module';
439
  module_list(NULL, $module_list);
440 441
  drupal_load('module', 'system');

442 443
  // Reset the module_implements() cache so that any new hook implementations
  // in updated code are picked up.
444
  module_implements_reset();
445

446
  // Set up $language, since the installer components require it.
447
  drupal_language_initialize();
448 449 450 451

  // Set up theme system for the maintenance page.
  drupal_maintenance_theme();

452 453 454
  // Check the update requirements for Drupal. Only report on errors at this
  // stage, since the real requirements check happens further down.
  update_check_requirements(TRUE);
455

456
  // Redirect to the update information page if all requirements were met.
457
  install_goto('core/update.php?op=info');
458
}
459

460 461 462
// Allow update_fix_d8_requirements() to run before code that can break on a
// Drupal 7 database.
drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
463
update_fix_d8_requirements();
464
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
Steven Wittens's avatar
Steven Wittens committed
465
drupal_maintenance_theme();
466

467 468 469 470
// Turn error reporting back on. From now on, only fatal errors (which are
// not passed through the error handler) will cause a message to be printed.
ini_set('display_errors', TRUE);

471

472
// Only proceed with updates if the user is allowed to run them.
473
if (update_access_allowed()) {
474

475 476
  include_once DRUPAL_ROOT . '/core/includes/install.inc';
  include_once DRUPAL_ROOT . '/core/includes/batch.inc';
477
  drupal_load_updates();
478

479
  update_fix_compatibility();
480

481 482 483 484
  // Check the update requirements for all modules. If there are warnings, but
  // no errors, skip reporting them if the user has provided a URL parameter
  // acknowledging the warnings and indicating a desire to continue anyway. See
  // drupal_requirements_url().
485 486
  $continue = $request->query->get('continue');
  $skip_warnings = !empty($continue);
487
  update_check_requirements($skip_warnings);
488

489
  switch ($op) {
490
    // update.php ops.
491

492
    case 'selection':
493
      $token = $request->query->get('token');
494
      if (isset($token) && drupal_valid_token($token, 'update')) {
495 496 497
        $output = update_selection_page();
        break;
      }
498

499
    case 'Apply pending updates':
500
      $token = $request->query->get('token');
501
      if (isset($token) && drupal_valid_token($token, 'update')) {
502 503 504 505 506
        // Generate absolute URLs for the batch processing (using $base_root),
        // since the batch API will pass them to url() which does not handle
        // update.php correctly by default.
        $batch_url = $base_root . drupal_current_script_url();
        $redirect_url = $base_root . drupal_current_script_url(array('op' => 'results'));
507
        update_batch($request->request->get('start'), $redirect_url, $batch_url);
508 509 510 511 512
        break;
      }

    case 'info':
      $output = update_info_page();
513 514
      break;

515 516
    case 'results':
      $output = update_results_page();
517 518
      break;

519
    // Regular batch ops : defer to batch processing API.
520
    default:
521 522
      update_task_list('run');
      $output = _batch_page();
523
      break;
Kjartan's avatar
Kjartan committed
524 525 526
  }
}
else {
527
  $output = update_access_denied_page();
528
}
529
if (isset($output) && $output) {
530
  // Explicitly start a session so that the update.php token will be accepted.
531
  drupal_session_start();
532 533
  // We defer the display of messages until all updates are done.
  $progress_page = ($batch = batch_get()) && isset($batch['running']);
534 535 536 537 538 539
  if ($output instanceof Response) {
    $output->send();
  }
  else {
    print theme('update_page', array('content' => $output, 'show_messages' => !$progress_page));
  }
540
}