update.php 20.8 KB
Newer Older
1
<?php
Dries's avatar
 
Dries committed
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
Dries's avatar
 
Dries committed
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!
Dries's avatar
 
Dries committed
15
 */
Dries's avatar
 
Dries committed
16

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

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

24
// Exit early if an incompatible PHP version would cause fatal errors.
25 26 27
// 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.
28 29
if (version_compare(PHP_VERSION, '5.3.10') < 0) {
  print 'Your PHP installation is too old. Drupal requires at least PHP 5.3.10. See the <a href="http://drupal.org/requirements">system requirements</a> page for more information.';
30 31 32
  exit;
}

33
/**
34 35 36
 * Global flag indicating that update.php is being run.
 *
 * When this flag is set, various operations do not take place, such as invoking
37
 * hook_init(), css/js preprocessing, and translation.
38 39 40 41
 *
 * 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.
42
 */
43
define('MAINTENANCE_MODE', 'update');
44

45
/**
46
 * Renders a form with a list of available database updates.
47
 */
48
function update_selection_page() {
49 50 51
  // Make sure there is no stale theme registry.
  cache()->deleteAll();

52
  drupal_set_title('Drupal database update');
53 54
  $elements = drupal_get_form('update_script_selection_form');
  $output = drupal_render($elements);
55

56 57
  update_task_list('select');

58 59 60
  return $output;
}

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

73
  // Ensure system.module's updates appear first.
74 75
  $form['start']['system'] = array();

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

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  // 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');
  }

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

    // No updates to run, so caches won't get flushed later.  Clear them now.
    drupal_flush_all_caches();
138 139 140 141 142 143
  }
  else {
    $form['help'] = array(
      '#markup' => '<p>The version of Drupal you are updating from has been automatically detected.</p>',
      '#weight' => -5,
    );
144 145 146 147 148 149 150 151 152 153 154
    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');
    }
155 156
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
157
      '#type' => 'submit',
158
      '#value' => 'Apply pending updates',
159 160
    );
  }
161
  return $form;
162 163
}

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

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

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

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

209 210
  if (settings()->get('update_free_access')) {
    $output .= "<p><strong>Reminder: don't forget to set the <code>\$settings['update_free_access']</code> value in your <code>settings.php</code> file back to <code>FALSE</code>.</strong></p>";
211
  }
212

213
  $output .= theme('links', array('links' => update_helpful_links()));
214

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

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

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

        // 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;
        }
250 251
      }
    }
252
    if ($all_messages) {
253
      $output .= '<div class="update-results"><h2>The following updates returned messages</h2>';
254 255 256
      $output .= $all_messages;
      $output .= '</div>';
    }
257
  }
258 259
  unset($_SESSION['update_results']);
  unset($_SESSION['update_success']);
260

261
  return $output;
262 263
}

264 265 266 267 268 269 270 271 272
/**
 * 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.
 */
273
function update_info_page() {
274 275
  // Change query-strings on css/js files to enforce reload for all users.
  _drupal_flush_css_js();
276
  // Flush the cache of all data for the update status module.
277 278
  drupal_container()->get('keyvalue.expirable')->get('update')->deleteAll();
  drupal_container()->get('keyvalue.expirable')->get('update_available_release')->deleteAll();
279

280
  update_task_list('info');
Steven Wittens's avatar
Steven Wittens committed
281
  drupal_set_title('Drupal database update');
282
  $token = drupal_get_token('update');
283
  $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>';
284 285
  $output .= "<ol>\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";
286
  $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
287
  $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";
288 289 290
  $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";
291 292
  $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>';
293
  $output .= "\n";
294 295 296
  return $output;
}

297 298 299 300 301 302
/**
 * Renders a 403 access denied page for update.php.
 *
 * @return
 *   Rendered HTML warning with 403 status.
 */
303
function update_access_denied_page() {
304
  drupal_add_http_header('Status', '403 Forbidden');
305
  watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
306
  drupal_set_title('Access denied');
307
  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>
308
<ol>
309
 <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>
310 311
 <li>There is a line inside your settings.php file that says <code>$settings[\'update_free_access\'] = FALSE;</code>. Change it to <code>$settings[\'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>$settings[\'update_free_access\'] = FALSE;</code>.</li>
312
 <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>
313
</ol>';
314
}
315

316 317 318 319 320 321 322
/**
 * 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() {
323
  global $user;
324 325

  // Allow the global variable in settings.php to override the access check.
326
  if (settings()->get('update_free_access')) {
327 328 329 330 331
    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 {
332 333 334 335 336 337
    $module_handler = drupal_container()->get('module_handler');
    $module_filenames = $module_handler->getModuleList();
    $module_filenames['user'] = 'core/modules/user/user.module';
    $module_handler->setModuleList($module_filenames);
    $module_handler->reload();
    drupal_container()->get('kernel')->updateModules($module_filenames, $module_filenames);
338 339
    return user_access('administer software updates');
  }
340
  catch (\Exception $e) {
341 342 343 344
    return ($user->uid == 1);
  }
}

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

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

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

/**
373
 * Checks update requirements and reports errors and (optionally) warnings.
374 375 376 377 378
 *
 * @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.
379
 */
380
function update_check_requirements($skip_warnings = FALSE) {
381 382
  // Check requirements of all loaded modules.
  $requirements = module_invoke_all('requirements', 'update');
383 384 385
  $requirements += update_extra_requirements();
  $severity = drupal_requirements_severity($requirements);

386 387 388
  // 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)) {
389 390
    update_task_list('requirements');
    drupal_set_title('Requirements problem');
391
    $status_report = theme('status_report', array('requirements' => $requirements));
392
    $status_report .= 'Check the messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
393 394
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    print theme('maintenance_page', array('content' => $status_report));
395
    exit();
396
  }
397 398
}

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

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

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

416 417 418 419
// 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();
420 421
drupal_container()
  ->set('request', $request);
422 423 424 425 426 427 428 429 430

// 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');
}

431 432 433
// 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).
434
if (is_null($op) && update_access_allowed()) {
435
  require_once __DIR__ . '/includes/install.inc';
436
  require_once DRUPAL_ROOT . '/core/modules/system/system.install';
437 438

  // Load module basics.
439
  include_once __DIR__ . '/includes/module.inc';
440 441 442 443
  $module_list['system'] = 'core/modules/system/system.module';
  $module_handler = drupal_container()->get('module_handler');
  $module_handler->setModuleList($module_list);
  $module_handler->load('system');
444 445

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

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

451 452 453
  // 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);
454

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

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

466 467 468 469
// 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);

470

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

474 475
  include_once __DIR__ . '/includes/install.inc';
  include_once __DIR__ . '/includes/batch.inc';
476
  drupal_load_updates();
Dries's avatar
 
Dries committed
477

478
  update_fix_compatibility();
479

480 481 482 483
  // 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().
484 485
  $continue = $request->query->get('continue');
  $skip_warnings = !empty($continue);
486
  update_check_requirements($skip_warnings);
487

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

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

498
    case 'Apply pending updates':
499
      $token = $request->query->get('token');
500
      if (isset($token) && drupal_valid_token($token, 'update')) {
501 502 503 504 505
        // 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'));
506
        update_batch($request->request->get('start'), $redirect_url, $batch_url);
507 508 509 510 511
        break;
      }

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

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

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