initial import from onelab svn codebase
[plewww.git] / update.php
1 <?php
2 // $Id: update.php 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Administrative page for handling updates from one Drupal version to another.
7  *
8  * Point your browser to "http://www.example.com/update.php" and follow the
9  * instructions.
10  *
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!
15  */
16
17 // Enforce access checking?
18 $access_check = TRUE;
19
20
21 function update_sql($sql) {
22   $result = db_query($sql);
23   return array('success' => $result !== FALSE, 'query' => check_plain($sql));
24 }
25
26 /**
27  * Add a column to a database using syntax appropriate for PostgreSQL.
28  * Save result of SQL commands in $ret array.
29  *
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
34  * DEFAULT value.
35  *
36  * @param $ret
37  *   Array to which results will be added.
38  * @param $table
39  *   Name of the table, without {}
40  * @param $column
41  *   Name of the column
42  * @param $type
43  *   Type of column
44  * @param $attributes
45  *   Additional optional attributes. Recognized attributes:
46  *     not null => TRUE|FALSE
47  *     default  => NULL|FALSE|value (with or without '', it won't be added)
48  * @return
49  *   nothing, but modifies $ret parameter.
50  */
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';
54   }
55   if (array_key_exists('default', $attributes)) {
56     if (is_null($attributes['default'])) {
57       $default_val = 'NULL';
58       $default = 'default NULL';
59     }
60     elseif ($attributes['default'] === FALSE) {
61       $default = '';
62     }
63     else {
64       $default_val = "$attributes[default]";
65       $default = "default $attributes[default]";
66     }
67   }
68
69   $ret[] = update_sql("ALTER TABLE {". $table ."} ADD $column $type");
70   if ($default) { $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET $default"); }
71   if ($not_null) {
72     if ($default) { $ret[] = update_sql("UPDATE {". $table ."} SET $column = $default_val"); }
73     $ret[] = update_sql("ALTER TABLE {". $table ."} ALTER $column SET NOT NULL");
74   }
75 }
76
77 /**
78  * Change a column definition using syntax appropriate for PostgreSQL.
79  * Save result of SQL commands in $ret array.
80  *
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
84  * recreated.
85  *
86  * @param $ret
87  *   Array to which results will be added.
88  * @param $table
89  *   Name of the table, without {}
90  * @param $column
91  *   Name of the column to change
92  * @param $column_new
93  *   New name for the column (set to the same as $column if you don't want to change the name)
94  * @param $type
95  *   Type of column
96  * @param $attributes
97  *   Additional optional attributes. Recognized attributes:
98  *     not null => TRUE|FALSE
99  *     default  => NULL|FALSE|value (with or without '', it won't be added)
100  * @return
101  *   nothing, but modifies $ret parameter.
102  */
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';
106   }
107   if (array_key_exists('default', $attributes)) {
108     if (is_null($attributes['default'])) {
109       $default_val = 'NULL';
110       $default = 'default NULL';
111     }
112     elseif ($attributes['default'] === FALSE) {
113       $default = '';
114     }
115     else {
116       $default_val = "$attributes[default]";
117       $default = "default $attributes[default]";
118     }
119   }
120
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");
127 }
128
129 /**
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
132  * table.
133  *
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.
136  */
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
141     // throwing errors.
142     switch ($update_start) {
143       case '2005-04-14':
144         variable_set('update_132_done', TRUE);
145         break;
146
147       case '2005-05-06':
148         variable_set('update_132_done', TRUE);
149         variable_set('update_135_done', TRUE);
150         break;
151
152       case '2005-05-07':
153         variable_set('update_132_done', TRUE);
154         variable_set('update_135_done', TRUE);
155         variable_set('update_137_done', TRUE);
156         break;
157
158     }
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);
162
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,
183     );
184
185     // Add schema version column
186     switch ($GLOBALS['db_type']) {
187       case 'pgsql':
188         $ret = array();
189         db_add_column($ret, 'system', 'schema_version', 'smallint', array('not null' => TRUE, 'default' => -1));
190         break;
191
192       case 'mysql':
193       case 'mysqli':
194         db_query('ALTER TABLE {system} ADD schema_version smallint(3) not null default -1');
195         break;
196     }
197     // Set all enabled (contrib) modules to schema version 0 (installed)
198     db_query('UPDATE {system} SET schema_version = 0 WHERE status = 1');
199
200     // Set schema version for core
201     drupal_set_installed_schema_version('system', $sql_updates[$update_start]);
202     variable_del('update_start');
203   }
204 }
205
206 /**
207  * System update 130 changes the sessions table, which breaks the update
208  * script's ability to use session variables. This changes the table
209  * appropriately.
210  *
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.
213  */
214 function update_fix_sessions() {
215   $ret = array();
216
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");
220     }
221     elseif ($GLOBALS['db_type'] == 'pgsql') {
222       db_add_column($ret, 'sessions', 'cache', 'int', array('default' => 0, 'not null' => TRUE));
223     }
224
225     variable_set('update_sessions_fixed', TRUE);
226   }
227 }
228
229 /**
230  * System update 115 changes the watchdog table, which breaks the update
231  * script's ability to use logging. This changes the table appropriately.
232  *
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.
235  */
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'");
240     }
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');
246     }
247
248     variable_set('update_watchdog_115_fixed', TRUE);
249   }
250 }
251
252 /**
253  * System update 142 changes the watchdog table, which breaks the update
254  * script's ability to use logging. This changes the table appropriately.
255  *
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.
258  */
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']) {
262       case 'pgsql':
263         $ret = array();
264         db_add_column($ret, 'watchdog', 'referer', 'varchar(128)', array('not null' => TRUE, 'default' => "''"));
265         break;
266       case 'mysql':
267       case 'mysqli':
268         db_query("ALTER TABLE {watchdog} ADD COLUMN referer varchar(128) NOT NULL");
269         break;
270     }
271
272     variable_set('update_watchdog_fixed', TRUE);
273   }
274 }
275
276 /**
277  * Perform one update and store the results which will later be displayed on
278  * the finished page.
279  *
280  * @param $module
281  *   The module whose update will be run.
282  * @param $number
283  *   The update number to run.
284  *
285  * @return
286  *   TRUE if the update was finished. Otherwise, FALSE.
287  */
288 function update_data($module, $number) {
289   $ret = module_invoke($module, 'update_'. $number);
290   // Assume the update finished unless the update results indicate otherwise.
291   $finished = 1;
292   if (isset($ret['#finished'])) {
293     $finished = $ret['#finished'];
294     unset($ret['#finished']);
295   }
296
297   // Save the query and results for display by update_finished_page().
298   if (!isset($_SESSION['update_results'])) {
299     $_SESSION['update_results'] = array();
300   }
301   if (!isset($_SESSION['update_results'][$module])) {
302     $_SESSION['update_results'][$module] = array();
303   }
304   if (!isset($_SESSION['update_results'][$module][$number])) {
305     $_SESSION['update_results'][$module][$number] = array();
306   }
307   $_SESSION['update_results'][$module][$number] = array_merge($_SESSION['update_results'][$module][$number], $ret);
308
309   if ($finished == 1) {
310     // Update the installed version
311     drupal_set_installed_schema_version($module, $number);
312   }
313
314   return $finished;
315 }
316
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>';
320
321   $form = array();
322   $form['start'] = array(
323     '#tree' => TRUE,
324     '#type' => 'fieldset',
325     '#title' => 'Select versions',
326     '#collapsible' => TRUE,
327     '#collapsed' => TRUE,
328   );
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';
334
335       $form['start'][$module] = array(
336         '#type' => 'select',
337         '#title' => $module . ' module',
338         '#default_value' => array_search(drupal_get_installed_schema_version($module), $updates) + 1,
339         '#options' => $updates,
340       );
341     }
342   }
343
344   $form['has_js'] = array(
345     '#type' => 'hidden',
346     '#default_value' => FALSE,
347     '#attributes' => array('id' => 'edit-has_js'),
348   );
349   $form['submit'] = array(
350     '#type' => 'submit',
351     '#value' => 'Update',
352   );
353
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);
358
359   return $output;
360 }
361
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);
371       }
372     }
373   }
374   // Keep track of total number of updates
375   $_SESSION['update_total'] = count($_SESSION['update_remaining']);
376
377   if ($_POST['edit']['has_js']) {
378     return update_progress_page();
379   }
380   else {
381     return update_progress_page_nojs();
382   }
383 }
384
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);
389
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>';
393   return $output;
394 }
395
396 /**
397  * Perform updates for one second or until finished.
398  *
399  * @return
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.
402  */
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
410     }
411     if (timer_read('page') > 1000) {
412       break;
413     }
414   }
415
416   if ($_SESSION['update_total']) {
417     $percentage = floor(($_SESSION['update_total'] - count($_SESSION['update_remaining']) + $update_finished) / $_SESSION['update_total'] * 100);
418   }
419   else {
420     $percentage = 100;
421   }
422
423   // When no updates remain, clear the cache.
424   if (!isset($update['module'])) {
425     db_query('DELETE FROM {cache}');
426   }
427
428   return array($percentage, isset($update['module']) ? 'Updating '. $update['module'] .' module' : 'Updating complete');
429 }
430
431 /**
432  * Perform updates for the JS version and return progress.
433  */
434 function update_do_update_page() {
435   global $conf;
436
437   // HTTP Post required
438   if ($_SERVER['REQUEST_METHOD'] != 'POST') {
439     drupal_set_message('HTTP Post is required.', 'error');
440     drupal_set_title('Error');
441     return '';
442   }
443
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));
448 }
449
450 /**
451  * Perform updates for the non-JS version and return the status page.
452  */
453 function update_progress_page_nojs() {
454   drupal_set_title('Updating');
455
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.
460     ob_start();
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);
463
464     list($percentage, $message) = update_do_updates();
465     if ($percentage == 100) {
466       $new_op = 'finished';
467     }
468
469     // Updates successful; remove fallback
470     ob_end_clean();
471   }
472   else {
473     // This is the first page so return some output immediately.
474     $percentage = 0;
475     $message = 'Starting updates';
476   }
477
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>';
481
482   // Note: do not output drupal_set_message()s until the summary page.
483   print theme('maintenance_page', $output, FALSE);
484   return NULL;
485 }
486
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>';
492
493   // Report end result
494   if ($success) {
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>';
496   }
497   else {
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>';
500   }
501
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>";
504   }
505
506   $output .= theme('item_list', $links);
507
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>';
516         $output .= '<ul>';
517         foreach ($queries as $query) {
518           if ($query['success']) {
519             $output .= '<li class="success">'. $query['query'] .'</li>';
520           }
521           else {
522             $output .= '<li class="failure"><strong>Failed:</strong> '. $query['query'] .'</li>';
523           }
524         }
525         if (!count($queries)) {
526           $output .= '<li class="none">No queries</li>';
527         }
528         $output .= '</ul>';
529       }
530     }
531     $output .= '</div>';
532     unset($_SESSION['update_results']);
533   }
534
535   return $output;
536 }
537
538 function update_info_page() {
539   drupal_set_title('Drupal database update');
540   $output = "<ol>\n";
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";
545   $output .= "</ol>";
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>';
547   return $output;
548 }
549
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>
553 <ol>
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>
558 </ol>';
559 }
560
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)) {
566     $ret = array();
567     switch ($GLOBALS['db_type']) {
568       case 'pgsql':
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)');
571         break;
572       case 'mysql':
573       case 'mysqli':
574         $ret[] = update_sql("ALTER TABLE {system} ADD weight tinyint(2) default '0' NOT NULL, ADD KEY (weight)");
575         break;
576     }
577   }
578 }
579
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)) {
583     return;
584   }
585
586   switch ($GLOBALS['db_type']) {
587     // Only for MySQL 4.1+
588     case 'mysqli':
589       break;
590     case 'mysql':
591       if (version_compare(mysql_get_server_info($GLOBALS['active_db']), '4.1.0', '<')) {
592         return;
593       }
594       break;
595     case 'pgsql':
596       return;
597   }
598
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');
603   }
604
605   // Don't run again
606   variable_set('update_access_fixed', TRUE);
607 }
608
609 /**
610  * Convert a single MySQL table to UTF-8.
611  *
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
615  */
616 function update_convert_table_utf8($table) {
617   $ret = array();
618   $types = array('char' => 'binary',
619                  'varchar' => 'varbinary',
620                  'tinytext' => 'tinyblob',
621                  'text' => 'blob',
622                  'mediumtext' => 'mediumblob',
623                  'longtext' => 'longblob');
624
625   // Get next table in list
626   $convert_to_binary = array();
627   $convert_to_utf8 = array();
628
629   // Set table default charset
630   $ret[] = update_sql('ALTER TABLE {'. $table .'} DEFAULT CHARACTER SET utf8');
631
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');
641
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;
644     }
645   }
646
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));
652   }
653   return $ret;
654 }
655
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);
659
660 include_once './includes/bootstrap.inc';
661 update_fix_system_table();
662 update_fix_access_table();
663
664 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
665 drupal_maintenance_theme();
666
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);
670
671 // Access check:
672 if (($access_check == FALSE) || ($user->uid == 1)) {
673
674   include_once './includes/install.inc';
675
676   update_fix_schema_version();
677   update_fix_watchdog_115();
678   update_fix_watchdog();
679   update_fix_sessions();
680
681   $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
682   switch ($op) {
683     case 'Update':
684       $output = update_update_page();
685       break;
686
687     case 'finished':
688       $output = update_finished_page(true);
689       break;
690
691     case 'error':
692       $output = update_finished_page(false);
693       break;
694
695     case 'do_update':
696       $output = update_do_update_page();
697       break;
698
699     case 'do_update_nojs':
700       $output = update_progress_page_nojs();
701       break;
702
703     case 'selection':
704       $output = update_selection_page();
705       break;
706
707     default:
708       $output = update_info_page();
709       break;
710   }
711 }
712 else {
713   $output = update_access_denied_page();
714 }
715
716 if (isset($output)) {
717   print theme('maintenance_page', $output);
718 }