Project

General

Profile

Paste
Download (19.5 KB) Statistics
| Branch: | Revision:

root / drupal7 / update.php @ e9734207

1
<?php
2

    
3
/**
4
 * Defines the root directory of the 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
/**
31
 * Renders a form with a list of available database updates.
32
 */
33
function update_selection_page() {
34
  drupal_set_title('Drupal database update');
35
  $elements = drupal_get_form('update_script_selection_form');
36
  $output = drupal_render($elements);
37

    
38
  update_task_list('select');
39

    
40
  return $output;
41
}
42

    
43
/**
44
 * Form constructor for the list of available database module updates.
45
 */
46
function update_script_selection_form($form, &$form_state) {
47
  $count = 0;
48
  $incompatible_count = 0;
49
  $form['start'] = array(
50
    '#tree' => TRUE,
51
    '#type' => 'fieldset',
52
    '#collapsed' => TRUE,
53
    '#collapsible' => TRUE,
54
  );
55

    
56
  // Ensure system.module's updates appear first.
57
  $form['start']['system'] = array();
58

    
59
  $updates = update_get_update_list();
60
  $starting_updates = array();
61
  $incompatible_updates_exist = FALSE;
62
  foreach ($updates as $module => $update) {
63
    if (!isset($update['start'])) {
64
      $form['start'][$module] = array(
65
        '#type' => 'item',
66
        '#title' => $module . ' module',
67
        '#markup'  => $update['warning'],
68
        '#prefix' => '<div class="messages warning">',
69
        '#suffix' => '</div>',
70
      );
71
      $incompatible_updates_exist = TRUE;
72
      continue;
73
    }
74
    if (!empty($update['pending'])) {
75
      $starting_updates[$module] = $update['start'];
76
      $form['start'][$module] = array(
77
        '#type' => 'hidden',
78
        '#value' => $update['start'],
79
      );
80
      $form['start'][$module . '_updates'] = array(
81
        '#theme' => 'item_list',
82
        '#items' => $update['pending'],
83
        '#title' => $module . ' module',
84
      );
85
    }
86
    if (isset($update['pending'])) {
87
      $count = $count + count($update['pending']);
88
    }
89
  }
90

    
91
  // Find and label any incompatible updates.
92
  foreach (update_resolve_dependencies($starting_updates) as $function => $data) {
93
    if (!$data['allowed']) {
94
      $incompatible_updates_exist = TRUE;
95
      $incompatible_count++;
96
      $module_update_key = $data['module'] . '_updates';
97
      if (isset($form['start'][$module_update_key]['#items'][$data['number']])) {
98
        $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.";
99
        $form['start'][$module_update_key]['#items'][$data['number']] .= '<div class="warning">' . $text . '</div>';
100
      }
101
      // Move the module containing this update to the top of the list.
102
      $form['start'] = array($module_update_key => $form['start'][$module_update_key]) + $form['start'];
103
    }
104
  }
105

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

    
111
  if (empty($count)) {
112
    drupal_set_message(t('No pending updates.'));
113
    unset($form);
114
    $form['links'] = array(
115
      '#markup' => theme('item_list', array('items' => update_helpful_links())),
116
    );
117

    
118
    // No updates to run, so caches won't get flushed later.  Clear them now.
119
    drupal_flush_all_caches();
120
  }
121
  else {
122
    $form['help'] = array(
123
      '#markup' => '<p>The version of Drupal you are updating from has been automatically detected.</p>',
124
      '#weight' => -5,
125
    );
126
    if ($incompatible_count) {
127
      $form['start']['#title'] = format_plural(
128
        $count,
129
        '1 pending update (@number_applied to be applied, @number_incompatible skipped)',
130
        '@count pending updates (@number_applied to be applied, @number_incompatible skipped)',
131
        array('@number_applied' => $count - $incompatible_count, '@number_incompatible' => $incompatible_count)
132
      );
133
    }
134
    else {
135
      $form['start']['#title'] = format_plural($count, '1 pending update', '@count pending updates');
136
    }
137
    $form['has_js'] = array(
138
      '#type' => 'hidden',
139
      '#default_value' => FALSE,
140
    );
141
    $form['actions'] = array('#type' => 'actions');
142
    $form['actions']['submit'] = array(
143
      '#type' => 'submit',
144
      '#value' => 'Apply pending updates',
145
    );
146
  }
147
  return $form;
148
}
149

    
150
/**
151
 * Provides links to the homepage and administration pages.
152
 */
