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