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