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