153
function update_helpful_links() {
154
  $links[] = '<a href="' . base_path() . '">Front page</a>';
155
  if (user_access('access administration pages')) {
156
    $links[] = '<a href="' . base_path() . '?q=admin">Administration pages</a>';
157
  }
158
  return $links;
159
}
160

    
161
/**
162
 * Displays results of the update script with any accompanying errors.
163
 */
164
function update_results_page() {
165
  drupal_set_title('Drupal database update');
166
  $links = update_helpful_links();
167

    
168
  update_task_list();
169
  // Report end result.
170
  if (module_exists('dblog') && user_access('access site reports')) {
171
    $log_message = ' All errors have been <a href="' . base_path() . '?q=admin/reports/dblog">logged</a>.';
172
  }
173
  else {
174
    $log_message = ' All errors have been logged.';
175
  }
176

    
177
  if ($_SESSION['update_success']) {
178
    $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>';
179
  }
180
  else {
181
    $updates_remaining = reset($_SESSION['updates_remaining']);
182
    list($module, $version) = array_pop($updates_remaining);
183
    $output = '<p class="error">The update process was aborted prematurely while running <strong>update #' . $version . ' in ' . $module . '.module</strong>.' . $log_message;
184
    if (module_exists('dblog')) {
185
      $output .= ' You may need to check the <code>watchdog</code> database table manually.';
186
    }
187
    $output .= '</p>';
188
  }
189

    
190
  if (!empty($GLOBALS['update_free_access'])) {
191
    $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>";
192
  }
193

    
194
  $output .= theme('item_list', array('items' => $links));
195

    
196
  // Output a list of queries executed.
197
  if (!empty($_SESSION['update_results'])) {
198
    $all_messages = '';
199
    foreach ($_SESSION['update_results'] as $module => $updates) {
200
      if ($module != '#abort') {
201
        $module_has_message = FALSE;
202
        $query_messages = '';
203
        foreach ($updates as $number => $queries) {
204
          $messages = array();
205
          foreach ($queries as $query) {
206
            // If there is no message for this update, don't show anything.
207
            if (empty($query['query'])) {
208
              continue;
209
            }
210

    
211
            if ($query['success']) {
212
              $messages[] = '<li class="success">' . $query['query'] . '</li>';
213
            }
214
            else {
215
              $messages[] = '<li class="failure"><strong>Failed:</strong> ' . $query['query'] . '</li>';
216
            }
217
          }
218

    
219
          if ($messages) {
220
            $module_has_message = TRUE;
221
            $query_messages .= '<h4>Update #' . $number . "</h4>\n";
222
            $query_messages .= '<ul>' . implode("\n", $messages) . "</ul>\n";
223
          }
224
        }
225

    
226
        // If there were any messages in the queries then prefix them with the
227
        // module name and add it to the global message list.
228
        if ($module_has_message) {
229
          $all_messages .= '<h3>' . $module . " module</h3>\n" . $query_messages;
230
        }
231
      }
232
    }
233
    if ($all_messages) {
234
      $output .= '<div id="update-results"><h2>The following updates returned messages</h2>';
235
      $output .= $all_messages;
236
      $output .= '</div>';
237
    }
238
  }
239
  unset($_SESSION['update_results']);
240
  unset($_SESSION['update_success']);
241

    
242
  return $output;
243
}
244

    
245
/**
246
 * Provides an overview of the Drupal database update.
247
 *
248
 * This page provides cautionary suggestions that should happen before
249
 * proceeding with the update to ensure data integrity.
250
 *
251
 * @return
252
 *   Rendered HTML form.
253
 */
254
function update_info_page() {
255
  // Change query-strings on css/js files to enforce reload for all users.
256
  _drupal_flush_css_js();
257
  // Flush the cache of all data for the update status module.
258
  if (db_table_exists('cache_update')) {
259
    cache_clear_all('*', 'cache_update', TRUE);
260
  }
261

    
262
  update_task_list('info');
263
  drupal_set_title('Drupal database update');
264
  $token = drupal_get_token('update');
265
  $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>';
266
  $output .= "<ol>\n";
267
  $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";
268
  $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";
269
  $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
270
  $output .= "<li>Install your new files in the appropriate location, as described in the handbook.</li>\n";
271
  $output .= "</ol>\n";
272
  $output .= "<p>When you have performed the steps above, you may proceed.</p>\n";
273
  $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token)));
