update.php 18.3 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
use Drupal\Core\DrupalKernel;
18
use Drupal\Core\Update\Form\UpdateScriptSelectionForm;
19 20
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\DependencyInjection\Reference;
22

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

26 27
require_once __DIR__ . '/vendor/autoload.php';

28
// Exit early if an incompatible PHP version would cause fatal errors.
29 30 31
// 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.
32 33
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.';
34 35 36
  exit;
}

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

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

56
  drupal_set_title('Drupal database update');
57
  $elements = \Drupal::formBuilder()->getForm('Drupal\Core\Update\Form\UpdateScriptSelectionForm');
58
  $output = drupal_render($elements);
59

60 61
  update_task_list('select');

62 63 64
  return $output;
}

65 66 67
/**
 * Provides links to the homepage and administration pages.
 */
68
function update_helpful_links() {
69 70 71 72
  $links['front'] = array(
    'title' => t('Front page'),
    'href' => '<front>',
  );
73
  if (user_access('access administration pages')) {
74 75 76 77
    $links['admin-pages'] = array(
      'title' => t('Administration pages'),
      'href' => 'admin',
    );
78
  }
79 80 81
  return $links;
}

82 83 84 85 86 87 88
/**
 * Remove update overrides and flush all caches.
 *
 * This will need to be run once all (if any) updates are run. Do not call this
 * while updates are running.
 */
function update_flush_all_caches() {
89
  unset($GLOBALS['conf']['container_service_providers']['UpdateServiceProvider']);
90
  \Drupal::service('kernel')->updateModules(\Drupal::moduleHandler()->getModuleList());
91 92 93 94 95

  // No updates to run, so caches won't get flushed later.  Clear them now.
  drupal_flush_all_caches();
}

96 97 98
/**
 * Displays results of the update script with any accompanying errors.
 */
99 100
function update_results_page() {
  drupal_set_title('Drupal database update');
101

102
  update_task_list();
103
  // Report end result.
104
  if (\Drupal::moduleHandler()->moduleExists('dblog') && user_access('access site reports')) {
105
    $log_message = ' All errors have been <a href="' . base_path() . '?q=admin/reports/dblog">logged</a>.';
106 107 108 109 110
  }
  else {
    $log_message = ' All errors have been logged.';
  }

111
  if ($_SESSION['update_success']) {
112
    $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>';
113 114
  }
  else {
115 116
    $last = reset($_SESSION['updates_remaining']);
    list($module, $version) = array_pop($last);
117
    $output = '<p class="error">The update process was aborted prematurely while running <strong>update #' . $version . ' in ' . $module . '.module</strong>.' . $log_message;
118
    if (\Drupal::moduleHandler()->moduleExists('dblog')) {
119 120 121
      $output .= ' You may need to check the <code>watchdog</code> database table manually.';
    }
    $output .= '</p>';
122 123
  }

124 125
  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>";
126
  }
127

128 129 130 131 132
  $links = array(
    '#theme' => 'links',
    '#links' => update_helpful_links(),
  );
  $output .= drupal_render($links);
133

134
  // Output a list of queries executed.
135
  if (!empty($_SESSION['update_results'])) {
136
    $all_messages = '';
137
    foreach ($_SESSION['update_results'] as $module => $updates) {
138
      if ($module != '#abort') {
139 140
        $module_has_message = FALSE;
        $query_messages = '';
141
        foreach ($updates as $number => $queries) {
142
          $messages = array();
143
          foreach ($queries as $query) {
144 145 146 147
            // If there is no message for this update, don't show anything.
            if (empty($query['query'])) {
              continue;
            }
148

149
            if ($query['success']) {
150
              $messages[] = '<li class="success">' . $query['query'] . '</li>';
151 152
            }
            else {
153
              $messages[] = '<li class="failure"><strong>Failed:</strong> ' . $query['query'] . '</li>';
154
            }
155
          }
156 157

          if ($messages) {
158 159 160
            $module_has_message = TRUE;
            $query_messages .= '<h4>Update #' . $number . "</h4>\n";
            $query_messages .= '<ul>' . implode("\n", $messages) . "</ul>\n";
161 162
          }
        }
163 164 165 166 167 168

        // 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;
        }
169 170
      }
    }
