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