Localization update for he, and code style fix in en.
[mediawiki.git] / maintenance / updaters.inc
bloba1595e4adb01d723dc65f1b7494f88e2d12d3a5e
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         if ( update_row_exists( 'initial_indexes' ) ) {
1271                 wfOut( "...have initial indexes\n" );
1272                 return;
1273         }
1274         wfOut( "Adding initial indexes..." );
1275         $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1276         wfOut( "done\n" );
1279 function do_unique_pl_tl_il() {
1280         global $wgDatabase;
1281         $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1282         if( is_array($info) && !$info[0]->Non_unique ) {
1283                 wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
1284         } else {
1285                 wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
1286                 $wgDatabase->sourceFile( archive( 'patch-pl-tl-il-unique.sql' ) );
1287                 wfOut( "ok\n" );
1288         }
1291 function do_log_search_population() {
1292         global $wgDatabase;
1293         if( update_row_exists( 'populate log_search' ) ) {
1294                 wfOut( "...log_search table already populated.\n" );
1295                 return;
1296         }
1297         require_once( 'populateLogSearch.inc' );
1298         wfOut(
1299 "Populating log_search table, printing progress markers. For large\n" .
1300 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1301 "maintenance/populateLogSearch.php.\n" );
1302         migrate_log_params( $wgDatabase );
1303         wfOut( "Done populating log_search table.\n" );
1306 /***********************************************************************
1307  * Start PG crap
1308  * TODO: merge with above
1309  ***********************************************************************/
1311 function
1312 pg_describe_table($table)
1314 global  $wgDatabase, $wgDBmwschema;
1315         $q = <<<END
1316 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1317         WHERE pg_class.relnamespace = pg_namespace.oid 
1318           AND attrelid=pg_class.oid AND attnum > 0
1319           AND relname=%s AND nspname=%s
1320 END;
1321         $res = $wgDatabase->query(sprintf($q,
1322                         $wgDatabase->addQuotes($table),
1323                         $wgDatabase->addQuotes($wgDBmwschema)));
1324         if (!$res)
1325                 return null;
1327         $cols = array();
1328         while ($r = $wgDatabase->fetchRow($res)) {
1329                 $cols[] = array(        
1330                                 "name" => $r[0],
1331                                 "ord" => $r[1],
1332                         );
1333         }
1334         return $cols;
1337 function
1338 pg_describe_index($idx)
1340 global  $wgDatabase, $wgDBmwschema;
1342         // first fetch the key (which is a list of columns ords) and
1343         // the table the index applies to (an oid)
1344         $q = <<<END
1345 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1346         WHERE nspname=%s
1347           AND pg_class.relnamespace = pg_namespace.oid
1348           AND relname=%s
1349           AND indexrelid=pg_class.oid
1350 END;
1351         $res = $wgDatabase->query(sprintf($q,
1352                         $wgDatabase->addQuotes($wgDBmwschema),
1353                         $wgDatabase->addQuotes($idx)));
1354         if (!$res)
1355                 return null;
1356         if (!($r = $wgDatabase->fetchRow($res))) {
1357                 $wgDatabase->freeResult($res);
1358                 return null;
1359         }
1361         $indkey = $r[0];
1362         $relid = intval($r[1]);
1363         $indkeys = explode(" ", $indkey);
1364         $wgDatabase->freeResult($res);
1366         $colnames = array();
1367         foreach ($indkeys as $rid) {
1368                 $query = <<<END
1369 SELECT attname FROM pg_class, pg_attribute
1370         WHERE attrelid=$relid
1371           AND attnum=%d
1372           AND attrelid=pg_class.oid
1373 END;
1374                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1375                 if (!$r2)
1376                         return null;
1377                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1378                         $wgDatabase->freeResult($r2);
1379                         return null;
1380                 }
1381                 $colnames[] = $row2[0];
1382                 $wgDatabase->freeResult($r2);
1383         }
1385         return $colnames;
1388 function
1389 pg_index_exists($table, $index)
1391 global  $wgDatabase, $wgDBmwschema;
1392         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1393                         array(  "indexname" => $index,
1394                                 "tablename" => $table,
1395                                 "schemaname" => $wgDBmwschema));
1396         return $exists === $index;
1399 function
1400 pg_fkey_deltype($fkey)
1402 global  $wgDatabase, $wgDBmwschema;
1403         $q = <<<END
1404 SELECT confdeltype FROM pg_constraint, pg_namespace
1405         WHERE connamespace=pg_namespace.oid
1406           AND nspname=%s
1407           AND conname=%s;
1408 END;
1409         $r = $wgDatabase->query(sprintf($q,
1410                 $wgDatabase->addQuotes($wgDBmwschema),
1411                 $wgDatabase->addQuotes($fkey)));
1412         if (!($row = $wgDatabase->fetchRow($r)))
1413                 return null;
1414         return $row[0];
1417 function
1418 pg_rule_def($table, $rule)
1420 global  $wgDatabase, $wgDBmwschema;
1421         $q = <<<END
1422 SELECT definition FROM pg_rules
1423         WHERE schemaname = %s
1424           AND tablename = %s
1425           AND rulename = %s
1426 END;
1427         $r = $wgDatabase->query(sprintf($q,
1428                         $wgDatabase->addQuotes($wgDBmwschema),
1429                         $wgDatabase->addQuotes($table),
1430                         $wgDatabase->addQuotes($rule)));
1431         $row = $wgDatabase->fetchRow($r);
1432         if (!$row)
1433                 return null;
1434         $d = $row[0];
1435         $wgDatabase->freeResult($r);
1436         return $d;
1439 function do_postgres_updates() {
1440         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1442         ## Gather version numbers in case we need them
1443         $version = $wgDatabase->getServerVersion(); ## long string
1444         $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1446         $wgShowExceptionDetails = 1;
1448         # Just in case their LocalSettings.php does not have this:
1449         if ( !isset( $wgDBmwschema ))
1450                 $wgDBmwschema = 'mediawiki';
1452         # Verify that this user is configured correctly
1453         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1454         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1455         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1456         $conf = array();
1457         foreach( explode( '*', $config ) as $c ) {
1458                 list( $x,$y ) = explode( '=', $c );
1459                 $conf[$x] = $y;
1460         }
1461         if( !array_key_exists( 'search_path', $conf ) ) {
1462                 $search_path = '';
1463         }
1464         else {
1465                 $search_path = $conf['search_path'];
1466         }
1467         if( strpos( $search_path, $wgDBmwschema ) === false ) {
1468                 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1469                 $search_path = "$wgDBmwschema, $search_path";
1470         }
1471         if( strpos( $search_path, $wgDBts2schema ) === false ) {
1472                 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1473                 $search_path = "$search_path, $wgDBts2schema";
1474         }
1475         $search_path = str_replace( ', ,', ',', $search_path);
1476         if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1477                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1478                 $wgDatabase->doQuery( "SET search_path = $search_path" );
1479         }
1480         else {
1481                 $path = $conf['search_path'];
1482                 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1483         }
1484         $goodconf = array(
1485                 'client_min_messages' => 'error',
1486                 'DateStyle'           => 'ISO, YMD',
1487                 'TimeZone'            => 'GMT'
1488         );
1489         foreach( array_keys( $goodconf ) AS $key ) {
1490                 $value = $goodconf[$key];
1491                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1492                         wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1493                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1494                         $wgDatabase->doQuery( "SET $key = '$value'" );
1495                 }
1496                 else {
1497                         wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1498                 }
1499         }
1501         $newsequences = array(
1502                 "log_log_id_seq",
1503                 "pr_id_val",
1504         );
1506         $newtables = array(
1507                 array("category",          "patch-category.sql"),
1508                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1509                 array("mwuser",            "patch-mwuser.sql"),
1510                 array("pagecontent",       "patch-pagecontent.sql"),
1511                 array("querycachetwo",     "patch-querycachetwo.sql"),
1512                 array("page_props",        "patch-page_props.sql"),
1513                 array("page_restrictions", "patch-page_restrictions.sql"),
1514                 array("profiling",         "patch-profiling.sql"),
1515                 array("protected_titles",  "patch-protected_titles.sql"),
1516                 array("redirect",          "patch-redirect.sql"),
1517                 array("updatelog",         "patch-updatelog.sql"),
1518                 array('change_tag',        'patch-change_tag.sql'),
1519                 array('tag_summary',       'patch-change_tag.sql'),
1520                 array('valid_tag',         'patch-change_tag.sql'),
1521                 array('user_properties',   'patch-user_properties.sql'),
1522                 array('log_search',        'patch-log_search.sql'),
1523                 array('l10n_cache',        'patch-l10n_cache.sql'),
1524         );
1526         $newcols = array(
1527                 array("archive",       "ar_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1528                 array("archive",       "ar_len",               "INTEGER"),
1529                 array("archive",       "ar_page_id",           "INTEGER"),
1530                 array("archive",       "ar_parent_id",         "INTEGER"),
1531                 array("image",         "img_sha1",             "TEXT NOT NULL DEFAULT ''"),
1532                 array("ipblocks",      "ipb_allow_usertalk",   "SMALLINT NOT NULL DEFAULT 0"),
1533                 array("ipblocks",      "ipb_anon_only",        "SMALLINT NOT NULL DEFAULT 0"),
1534                 array("ipblocks",      "ipb_by_text",          "TEXT NOT NULL DEFAULT ''"),
1535                 array("ipblocks",      "ipb_block_email",      "SMALLINT NOT NULL DEFAULT 0"),
1536                 array("ipblocks",      "ipb_create_account",   "SMALLINT NOT NULL DEFAULT 1"),
1537                 array("ipblocks",      "ipb_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1538                 array("ipblocks",      "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1539                 array("filearchive",   "fa_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1540                 array("logging",       "log_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1541                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1542                 array("logging",       "log_params",           "TEXT"),
1543                 array("mwuser",        "user_editcount",       "INTEGER"),
1544                 array("mwuser",        "user_hidden",          "SMALLINT NOT NULL DEFAULT 0"),
1545                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1546                 array("oldimage",      "oi_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1547                 array("oldimage",      "oi_major_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1548                 array("oldimage",      "oi_media_type",        "TEXT"),
1549                 array("oldimage",      "oi_metadata",          "BYTEA NOT NULL DEFAULT ''"),
1550                 array("oldimage",      "oi_minor_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1551                 array("oldimage",      "oi_sha1",              "TEXT NOT NULL DEFAULT ''"),
1552                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1553                 array("profiling",     "pf_memory",            "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1554                 array("recentchanges", "rc_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1555                 array("recentchanges", "rc_log_action",        "TEXT"),
1556         array("recentchanges", "rc_log_type",          "TEXT"),
1557         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1558                 array("recentchanges", "rc_new_len",           "INTEGER"),
1559                 array("recentchanges", "rc_old_len",           "INTEGER"),
1560                 array("recentchanges", "rc_params",            "TEXT"),
1561                 array("revision",      "rev_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1562                 array("revision",      "rev_len",              "INTEGER"),
1563                 array("revision",      "rev_parent_id",        "INTEGER DEFAULT NULL"),
1564                 array("site_stats",    "ss_active_users",      "INTEGER DEFAULT '-1'"),
1565                 array("user_newtalk",  "user_last_timestamp",  "TIMESTAMPTZ"),
1566                 array("logging",       "log_user_text",        "TEXT NOT NULL DEFAULT ''"),
1567                 array("logging",       "log_page",             "INTEGER"),
1568         );
1571         # table, column, desired type, USING clause if needed (with new default if needed)
1572         $typechanges = array(
1573                 array("archive",      "ar_deleted",      "smallint", ""),
1574                 array("archive",      "ar_minor_edit",   "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1575                 array("filearchive",  "fa_deleted",      "smallint", ""),
1576                 array("filearchive",  "fa_height",       "integer",  ""),
1577                 array("filearchive",  "fa_metadata",     "bytea",    "decode(fa_metadata,'escape')"),
1578                 array("filearchive",  "fa_size",         "integer",  ""),
1579                 array("filearchive",  "fa_width",        "integer",  ""),
1580                 array("filearchive",  "fa_storage_group","text",     ""),
1581                 array("filearchive",  "fa_storage_key",  "text",     ""),
1582                 array("image",        "img_metadata",    "bytea",    "decode(img_metadata,'escape')"),
1583                 array("image",        "img_size",        "integer",  ""),
1584                 array("image",        "img_width",       "integer",  ""),
1585                 array("image",        "img_height",      "integer",  ""),
1586                 array("interwiki",    "iw_local",        "smallint", "iw_local::smallint DEFAULT 0"),
1587                 array("interwiki",    "iw_trans",        "smallint", "iw_trans::smallint DEFAULT 0"),
1588                 array("ipblocks",     "ipb_auto",        "smallint", "ipb_auto::smallint DEFAULT 0"),
1589                 array("ipblocks",     "ipb_anon_only",   "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1590                 array("ipblocks",     "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1591                 array("ipblocks",     "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1592                 array("ipblocks",     "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1593                 array("ipblocks",     "ipb_address",     "text",     "ipb_address::text"),
1594                 array("ipblocks",     "ipb_deleted",     "smallint", "ipb_deleted::smallint DEFAULT 0"),
1595                 array("math",         "math_inputhash",  "bytea",    "decode(math_inputhash,'escape')"),
1596                 array("math",         "math_outputhash", "bytea",    "decode(math_outputhash,'escape')"),
1597                 array("mwuser",       "user_token",      "text",     ""),
1598                 array("mwuser",       "user_email_token","text",     ""),
1599                 array("objectcache",  "keyname",         "text",     ""),
1600                 array("oldimage",     "oi_height",       "integer",  ""),
1601                 array("oldimage",     "oi_metadata",     "bytea",    "decode(img_metadata,'escape')"),
1602                 array("oldimage",     "oi_size",         "integer",  ""),
1603                 array("oldimage",     "oi_width",        "integer",  ""),
1604                 array("page",         "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1605                 array("page",         "page_is_new",     "smallint", "page_is_new::smallint DEFAULT 0"),
1606                 array("querycache",   "qc_value",        "integer",  ""),
1607                 array("querycachetwo","qcc_value",       "integer",  ""),
1608                 array("recentchanges","rc_bot",          "smallint", "rc_bot::smallint DEFAULT 0"),
1609                 array("recentchanges","rc_deleted",      "smallint", ""),
1610                 array("recentchanges","rc_minor",        "smallint", "rc_minor::smallint DEFAULT 0"),
1611                 array("recentchanges","rc_new",          "smallint", "rc_new::smallint DEFAULT 0"),
1612                 array("recentchanges","rc_type",         "smallint", "rc_type::smallint DEFAULT 0"),
1613                 array("recentchanges","rc_patrolled",    "smallint", "rc_patrolled::smallint DEFAULT 0"),
1614                 array("revision",     "rev_deleted",     "smallint", "rev_deleted::smallint DEFAULT 0"),
1615                 array("revision",     "rev_minor_edit",  "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1616                 array("templatelinks","tl_namespace",    "smallint", "tl_namespace::smallint"),
1617                 array("user_newtalk", "user_ip",         "text",     "host(user_ip)"),
1618         );
1620         # table, column, nullability
1621         $nullchanges = array(
1622                 array("oldimage", "oi_bits",       "NULL"),
1623                 array("oldimage", "oi_timestamp",  "NULL"),
1624                 array("oldimage", "oi_major_mime", "NULL"),
1625                 array("oldimage", "oi_minor_mime", "NULL"),
1626         );
1628         $newindexes = array(
1629                 array("archive",       "archive_user_text",  "(ar_user_text)"),
1630                 array("image",         "img_sha1",           "(img_sha1)"),
1631                 array("oldimage",      "oi_sha1",            "(oi_sha1)"),
1632                 array("revision",      "rev_text_id_idx",    "(rev_text_id)"),
1633                 array("recentchanges", "rc_timestamp_bot",   "(rc_timestamp) WHERE rc_bot = 0"),
1634                 array("templatelinks", "templatelinks_from", "(tl_from)"),
1635                 array("watchlist",     "wl_user",            "(wl_user)"),
1636                 array("logging",       "logging_user_type_time", "(log_user, log_type, log_timestamp)"),
1637                 array("logging",       "logging_page_id_time",   "(log_page,log_timestamp)"),
1638         );
1640         $newrules = array(
1641         );
1643         foreach ($newsequences as $ns) {
1644                 if ($wgDatabase->sequenceExists($ns)) {
1645                         wfOut( "... sequence \"$ns\" already exists\n" );
1646                         continue;
1647                 }
1649                 wfOut( "Creating sequence \"$ns\"\n" );
1650                 $wgDatabase->query("CREATE SEQUENCE $ns");
1651         }
1653         foreach ($newtables as $nt) {
1654                 if ($wgDatabase->tableExists($nt[0])) {
1655                         wfOut( "... table \"$nt[0]\" already exists\n" );
1656                         continue;
1657                 }
1659                 wfOut( "Creating table \"$nt[0]\"\n" );
1660                 $wgDatabase->sourceFile(archive($nt[1]));
1661         }
1663         ## Needed before newcols
1664         if ($wgDatabase->tableExists("archive2")) {
1665                 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1666                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1667                         wfOut( "Dropping rule \"archive_insert\"\n" );
1668                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1669                 }
1670                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1671                         wfOut( "Dropping rule \"archive_delete\"\n" );
1672                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1673                 }
1674                 $wgDatabase->sourceFile(archive("patch-remove-archive2.sql"));
1675         }
1676         else
1677                 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1679         foreach ($newcols as $nc) {
1680                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1681                 if (!is_null($fi)) {
1682                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1683                         continue;
1684                 }
1686                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1687                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1688         }
1690         foreach ($typechanges as $tc) {
1691                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1692                 if (is_null($fi)) {
1693                         wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1694                         exit(1);
1695                 }
1697                 if ($fi->type() === $tc[2])
1698                         wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1699                 else {
1700                         wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1701                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1702                         if (strlen($tc[3])) {
1703                                 $default = array();
1704                                 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1705                                         $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1706                                         $wgDatabase->query($sqldef);
1707                                         $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1708                                 }
1709                                 $sql .= " USING $tc[3]";
1710                         }
1711                         $sql .= ";\nCOMMIT;\n";
1712                         $wgDatabase->query($sql);
1713                 }
1714         }
1716         foreach ($nullchanges as $nc) {
1717                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1718                 if (is_null($fi)) {
1719                         wfOut( "... error: expected column $nc[0].$nc[1] to exist\n" );
1720                         exit(1);
1721                 }
1722                 if ($fi->nullable()) {
1723                         ## It's NULL - does it need to be NOT NULL?
1724                         if ('NOT NULL' === $nc[2]) {
1725                                 wfOut( "Changing \"$nc[0].$nc[1]\" to not allow NULLs\n" );
1726                                 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] SET NOT NULL" );
1727                         }
1728                         else {
1729                                 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NULL\n" );
1730                         }
1731                 }
1732                 else {
1733                         ## It's NOT NULL - does it need to be NULL?
1734                         if ('NULL' === $nc[2]) {
1735                                 wfOut( "Changing \"$nc[0].$nc[1]\" to allow NULLs\n" );
1736                                 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] DROP NOT NULL" );
1737                         }
1738                         else {
1739                                 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NOT NULL\n" );
1740                         }
1741                 }
1742         }
1744         if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1745                 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1746                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1747                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1748                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1749         }
1750         else
1751                 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1754         foreach ($newindexes as $ni) {
1755                 if (pg_index_exists($ni[0], $ni[1])) {
1756                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1757                         continue;
1758                 }
1759                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1760                 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1761         }
1763         foreach ($newrules as $nr) {
1764                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1765                         wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1766                         continue;
1767                 }
1768                 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1769                 $wgDatabase->sourceFile(archive($nr[2]));
1770         }
1772         if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascaded")) {
1773                 wfOut( "... table \"oldimage\" has correct cascading delete/update foreign key to image\n" );
1774         }
1775         else {
1776                 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1777                         $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1778                 }
1779                 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascade")) {
1780                         $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey_cascade" );
1781                 }
1782                 wfOut( "Making foreign key on table \"oldimage\" (to image) a cascade delete/update\n" );
1783                 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded ".
1784                         "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" );
1785         }
1787         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1788                 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1789                 $wgDatabase->sourceFile(archive('patch-page_deleted.sql'));
1790         }
1791         else
1792                 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1794         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1795         if (!$fi->nullable()) {
1796                 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1797                 $wgDatabase->sourceFile(archive('patch-rc_cur_id-not-null.sql'));
1798         }
1799         else
1800                 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1802         $pu = pg_describe_index("pagelink_unique");
1803         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1804                 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1805                 $wgDatabase->query("DROP INDEX pagelink_unique");
1806                 $pu = null;
1807         }
1808         else
1809                 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1811         if (is_null($pu)) {
1812                 wfOut( "Creating index \"pagelink_unique index\"\n" );
1813                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1814         }
1815         else
1816                 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1818         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1819                 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1820         }
1821         else {
1822                 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1823                 $wgDatabase->sourceFile(archive('patch-revision_rev_user_fkey.sql'));
1824         }
1826         # Fix ipb_address index
1827         if (pg_index_exists('ipblocks', 'ipb_address' )) {
1828                 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1829                 $wgDatabase->query('DROP INDEX ipb_address');
1830         }
1831         if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1832                 wfOut( "... have ipb_address_unique\n" );
1833         }
1834         else {
1835                 wfOut( "Adding ipb_address_unique index\n" );
1836                 $wgDatabase->sourceFile(archive('patch-ipb_address_unique.sql'));
1837         }
1839         global $wgExtNewTables, $wgExtPGNewFields, $wgExtPGAlteredFields, $wgExtNewIndexes;
1840         # Add missing extension tables
1841         foreach ( $wgExtNewTables as $nt ) {
1842                 if ($wgDatabase->tableExists($nt[0])) {
1843                         wfOut( "... table \"$nt[0]\" already exists\n" );
1844                         continue;
1845                 }
1846                 wfOut( "Creating table \"$nt[0]\"\n" );
1847                 $wgDatabase->sourceFile($nt[1]);
1848         }
1849         # Add missing extension fields
1850         foreach ( $wgExtPGNewFields as $nc ) {
1851                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1852                 if (!is_null($fi)) {
1853                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1854                         continue;
1855                 }
1856                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1857                 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1858         }
1859         # Change altered columns
1860         foreach ( $wgExtPGAlteredFields as $nc ) {
1861                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1862                 if (is_null($fi)) {
1863                         wfOut( "WARNING! Column \"$nc[0].$nc[1]\" does not exist but had an alter request! Please report this.\n" );
1864                         continue;
1865                 }
1866                 $oldtype = $fi->type();
1867                 $newtype = strtolower( $nc[2] );
1868                 if ($oldtype === $newtype) {
1869                         wfOut( "... column \"$nc[0].$nc[1]\" has correct type of \"$newtype\"\n" );
1870                         continue;
1871                 }
1872                 $command = "ALTER TABLE $nc[0] ALTER $nc[1] TYPE $nc[2]";
1873                 if ( isset( $nc[3] ) ) {
1874                         $command .= " USING $nc[3]";
1875                 }
1876                 wfOut( "Altering column \"$nc[0].$nc[1]\" from type \"$oldtype\" to \"$newtype\"\n" );
1877                 $wgDatabase->query( $command );
1878         }
1879         # Add missing extension indexes
1880         foreach ( $wgExtNewIndexes as $ni ) {
1881                 if (pg_index_exists($ni[0], $ni[1])) {
1882                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1883                         continue;
1884                 }
1885                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
1886                 if ( preg_match( '/^\(/', $ni[2] ) ) {
1887                         $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1888                 }
1889                 else {
1890                         $wgDatabase->sourceFile($ni[2]);
1891                 }
1892         }
1894         # Tweak the page_title tsearch2 trigger to filter out slashes
1895         # This is create or replace, so harmless to call if not needed
1896         $wgDatabase->sourceFile(archive('patch-ts2pagetitle.sql'));
1898         ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
1899         ## in case they have the old 'default' versions
1900         if ( $numver >= 8.3 )
1901                 $wgDatabase->sourceFile(archive('patch-tsearch2funcs.sql'));
1903         ## Put a new row in the mediawiki_version table
1904         $wgDatabase->insert( 'mediawiki_version',
1905                 array(
1906                         'type' => 'Update',
1907                         'ctype' => 'U',
1908                         'mw_version' => $wgVersion,
1909                         'pg_version' => $version,
1910                         'sql_version' => '$LastChangedRevision$',
1911                         'sql_date' => '$LastChangedDate$',
1912                 ) );
1913         return;