171
    if ($all_messages) {
172
      $output .= '<div class="update-results"><h2>The following updates returned messages</h2>';
173 174 175
      $output .= $all_messages;
      $output .= '</div>';
    }
176
  }
177 178
  unset($_SESSION['update_results']);
  unset($_SESSION['update_success']);
179

180
  return $output;
181 182
}

183 184 185 186 187 188 189 190 191
/**
 * 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.
 */
192
function update_info_page() {
193 194
  // Change query-strings on css/js files to enforce reload for all users.
  _drupal_flush_css_js();
195
  // Flush the cache of all data for the update status module.
196 197
  drupal_container()->get('keyvalue.expirable')->get('update')->deleteAll();
  drupal_container()->get('keyvalue.expirable')->get('update_available_release')->deleteAll();
198

199
  update_task_list('info');
200
  drupal_set_title('Drupal database update');
201
  $token = drupal_get_token('update');
202
  $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>';
203 204
  $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";
205
  $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
206
  $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";
207 208 209
  $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";
210
  $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token)));
211
  $output .= '<form method="post" action="' . $form_action . '"><p><input type="submit" value="Continue" class="form-submit button button-primary" /></p></form>';
212
  $output .= "\n";
213 214 215
  return $output;
}

216 217 218 219 220 221
/**
 * Renders a 403 access denied page for update.php.
 *
 * @return
 *   Rendered HTML warning with 403 status.
 */
222
function update_access_denied_page() {
223
  drupal_add_http_header('Status', '403 Forbidden');
224
  header(\Drupal::request()->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
225
  watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
226
  drupal_set_title('Access denied');
227
  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>
228
<ol>
229
 <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>
230 231
 <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>
232
 <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>
233
</ol>';
234
}
235

236 237 238 239 240 241 242
/**
 * 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() {
243
  $user = \Drupal::currentUser();
244 245

  // Allow the global variable in settings.php to override the access check.
246
  if (settings()->get('update_free_access')) {
247 248 249 250 251
    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 {
252
    $module_handler = \Drupal::moduleHandler();
253 254 255 256 257
    $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);
258 259
    return user_access('administer software updates');
  }
260
  catch (\Exception $e) {
261
    return ($user->id() == 1);
262 263 264
  }
}

265
/**
266
 * Adds the update task list to the current page.
267 268 269 270
 */
function update_task_list($active = NULL) {
  // Default list of tasks.
  $tasks = array(
271
    'requirements' => 'Verify requirements',
272
    'info' => 'Overview',
273
    'select' => 'Review updates',
274 275 276 277
    'run' => 'Run updates',
    'finished' => 'Review log',
  );

278 279 280 281 282 283 284
  $task_list = array(
    '#theme' => 'task_list',
    '#items' => $tasks,
    '#active' => $active,
  );

  drupal_add_region_content('sidebar_first', drupal_render($task_list));
285 286
}

287
/**
288
 * Returns and stores extra requirements that apply during the update process.
289
 */
290 291 292 293
function update_extra_requirements($requirements = NULL) {
  static $extra_requirements = array();
  if (isset($requirements)) {
    $extra_requirements += $requirements;
294
  }
295
  return $extra_requirements;
296 297 298
}

/**
299
 * Checks update requirements and reports errors and (optionally) warnings.
300 301 302 303 304
 *
 * @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.
305
 */
306
function update_check_requirements($skip_warnings = FALSE) {
307
  // Check requirements of all loaded modules.
308
  $requirements = \Drupal::moduleHandler()->invokeAll('requirements', array('update'));
309 310 311
  $requirements += update_extra_requirements();
  $severity = drupal_requirements_severity($requirements);

312 313 314
  // 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)) {
315 316
    update_task_list('requirements');
    drupal_set_title('Requirements problem');
317 318 319 320 321
    $status = array(
      '#theme' => 'status_report',
      '#requirements' => $requirements,
    );
    $status_report = drupal_render($status);
322
    $status_report .= 'Check the messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
323
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
324 325 326 327 328
    $maintenance_page = array(
      '#theme' => 'maintenance_page',
      '#content' => $status_report,
    );
    print drupal_render($maintenance_page);
329
    exit();
330
  }
331 332
}

