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