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