333

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

338 339
// We prepare a minimal bootstrap for the update requirements check to avoid
// reaching the PHP memory limit.
340 341 342 343 344 345
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';
346
update_prepare_d8_bootstrap();
347

348
// Determine if the current user has access to run update.php.
349
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
350

351 352
// A request object from the HTTPFoundation to tell us about the request.
$request = Request::createFromGlobals();
353
\Drupal::getContainer()->set('request', $request);
354

355 356 357
require_once DRUPAL_ROOT . '/' . settings()->get('session_inc', 'core/includes/session.inc');
drupal_session_initialize();

358 359
// Ensure that URLs generated for the home and admin pages don't have 'update.php'
// in them.
360
$generator = \Drupal::urlGenerator();
361 362 363
$generator->setBasePath(str_replace('/core', '', $request->getBasePath()) . '/');
$generator->setScriptPath('');

364 365 366 367 368 369 370 371
// 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');
}

372 373 374
// 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).
375
if (is_null($op) && update_access_allowed()) {
376
  require_once __DIR__ . '/includes/install.inc';
377
  require_once DRUPAL_ROOT . '/core/modules/system/system.install';
378 379

  // Set up $language, since the installer components require it.
380
  drupal_language_initialize();
381 382 383 384

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

385 386 387
  // 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);
388

389
  // Redirect to the update information page if all requirements were met.
390
  install_goto('core/update.php?op=info');
391
}
392

393 394 395
// Allow update_fix_d8_requirements() to run before code that can break on a
// Drupal 7 database.
drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
396
update_fix_d8_requirements();
397
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
398
drupal_maintenance_theme();
399

400 401 402 403
// 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);

404

405
// Only proceed with updates if the user is allowed to run them.
406
if (update_access_allowed()) {
407

408 409
  include_once __DIR__ . '/includes/install.inc';
  include_once __DIR__ . '/includes/batch.inc';
410
  drupal_load_updates();
411

412
  update_fix_compatibility();
413

414 415 416 417
  // 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().
418 419
  $continue = $request->query->get('continue');
  $skip_warnings = !empty($continue);
420
  update_check_requirements($skip_warnings);
421

422
  switch ($op) {
423
    // update.php ops.
424

425
    case 'selection':
426
      $token = $request->query->get('token');
427
      if (isset($token) && drupal_valid_token($token, 'update')) {
428 429 430
        $output = update_selection_page();
        break;
      }
431

432
    case 'Apply pending updates':
433
      $token = $request->query->get('token');
434
      if (isset($token) && drupal_valid_token($token, 'update')) {
435 436 437 438 439
        // 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'));
440
        $output = update_batch($request->request->get('start'), $redirect_url, $batch_url);
441 442 443 444 445
        break;
      }

    case 'info':
      $output = update_info_page();
446 447
      break;

448 449
    case 'results':
      $output = update_results_page();
450 451
      break;

452
    // Regular batch ops : defer to batch processing API.
453
    default:
454
      update_task_list('run');
455
      $output = _batch_page($request);
456
      break;
457 458 459
  }
}
else {
460
  $output = update_access_denied_page();
461
}
462
if (isset($output) && $output) {
463
  // Explicitly start a session so that the update.php token will be accepted.
464
  drupal_session_start();
465 466
  // We defer the display of messages until all updates are done.
  $progress_page = ($batch = batch_get()) && isset($batch['running']);
467 468 469 470
  if ($output instanceof Response) {
    $output->send();
  }
  else {
471
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
472 473 474 475 476 477
    $maintenance_page = array(
      '#theme' => 'maintenance_page',
      '#content' => $output,
      '#show_messages' => !$progress_page,
    );
    print drupal_render($maintenance_page);
478
  }
479
}