Back to 7.x-dev.
[project/drupal.git] / update.php
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 $links[] = '<a href="' . base_path() . '?q=admin">Administration pages</a>';
149 return $links;
150 }
151
152 function update_results_page() {
153 drupal_set_title('Drupal database update');
154 $links = update_helpful_links();
155
156 update_task_list();
157 // Report end result.
158 if (module_exists('dblog')) {
159 $log_message = ' All errors have been <a href="' . base_path() . '?q=admin/reports/dblog">logged</a>.';
160 }
161 else {
162 $log_message = ' All errors have been logged.';
163 }
164
165 if ($_SESSION['update_success']) {
166 $output = '<p>Updates were attempted. If you see no failures below, you may proceed happily to the <a href="' . base_path() . '?q=admin">administration pages</a>. Otherwise, you may need to update your database manually.' . $log_message . '</p>';
167 }
168 else {
169 list($module, $version) = array_pop(reset($_SESSION['updates_remaining']));
170 $output = '<p class="error">The update process was aborted prematurely while running <strong>update #' . $version . ' in ' . $module . '.module</strong>.' . $log_message;
171 if (module_exists('dblog')) {
172 $output .= ' You may need to check the <code>watchdog</code> database table manually.';
173 }
174 $output .= '</p>';
175 }
176
177 if (!empty($GLOBALS['update_free_access'])) {
178 $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>";
179 }
180
181 $output .= theme('item_list', array('items' => $links));
182
183 // Output a list of queries executed.
184 if (!empty($_SESSION['update_results'])) {
185 $all_messages = '';
186 foreach ($_SESSION['update_results'] as $module => $updates) {
187 if ($module != '#abort') {
188 $module_has_message = FALSE;
189 $query_messages = '';
190 foreach ($updates as $number => $queries) {
191 $messages = array();
192 foreach ($queries as $query) {
193 // If there is no message for this update, don't show anything.
194 if (empty($query['query'])) {
195 continue;
196 }
197
198 if ($query['success']) {
199 $messages[] = '<li class="success">' . $query['query'] . '</li>';
200 }
201 else {
202 $messages[] = '<li class="failure"><strong>Failed:</strong> ' . $query['query'] . '</li>';
203 }
204 }
205
206 if ($messages) {
207 $module_has_message = TRUE;
208 $query_messages .= '<h4>Update #' . $number . "</h4>\n";
209 $query_messages .= '<ul>' . implode("\n", $messages) . "</ul>\n";
210 }
211 }
212
213 // If there were any messages in the queries then prefix them with the
214 // module name and add it to the global message list.
215 if ($module_has_message) {
216 $all_messages .= '<h3>' . $module . " module</h3>\n" . $query_messages;
217 }
218 }
219 }
220 if ($all_messages) {
221 $output .= '<div id="update-results"><h2>The following updates returned messages</h2>';
222 $output .= $all_messages;
223 $output .= '</div>';
224 }
225 }
226 unset($_SESSION['update_results']);
227 unset($_SESSION['update_success']);
228
229 return $output;
230 }
231
232 function update_info_page() {
233 // Change query-strings on css/js files to enforce reload for all users.
234 _drupal_flush_css_js();
235 // Flush the cache of all data for the update status module.
236 if (db_table_exists('cache_update')) {
237 cache_clear_all('*', 'cache_update', TRUE);
238 }
239
240 update_task_list('info');
241 drupal_set_title('Drupal database update');
242 $token = drupal_get_token('update');
243 $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>';
244 $output .= "<ol>\n";
245 $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";
246 $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";
247 $output .= '<li>Put your site into <a href="' . base_path() . '?q=admin/config/development/maintenance">maintenance mode</a>.</li>' . "\n";
248 $output .= "<li>Install your new files in the appropriate location, as described in the handbook.</li>\n";
249 $output .= "</ol>\n";
250 $output .= "<p>When you have performed the steps above, you may proceed.</p>\n";
251 $form_action = check_url(drupal_current_script_url(array('op' => 'selection', 'token' => $token)));
252 $output .= '<form method="post" action="' . $form_action . '"><p><input type="submit" value="Continue" class="form-submit" /></p></form>';
253 $output .= "\n";
254 return $output;
255 }
256
257 function update_access_denied_page() {
258 drupal_add_http_header('Status', '403 Forbidden');
259 watchdog('access denied', 'update.php', NULL, WATCHDOG_WARNING);
260 drupal_set_title('Access denied');
261 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>
262 <ol>
263 <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>
264 <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>
265 <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>
266 <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>
267 </ol>';
268 }
269
270 /**
271 * Determines if the current user is allowed to run update.php.
272 *
273 * @return
274 * TRUE if the current user should be granted access, or FALSE otherwise.
275 */
276 function update_access_allowed() {
277 global $update_free_access, $user;
278
279 // Allow the global variable in settings.php to override the access check.
280 if (!empty($update_free_access)) {
281 return TRUE;
282 }
283 // Calls to user_access() might fail during the Drupal 6 to 7 update process,
284 // so we fall back on requiring that the user be logged in as user #1.
285 try {
286 require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'user') . '/user.module';
287 return user_access('administer software updates');
288 }
289 catch (Exception $e) {
290 return ($user->uid == 1);
291 }
292 }
293
294 /**
295 * Add the update task list to the current page.
296 */
297 function update_task_list($active = NULL) {
298 // Default list of tasks.
299 $tasks = array(
300 'requirements' => 'Verify requirements',
301 'info' => 'Overview',
302 'select' => 'Review updates',
303 'run' => 'Run updates',
304 'finished' => 'Review log',
305 );
306
307 drupal_add_region_content('sidebar_first', theme('task_list', array('items' => $tasks, 'active' => $active)));
308 }
309
310 /**
311 * Returns (and optionally stores) extra requirements that only apply during
312 * particular parts of the update.php process.
313 */
314 function update_extra_requirements($requirements = NULL) {
315 static $extra_requirements = array();
316 if (isset($requirements)) {
317 $extra_requirements += $requirements;
318 }
319 return $extra_requirements;
320 }
321
322 /**
323 * Check update requirements and report any errors or (optionally) warnings.
324 *
325 * @param $skip_warnings
326 * (optional) If set to TRUE, requirement warnings will be ignored, and a
327 * report will only be issued if there are requirement errors. Defaults to
328 * FALSE.
329 */
330 function update_check_requirements($skip_warnings = FALSE) {
331 // Check requirements of all loaded modules.
332 $requirements = module_invoke_all('requirements', 'update');
333 $requirements += update_extra_requirements();
334 $severity = drupal_requirements_severity($requirements);
335
336 // If there are errors, always display them. If there are only warnings, skip
337 // them if the caller has indicated they should be skipped.
338 if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && !$skip_warnings)) {
339 update_task_list('requirements');
340 drupal_set_title('Requirements problem');
341 $status_report = theme('status_report', array('requirements' => $requirements));
342 $status_report .= 'Check the error messages and <a href="' . check_url(drupal_requirements_url($severity)) . '">try again</a>.';
343 print theme('update_page', array('content' => $status_report));
344 exit();
345 }
346 }
347
348 // Some unavoidable errors happen because the database is not yet up-to-date.
349 // Our custom error handler is not yet installed, so we just suppress them.
350 ini_set('display_errors', FALSE);
351
352 // We prepare a minimal bootstrap for the update requirements check to avoid
353 // reaching the PHP memory limit.
354 require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
355 require_once DRUPAL_ROOT . '/includes/update.inc';
356 require_once DRUPAL_ROOT . '/includes/common.inc';
357 require_once DRUPAL_ROOT . '/includes/file.inc';
358 require_once DRUPAL_ROOT . '/includes/entity.inc';
359 require_once DRUPAL_ROOT . '/includes/unicode.inc';
360 update_prepare_d7_bootstrap();
361
362 // Temporarily disable configurable timezones so the upgrade process uses the
363 // site-wide timezone. This prevents a PHP notice during session initlization
364 // and before offsets have been converted in user_update_7002().
365 $configurable_timezones = variable_get('configurable_timezones', 1);
366 $conf['configurable_timezones'] = 0;
367
368 // Determine if the current user has access to run update.php.
369 drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
370
371 // Reset configurable timezones.
372 $conf['configurable_timezones'] = $configurable_timezones;
373
374 // Only allow the requirements check to proceed if the current user has access
375 // to run updates (since it may expose sensitive information about the site's
376 // configuration).
377 $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
378 if (empty($op) && update_access_allowed()) {
379 require_once DRUPAL_ROOT . '/includes/install.inc';
380 require_once DRUPAL_ROOT . '/modules/system/system.install';
381
382 // Load module basics.
383 include_once DRUPAL_ROOT . '/includes/module.inc';
384 $module_list['system']['filename'] = 'modules/system/system.module';
385 module_list(TRUE, FALSE, FALSE, $module_list);
386 drupal_load('module', 'system');
387
388 // Reset the module_implements() cache so that any new hook implementations
389 // in updated code are picked up.
390 module_implements('', FALSE, TRUE);
391
392 // Set up $language, since the installer components require it.
393 drupal_language_initialize();
394
395 // Set up theme system for the maintenance page.
396 drupal_maintenance_theme();
397
398 // Check the update requirements for Drupal. Only report on errors at this
399 // stage, since the real requirements check happens further down.
400 update_check_requirements(TRUE);
401
402 // Redirect to the update information page if all requirements were met.
403 install_goto('update.php?op=info');
404 }
405
406 // update_fix_d7_requirements() needs to run before bootstrapping beyond path.
407 // So bootstrap to DRUPAL_BOOTSTRAP_LANGUAGE then include unicode.inc.
408
409 drupal_bootstrap(DRUPAL_BOOTSTRAP_LANGUAGE);
410 include_once DRUPAL_ROOT . '/includes/unicode.inc';
411
412 update_fix_d7_requirements();
413
414 // Now proceed with a full bootstrap.
415
416 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
417 drupal_maintenance_theme();
418
419 // Turn error reporting back on. From now on, only fatal errors (which are
420 // not passed through the error handler) will cause a message to be printed.
421 ini_set('display_errors', TRUE);
422
423 // Only proceed with updates if the user is allowed to run them.
424 if (update_access_allowed()) {
425
426 include_once DRUPAL_ROOT . '/includes/install.inc';
427 include_once DRUPAL_ROOT . '/includes/batch.inc';
428 drupal_load_updates();
429
430 update_fix_compatibility();
431
432 // Check the update requirements for all modules. If there are warnings, but
433 // no errors, skip reporting them if the user has provided a URL parameter
434 // acknowledging the warnings and indicating a desire to continue anyway. See
435 // drupal_requirements_url().
436 $skip_warnings = !empty($_GET['continue']);
437 update_check_requirements($skip_warnings);
438
439 $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
440 switch ($op) {
441 // update.php ops.
442
443 case 'selection':
444 if (isset($_GET['token']) && $_GET['token'] == drupal_get_token('update')) {
445 $output = update_selection_page();
446 break;
447 }
448
449 case 'Apply pending updates':
450 if (isset($_GET['token']) && $_GET['token'] == drupal_get_token('update')) {
451 // Generate absolute URLs for the batch processing (using $base_root),
452 // since the batch API will pass them to url() which does not handle
453 // update.php correctly by default.
454 $batch_url = $base_root . drupal_current_script_url();
455 $redirect_url = $base_root . drupal_current_script_url(array('op' => 'results'));
456 update_batch($_POST['start'], $redirect_url, $batch_url);
457 break;
458 }
459
460 case 'info':
461 $output = update_info_page();
462 break;
463
464 case 'results':
465 $output = update_results_page();
466 break;
467
468 // Regular batch ops : defer to batch processing API.
469 default:
470 update_task_list('run');
471 $output = _batch_page();
472 break;
473 }
474 }
475 else {
476 $output = update_access_denied_page();
477 }
478 if (isset($output) && $output) {
479 // Explicitly start a session so that the update.php token will be accepted.
480 drupal_session_start();
481 // We defer the display of messages until all updates are done.
482 $progress_page = ($batch = batch_get()) && isset($batch['running']);
483 print theme('update_page', array('content' => $output, 'show_messages' => !$progress_page));
484 }