]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - maintenance/updaters.inc
MediaWiki 1.14.0-scripts
[autoinstallsdev/mediawiki.git] / maintenance / updaters.inc
1 <?php
2 /**
3  * @file
4  * @ingroup Maintenance
5  */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8         echo "This file is not a valid entry point\n";
9         exit( 1 );
10 }
11
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 require_once 'deleteDefaultMessages.php';
15 # Extension updates
16 require_once( "$IP/includes/Hooks.php" );
17
18 /**
19  * List of update functions to call on a MySQL-based MediaWiki installation,
20  * in sequence. First item is function name, rest are parameters to pass.
21  */
22 $wgMysqlUpdates = array(
23         // 1.2
24         // update_passwords obsolete
25         array( 'add_field', 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
26         array( 'add_field', 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
27         array( 'do_interwiki_update' ),
28         array( 'do_index_update' ),
29         // do_linkscc_update obsolete
30         array( 'add_table', 'hitcounter',                        'patch-hitcounter.sql' ),
31         array( 'add_field', 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
32         
33         // 1.3
34         array( 'add_field', 'user',          'user_real_name',   'patch-user-realname.sql' ),
35         array( 'add_table', 'querycache',                        'patch-querycache.sql' ),
36         array( 'add_table', 'objectcache',                       'patch-objectcache.sql' ),
37         array( 'add_table', 'categorylinks',                     'patch-categorylinks.sql' ),
38         // do_linkscc_1_3_update obsolete
39         array( 'do_old_links_update' ),
40         array( 'add_field', 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
41         
42         // 1.4
43         array( 'do_image_name_unique_update' ),
44         array( 'add_field', 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
45         array( 'add_field', 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
46         array( 'add_table', 'logging',                           'patch-logging.sql' ),
47         // do_user_rights_update obsolete
48         array( 'add_field', 'user',          'user_token',       'patch-user_token.sql' ),
49         // old, old_articleid, patch-remove-old-title-namespace.sql obsolete
50         // user_groups, patch-userlevels.sql obsolete
51         // do_group_update() obsolete
52         array( 'do_watchlist_update' ),
53         array( 'do_user_update' ),
54         // do_copy_newtalk_to_watchlist obsolete
55         
56         // 1.5
57         array( 'do_schema_restructuring' ),
58         array( 'add_field', 'logging',       'log_params',       'patch-log_params.sql' ),
59         array( 'check_bin', 'logging',       'log_title',        'patch-logging-title.sql', ),
60         array( 'add_field', 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
61         array( 'add_field', 'page',          'page_len',         'patch-page_len.sql' ),
62         array( 'do_inverse_timestamp' ),
63         array( 'do_text_id' ),
64         array( 'add_field', 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
65         array( 'add_field', 'image',         'img_width',        'patch-img_width.sql' ),
66         array( 'add_field', 'image',         'img_metadata',     'patch-img_metadata.sql' ),
67         array( 'add_field', 'user',          'user_email_token', 'patch-user_email_token.sql' ),
68         array( 'add_field', 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
69         array( 'do_namespace_size' ),
70         array( 'add_field', 'image',         'img_media_type',   'patch-img_media_type.sql' ),
71         array( 'do_pagelinks_update' ),
72         array( 'do_drop_img_type' ),
73         array( 'do_user_unique_update' ),
74         array( 'do_user_groups_update' ),
75         array( 'add_field', 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
76         array( 'add_table', 'user_newtalk',                      'patch-usernewtalk2.sql' ),
77         array( 'add_table', 'transcache',                        'patch-transcache.sql' ),
78         array( 'add_field', 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
79         array( 'add_table', 'trackbacks',                        'patch-trackbacks.sql' ),
80         
81         // 1.6
82         array( 'do_watchlist_null' ),
83         // do_image_index_update obsolete
84         array( 'do_logging_timestamp_index' ),
85         array( 'add_field', 'ipblocks',        'ipb_range_start',  'patch-ipb_range_start.sql' ),
86         array( 'do_page_random_update' ),
87         array( 'add_field', 'user',            'user_registration','patch-user_registration.sql' ),
88         array( 'do_templatelinks_update' ),
89         array( 'add_table', 'externallinks',                       'patch-externallinks.sql' ),
90         array( 'add_table', 'job',                                 'patch-job.sql' ),
91         array( 'add_field', 'site_stats',      'ss_images',        'patch-ss_images.sql' ),
92         array( 'add_table', 'langlinks',                           'patch-langlinks.sql' ),
93         array( 'add_table', 'querycache_info',                     'patch-querycacheinfo.sql' ),
94         array( 'add_table', 'filearchive',                         'patch-filearchive.sql' ),
95         array( 'add_field', 'ipblocks',        'ipb_anon_only',    'patch-ipb_anon_only.sql' ),
96         array( 'do_rc_indices_update' ),
97         
98         // 1.9
99         array( 'add_field', 'user',          'user_newpass_time', 'patch-user_newpass_time.sql' ),
100         array( 'add_table', 'redirect',                           'patch-redirect.sql' ),
101         array( 'add_table', 'querycachetwo', 'patch-querycachetwo.sql' ),
102         array( 'add_field', 'ipblocks',      'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
103         array( 'do_backlinking_indices_update' ),
104         array( 'add_field', 'recentchanges', 'rc_old_len',        'patch-rc_len.sql' ),
105         array( 'add_field', 'user',          'user_editcount',    'patch-user_editcount.sql' ),
106         
107         // 1.10
108         array( 'do_restrictions_update' ),
109         array( 'add_field', 'logging',       'log_id',           'patch-log_id.sql' ),
110         array( 'add_field', 'revision',      'rev_parent_id',    'patch-rev_parent_id.sql' ),
111         array( 'add_field', 'page_restrictions', 'pr_id',        'patch-page_restrictions_sortkey.sql' ),
112         array( 'add_field', 'revision',      'rev_len',          'patch-rev_len.sql' ),
113         array( 'add_field', 'recentchanges', 'rc_deleted',       'patch-rc_deleted.sql' ),
114         array( 'add_field', 'logging',       'log_deleted',      'patch-log_deleted.sql' ),
115         array( 'add_field', 'archive',       'ar_deleted',       'patch-ar_deleted.sql' ),
116         array( 'add_field', 'ipblocks',      'ipb_deleted',      'patch-ipb_deleted.sql' ),
117         array( 'add_field', 'filearchive',   'fa_deleted',       'patch-fa_deleted.sql' ),
118         array( 'add_field', 'archive',       'ar_len',           'patch-ar_len.sql' ),
119         
120         // 1.11
121         array( 'add_field', 'ipblocks',      'ipb_block_email',  'patch-ipb_emailban.sql' ),
122         array( 'do_categorylinks_indices_update' ),
123         array( 'add_field', 'oldimage',      'oi_metadata',      'patch-oi_metadata.sql'),
124         array( 'do_archive_user_index' ),
125         array( 'do_image_user_index' ),
126         array( 'do_oldimage_user_index' ),
127         array( 'add_field', 'archive',       'ar_page_id',       'patch-archive-page_id.sql'),
128         array( 'add_field', 'image',         'img_sha1',         'patch-img_sha1.sql' ),
129
130         // 1.12
131         array( 'add_table', 'protected_titles',                  'patch-protected_titles.sql' ),
132         
133         // 1.13
134         array( 'add_field', 'ipblocks',      'ipb_by_text',      'patch-ipb_by_text.sql' ),
135         array( 'add_table', 'page_props',                        'patch-page_props.sql' ),
136         array( 'add_table', 'updatelog',                         'patch-updatelog.sql' ),
137         array( 'add_table', 'category',                          'patch-category.sql' ),
138         array( 'do_category_population' ),
139         array( 'add_field', 'archive',       'ar_parent_id',     'patch-ar_parent_id.sql'),
140         array( 'add_field', 'user_newtalk',  'user_last_timestamp', 'patch-user_last_timestamp.sql'),
141         array( 'do_populate_parent_id' ),
142         array( 'check_bin', 'protected_titles', 'pt_title',      'patch-pt_title-encoding.sql', ),
143         array( 'maybe_do_profiling_memory_update' ),
144         array( 'do_filearchive_indices_update' ),
145         array( 'update_password_format' ),
146         
147         // 1.14
148         array( 'add_field', 'site_stats',     'ss_active_users',  'patch-ss_active_users.sql' ),
149         array( 'do_active_users_init' ),
150         array( 'add_field', 'ipblocks',     'ipb_allow_usertalk',  'patch-ipb_allow_usertalk.sql' )
151 );
152
153
154 # For extensions only, should be populated via hooks
155 # $wgDBtype should be checked to specifiy the proper file
156 $wgExtNewTables = array(); // table, dir
157 $wgExtNewFields = array(); // table, column, dir
158 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
159 $wgExtNewIndexes = array(); // table, index, dir
160
161 # Helper function: check if the given key is present in the updatelog table.
162 # Obviously, only use this for updates that occur after the updatelog table was
163 # created!
164 function update_row_exists( $key ) {
165         $dbr = wfGetDB( DB_SLAVE );
166         $row = $dbr->selectRow(
167                 'updatelog',
168                 '1',
169                 array( 'ul_key' => $key ),
170                 __FUNCTION__
171         );
172         return (bool)$row;
173 }
174
175 function rename_table( $from, $to, $patch ) {
176         global $wgDatabase;
177         if ( $wgDatabase->tableExists( $from ) ) {
178                 if ( $wgDatabase->tableExists( $to ) ) {
179                         wfOut( "...can't move table $from to $to, $to already exists.\n" );
180                 } else {
181                         wfOut( "Moving table $from to $to..." );
182                         dbsource( archive($patch), $wgDatabase );
183                         wfOut( "ok\n" );
184                 }
185         } else {
186                 // Source table does not exist
187                 // Renames are done before creations, so this is typical for a new installation
188                 // Ignore silently
189         }
190 }
191
192 function add_table( $name, $patch, $fullpath=false ) {
193         global $wgDatabase;
194         if ( $wgDatabase->tableExists( $name ) ) {
195                 wfOut( "...$name table already exists.\n" );
196         } else {
197                 wfOut( "Creating $name table..." );
198                 if( $fullpath ) {
199                         dbsource( $patch, $wgDatabase );
200                 } else {
201                         dbsource( archive($patch), $wgDatabase );
202                 }
203                 wfOut( "ok\n" );
204         }
205 }
206
207 function add_field( $table, $field, $patch, $fullpath=false ) {
208         global $wgDatabase;
209         if ( !$wgDatabase->tableExists( $table ) ) {
210                 wfOut( "...$table table does not exist, skipping new field patch\n" );
211         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
212                 wfOut( "...have $field field in $table table.\n" );
213         } else {
214                 wfOut( "Adding $field field to table $table..." );
215                 if( $fullpath ) {
216                         dbsource( $patch, $wgDatabase );
217                 } else {
218                         dbsource( archive($patch), $wgDatabase );
219                 }
220                 wfOut( "ok\n" );
221         }
222 }
223
224 function add_index( $table, $index, $patch, $fullpath=false ) {
225         global $wgDatabase;
226         if( $wgDatabase->indexExists( $table, $index ) ) {
227                 wfOut( "...$index key already set on $table table.\n" );
228         } else {
229                 wfOut( "Adding $index key to table $table... " );
230                 if( $fullpath ) {
231                         dbsource( $patch, $wgDatabase );
232                 } else {
233                         dbsource( archive($patch), $wgDatabase );
234                 }
235                 wfOut( "ok\n" );
236         }
237 }
238
239 function do_revision_updates() {
240         global $wgSoftwareRevision;
241         if ( $wgSoftwareRevision < 1001 ) {
242                 update_passwords();
243         }
244 }
245
246 function update_passwords() {
247         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
248
249         global $wgDatabase;
250         $fname = "Update script: update_passwords()";
251         wfOut( "\nIt appears that you need to update the user passwords in your\n" .
252           "database. If you have already done this (if you've run this update\n" .
253           "script once before, for example), doing so again will make all your\n" .
254           "user accounts inaccessible, so be sure you only do this once.\n" .
255           "Update user passwords? (yes/no)" );
256
257         $resp = readconsole();
258     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
259
260         $sql = "SELECT user_id,user_password FROM user";
261         $source = $wgDatabase->query( $sql, $fname );
262
263         while ( $row = $wgDatabase->fetchObject( $source ) ) {
264                 $id = $row->user_id;
265                 $oldpass = $row->user_password;
266                 $newpass = md5( "{$id}-{$oldpass}" );
267
268                 $sql = "UPDATE user SET user_password='{$newpass}' " .
269                   "WHERE user_id={$id}";
270                 $wgDatabase->query( $sql, $fname );
271         }
272 }
273
274 function do_interwiki_update() {
275         # Check that interwiki table exists; if it doesn't source it
276         global $wgDatabase, $IP;
277         if( $wgDatabase->tableExists( "interwiki" ) ) {
278                 wfOut( "...already have interwiki table\n" );
279                 return true;
280         }
281         wfOut( "Creating interwiki table: " );
282         dbsource( archive("patch-interwiki.sql") );
283         wfOut( "ok\n" );
284         wfOut( "Adding default interwiki definitions: " );
285         dbsource( "$IP/maintenance/interwiki.sql" );
286         wfOut( "ok\n" );
287 }
288
289 function do_index_update() {
290         # Check that proper indexes are in place
291         global $wgDatabase;
292         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
293         if( !$meta->isMultipleKey() ) {
294                 wfOut( "Updating indexes to 20031107: " );
295                 dbsource( archive("patch-indexes.sql") );
296                 wfOut( "ok\n" );
297                 return true;
298         }
299         wfOut( "...indexes seem up to 20031107 standards\n" );
300         return false;
301 }
302
303 function do_image_index_update() {
304         global $wgDatabase;
305
306         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
307         if( !$meta->isMultipleKey() ) {
308                 wfOut( "Updating indexes to 20050912: " );
309                 dbsource( archive("patch-mimesearch-indexes.sql") );
310                 wfOut( "ok\n" );
311                 return true;
312         }
313         wfOut( "...indexes seem up to 20050912 standards\n" );
314         return false;
315 }
316
317 function do_image_name_unique_update() {
318         global $wgDatabase;
319         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
320                 wfOut( "...image primary key already set.\n" );
321         } else {
322                 wfOut( "Making img_name the primary key... " );
323                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
324                 wfOut( "ok\n" );
325         }
326 }
327
328 function do_logging_timestamp_index() {
329         global $wgDatabase;
330         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
331                 wfOut( "...timestamp key on logging already exists.\n" );
332         } else {
333                 wfOut( "Adding timestamp key on logging table... " );
334                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
335                 wfOut( "ok\n" );
336         }
337 }
338
339 function do_archive_user_index() {
340         global $wgDatabase;
341         if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
342                 wfOut( "...usertext,timestamp key on archive already exists.\n" );
343         } else {
344                 wfOut( "Adding usertext,timestamp key on archive table... " );
345                 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
346                 wfOut( "ok\n" );
347         }
348 }
349
350 function do_image_user_index() {
351         global $wgDatabase;
352         if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
353                 wfOut( "...usertext,timestamp key on image already exists.\n" );
354         } else {
355                 wfOut( "Adding usertext,timestamp key on image table... " );
356                 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
357                 wfOut( "ok\n" );
358         }
359 }
360
361 function do_oldimage_user_index() {
362         global $wgDatabase;
363         if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
364                 wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
365         } else {
366                 wfOut( "Adding usertext,timestamp key on oldimage table... " );
367                 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
368                 wfOut( "ok\n" );
369         }
370 }
371
372 function do_watchlist_update() {
373         global $wgDatabase;
374         $fname = 'do_watchlist_update';
375         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
376                 wfOut( "The watchlist table is already set up for email notification.\n" );
377         } else {
378                 wfOut( "Adding wl_notificationtimestamp field for email notification management." );
379                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
380                 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
381                 wfOut( "ok\n" );
382         }
383         # Check if we need to add talk page rows to the watchlist
384         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
385         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
386         if ( $talk != $nontalk ) {
387                 wfOut( "Adding missing watchlist talk page rows... " );
388                 flush();
389
390                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
391                         array(
392                                 'wl_user' => 'wl_user',
393                                 'wl_namespace' => 'wl_namespace | 1',
394                                 'wl_title' => 'wl_title',
395                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
396                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
397                 wfOut( "ok\n" );
398         } else {
399                 wfOut( "...watchlist talk page rows already present\n" );
400         }
401 }
402
403 function do_copy_newtalk_to_watchlist() {
404         global $wgDatabase;
405         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
406
407         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
408                 $wgDatabase->tableName( 'user_newtalk' ) );
409         $num_newtalks=$wgDatabase->numRows($res);
410         wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
411
412         $user = new User();
413         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
414                 $wluser = $wgDatabase->fetchObject( $res );
415                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
416                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
417                                 $wgDatabase->replace( 'watchlist',
418                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
419                                           array('wl_user'                       => 0,
420                                                 'wl_namespace'                  => NS_USER_TALK,
421                                                 'wl_title'                      => $wluser->user_ip,
422                                                 'wl_notificationtimestamp'      => '19700101000000'
423                                                 ), 'updaters.inc::do_watchlist_update2'
424                                         );
425                         }
426                 } else { # normal users ... have user_ids
427                         $user->setID($wluser->user_id);
428                         $wgDatabase->replace( 'watchlist',
429                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
430                                   array('wl_user'                       => $user->getID(),
431                                         'wl_namespace'                  => NS_USER_TALK,
432                                         'wl_title'                      => $user->getName(),
433                                         'wl_notificationtimestamp'      => '19700101000000'
434                                         ), 'updaters.inc::do_watchlist_update3'
435                                 );
436                 }
437         }
438         wfOut( "Done.\n" );
439 }
440
441
442 function do_user_update() {
443         global $wgDatabase;
444         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
445                 wfOut( "User table contains old email authentication field. Dropping... " );
446                 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
447                 wfOut( "ok\n" );
448         } else {
449                 wfOut( "...user table does not contain old email authentication field.\n" );
450         }
451 }
452
453 /**
454  * 1.4 betas were missing the 'binary' marker from logging.log_title,
455  * which causes a collation mismatch error on joins in MySQL 4.1.
456  */
457 function check_bin( $table, $field, $patchFile ) {
458         global $wgDatabase, $wgDBtype;
459         if ($wgDBtype != 'mysql')
460                 return;
461         $tableName = $wgDatabase->tableName( $table );
462         $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
463         $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
464         $wgDatabase->freeResult( $res );
465
466         if( in_array( 'binary', $flags ) ) {
467                 wfOut( "$table table has correct $field encoding.\n" );
468         } else {
469                 wfOut( "Fixing $field encoding on $table table... " );
470                 dbsource( archive( $patchFile ), $wgDatabase );
471                 wfOut( "ok\n" );
472         }
473 }
474
475 function do_schema_restructuring() {
476         global $wgDatabase;
477         $fname="do_schema_restructuring";
478         if ( $wgDatabase->tableExists( 'page' ) ) {
479                 wfOut( "...page table already exists.\n" );
480         } else {
481                 wfOut( "...converting from cur/old to page/revision/text DB structure.\n" );
482                 wfOut( wfTimestamp( TS_DB ) );
483                 wfOut( "......checking for duplicate entries.\n" );
484
485                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
486
487                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
488                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
489
490                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
491                         wfOut( wfTimestamp( TS_DB ) );
492                         wfOut( "......<b>Found duplicate entries</b>\n" );
493                         wfOut( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
494                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
495                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
496                                         $duplicate[$row->cur_namespace] = array();
497                                 }
498                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
499                                 wfOut( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
500                         }
501                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
502                         $firstCond = true;
503                         foreach ( $duplicate as $ns => $titles ) {
504                                 if ( $firstCond ) {
505                                         $firstCond = false;
506                                 } else {
507                                         $sql .= ' OR ';
508                                 }
509                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
510                                 $first = true;
511                                 foreach ( $titles as $t ) {
512                                         if ( $first ) {
513                                                 $sql .= $wgDatabase->addQuotes( $t );
514                                                 $first = false;
515                                         } else {
516                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
517                                         }
518                                 }
519                                 $sql .= ") ) \n";
520                         }
521                         # By sorting descending, the most recent entry will be the first in the list.
522                         # All following entries will be deleted by the next while-loop.
523                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
524
525                         $rows = $wgDatabase->query( $sql, $fname );
526
527                         $prev_title = $prev_namespace = false;
528                         $deleteId = array();
529
530                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
531                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
532                                         $deleteId[] = $row->cur_id;
533                                 }
534                                 $prev_title     = $row->cur_title;
535                                 $prev_namespace = $row->cur_namespace;
536                         }
537                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
538                         $rows = $wgDatabase->query( $sql, $fname );
539                         wfOut( wfTimestamp( TS_DB ) );
540                         wfOut( "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n" );
541                 }
542
543
544                 wfOut( wfTimestamp( TS_DB ) );
545                 wfOut( "......Creating tables.\n" );
546                 $wgDatabase->query("CREATE TABLE $page (
547                         page_id int(8) unsigned NOT NULL auto_increment,
548                         page_namespace int NOT NULL,
549                         page_title varchar(255) binary NOT NULL,
550                         page_restrictions tinyblob NOT NULL,
551                         page_counter bigint(20) unsigned NOT NULL default '0',
552                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
553                         page_is_new tinyint(1) unsigned NOT NULL default '0',
554                         page_random real unsigned NOT NULL,
555                         page_touched char(14) binary NOT NULL default '',
556                         page_latest int(8) unsigned NOT NULL,
557                         page_len int(8) unsigned NOT NULL,
558
559                         PRIMARY KEY page_id (page_id),
560                         UNIQUE INDEX name_title (page_namespace,page_title),
561                         INDEX (page_random),
562                         INDEX (page_len)
563                         ) ENGINE=InnoDB", $fname );
564                 $wgDatabase->query("CREATE TABLE $revision (
565                         rev_id int(8) unsigned NOT NULL auto_increment,
566                         rev_page int(8) unsigned NOT NULL,
567                         rev_comment tinyblob NOT NULL,
568                         rev_user int(5) unsigned NOT NULL default '0',
569                         rev_user_text varchar(255) binary NOT NULL default '',
570                         rev_timestamp char(14) binary NOT NULL default '',
571                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
572                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
573                         rev_len int(8) unsigned,
574                         rev_parent_id int(8) unsigned default NULL,
575                         PRIMARY KEY rev_page_id (rev_page, rev_id),
576                         UNIQUE INDEX rev_id (rev_id),
577                         INDEX rev_timestamp (rev_timestamp),
578                         INDEX page_timestamp (rev_page,rev_timestamp),
579                         INDEX user_timestamp (rev_user,rev_timestamp),
580                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
581                         ) ENGINE=InnoDB", $fname );
582
583                 wfOut( wfTimestamp( TS_DB ) );
584                 wfOut( "......Locking tables.\n" );
585                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
586
587                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
588                 wfOut( wfTimestamp( TS_DB ) );
589                 wfOut( "......maxold is {$maxold}\n" );
590
591                 wfOut( wfTimestamp( TS_DB ) );
592                 global $wgLegacySchemaConversion;
593                 if( $wgLegacySchemaConversion ) {
594                         // Create HistoryBlobCurStub entries.
595                         // Text will be pulled from the leftover 'cur' table at runtime.
596                         wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
597                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
598                         $cur_flags = "'object'";
599                 } else {
600                         // Copy all cur text in immediately: this may take longer but avoids
601                         // having to keep an extra table around.
602                         wfOut( "......Moving text from cur.\n" );
603                         $cur_text = 'cur_text';
604                         $cur_flags = "''";
605                 }
606                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
607                                 old_timestamp, old_minor_edit, old_flags)
608                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
609                         FROM $cur", $fname );
610
611                 wfOut( wfTimestamp( TS_DB ) );
612                 wfOut( "......Setting up revision table.\n" );
613                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
614                                 rev_minor_edit)
615                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
616                                 old_timestamp, old_minor_edit
617                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
618
619                 wfOut( wfTimestamp( TS_DB ) );
620                 wfOut( "......Setting up page table.\n" );
621                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
622                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
623                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
624                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
625                         FROM $cur,$revision
626                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
627
628                 wfOut( wfTimestamp( TS_DB ) );
629                 wfOut( "......Unlocking tables.\n" );
630                 $wgDatabase->query( "UNLOCK TABLES", $fname );
631
632                 wfOut( wfTimestamp( TS_DB ) );
633                 wfOut( "......Renaming old.\n" );
634                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
635
636                 wfOut( wfTimestamp( TS_DB ) );
637                 wfOut( "...done.\n" );
638         }
639 }
640
641 function do_inverse_timestamp() {
642         global $wgDatabase;
643         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
644                 wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
645                 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
646                 wfOut( "ok\n" );
647         } else {
648                 wfOut( "revision timestamp indexes already up to 2005-03-13\n" );
649         }
650 }
651
652 function do_text_id() {
653         global $wgDatabase;
654         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
655                 wfOut( "...rev_text_id already in place.\n" );
656         } else {
657                 wfOut( "Adding rev_text_id field... " );
658                 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
659                 wfOut( "ok\n" );
660         }
661 }
662
663 function do_namespace_size() {
664         $tables = array(
665                 'page'          => 'page',
666                 'archive'       => 'ar',
667                 'recentchanges' => 'rc',
668                 'watchlist'     => 'wl',
669                 'querycache'    => 'qc',
670                 'logging'       => 'log',
671         );
672         foreach( $tables as $table => $prefix ) {
673                 do_namespace_size_on( $table, $prefix );
674                 flush();
675         }
676 }
677
678 function do_namespace_size_on( $table, $prefix ) {
679         global $wgDatabase, $wgDBtype;
680         if ($wgDBtype != 'mysql')
681                 return;
682         $field = $prefix . '_namespace';
683
684         $tablename = $wgDatabase->tableName( $table );
685         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
686         $info = $wgDatabase->fetchObject( $result );
687         $wgDatabase->freeResult( $result );
688
689         if( substr( $info->Type, 0, 3 ) == 'int' ) {
690                 wfOut( "...$field is already a full int ($info->Type).\n" );
691         } else {
692                 wfOut( "Promoting $field from $info->Type to int... " );
693
694                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
695                 $wgDatabase->query( $sql );
696
697                 wfOut( "ok\n" );
698         }
699 }
700
701 function do_pagelinks_update() {
702         global $wgDatabase;
703         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
704                 wfOut( "...already have pagelinks table.\n" );
705         } else {
706                 wfOut( "Converting links and brokenlinks tables to pagelinks... " );
707                 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
708                 wfOut( "ok\n" );
709                 flush();
710
711                 global $wgCanonicalNamespaceNames;
712                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
713                         if( $ns != 0 ) {
714                                 do_pagelinks_namespace( $ns );
715                         }
716                 }
717         }
718 }
719
720 function do_pagelinks_namespace( $namespace ) {
721         global $wgDatabase, $wgContLang;
722
723         $ns = intval( $namespace );
724         wfOut( "Cleaning up broken links for namespace $ns... " );
725
726         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
727         $name = $wgContLang->getNsText( $ns );
728         $prefix = $wgDatabase->strencode( $name );
729         $likeprefix = str_replace( '_', '\\_', $prefix);
730
731         $sql = "UPDATE $pagelinks
732                    SET pl_namespace=$ns,
733                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
734                  WHERE pl_namespace=0
735                    AND pl_title LIKE '$likeprefix:%'";
736
737         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
738         wfOut( "ok\n" );
739 }
740
741 function do_drop_img_type() {
742         global $wgDatabase;
743
744         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
745                 wfOut( "Dropping unused img_type field in image table... " );
746                 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
747                 wfOut( "ok\n" );
748         } else {
749                 wfOut( "No img_type field in image table; Good.\n" );
750         }
751 }
752
753 function do_old_links_update() {
754         global $wgDatabase;
755         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
756                 wfOut( "Already have pagelinks; skipping old links table updates.\n" );
757         } else {
758                 convertLinks(); flush();
759         }
760 }
761
762 function do_user_unique_update() {
763         global $wgDatabase;
764         $duper = new UserDupes( $wgDatabase );
765         if( $duper->hasUniqueIndex() ) {
766                 wfOut( "Already have unique user_name index.\n" );
767         } else {
768                 if( !$duper->clearDupes() ) {
769                         wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
770                 }
771                 wfOut( "Adding unique index on user_name... " );
772                 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
773                 wfOut( "ok\n" );
774         }
775 }
776
777 function do_user_groups_update() {
778         $fname = 'do_user_groups_update';
779         global $wgDatabase;
780
781         if( $wgDatabase->tableExists( 'user_groups' ) ) {
782                 wfOut( "...user_groups table already exists.\n" );
783                 return do_user_groups_reformat();
784         }
785
786         wfOut( "Adding user_groups table... " );
787         dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
788         wfOut( "ok\n" );
789
790         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
791                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
792                         wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
793                         dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
794                         wfOut( "ok\n" );
795                 } else {
796                         wfOut( "*** WARNING: couldn't locate user_rights table or field for upgrade.\n" );
797                         wfOut( "*** You may need to manually configure some sysops by manipulating\n" );
798                         wfOut( "*** the user_groups table.\n" );
799                         return;
800                 }
801         }
802
803         wfOut( "Converting user_rights table to user_groups... " );
804         $result = $wgDatabase->select( 'user_rights',
805                 array( 'ur_user', 'ur_rights' ),
806                 array( "ur_rights != ''" ),
807                 $fname );
808
809         while( $row = $wgDatabase->fetchObject( $result ) ) {
810                 $groups = array_unique(
811                         array_map( 'trim',
812                                 explode( ',', $row->ur_rights ) ) );
813
814                 foreach( $groups as $group ) {
815                         $wgDatabase->insert( 'user_groups',
816                                 array(
817                                         'ug_user'  => $row->ur_user,
818                                         'ug_group' => $group ),
819                                 $fname );
820                 }
821         }
822         $wgDatabase->freeResult( $result );
823         wfOut( "ok\n" );
824 }
825
826 function do_user_groups_reformat() {
827         # Check for bogus formats from previous 1.5 alpha code.
828         global $wgDatabase;
829         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
830
831         if( $info->type() == 'int' ) {
832                 $oldug = $wgDatabase->tableName( 'user_groups' );
833                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
834                 wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
835                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
836                 wfOut( "ok\n" );
837
838                 wfOut( "Re-adding fresh user_groups table... " );
839                 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
840                 wfOut( "ok\n" );
841
842                 wfOut( "***\n" );
843                 wfOut( "*** WARNING: You will need to manually fix up user permissions in the user_groups\n" );
844                 wfOut( "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n" );
845                 wfOut( "***\n" );
846         } else {
847                 wfOut( "...user_groups is in current format.\n" );
848         }
849
850 }
851
852 function do_watchlist_null() {
853         # Make sure wl_notificationtimestamp can be NULL,
854         # and update old broken items.
855         global $wgDatabase;
856         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
857
858         if( !$info->nullable() ) {
859                 wfOut( "Making wl_notificationtimestamp nullable... " );
860                 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
861                 wfOut( "ok\n" );
862         } else {
863                 wfOut( "...wl_notificationtimestamp is already nullable.\n" );
864         }
865
866 }
867
868 /**
869  * @bug 3946
870  */
871 function do_page_random_update() {
872         global $wgDatabase;
873
874         wfOut( "Setting page_random to a random value on rows where it equals 0..." );
875
876         $page = $wgDatabase->tableName( 'page' );
877         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
878         $rows = $wgDatabase->affectedRows();
879
880         wfOut( "changed $rows rows\n" );
881 }
882
883 function do_templatelinks_update() {
884         global $wgDatabase, $wgLoadBalancer;
885         $fname = 'do_templatelinks_update';
886
887         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
888                 wfOut( "...templatelinks table already exists\n" );
889                 return;
890         }
891         wfOut( "Creating templatelinks table...\n" );
892         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
893         wfOut( "Populating...\n" );
894         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
895                 // Slow, replication-friendly update
896                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
897                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
898                 $count = 0;
899                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
900                         $count = ($count + 1) % 100;
901                         if ( $count == 0 ) {
902                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
903                                         wfWaitForSlaves( 10 );
904                                 } else {
905                                         sleep( 1 );
906                                 }
907                         }
908                         $wgDatabase->insert( 'templatelinks',
909                                 array(
910                                         'tl_from' => $row->pl_from,
911                                         'tl_namespace' => $row->pl_namespace,
912                                         'tl_title' => $row->pl_title,
913                                 ), $fname
914                         );
915
916                 }
917                 $wgDatabase->freeResult( $res );
918         } else {
919                 // Fast update
920                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
921                         array(
922                                 'tl_from' => 'pl_from',
923                                 'tl_namespace' => 'pl_namespace',
924                                 'tl_title' => 'pl_title'
925                         ), array(
926                                 'pl_namespace' => 10
927                         ), $fname
928                 );
929         }
930         wfOut( "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n" );
931 }
932
933 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
934 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
935 function do_rc_indices_update() {
936         global $wgDatabase;
937         wfOut( "Checking for additional recent changes indices...\n" );
938
939         $indexes = array(
940                 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
941                 'rc_user_text' => 'patch-rc_user_text-index.sql',
942         );
943         
944         foreach( $indexes as $index => $patch ) {
945                 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
946                 if( !$info ) {
947                         wfOut( "...index `{$index}` not found; adding..." );
948                         dbsource( archive( $patch ) );
949                         wfOut( "done.\n" );
950                 } else {
951                         wfOut( "...index `{$index}` seems ok.\n" );
952                 }
953         }
954 }
955
956 function index_has_field($table, $index, $field) {
957         global $wgDatabase;
958         wfOut( "Checking if $table index $index includes field $field...\n" );
959         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
960         if( $info ) {
961                 foreach($info as $row) {
962                         if($row->Column_name == $field) {
963                                 wfOut( "...index $index on table $table seems to be ok\n" );
964                                 return true;
965                         }
966                 }
967         }
968         wfOut( "...index $index on table $table has no field $field; adding\n" );
969         return false;
970 }
971
972 function do_backlinking_indices_update() {
973         wfOut( "Checking for backlinking indices...\n" );
974         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
975                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
976                 !index_has_field('imagelinks', 'il_to', 'il_from'))
977         {       
978                 dbsource( archive( 'patch-backlinkindexes.sql' ) );
979                 wfOut( "...backlinking indices updated\n" );
980         }
981 }
982
983 function do_categorylinks_indices_update() {
984         wfOut( "Checking for categorylinks indices...\n" );
985         if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
986         {       
987                 dbsource( archive( 'patch-categorylinksindex.sql' ) );
988                 wfOut( "...categorylinks indices updated\n" );
989         }
990 }
991
992 function do_filearchive_indices_update() {
993         global $wgDatabase;
994         wfOut( "Checking filearchive indices...\n" );
995         $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
996         if ( !$info )
997         {       
998                 dbsource( archive( 'patch-filearhive-user-index.sql' ) );
999                 wfOut( "...filearchive indices updated\n" );
1000         }
1001 }
1002
1003 function maybe_do_profiling_memory_update() {
1004         global $wgDatabase;
1005         if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1006                 // Simply ignore
1007         } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1008                 wfOut( "profiling table has pf_memory field.\n" );
1009         } else {
1010                 wfOut( "Adding pf_memory field to table profiling..." );
1011                 dbsource( archive( 'patch-profiling-memory.sql' ), $wgDatabase );
1012                 wfOut( "ok\n" );
1013         }
1014 }
1015
1016 function do_stats_init() {
1017         // Sometimes site_stats table is not properly populated.
1018         global $wgDatabase;
1019         wfOut( "Checking site_stats row..." );
1020         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1021         if( $row === false ) {
1022                 wfOut( "data is missing! rebuilding...\n" );
1023         } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1024                 wfOut( "missing ss_total_pages, rebuilding...\n" );
1025         } else {
1026                 wfOut( "ok.\n" );
1027                 return;
1028         }
1029
1030         global $IP;
1031         require_once "$IP/maintenance/initStats.inc";
1032         wfInitStats();
1033 }
1034
1035 function do_active_users_init() {
1036         global $wgDatabase;
1037         $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1038         if( $activeUsers == -1 ) {
1039                 $activeUsers = $wgDatabase->selectField( 'recentchanges', 
1040                         'COUNT( DISTINCT rc_user_text )',
1041                         array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__ 
1042                 );
1043                 $wgDatabase->update( 'site_stats', 
1044                         array( 'ss_active_users' => intval($activeUsers) ),
1045                         array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
1046                 );
1047         }
1048         wfOut( "...ss_active_users user count set...\n" );
1049 }
1050
1051 function purge_cache() {
1052         global $wgDatabase;
1053         # We can't guarantee that the user will be able to use TRUNCATE,
1054         # but we know that DELETE is available to us
1055         wfOut( "Purging caches..." );
1056         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1057         wfOut( "done.\n" );
1058 }
1059
1060 function do_all_updates( $shared = false, $purge = true ) {
1061         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
1062
1063         wfRunHooks('LoadExtensionSchemaUpdates');
1064
1065         $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
1066
1067         if ($wgDBtype === 'postgres') {
1068                 do_postgres_updates();
1069                 return;
1070         }
1071         
1072         # Run core updates in sequence...
1073         global $wgMysqlUpdates;
1074         foreach( $wgMysqlUpdates as $params ) {
1075                 $func = array_shift( $params );
1076                 call_user_func_array( $func, $params );
1077                 flush();
1078         }
1079         
1080         /// @fixme clean up this mess too!
1081         global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1082         # Add missing extension tables
1083         foreach ( $wgExtNewTables as $tableRecord ) {
1084                 add_table( $tableRecord[0], $tableRecord[1], true );
1085                 flush();
1086         }
1087         # Add missing extension fields
1088         foreach ( $wgExtNewFields as $fieldRecord ) {
1089                 if ( $fieldRecord[0] != 'user' || $doUser ) {
1090                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1091                 }
1092                 flush();
1093         }
1094         # Add missing extension indexes
1095         foreach ( $wgExtNewIndexes as $fieldRecord ) {
1096                 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1097                 flush();
1098         }
1099
1100
1101         wfOut( "Deleting old default messages (this may take a long time!)..." ); 
1102         deleteDefaultMessages();
1103         wfOut( "Done\n" );
1104         
1105         do_stats_init();
1106         
1107         if( $purge ) {
1108                 purge_cache();
1109         }
1110 }
1111
1112 function archive($name) {
1113         global $wgDBtype, $IP;
1114         switch ($wgDBtype) {
1115         case "postgres":
1116                 return "$IP/maintenance/postgres/archives/$name";
1117         default:
1118                 return "$IP/maintenance/archives/$name";
1119         }
1120 }
1121
1122 function do_restrictions_update() {
1123         # Adding page_restrictions table, obsoleting page.page_restrictions.
1124         #  Migrating old restrictions to new table
1125         # -- Andrew Garrett, January 2007.
1126
1127         global $wgDatabase;
1128
1129         $name = 'page_restrictions';
1130         $patch = 'patch-page_restrictions.sql';
1131         $patch2 = 'patch-page_restrictions_sortkey.sql';
1132
1133         if ( $wgDatabase->tableExists( $name ) ) {
1134                 wfOut( "...$name table already exists.\n" );
1135         } else {
1136                 wfOut( "Creating $name table..." );
1137                 dbsource( archive($patch), $wgDatabase );
1138                 dbsource( archive($patch2), $wgDatabase );
1139                 wfOut( "ok\n" );
1140
1141                 wfOut( "Migrating old restrictions to new table..." );
1142
1143                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1144
1145                 $count = 0;
1146
1147                 while ($row = $wgDatabase->fetchObject($res) ) {
1148                         $count = ($count + 1) % 100;
1149
1150                         if ($count == 0) {
1151                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
1152                                         wfWaitForSlaves( 10 );
1153                                 } else {
1154                                         sleep( 1 );
1155                                 }
1156                         }
1157
1158                         # Figure out what the restrictions are..
1159                         $id = $row->page_id;
1160                         $flatrestrictions = explode( ':', $row->page_restrictions );
1161
1162                         $restrictions = array ();
1163                         foreach( $flatrestrictions as $restriction ) {
1164                                 $thisrestriction = explode( '=', $restriction, 2 );
1165                                 if( count( $thisrestriction ) == 1 ) {
1166                                         // Compatibility with old protections from before
1167                                         // separate move protection was added.
1168                                         list( $level ) = $thisrestriction;
1169                                         if( $level ) {
1170                                                 $restrictions['edit'] = $level;
1171                                                 $restrictions['move'] = $level;
1172                                         }
1173                                 } else {
1174                                         list( $type, $level ) = $thisrestriction;
1175                                         if( $level ) {
1176                                                 $restrictions[$type] = $level;
1177                                         }
1178                                 }
1179
1180                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1181
1182                         }
1183                         
1184                         foreach( $restrictions as $type => $level ) {
1185                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1186                                                                                         'pr_type' => $type,
1187                                                                                         'pr_level' => $level,
1188                                                                                         'pr_cascade' => 0,
1189                                                                                         'pr_expiry' => 'infinity' ),
1190                                                                                         __METHOD__ );
1191                         }
1192                 }
1193                 wfOut( "ok\n" );
1194         }
1195 }
1196
1197 function do_category_population() {
1198         if( update_row_exists( 'populate category' ) ) {
1199                 wfOut( "...category table already populated.\n" );
1200                 return;
1201         }
1202         require_once( 'populateCategory.inc' );
1203         wfOut( "Populating category table, printing progress markers.  " ).
1204 "For large databases, you\n".
1205 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1206 "populateCategory.php.\n";
1207         populateCategory( '', 10, 0, true );
1208         wfOut( "Done populating category table.\n" );
1209 }
1210
1211 function do_populate_parent_id() {
1212         if( update_row_exists( 'populate rev_parent_id' ) ) {
1213                 wfOut( "...rev_parent_id column already populated.\n" );
1214                 return;
1215         }
1216         require_once( 'populateParentId.inc' );
1217         
1218         global $wgDatabase;
1219         populate_rev_parent_id( $wgDatabase );
1220 }
1221
1222 function update_password_format() {
1223         if ( update_row_exists( 'password format' ) ) {
1224                 wfOut( "...password hash format already changed\n" );
1225                 return;
1226         }
1227
1228         wfOut( "Updating password hash format..." );
1229
1230         global $wgDatabase, $wgPasswordSalt;
1231         $user = $wgDatabase->tableName( 'user' );
1232         if ( $wgPasswordSalt ) {
1233                 $sql = "UPDATE $user SET user_password=CONCAT(':B:', user_id, ':', user_password) " .
1234                         "WHERE user_password NOT LIKE ':%'";
1235         } else {
1236                 $sql = "UPDATE $user SET user_password=CONCAT(':A:', user_password) " .
1237                         "WHERE user_password NOT LIKE ':%'";
1238         }
1239         $wgDatabase->query( $sql, __METHOD__ );
1240         $wgDatabase->insert( 'updatelog', array( 'ul_key' => 'password format' ), __METHOD__ );
1241
1242         wfOut( "done\n" );
1243 }
1244
1245 function
1246 pg_describe_table($table)
1247 {
1248 global  $wgDatabase, $wgDBmwschema;
1249         $q = <<<END
1250 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1251         WHERE pg_class.relnamespace = pg_namespace.oid 
1252           AND attrelid=pg_class.oid AND attnum > 0
1253           AND relname=%s AND nspname=%s
1254 END;
1255         $res = $wgDatabase->query(sprintf($q,
1256                         $wgDatabase->addQuotes($table),
1257                         $wgDatabase->addQuotes($wgDBmwschema)));
1258         if (!$res)
1259                 return null;
1260
1261         $cols = array();
1262         while ($r = $wgDatabase->fetchRow($res)) {
1263                 $cols[] = array(        
1264                                 "name" => $r[0],
1265                                 "ord" => $r[1],
1266                         );
1267         }
1268         return $cols;
1269 }
1270
1271 function
1272 pg_describe_index($idx)
1273 {
1274 global  $wgDatabase, $wgDBmwschema;
1275
1276         // first fetch the key (which is a list of columns ords) and
1277         // the table the index applies to (an oid)
1278         $q = <<<END
1279 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1280         WHERE nspname=%s
1281           AND pg_class.relnamespace = pg_namespace.oid
1282           AND relname=%s
1283           AND indexrelid=pg_class.oid
1284 END;
1285         $res = $wgDatabase->query(sprintf($q,
1286                         $wgDatabase->addQuotes($wgDBmwschema),
1287                         $wgDatabase->addQuotes($idx)));
1288         if (!$res)
1289                 return null;
1290         if (!($r = $wgDatabase->fetchRow($res))) {
1291                 $wgDatabase->freeResult($res);
1292                 return null;
1293         }
1294
1295         $indkey = $r[0];
1296         $relid = intval($r[1]);
1297         $indkeys = explode(" ", $indkey);
1298         $wgDatabase->freeResult($res);
1299
1300         $colnames = array();
1301         foreach ($indkeys as $rid) {
1302                 $query = <<<END
1303 SELECT attname FROM pg_class, pg_attribute
1304         WHERE attrelid=$relid
1305           AND attnum=%d
1306           AND attrelid=pg_class.oid
1307 END;
1308                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1309                 if (!$r2)
1310                         return null;
1311                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1312                         $wgDatabase->freeResult($r2);
1313                         return null;
1314                 }
1315                 $colnames[] = $row2[0];
1316                 $wgDatabase->freeResult($r2);
1317         }
1318
1319         return $colnames;
1320 }
1321
1322 function
1323 pg_index_exists($table, $index)
1324 {
1325 global  $wgDatabase, $wgDBmwschema;
1326         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1327                         array(  "indexname" => $index,
1328                                 "tablename" => $table,
1329                                 "schemaname" => $wgDBmwschema));
1330         return $exists === $index;
1331 }
1332
1333 function
1334 pg_fkey_deltype($fkey)
1335 {
1336 global  $wgDatabase, $wgDBmwschema;
1337         $q = <<<END
1338 SELECT confdeltype FROM pg_constraint, pg_namespace
1339         WHERE connamespace=pg_namespace.oid
1340           AND nspname=%s
1341           AND conname=%s;
1342 END;
1343         $r = $wgDatabase->query(sprintf($q,
1344                 $wgDatabase->addQuotes($wgDBmwschema),
1345                 $wgDatabase->addQuotes($fkey)));
1346         if (!($row = $wgDatabase->fetchRow($r)))
1347                 return null;
1348         return $row[0];
1349 }
1350
1351 function
1352 pg_rule_def($table, $rule)
1353 {
1354 global  $wgDatabase, $wgDBmwschema;
1355         $q = <<<END
1356 SELECT definition FROM pg_rules
1357         WHERE schemaname = %s
1358           AND tablename = %s
1359           AND rulename = %s
1360 END;
1361         $r = $wgDatabase->query(sprintf($q,
1362                         $wgDatabase->addQuotes($wgDBmwschema),
1363                         $wgDatabase->addQuotes($table),
1364                         $wgDatabase->addQuotes($rule)));
1365         $row = $wgDatabase->fetchRow($r);
1366         if (!$row)
1367                 return null;
1368         $d = $row[0];
1369         $wgDatabase->freeResult($r);
1370         return $d;
1371 }
1372
1373 function do_postgres_updates() {
1374         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1375
1376         ## Gather version numbers in case we need them
1377         $version = $wgDatabase->getServerVersion(); ## long string
1378         $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1379
1380         $wgShowExceptionDetails = 1;
1381
1382         # Just in case their LocalSettings.php does not have this:
1383         if ( !isset( $wgDBmwschema ))
1384                 $wgDBmwschema = 'mediawiki';
1385
1386         # Verify that this user is configured correctly
1387         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1388         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1389         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1390         $conf = array();
1391         foreach( explode( '*', $config ) as $c ) {
1392                 list( $x,$y ) = explode( '=', $c );
1393                 $conf[$x] = $y;
1394         }
1395         if( !array_key_exists( 'search_path', $conf ) ) {
1396                 $search_path = '';
1397         }
1398         else {
1399                 $search_path = $conf['search_path'];
1400         }
1401         if( strpos( $search_path, $wgDBmwschema ) === false ) {
1402                 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1403                 $search_path = "$wgDBmwschema, $search_path";
1404         }
1405         if( strpos( $search_path, $wgDBts2schema ) === false ) {
1406                 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1407                 $search_path = "$search_path, $wgDBts2schema";
1408         }
1409         if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1410                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1411                 $wgDatabase->doQuery( "SET search_path = $search_path" );
1412         }
1413         else {
1414                 $path = $conf['search_path'];
1415                 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1416         }
1417         $goodconf = array(
1418                 'client_min_messages' => 'error',
1419                 'DateStyle'           => 'ISO, YMD',
1420                 'TimeZone'            => 'GMT'
1421         );
1422         foreach( array_keys( $goodconf ) AS $key ) {
1423                 $value = $goodconf[$key];
1424                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1425                         wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1426                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1427                         $wgDatabase->doQuery( "SET $key = '$value'" );
1428                 }
1429                 else {
1430                         wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1431                 }
1432         }
1433
1434         $newsequences = array(
1435                 "log_log_id_seq",
1436                 "pr_id_val",
1437         );
1438
1439         $newtables = array(
1440                 array("category",          "patch-category.sql"),
1441                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1442                 array("mwuser",            "patch-mwuser.sql"),
1443                 array("pagecontent",       "patch-pagecontent.sql"),
1444                 array("querycachetwo",     "patch-querycachetwo.sql"),
1445                 array("page_props",        "patch-page_props.sql"),
1446                 array("page_restrictions", "patch-page_restrictions.sql"),
1447                 array("profiling",         "patch-profiling.sql"),
1448                 array("protected_titles",  "patch-protected_titles.sql"),
1449                 array("redirect",          "patch-redirect.sql"),
1450                 array("updatelog",         "patch-updatelog.sql"),
1451         );
1452
1453         $newcols = array(
1454                 array("archive",       "ar_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1455                 array("archive",       "ar_len",               "INTEGER"),
1456                 array("archive",       "ar_page_id",           "INTEGER"),
1457                 array("archive",       "ar_parent_id",         "INTEGER"),
1458                 array("image",         "img_sha1",             "TEXT NOT NULL DEFAULT ''"),
1459                 array("ipblocks",      "ipb_anon_only",        "SMALLINT NOT NULL DEFAULT 0"),
1460                 array("ipblocks",      "ipb_by_text",          "TEXT NOT NULL DEFAULT ''"),
1461                 array("ipblocks",      "ipb_block_email",      "SMALLINT NOT NULL DEFAULT 0"),
1462                 array("ipblocks",      "ipb_create_account",   "SMALLINT NOT NULL DEFAULT 1"),
1463                 array("ipblocks",      "ipb_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1464                 array("ipblocks",      "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1465                 array("ipblocks",      "ipb_allow_usertalk",   "SMALLINT NOT NULL DEFAULT 0"),
1466                 array("filearchive",   "fa_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1467                 array("logging",       "log_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1468                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1469                 array("logging",       "log_params",           "TEXT"),
1470                 array("mwuser",        "user_editcount",       "INTEGER"),
1471                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1472                 array("oldimage",      "oi_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1473                 array("oldimage",      "oi_metadata",          "BYTEA NOT NULL DEFAULT ''"),
1474                 array("oldimage",      "oi_media_type",        "TEXT"),
1475                 array("oldimage",      "oi_major_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1476                 array("oldimage",      "oi_minor_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1477                 array("oldimage",      "oi_sha1",              "TEXT NOT NULL DEFAULT ''"),
1478                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1479                 array("profiling",     "pf_memory",            "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1480                 array("recentchanges", "rc_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1481                 array("recentchanges", "rc_log_action",        "TEXT"),
1482         array("recentchanges", "rc_log_type",          "TEXT"),
1483         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1484                 array("recentchanges", "rc_new_len",           "INTEGER"),
1485                 array("recentchanges", "rc_old_len",           "INTEGER"),
1486                 array("recentchanges", "rc_params",            "TEXT"),
1487                 array("revision",      "rev_len",              "INTEGER"),
1488                 array("revision",      "rev_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1489                 array("user_newtalk",  "user_last_timestamp",  "TIMESTAMPTZ"),
1490                 array("site_stats",    "ss_active_users",      "INTEGER DEFAULT '-1'"),
1491                 array("revision",      "rev_parent_id",        "INTEGER DEFAULT NULL"),
1492         );
1493
1494
1495         # table, column, desired type, USING clause if needed (with new default if needed)
1496         $typechanges = array(
1497                 array("archive",      "ar_deleted",      "smallint", ""),
1498                 array("archive",      "ar_minor_edit",   "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1499                 array("filearchive",  "fa_deleted",      "smallint", ""),
1500                 array("filearchive",  "fa_height",       "integer",  ""),
1501                 array("filearchive",  "fa_metadata",     "bytea",    "decode(fa_metadata,'escape')"),
1502                 array("filearchive",  "fa_size",         "integer",  ""),
1503                 array("filearchive",  "fa_width",        "integer",  ""),
1504                 array("filearchive",  "fa_storage_group","text",     ""),
1505                 array("filearchive",  "fa_storage_key",  "text",     ""),
1506                 array("image",        "img_metadata",    "bytea",    "decode(img_metadata,'escape')"),
1507                 array("image",        "img_size",        "integer",  ""),
1508                 array("image",        "img_width",       "integer",  ""),
1509                 array("image",        "img_height",      "integer",  ""),
1510                 array("interwiki",    "iw_local",        "smallint", "iw_local::smallint DEFAULT 0"),
1511                 array("interwiki",    "iw_trans",        "smallint", "iw_trans::smallint DEFAULT 0"),
1512                 array("ipblocks",     "ipb_auto",        "smallint", "ipb_auto::smallint DEFAULT 0"),
1513                 array("ipblocks",     "ipb_anon_only",   "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1514                 array("ipblocks",     "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1515                 array("ipblocks",     "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1516                 array("ipblocks",     "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1517                 array("ipblocks",     "ipb_address",     "text",     "ipb_address::text"),
1518                 array("ipblocks",     "ipb_deleted",     "smallint", "ipb_deleted::smallint"),
1519                 array("math",         "math_inputhash",  "bytea",    "decode(math_inputhash,'escape')"),
1520                 array("math",         "math_outputhash", "bytea",    "decode(math_outputhash,'escape')"),
1521                 array("mwuser",       "user_token",      "text",     ""),
1522                 array("mwuser",       "user_email_token","text",     ""),
1523                 array("objectcache",  "keyname",         "text",     ""),
1524                 array("oldimage",     "oi_height",       "integer",  ""),
1525                 array("oldimage",     "oi_metadata",     "bytea",    "decode(img_metadata,'escape')"),
1526                 array("oldimage",     "oi_size",         "integer",  ""),
1527                 array("oldimage",     "oi_width",        "integer",  ""),
1528                 array("page",         "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1529                 array("page",         "page_is_new",     "smallint", "page_is_new::smallint DEFAULT 0"),
1530                 array("querycache",   "qc_value",        "integer",  ""),
1531                 array("querycachetwo","qcc_value",       "integer",  ""),
1532                 array("recentchanges","rc_bot",          "smallint", "rc_bot::smallint DEFAULT 0"),
1533                 array("recentchanges","rc_deleted",      "smallint", ""),
1534                 array("recentchanges","rc_minor",        "smallint", "rc_minor::smallint DEFAULT 0"),
1535                 array("recentchanges","rc_new",          "smallint", "rc_new::smallint DEFAULT 0"),
1536                 array("recentchanges","rc_type",         "smallint", "rc_type::smallint DEFAULT 0"),
1537                 array("recentchanges","rc_patrolled",    "smallint", "rc_patrolled::smallint DEFAULT 0"),
1538                 array("revision",     "rev_deleted",     "smallint", "rev_deleted::smallint DEFAULT 0"),
1539                 array("revision",     "rev_minor_edit",  "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1540                 array("templatelinks","tl_namespace",    "smallint", "tl_namespace::smallint"),
1541                 array("user_newtalk", "user_ip",         "text",     "host(user_ip)"),
1542         );
1543
1544         $newindexes = array(
1545                 array("archive",       "archive_user_text",  "(ar_user_text)"),
1546                 array("image",         "img_sha1",           "(img_sha1)"),
1547                 array("oldimage",      "oi_sha1",            "(oi_sha1)"),
1548                 array("revision",      "rev_text_id_idx",    "(rev_text_id)"),
1549                 array("recentchanges", "rc_timestamp_nobot", "(rc_timestamp) WHERE rc_bot = 0"),
1550                 array("templatelinks", "templatelinks_from", "(tl_from)"),
1551                 array("watchlist",     "wl_user",            "(wl_user)"),
1552         );
1553
1554         $newrules = array(
1555         );
1556
1557         foreach ($newsequences as $ns) {
1558                 if ($wgDatabase->sequenceExists($ns)) {
1559                         wfOut( "... sequence \"$ns\" already exists\n" );
1560                         continue;
1561                 }
1562
1563                 wfOut( "Creating sequence \"$ns\"\n" );
1564                 $wgDatabase->query("CREATE SEQUENCE $ns");
1565         }
1566
1567         foreach ($newtables as $nt) {
1568                 if ($wgDatabase->tableExists($nt[0])) {
1569                         wfOut( "... table \"$nt[0]\" already exists\n" );
1570                         continue;
1571                 }
1572
1573                 wfOut( "Creating table \"$nt[0]\"\n" );
1574                 dbsource(archive($nt[1]));
1575         }
1576
1577         ## Needed before newcols
1578         if ($wgDatabase->tableExists("archive2")) {
1579                 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1580                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1581                         wfOut( "Dropping rule \"archive_insert\"\n" );
1582                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1583                 }
1584                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1585                         wfOut( "Dropping rule \"archive_delete\"\n" );
1586                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1587                 }
1588                 dbsource(archive("patch-remove-archive2.sql"));
1589         }
1590         else
1591                 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1592
1593         foreach ($newcols as $nc) {
1594                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1595                 if (!is_null($fi)) {
1596                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1597                         continue;
1598                 }
1599
1600                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1601                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1602         }
1603
1604         foreach ($typechanges as $tc) {
1605                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1606                 if (is_null($fi)) {
1607                         wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1608                         exit(1);
1609                 }
1610
1611                 if ($fi->type() === $tc[2])
1612                         wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1613                 else {
1614                         wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1615                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1616                         if (strlen($tc[3])) {
1617                                 $default = array();
1618                                 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1619                                         $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1620                                         $wgDatabase->query($sqldef);
1621                                         $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1622                                 }
1623                                 $sql .= " USING $tc[3]";
1624                         }
1625                         $sql .= ";\nCOMMIT;\n";
1626                         $wgDatabase->query($sql);
1627                 }
1628         }
1629
1630         if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1631                 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1632                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1633                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1634                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1635         }
1636         else
1637                 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1638
1639
1640         foreach ($newindexes as $ni) {
1641                 if (pg_index_exists($ni[0], $ni[1])) {
1642                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1643                         continue;
1644                 }
1645                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1646                 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1647         }
1648
1649         foreach ($newrules as $nr) {
1650                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1651                         wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1652                         continue;
1653                 }
1654                 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1655                 dbsource(archive($nr[2]));
1656         }
1657
1658         if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1659                 wfOut( "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n" );
1660                 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1661                 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1662                         "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1663         }
1664         else
1665                 wfOut( "... table \"oldimage\" has correct cascade delete foreign key to image\n" );
1666
1667         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1668                 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1669                 dbsource(archive('patch-page_deleted.sql'));
1670         }
1671         else
1672                 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1673
1674         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1675         if (!$fi->nullable()) {
1676                 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1677                 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1678         }
1679         else
1680                 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1681
1682         $pu = pg_describe_index("pagelink_unique");
1683         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1684                 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1685                 $wgDatabase->query("DROP INDEX pagelink_unique");
1686                 $pu = null;
1687         }
1688         else
1689                 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1690
1691         if (is_null($pu)) {
1692                 wfOut( "Creating index \"pagelink_unique index\"\n" );
1693                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1694         }
1695         else
1696                 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1697
1698         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1699                 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1700         }
1701         else {
1702                 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1703                 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1704         }
1705
1706         # Fix ipb_address index
1707         if (pg_index_exists('ipblocks', 'ipb_address' )) {
1708                 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1709                 $wgDatabase->query('DROP INDEX ipb_address');
1710         }
1711         if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1712                 wfOut( "... have ipb_address_unique\n" );
1713         }
1714         else {
1715                 wfOut( "Adding ipb_address_unique index\n" );
1716                 dbsource(archive('patch-ipb_address_unique.sql'));
1717         }
1718
1719         global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1720         # Add missing extension tables
1721         foreach ( $wgExtNewTables as $nt ) {
1722                 if ($wgDatabase->tableExists($nt[0])) {
1723                         wfOut( "... table \"$nt[0]\" already exists\n" );
1724                         continue;
1725                 }
1726                 wfOut( "Creating table \"$nt[0]\"\n" );
1727                 dbsource($nt[1]);
1728         }
1729         # Add missing extension fields
1730         foreach ( $wgExtPGNewFields as $nc ) {
1731                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1732                 if (!is_null($fi)) {
1733                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1734                         continue;
1735                 }
1736                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1737                 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1738         }
1739         # Add missing extension indexes
1740         foreach ( $wgExtNewIndexes as $ni ) {
1741                 if (pg_index_exists($ni[0], $ni[1])) {
1742                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1743                         continue;
1744                 }
1745                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
1746                 dbsource($ni[2]);
1747         }
1748
1749         # Tweak the page_title tsearch2 trigger to filter out slashes
1750         # This is create or replace, so harmless to call if not needed
1751         dbsource(archive('patch-ts2pagetitle.sql'));
1752
1753         ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
1754         ## in case they have the old 'default' versions
1755         if ( $numver >= 8.3 )
1756                 dbsource(archive('patch-tsearch2funcs.sql'));
1757
1758         ## Put a new row in the mediawiki_version table
1759         $wgDatabase->insert( 'mediawiki_version',
1760                 array(
1761                         'type' => 'Update',
1762                         'ctype' => 'U',
1763                         'mw_version' => $wgVersion,
1764                         'pg_version' => $version,
1765                         'sql_version' => '$LastChangedRevision: 46891 $',
1766                         'sql_date' => '$LastChangedDate: 2009-02-05 22:54:47 -0600 (Thu, 05 Feb 2009) $',
1767                 ) );
1768         return;
1769 }