274
  $output .= '<form method="post" action="' . $form_action . '"><p><input type="submit" value="Continue" class="form-submit" /></p></form>';
275
  $output .= "\n";
276
  return $output;
277
}
278

    
279
/**
280
 * Renders a 403 access denied page for update.php.
281
 *
282
 * @return
283
 *   Rendered HTML warning with 403 status.
284
 */
285
function update_access_denied_page() {
286
  drupal_add_http_header('Status', '403 Forbidden');
287
  watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
288
  drupal_set_title('Access denied');
289
  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>
290
<ol>
291
 <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>
292
 <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>
293
 <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>
294
 <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>
295
</ol>';
296
}
297

    
298
/**
299
 * Determines if the current user is allowed to run update.php.
300
 *
301
 * @return
302
 *   TRUE if the current user should be granted access, or FALSE otherwise.
303
 */
304
function update_access_allowed() {
305
  global $update_free_access, $user;
306

    
307
  // Allow the global variable in settings.php to override the access check.
308
  if (!empty($update_free_access)) {
309
    return TRUE;
310
  }
311
  // Calls to user_access() might fail during the Drupal 6 to 7 update process,
312
  // so we fall back on requiring that the user be logged in as user #1.
313
  try {
314
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'user') . '/user.module';
315
    return user_access('administer software updates');
316
  }
317
  catch (Exception $e) {
318
    return ($user->uid == 1);
319
  }
320
}
321

    
322
/**
323
 * Adds the update task list to the current page.
324
 */
325
function update_task_list($active = NULL) {
326
  // Default list of tasks.
327
  $tasks = array(
328
    'requirements' => 'Verify requirements',
329
    'info' => 'Overview',
330
    'select' => 'Review updates',
331
    'run' => 'Run updates',
332
    'finished' => 'Review log',
333
  );
334

    
335
  drupal_add_region_content('sidebar_first', theme('task_list', array('items' => $tasks, 'active' => $active)));
336
}
337

    
338
/**
339
 * Returns and stores extra requirements that apply during the update process.
340
 */
341
function update_extra_requirements($requirements = NULL) {
342
  static $extra_requirements = array();
343
  if (isset($requirements)) {
344
    $extra_requirements += $requirements;
345
  }
346
  return $extra_requirements;
347
}
348

    
349
/**
350
 * Checks update requirements and reports errors and (optionally) warnings.
351
 *
352
 * @param $skip_warnings
353
 *   (optional) If set to TRUE, requirement warnings will be ignored, and a
354
 *   report will only be issued if there are requirement errors. Defaults to
355
 *   FALSE.
356
 */
357
function update_check_requirements($skip_warnings = FALSE) {
358
  // Check requirements of all loaded modules.
359
  $requirements = module_invoke_all('requirements', 'update');
360
  $requirements += update_extra_requirements();
361
  $severity = drupal_requirements_severity($requirements);
362

    
363
  // If there are errors, always display them. If there are only warnings, skip
364
  // them if the caller has indicated they should be skipped.
365
  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && !$skip_warnings)) {
366
    update_task_list('requirements');
367
    drupal_set_title('Requirements problem');
368
    $status_report = theme('status_report', array('requirements' => $requirements));
369
    $status_report .= 'Check the error messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
370
    print theme('update_page', array('content' => $status_report));
371
    exit();
372
  }
