2 // $Id: update.php 144 2007-03-28 07:52:20Z thierry $
6 * Administrative page for handling updates from one Drupal version to another.
8 * Point your browser to "http://www.example.com/update.php" and follow the
11 * If you are not logged in as administrator, you will need to modify the access
12 * check statement below. Change the TRUE to a FALSE to disable the access
13 * check. After finishing the upgrade, be sure to open this file and change the
14 * FALSE back to a TRUE!
17 // Enforce access checking?
21 function update_sql($sql) {
22 $result = db_query($sql);
23 return array('success' => $result !== FALSE, 'query' => check_plain($sql));
27 * Add a column to a database using syntax appropriate for PostgreSQL.
28 * Save result of SQL commands in $ret array.
30 * Note: when you add a column with NOT NULL and you are not sure if there are
31 * already rows in the table, you MUST also add DEFAULT. Otherwise PostgreSQL won't
32 * work when the table is not empty. If NOT NULL and DEFAULT are set the
33 * PostgreSQL version will set values of the added column in old rows to the
37 * Array to which results will be added.
39 * Name of the table, without {}
45 * Additional optional attributes. Recognized attributes:
46 * not null => TRUE|FALSE
47 * default => NULL|FALSE|value (with or without '', it won't be added)
49 * nothing, but modifies $ret parameter.
51 function db_add_column(&$ret, $table, $column, $type, $attributes = array()) {
52 if (array_key_exists('not null', $attributes) and $attributes['not null']) {
53 $not_null = 'NOT NULL';
55 if (array_key_exists('default', $attributes)) {
56 if (is_null($attributes['default'])) {
57 $default_val = 'NULL';
58 $default = 'default NULL';
60 elseif ($attributes['default'] === FALSE) {
64 $default_val = "$attributes[default]";
65 $default = "default $attributes[default]";
69 $ret[] = update_sql("ALTER TABLE {". $table ."} ADD $column $type");
70 if ($default) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET $default"); }
72 if ($default) { $ret[] = update_sql("UPDATE {". $table ."} SET $column = $default_val"); }
73 $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET NOT NULL");
78 * Change a column definition using syntax appropriate for PostgreSQL.
79 * Save result of SQL commands in $ret array.
81 * Remember that changing a column definition involves adding a new column
82 * and dropping an old one. This means that any indices, primary keys and
83 * sequences from serial-type columns are dropped and might need to be
87 * Array to which results will be added.
89 * Name of the table, without {}
91 * Name of the column to change
93 * New name for the column (set to the same as $column if you don't want to change the name)
97 * Additional optional attributes. Recognized attributes:
98 * not null => TRUE|FALSE
99 * default => NULL|FALSE|value (with or without '', it won't be added)
101 * nothing, but modifies $ret parameter.
103 function db_change_column(&$ret, $table, $column, $column_new, $type, $attributes = array()) {
104 if (array_key_exists('not null', $attributes) and $attributes['not null']) {
105 $not_null = 'NOT NULL';
107 if (array_key_exists('default', $attributes)) {
108 if (is_null($attributes['default'])) {
109 $default_val = 'NULL';
110 $default = 'default NULL';
112 elseif ($attributes['default'] === FALSE) {
116 $default_val = "$attributes[default]";
117 $default = "default $attributes[default]";
121 $ret[] = update_sql("ALTER TABLE {". $table ."} RENAME $column TO ". $column ."_old");
122 $ret[] = update_sql("ALTER TABLE {". $table ."} ADD $column_new $type");
123 $ret[] = update_sql("UPDATE {". $table ."} SET $column_new = ". $column ."_old");
124 if ($default) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column_new SET $default"); }
125 if ($not_null) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column_new SET NOT NULL"); }
126 $ret[] = update_sql("ALTER TABLE {". $table ."} DROP ". $column ."_old");
130 * If the schema version for Drupal core is stored in the variables table
131 * (4.6.x and earlier) move it to the schema_version column of the system
134 * This function may be removed when update 156 is removed, which is the last
135 * update in the 4.6 to 4.7 migration.
137 function update_fix_schema_version() {
138 if ($update_start = variable_get('update_start', FALSE)) {
139 // Some updates were made to the 4.6 branch and 4.7 branch. This sets
140 // temporary variables to prevent the updates from being executed twice and
142 switch ($update_start) {
144 variable_set('update_132_done', TRUE);
148 variable_set('update_132_done', TRUE);
149 variable_set('update_135_done', TRUE);
153 variable_set('update_132_done', TRUE);
154 variable_set('update_135_done', TRUE);
155 variable_set('update_137_done', TRUE);
159 // The schema_version column (added below) was changed during 4.7beta.
160 // Update_170 is only for those beta users.
161 variable_set('update_170_done', TRUE);
163 $sql_updates = array(
164 '2004-10-31: first update since Drupal 4.5.0 release' => 110,
165 '2004-11-07' => 111, '2004-11-15' => 112, '2004-11-28' => 113,
166 '2004-12-05' => 114, '2005-01-07' => 115, '2005-01-14' => 116,
167 '2005-01-18' => 117, '2005-01-19' => 118, '2005-01-20' => 119,
168 '2005-01-25' => 120, '2005-01-26' => 121, '2005-01-27' => 122,
169 '2005-01-28' => 123, '2005-02-11' => 124, '2005-02-23' => 125,
170 '2005-03-03' => 126, '2005-03-18' => 127, '2005-03-21' => 128,
171 // The following three updates were made on the 4.6 branch
172 '2005-04-14' => 128, '2005-05-06' => 128, '2005-05-07' => 128,
173 '2005-04-08: first update since Drupal 4.6.0 release' => 129,
174 '2005-04-10' => 130, '2005-04-11' => 131, '2005-04-14' => 132,
175 '2005-04-24' => 133, '2005-04-30' => 134, '2005-05-06' => 135,
176 '2005-05-08' => 136, '2005-05-09' => 137, '2005-05-10' => 138,
177 '2005-05-11' => 139, '2005-05-12' => 140, '2005-05-22' => 141,
178 '2005-07-29' => 142, '2005-07-30' => 143, '2005-08-08' => 144,
179 '2005-08-15' => 145, '2005-08-25' => 146, '2005-09-07' => 147,
180 '2005-09-18' => 148, '2005-09-27' => 149, '2005-10-15' => 150,
181 '2005-10-23' => 151, '2005-10-28' => 152, '2005-11-03' => 153,
182 '2005-11-14' => 154, '2005-11-27' => 155, '2005-12-03' => 156,
185 // Add schema version column
186 switch ($GLOBALS['db_type']) {
189 db_add_column($ret, 'system', 'schema_version', 'smallint', array('not null' => TRUE, 'default' => -1));
194 db_query('ALTER TABLE {system} ADD schema_version smallint(3) not null default -1');
197 // Set all enabled (contrib) modules to schema version 0 (installed)
198 db_query('UPDATE {system} SET schema_version = 0 WHERE status = 1');
200 // Set schema version for core
201 drupal_set_installed_schema_version('system', $sql_updates[$update_start]);
202 variable_del('update_start');
207 * System update 130 changes the sessions table, which breaks the update
208 * script's ability to use session variables. This changes the table
211 * This code, including the 'update_sessions_fixed' variable, may be removed
212 * when update 130 is removed. It is part of the Drupal 4.6 to 4.7 migration.
214 function update_fix_sessions() {
217 if (drupal_get_installed_schema_version('system') < 130 && !variable_get('update_sessions_fixed', FALSE)) {
218 if ($GLOBALS['db_type'] == 'mysql') {
219 db_query("ALTER TABLE {sessions} ADD cache int(11) NOT NULL default '0' AFTER timestamp");
221 elseif ($GLOBALS['db_type'] == 'pgsql') {
222 db_add_column($ret, 'sessions', 'cache', 'int', array('default' => 0, 'not null' => TRUE));
225 variable_set('update_sessions_fixed', TRUE);
230 * System update 115 changes the watchdog table, which breaks the update
231 * script's ability to use logging. This changes the table appropriately.
233 * This code, including the 'update_watchdog_115_fixed' variable, may be removed
234 * when update 115 is removed. It is part of the Drupal 4.5 to 4.7 migration.
236 function update_fix_watchdog_115() {
237 if (drupal_get_installed_schema_version('system') < 115 && !variable_get('update_watchdog_115_fixed', FALSE)) {
238 if ($GLOBALS['db_type'] == 'mysql') {
239 $ret[] = update_sql("ALTER TABLE {watchdog} ADD severity tinyint(3) unsigned NOT NULL default '0'");
241 else if ($GLOBALS['db_type'] == 'pgsql') {
242 $ret[] = update_sql('ALTER TABLE {watchdog} ADD severity smallint');
243 $ret[] = update_sql('UPDATE {watchdog} SET severity = 0');
244 $ret[] = update_sql('ALTER TABLE {watchdog} ALTER COLUMN severity SET NOT NULL');
245 $ret[] = update_sql('ALTER TABLE {watchdog} ALTER COLUMN severity SET DEFAULT 0');
248 variable_set('update_watchdog_115_fixed', TRUE);
253 * System update 142 changes the watchdog table, which breaks the update
254 * script's ability to use logging. This changes the table appropriately.
256 * This code, including the 'update_watchdog_fixed' variable, may be removed
257 * when update 142 is removed. It is part of the Drupal 4.6 to 4.7 migration.
259 function update_fix_watchdog() {
260 if (drupal_get_installed_schema_version('system') < 142 && !variable_get('update_watchdog_fixed', FALSE)) {
261 switch ($GLOBALS['db_type']) {
264 db_add_column($ret, 'watchdog', 'referer', 'varchar(128)', array('not null' => TRUE, 'default' => "''"));
268 db_query("ALTER TABLE {watchdog} ADD COLUMN referer varchar(128) NOT NULL");
272 variable_set('update_watchdog_fixed', TRUE);
277 * Perform one update and store the results which will later be displayed on
281 * The module whose update will be run.
283 * The update number to run.
286 * TRUE if the update was finished. Otherwise, FALSE.
288 function update_data($module, $number) {
289 $ret = module_invoke($module, 'update_'. $number);
290 // Assume the update finished unless the update results indicate otherwise.
292 if (isset($ret['#finished'])) {
293 $finished = $ret['#finished'];
294 unset($ret['#finished']);
297 // Save the query and results for display by update_finished_page().
298 if (!isset($_SESSION['update_results'])) {
299 $_SESSION['update_results'] = array();
301 if (!isset($_SESSION['update_results'][$module])) {
302 $_SESSION['update_results'][$module] = array();
304 if (!isset($_SESSION['update_results'][$module][$number])) {
305 $_SESSION['update_results'][$module][$number] = array();
307 $_SESSION['update_results'][$module][$number] = array_merge($_SESSION['update_results'][$module][$number], $ret);
309 if ($finished == 1) {
310 // Update the installed version
311 drupal_set_installed_schema_version($module, $number);
317 function update_selection_page() {
318 $output = '<p>The version of Drupal you are updating from has been automatically detected. You can select a different version, but you should not need to.</p>';
319 $output .= '<p>Click Update to start the update process.</p>';
322 $form['start'] = array(
324 '#type' => 'fieldset',
325 '#title' => 'Select versions',
326 '#collapsible' => TRUE,
327 '#collapsed' => TRUE,
329 foreach (module_list() as $module) {
330 $updates = drupal_get_schema_versions($module);
331 if ($updates !== FALSE) {
332 $updates = drupal_map_assoc($updates);
333 $updates[] = 'No updates available';
335 $form['start'][$module] = array(
337 '#title' => $module . ' module',
338 '#default_value' => array_search(drupal_get_installed_schema_version($module), $updates) + 1,
339 '#options' => $updates,
344 $form['has_js'] = array(
346 '#default_value' => FALSE,
347 '#attributes' => array('id' => 'edit-has_js'),
349 $form['submit'] = array(
351 '#value' => 'Update',
354 drupal_set_title('Drupal database update');
355 // Prevent browser from using cached drupal.js or update.js
356 drupal_add_js('misc/update.js', TRUE);
357 $output .= drupal_get_form('update_script_selection_form', $form);
362 function update_update_page() {
363 // Set the installed version so updates start at the correct place.
364 $_SESSION['update_remaining'] = array();
365 foreach ($_POST['edit']['start'] as $module => $version) {
366 drupal_set_installed_schema_version($module, $version - 1);
367 $max_version = max(drupal_get_schema_versions($module));
368 if ($version <= $max_version) {
369 foreach (range($version, $max_version) as $update) {
370 $_SESSION['update_remaining'][] = array('module' => $module, 'version' => $update);
374 // Keep track of total number of updates
375 $_SESSION['update_total'] = count($_SESSION['update_remaining']);
377 if ($_POST['edit']['has_js']) {
378 return update_progress_page();
381 return update_progress_page_nojs();
385 function update_progress_page() {
386 // Prevent browser from using cached drupal.js or update.js
387 drupal_add_js('misc/progress.js', TRUE);
388 drupal_add_js('misc/update.js', TRUE);
390 drupal_set_title('Updating');
391 $output = '<div id="progress"></div>';
392 $output .= '<p id="wait">Please wait while your site is being updated.</p>';
397 * Perform updates for one second or until finished.
400 * An array indicating the status after doing updates. The first element is
401 * the overall percentage finished. The second element is a status message.
403 function update_do_updates() {
404 while (($update = reset($_SESSION['update_remaining']))) {
405 $update_finished = update_data($update['module'], $update['version']);
406 if ($update_finished == 1) {
407 // Dequeue the completed update.
408 unset($_SESSION['update_remaining'][key($_SESSION['update_remaining'])]);
409 $update_finished = 0; // Make sure this step isn't counted double
411 if (timer_read('page') > 1000) {
416 if ($_SESSION['update_total']) {
417 $percentage = floor(($_SESSION['update_total'] - count($_SESSION['update_remaining']) + $update_finished) / $_SESSION['update_total'] * 100);
423 // When no updates remain, clear the cache.
424 if (!isset($update['module'])) {
425 db_query('DELETE FROM {cache}');
428 return array($percentage, isset($update['module']) ? 'Updating '. $update['module'] .' module' : 'Updating complete');
432 * Perform updates for the JS version and return progress.
434 function update_do_update_page() {
437 // HTTP Post required
438 if ($_SERVER['REQUEST_METHOD'] != 'POST') {
439 drupal_set_message('HTTP Post is required.', 'error');
440 drupal_set_title('Error');
444 // Error handling: if PHP dies, the output will fail to parse as JSON, and
445 // the Javascript will tell the user to continue to the op=error page.
446 list($percentage, $message) = update_do_updates();
447 print drupal_to_js(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
451 * Perform updates for the non-JS version and return the status page.
453 function update_progress_page_nojs() {
454 drupal_set_title('Updating');
456 $new_op = 'do_update_nojs';
457 if ($_SERVER['REQUEST_METHOD'] == 'GET') {
458 // Error handling: if PHP dies, it will output whatever is in the output
459 // buffer, followed by the error message.
461 $fallback = '<p class="error">An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference. Please continue to the <a href="update.php?op=error">update summary</a>.</p><p class="error">';
462 print theme('maintenance_page', $fallback, FALSE, TRUE);
464 list($percentage, $message) = update_do_updates();
465 if ($percentage == 100) {
466 $new_op = 'finished';
469 // Updates successful; remove fallback
473 // This is the first page so return some output immediately.
475 $message = 'Starting updates';
478 drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL=update.php?op='. $new_op .'">');
479 $output = theme('progress_bar', $percentage, $message);
480 $output .= '<p>Updating your site will take a few seconds.</p>';
482 // Note: do not output drupal_set_message()s until the summary page.
483 print theme('maintenance_page', $output, FALSE);
487 function update_finished_page($success) {
488 drupal_set_title('Drupal database update');
489 // NOTE: we can't use l() here because the URL would point to 'update.php?q=admin'.
490 $links[] = '<a href="'. base_path() .'">main page</a>';
491 $links[] = '<a href="'. base_path() .'?q=admin">administration pages</a>';
495 $output = '<p>Updates were attempted. If you see no failures below, you may proceed happily to the <a href="index.php?q=admin">administration pages</a>. Otherwise, you may need to update your database manually. All errors have been <a href="index.php?q=admin/logs">logged</a>.</p>';
498 $update = reset($_SESSION['update_remaining']);
499 $output = '<p class="error">The update process was aborted prematurely while running <strong>update #'. $update['version'] .' in '. $update['module'] .'.module</strong>. All other errors have been <a href="index.php?q=admin/logs">logged</a>. You may need to check the <code>watchdog</code> database table manually.</p>';
502 if ($GLOBALS['access_check'] == FALSE) {
503 $output .= "<p><strong>Reminder: don't forget to set the <code>\$access_check</code> value at the top of <code>update.php</code> back to <code>TRUE</code>.</strong></p>";
506 $output .= theme('item_list', $links);
508 // Output a list of queries executed
509 if ($_SESSION['update_results']) {
510 $output .= '<div id="update-results">';
511 $output .= '<h2>The following queries were executed</h2>';
512 foreach ($_SESSION['update_results'] as $module => $updates) {
513 $output .= '<h3>'. $module .' module</h3>';
514 foreach ($updates as $number => $queries) {
515 $output .= '<h4>Update #'. $number .'</h4>';
517 foreach ($queries as $query) {
518 if ($query['success']) {
519 $output .= '<li class="success">'. $query['query'] .'</li>';
522 $output .= '<li class="failure"><strong>Failed:</strong> '. $query['query'] .'</li>';
525 if (!count($queries)) {
526 $output .= '<li class="none">No queries</li>';
532 unset($_SESSION['update_results']);
538 function update_info_page() {
539 drupal_set_title('Drupal database update');
541 $output .= "<li>Use this script to <strong>upgrade an existing Drupal installation</strong>. You don't need this script when installing Drupal from scratch.</li>";
542 $output .= "<li>Before doing anything, backup your database. This process will change your database and its values, and some things might get lost.</li>\n";
543 $output .= "<li>Update your Drupal sources, check the notes below and <a href=\"update.php?op=selection\">run the database upgrade script</a>. Don't upgrade your database twice as it may cause problems.</li>\n";
544 $output .= "<li>Go through the various administration pages to change the existing and new settings to your liking.</li>\n";
546 $output .= '<p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>';
550 function update_access_denied_page() {
551 drupal_set_title('Access denied');
552 return '<p>Access denied. You are not authorized to access this page. Please log in as the admin user (the first user you created). If you cannot log in, you will have to edit <code>update.php</code> to bypass this access check. To do this:</p>
554 <li>With a text editor find the update.php file on your system. It should be in the main Drupal directory that you installed all the files into.</li>
555 <li>There is a line near top of update.php that says <code>$access_check = TRUE;</code>. Change it to <code>$access_check = FALSE;</code>.</li>
556 <li>As soon as the script is done, you must change the update.php script back to its original form to <code>$access_check = TRUE;</code>.</li>
557 <li>To avoid having this problem in future, remember to log in to your website as the admin user (the user you first created) before you backup your database at the beginning of the update process.</li>
561 // This code may be removed later. It is part of the Drupal 4.5 to 4.7 migration.
562 function update_fix_system_table() {
563 drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
564 $row = db_fetch_object(db_query_range('SELECT * FROM {system}', 0, 1));
565 if (!isset($row->weight)) {
567 switch ($GLOBALS['db_type']) {
569 db_add_column($ret, 'system', 'weight', 'smallint', array('not null' => TRUE, 'default' => 0));
570 $ret[] = update_sql('CREATE INDEX {system}_weight_idx ON {system} (weight)');
574 $ret[] = update_sql("ALTER TABLE {system} ADD weight tinyint(2) default '0' NOT NULL, ADD KEY (weight)");
580 // This code may be removed later. It is part of the Drupal 4.6 to 4.7 migration.
581 function update_fix_access_table() {
582 if (variable_get('update_access_fixed', FALSE)) {
586 switch ($GLOBALS['db_type']) {
587 // Only for MySQL 4.1+
591 if (version_compare(mysql_get_server_info($GLOBALS['active_db']), '4.1.0', '<')) {
599 // Convert access table to UTF-8 if needed.
600 $result = db_fetch_array(db_query('SHOW CREATE TABLE {access}'));
601 if (!preg_match('/utf8/i', array_pop($result))) {
602 update_convert_table_utf8('access');
606 variable_set('update_access_fixed', TRUE);
610 * Convert a single MySQL table to UTF-8.
612 * We change all text columns to their corresponding binary type,
613 * then back to text, but with a UTF-8 character set.
614 * See: http://dev.mysql.com/doc/refman/4.1/en/charset-conversion.html
616 function update_convert_table_utf8($table) {
618 $types = array('char' => 'binary',
619 'varchar' => 'varbinary',
620 'tinytext' => 'tinyblob',
622 'mediumtext' => 'mediumblob',
623 'longtext' => 'longblob');
625 // Get next table in list
626 $convert_to_binary = array();
627 $convert_to_utf8 = array();
629 // Set table default charset
630 $ret[] = update_sql('ALTER TABLE {'. $table .'} DEFAULT CHARACTER SET utf8');
632 // Find out which columns need converting and build SQL statements
633 $result = db_query('SHOW FULL COLUMNS FROM {'. $table .'}');
634 while ($column = db_fetch_array($result)) {
635 list($type) = explode('(', $column['Type']);
636 if (isset($types[$type])) {
637 $names = 'CHANGE `'. $column['Field'] .'` `'. $column['Field'] .'` ';
638 $attributes = ' DEFAULT '. ($column['Default'] == 'NULL' ? 'NULL ' :
639 "'". db_escape_string($column['Default']) ."' ") .
640 ($column['Null'] == 'YES' ? 'NULL' : 'NOT NULL');
642 $convert_to_binary[] = $names . preg_replace('/'. $type .'/i', $types[$type], $column['Type']) . $attributes;
643 $convert_to_utf8[] = $names . $column['Type'] .' CHARACTER SET utf8'. $attributes;
647 if (count($convert_to_binary)) {
648 // Convert text columns to binary
649 $ret[] = update_sql('ALTER TABLE {'. $table .'} '. implode(', ', $convert_to_binary));
650 // Convert binary columns to UTF-8
651 $ret[] = update_sql('ALTER TABLE {'. $table .'} '. implode(', ', $convert_to_utf8));
656 // Some unavoidable errors happen because the database is not yet up-to-date.
657 // Our custom error handler is not yet installed, so we just suppress them.
658 ini_set('display_errors', FALSE);
660 include_once './includes/bootstrap.inc';
661 update_fix_system_table();
662 update_fix_access_table();
664 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
665 drupal_maintenance_theme();
667 // Turn error reporting back on. From now on, only fatal errors (which are
668 // not passed through the error handler) will cause a message to be printed.
669 ini_set('display_errors', TRUE);
672 if (($access_check == FALSE) || ($user->uid == 1)) {
674 include_once './includes/install.inc';
676 update_fix_schema_version();
677 update_fix_watchdog_115();
678 update_fix_watchdog();
679 update_fix_sessions();
681 $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
684 $output = update_update_page();
688 $output = update_finished_page(true);
692 $output = update_finished_page(false);
696 $output = update_do_update_page();
699 case 'do_update_nojs':
700 $output = update_progress_page_nojs();
704 $output = update_selection_page();
708 $output = update_info_page();
713 $output = update_access_denied_page();
716 if (isset($output)) {
717 print theme('maintenance_page', $output);