373
}
374

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

    
379
// We prepare a minimal bootstrap for the update requirements check to avoid
380
// reaching the PHP memory limit.
381
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
382
require_once DRUPAL_ROOT . '/includes/update.inc';
383
require_once DRUPAL_ROOT . '/includes/common.inc';
384
require_once DRUPAL_ROOT . '/includes/file.inc';
385
require_once DRUPAL_ROOT . '/includes/entity.inc';
386
require_once DRUPAL_ROOT . '/includes/unicode.inc';
387
update_prepare_d7_bootstrap();
388

    
389
// Temporarily disable configurable timezones so the upgrade process uses the
390
// site-wide timezone. This prevents a PHP notice during session initlization
391
// and before offsets have been converted in user_update_7002().
392
$configurable_timezones = variable_get('configurable_timezones', 1);
393
$conf['configurable_timezones'] = 0;
394

    
395
// Determine if the current user has access to run update.php.
396
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
397

    
398
// Reset configurable timezones.
399
$conf['configurable_timezones'] = $configurable_timezones;
400

    
401
// Only allow the requirements check to proceed if the current user has access
402
// to run updates (since it may expose sensitive information about the site's
403
// configuration).
404
$op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
405
if (empty($op) && update_access_allowed()) {
406
  require_once DRUPAL_ROOT . '/includes/install.inc';
407
  require_once DRUPAL_ROOT . '/modules/system/system.install';
408

    
409
  // Load module basics.
410
  include_once DRUPAL_ROOT . '/includes/module.inc';
411
  $module_list['system']['filename'] = 'modules/system/system.module';
412
  module_list(TRUE, FALSE, FALSE, $module_list);
413
  drupal_load('module', 'system');
414

    
415
  // Reset the module_implements() cache so that any new hook implementations
416
  // in updated code are picked up.
417
  module_implements('', FALSE, TRUE);
418

    
419
  // Set up $language, since the installer components require it.
420
  drupal_language_initialize();
421

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

    
425
  // Check the update requirements for Drupal. Only report on errors at this
426
  // stage, since the real requirements check happens further down.
427
  update_check_requirements(TRUE);
428

    
429
  // Redirect to the update information page if all requirements were met.
430
  install_goto('update.php?op=info');
431
}
432

    
433
// update_fix_d7_requirements() needs to run before bootstrapping beyond path.
434
// So bootstrap to DRUPAL_BOOTSTRAP_LANGUAGE then include unicode.inc.
435

    
436
drupal_bootstrap(DRUPAL_BOOTSTRAP_LANGUAGE);
437
include_once DRUPAL_ROOT . '/includes/unicode.inc';
438

    
439
update_fix_d7_requirements();
440

    
441
// Now proceed with a full bootstrap.
442

    
443
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
444
drupal_maintenance_theme();
445

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

    
450
// Only proceed with updates if the user is allowed to run them.
451
if (update_access_allowed()) {
452

    
453
  include_once DRUPAL_ROOT . '/includes/install.inc';
454
  include_once DRUPAL_ROOT . '/includes/batch.inc';
455
  drupal_load_updates();
456

    
457
  update_fix_compatibility();
458

    
459
  // Check the update requirements for all modules. If there are warnings, but
460
  // no errors, skip reporting them if the user has provided a URL parameter
461
  // acknowledging the warnings and indicating a desire to continue anyway. See
462
  // drupal_requirements_url().
463
  $skip_warnings = !empty($_GET['continue']);
464
  update_check_requirements($skip_warnings);
465

    
466
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
467
  switch ($op) {
468
    // update.php ops.
469

    
470
    case 'selection':
471
      if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'update')) {
472
        $output = update_selection_page();
473
        break;
474
      }
475

    
476
    case 'Apply pending updates':
477
      if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'update')) {
478
        // Generate absolute URLs for the batch processing (using $base_root),
479
        // since the batch API will pass them to url() which does not handle
480
        // update.php correctly by default.
481
        $batch_url = $base_root . drupal_current_script_url();
482
        $redirect_url = $base_root . drupal_current_script_url(array('op' => 'results'));
483
        update_batch($_POST['start'], $redirect_url, $batch_url);
484
        break;
485
      }
486

    
487
    case 'info':
488
      $output = update_info_page();
489
      break;
490

    
491
    case 'results':
492
      $output = update_results_page();
493
      break;
494

    
495
    // Regular batch ops : defer to batch processing API.
496
    default:
497
      update_task_list('run');
498
      $output = _batch_page();
499
      break;
500
  }
501
}
502
else {
503
  $output = update_access_denied_page();
504
}
505
if (isset($output) && $output) {
506
  // Explicitly start a session so that the update.php token will be accepted.
507
  drupal_session_start();
508
  // We defer the display of messages until all updates are done.
509
  $progress_page = ($batch = batch_get()) && isset($batch['running']);
510
  print theme('update_page', array('content' => $output, 'show_messages' => !$progress_page));
511
}