Updated patch files to match the recent update to tables.sql. Removed some defunct...
[mediawiki.git] / maintenance / updaters.inc
blob21c43cc52095b0daf5eec98d23e3c9b5cf104813
1 <?php
2 /**
3  * @addtogroup Maintenance
4  */
6  /** */
8 if ( !defined( 'MEDIAWIKI' ) ) {
9         echo "This file is not a valid entry point\n";
10         exit( 1 );
13 require_once 'convertLinks.inc';
14 require_once 'userDupes.inc';
15 require_once 'deleteDefaultMessages.php';
17 $wgRenamedTables = array(
18 #           from             to                  patch file
19 #       array( 'group',         'groups',           'patch-rename-group.sql' ),
22 $wgNewTables = array(
23 #            table          patch file (in maintenance/archives)
24         array( 'hitcounter',    'patch-hitcounter.sql' ),
25         array( 'querycache',    'patch-querycache.sql' ),
26         array( 'objectcache',   'patch-objectcache.sql' ),
27         array( 'categorylinks', 'patch-categorylinks.sql' ),
28         array( 'logging',       'patch-logging.sql' ),
29         array( 'user_newtalk',  'patch-usernewtalk2.sql' ),
30         array( 'transcache',    'patch-transcache.sql' ),
31         array( 'trackbacks',    'patch-trackbacks.sql' ),
32         array( 'externallinks', 'patch-externallinks.sql' ),
33         array( 'job',           'patch-job.sql' ),
34         array( 'langlinks',     'patch-langlinks.sql' ),
35         array( 'querycache_info', 'patch-querycacheinfo.sql' ),
36         array( 'filearchive',   'patch-filearchive.sql' ),
37         array( 'querycachetwo', 'patch-querycachetwo.sql' ),
40 $wgNewFields = array(
41 #           table            field             patch file (in maintenance/archives)
42         array( 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
43         array( 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
44         array( 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
45         array( 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
46         array( 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
47         array( 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
48         array( 'recentchanges', 'rc_old_len',       'patch-rc_len.sql' ),
49         array( 'user',          'user_real_name',   'patch-user-realname.sql' ),
50         array( 'user',          'user_token',       'patch-user_token.sql' ),
51         array( 'user',          'user_email_token', 'patch-user_email_token.sql' ),
52         array( 'user',          'user_registration','patch-user_registration.sql' ),
53         array( 'logging',       'log_params',       'patch-log_params.sql' ),
54         array( 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
55         array( 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
56         array( 'page',          'page_len',         'patch-page_len.sql' ),
57         array( 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
58         array( 'image',         'img_width',        'patch-img_width.sql' ),
59         array( 'image',         'img_metadata',     'patch-img_metadata.sql' ),
60         array( 'image',         'img_media_type',   'patch-img_media_type.sql' ),
61         array( 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
62         array( 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
63         array( 'ipblocks',      'ipb_range_start',  'patch-ipb_range_start.sql' ),
64         array( 'site_stats',    'ss_images',        'patch-ss_images.sql' ),
65         array( 'ipblocks',      'ipb_anon_only',    'patch-ipb_anon_only.sql' ),
66         array( 'ipblocks',              'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
67         array( 'user',          'user_newpass_time','patch-user_newpass_time.sql' ),
68         array( 'user',          'user_editcount',   'patch-user_editcount.sql' ),
69         array( 'recentchanges', 'rc_deleted',           'patch-rc_deleted.sql' ),
70         array( 'logging',               'log_id',                       'patch-log_id.sql' ),
71         array( 'logging',               'log_deleted',          'patch-log_deleted.sql' ),
72         array( 'archive',               'ar_deleted',           'patch-ar_deleted.sql' ),
73         array( 'ipblocks',              'ipb_deleted',          'patch-ipb_deleted.sql' ),
74         array( 'filearchive',   'fa_deleted',           'patch-fa_deleted.sql' ),
75         array( 'revision',          'rev_len',          'patch-rev_len.sql' ),
76         array( 'archive',           'ar_len',           'patch-ar_len.sql' ),
77         array( 'revision',          'rev_parent_id',    'patch-rev_parent_id.sql' ),
78         array( 'page_restrictions', 'pr_id',            'patch-page_restrictions_sortkey.sql' ),
79         array( 'ipblocks',          'ipb_block_email',  'patch-ipb_emailban.sql' ),
82 function rename_table( $from, $to, $patch ) {
83         global $wgDatabase;
84         if ( $wgDatabase->tableExists( $from ) ) {
85                 if ( $wgDatabase->tableExists( $to ) ) {
86                         echo "...can't move table $from to $to, $to already exists.\n";
87                 } else {
88                         echo "Moving table $from to $to...";
89                         dbsource( archive($patch), $wgDatabase );
90                         echo "ok\n";
91                 }
92         } else {
93                 // Source table does not exist
94                 // Renames are done before creations, so this is typical for a new installation
95                 // Ignore silently
96         }
99 function add_table( $name, $patch ) {
100         global $wgDatabase;
101         if ( $wgDatabase->tableExists( $name ) ) {
102                 echo "...$name table already exists.\n";
103         } else {
104                 echo "Creating $name table...";
105                 dbsource( archive($patch), $wgDatabase );
106                 echo "ok\n";
107         }
110 function add_field( $table, $field, $patch ) {
111         global $wgDatabase;
112         if ( !$wgDatabase->tableExists( $table ) ) {
113                 echo "...$table table does not exist, skipping new field patch\n";
114         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
115                 echo "...have $field field in $table table.\n";
116         } else {
117                 echo "Adding $field field to table $table...";
118                 dbsource( archive($patch) , $wgDatabase );
119                 echo "ok\n";
120         }
123 function do_revision_updates() {
124         global $wgSoftwareRevision;
125         if ( $wgSoftwareRevision < 1001 ) {
126                 update_passwords();
127         }
130 function update_passwords() {
131         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
133         global $wgDatabase;
134         $fname = "Update script: update_passwords()";
135         print "\nIt appears that you need to update the user passwords in your\n" .
136           "database. If you have already done this (if you've run this update\n" .
137           "script once before, for example), doing so again will make all your\n" .
138           "user accounts inaccessible, so be sure you only do this once.\n" .
139           "Update user passwords? (yes/no)";
141         $resp = readconsole();
142     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
144         $sql = "SELECT user_id,user_password FROM user";
145         $source = $wgDatabase->query( $sql, $fname );
147         while ( $row = $wgDatabase->fetchObject( $source ) ) {
148                 $id = $row->user_id;
149                 $oldpass = $row->user_password;
150                 $newpass = md5( "{$id}-{$oldpass}" );
152                 $sql = "UPDATE user SET user_password='{$newpass}' " .
153                   "WHERE user_id={$id}";
154                 $wgDatabase->query( $sql, $fname );
155         }
158 function do_interwiki_update() {
159         # Check that interwiki table exists; if it doesn't source it
160         global $wgDatabase, $IP;
161         if( $wgDatabase->tableExists( "interwiki" ) ) {
162                 echo "...already have interwiki table\n";
163                 return true;
164         }
165         echo "Creating interwiki table: ";
166         dbsource( archive("patch-interwiki.sql") );
167         echo "ok\n";
168         echo "Adding default interwiki definitions: ";
169         dbsource( "$IP/maintenance/interwiki.sql" );
170         echo "ok\n";
173 function do_index_update() {
174         # Check that proper indexes are in place
175         global $wgDatabase;
176         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
177         if( !$meta->isMultipleKey() ) {
178                 echo "Updating indexes to 20031107: ";
179                 dbsource( archive("patch-indexes.sql") );
180                 echo "ok\n";
181                 return true;
182         }
183         echo "...indexes seem up to 20031107 standards\n";
184         return false;
187 function do_image_index_update() {
188         global $wgDatabase;
190         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
191         if( !$meta->isMultipleKey() ) {
192                 echo "Updating indexes to 20050912: ";
193                 dbsource( archive("patch-mimesearch-indexes.sql") );
194                 echo "ok\n";
195                 return true;
196         }
197         echo "...indexes seem up to 20050912 standards\n";
198         return false;
201 function do_image_name_unique_update() {
202         global $wgDatabase;
203         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
204                 echo "...image primary key already set.\n";
205         } else {
206                 echo "Making img_name the primary key... ";
207                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
208                 echo "ok\n";
209         }
212 function do_logging_timestamp_index() {
213         global $wgDatabase;
214         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
215                 echo "...timestamp key on logging already exists.\n";
216         } else {
217                 echo "Adding timestamp key on logging table... ";
218                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
219                 echo "ok\n";
220         }
224 function do_watchlist_update() {
225         global $wgDatabase;
226         $fname = 'do_watchlist_update';
227         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
228                 echo "The watchlist table is already set up for email notification.\n";
229         } else {
230                 echo "Adding wl_notificationtimestamp field for email notification management.";
231                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
232                 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
233                 echo "ok\n";
234         }
235         # Check if we need to add talk page rows to the watchlist
236         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
237         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
238         if ( $talk != $nontalk ) {
239                 echo "Adding missing watchlist talk page rows... ";
240                 flush();
242                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
243                         array(
244                                 'wl_user' => 'wl_user',
245                                 'wl_namespace' => 'wl_namespace | 1',
246                                 'wl_title' => 'wl_title',
247                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
248                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
249                 echo "ok\n";
250         } else {
251                 echo "...watchlist talk page rows already present\n";
252         }
255 function do_copy_newtalk_to_watchlist() {
256         global $wgDatabase;
257         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
259         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
260                 $wgDatabase->tableName( 'user_newtalk' ) );
261         $num_newtalks=$wgDatabase->numRows($res);
262         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
264         $user = new User();
265         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
266                 $wluser = $wgDatabase->fetchObject( $res );
267                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
268                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
269                                 $wgDatabase->replace( 'watchlist',
270                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
271                                           array('wl_user'                       => 0,
272                                                 'wl_namespace'                  => NS_USER_TALK,
273                                                 'wl_title'                      => $wluser->user_ip,
274                                                 'wl_notificationtimestamp'      => '19700101000000'
275                                                 ), 'updaters.inc::do_watchlist_update2'
276                                         );
277                         }
278                 } else { # normal users ... have user_ids
279                         $user->setID($wluser->user_id);
280                         $wgDatabase->replace( 'watchlist',
281                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
282                                   array('wl_user'                       => $user->getID(),
283                                         'wl_namespace'                  => NS_USER_TALK,
284                                         'wl_title'                      => $user->getName(),
285                                         'wl_notificationtimestamp'      => '19700101000000'
286                                         ), 'updaters.inc::do_watchlist_update3'
287                                 );
288                 }
289         }
290         echo "Done.\n";
294 function do_user_update() {
295         global $wgDatabase;
296         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
297                 echo "User table contains old email authentication field. Dropping... ";
298                 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
299                 echo "ok\n";
300         } else {
301                 echo "...user table does not contain old email authentication field.\n";
302         }
306  * 1.4 betas were missing the 'binary' marker from logging.log_title,
307  * which causes a collation mismatch error on joins in MySQL 4.1.
308  */
309 function do_logging_encoding() {
310         global $wgDatabase, $wgDBtype;
311         if ($wgDBtype != 'mysql')
312                 return;
313         $logging = $wgDatabase->tableName( 'logging' );
314         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
315         $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
316         $wgDatabase->freeResult( $res );
318         if( in_array( 'binary', $flags ) ) {
319                 echo "Logging table has correct title encoding.\n";
320         } else {
321                 echo "Fixing title encoding on logging table... ";
322                 dbsource( archive( 'patch-logging-title.sql' ), $wgDatabase );
323                 echo "ok\n";
324         }
327 function do_schema_restructuring() {
328         global $wgDatabase;
329         $fname="do_schema_restructuring";
330         if ( $wgDatabase->tableExists( 'page' ) ) {
331                 echo "...page table already exists.\n";
332         } else {
333                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
334                 echo wfTimestamp( TS_DB );
335                 echo "......checking for duplicate entries.\n"; flush();
337                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
339                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
340                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
342                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
343                         echo wfTimestamp( TS_DB );
344                         echo "......<b>Found duplicate entries</b>\n";
345                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
346                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
347                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
348                                         $duplicate[$row->cur_namespace] = array();
349                                 }
350                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
351                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
352                         }
353                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
354                         $firstCond = true;
355                         foreach ( $duplicate as $ns => $titles ) {
356                                 if ( $firstCond ) {
357                                         $firstCond = false;
358                                 } else {
359                                         $sql .= ' OR ';
360                                 }
361                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
362                                 $first = true;
363                                 foreach ( $titles as $t ) {
364                                         if ( $first ) {
365                                                 $sql .= $wgDatabase->addQuotes( $t );
366                                                 $first = false;
367                                         } else {
368                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
369                                         }
370                                 }
371                                 $sql .= ") ) \n";
372                         }
373                         # By sorting descending, the most recent entry will be the first in the list.
374                         # All following entries will be deleted by the next while-loop.
375                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
377                         $rows = $wgDatabase->query( $sql, $fname );
379                         $prev_title = $prev_namespace = false;
380                         $deleteId = array();
382                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
383                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
384                                         $deleteId[] = $row->cur_id;
385                                 }
386                                 $prev_title     = $row->cur_title;
387                                 $prev_namespace = $row->cur_namespace;
388                         }
389                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
390                         $rows = $wgDatabase->query( $sql, $fname );
391                         echo wfTimestamp( TS_DB );
392                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
393                 }
396                 echo wfTimestamp( TS_DB );
397                 echo "......Creating tables.\n";
398                 $wgDatabase->query("CREATE TABLE $page (
399                         page_id int(8) unsigned NOT NULL auto_increment,
400                         page_namespace int NOT NULL,
401                         page_title varchar(255) binary NOT NULL,
402                         page_restrictions tinyblob NOT NULL,
403                         page_counter bigint(20) unsigned NOT NULL default '0',
404                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
405                         page_is_new tinyint(1) unsigned NOT NULL default '0',
406                         page_random real unsigned NOT NULL,
407                         page_touched char(14) binary NOT NULL default '',
408                         page_latest int(8) unsigned NOT NULL,
409                         page_len int(8) unsigned NOT NULL,
411                         PRIMARY KEY page_id (page_id),
412                         UNIQUE INDEX name_title (page_namespace,page_title),
413                         INDEX (page_random),
414                         INDEX (page_len)
415                         ) TYPE=InnoDB", $fname );
416                 $wgDatabase->query("CREATE TABLE $revision (
417                         rev_id int(8) unsigned NOT NULL auto_increment,
418                         rev_page int(8) unsigned NOT NULL,
419                         rev_comment tinyblob NOT NULL,
420                         rev_user int(5) unsigned NOT NULL default '0',
421                         rev_user_text varchar(255) binary NOT NULL default '',
422                         rev_timestamp char(14) binary NOT NULL default '',
423                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
424                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
425                         rev_len int(8) unsigned,
426                         rev_parent_id int(8) unsigned default NULL,
427                         PRIMARY KEY rev_page_id (rev_page, rev_id),
428                         UNIQUE INDEX rev_id (rev_id),
429                         INDEX rev_timestamp (rev_timestamp),
430                         INDEX page_timestamp (rev_page,rev_timestamp),
431                         INDEX user_timestamp (rev_user,rev_timestamp),
432                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
433                         ) TYPE=InnoDB", $fname );
435                 echo wfTimestamp( TS_DB );
436                 echo "......Locking tables.\n";
437                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
439                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
440                 echo wfTimestamp( TS_DB );
441                 echo "......maxold is {$maxold}\n";
443                 echo wfTimestamp( TS_DB );
444                 global $wgLegacySchemaConversion;
445                 if( $wgLegacySchemaConversion ) {
446                         // Create HistoryBlobCurStub entries.
447                         // Text will be pulled from the leftover 'cur' table at runtime.
448                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
449                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
450                         $cur_flags = "'object'";
451                 } else {
452                         // Copy all cur text in immediately: this may take longer but avoids
453                         // having to keep an extra table around.
454                         echo "......Moving text from cur.\n";
455                         $cur_text = 'cur_text';
456                         $cur_flags = "''";
457                 }
458                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
459                                 old_timestamp, old_minor_edit, old_flags)
460                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
461                         FROM $cur", $fname );
463                 echo wfTimestamp( TS_DB );
464                 echo "......Setting up revision table.\n";
465                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
466                                 rev_minor_edit)
467                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
468                                 old_timestamp, old_minor_edit
469                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
471                 echo wfTimestamp( TS_DB );
472                 echo "......Setting up page table.\n";
473                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
474                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
475                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
476                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
477                         FROM $cur,$revision
478                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
480                 echo wfTimestamp( TS_DB );
481                 echo "......Unlocking tables.\n";
482                 $wgDatabase->query( "UNLOCK TABLES", $fname );
484                 echo wfTimestamp( TS_DB );
485                 echo "......Renaming old.\n";
486                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
488                 echo wfTimestamp( TS_DB );
489                 echo "...done.\n";
490         }
493 function do_inverse_timestamp() {
494         global $wgDatabase;
495         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
496                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
497                 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
498                 echo "ok\n";
499         } else {
500                 echo "revision timestamp indexes already up to 2005-03-13\n";
501         }
504 function do_text_id() {
505         global $wgDatabase;
506         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
507                 echo "...rev_text_id already in place.\n";
508         } else {
509                 echo "Adding rev_text_id field... ";
510                 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
511                 echo "ok\n";
512         }
515 function do_namespace_size() {
516         $tables = array(
517                 'page'          => 'page',
518                 'archive'       => 'ar',
519                 'recentchanges' => 'rc',
520                 'watchlist'     => 'wl',
521                 'querycache'    => 'qc',
522                 'logging'       => 'log',
523         );
524         foreach( $tables as $table => $prefix ) {
525                 do_namespace_size_on( $table, $prefix );
526                 flush();
527         }
530 function do_namespace_size_on( $table, $prefix ) {
531         global $wgDatabase, $wgDBtype;
532         if ($wgDBtype != 'mysql')
533                 return;
534         $field = $prefix . '_namespace';
536         $tablename = $wgDatabase->tableName( $table );
537         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
538         $info = $wgDatabase->fetchObject( $result );
539         $wgDatabase->freeResult( $result );
541         if( substr( $info->Type, 0, 3 ) == 'int' ) {
542                 echo "...$field is already a full int ($info->Type).\n";
543         } else {
544                 echo "Promoting $field from $info->Type to int... ";
546                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
547                 $wgDatabase->query( $sql );
549                 echo "ok\n";
550         }
553 function do_pagelinks_update() {
554         global $wgDatabase;
555         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
556                 echo "...already have pagelinks table.\n";
557         } else {
558                 echo "Converting links and brokenlinks tables to pagelinks... ";
559                 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
560                 echo "ok\n";
561                 flush();
563                 global $wgCanonicalNamespaceNames;
564                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
565                         if( $ns != 0 ) {
566                                 do_pagelinks_namespace( $ns );
567                         }
568                 }
569         }
572 function do_pagelinks_namespace( $namespace ) {
573         global $wgDatabase, $wgContLang;
575         $ns = intval( $namespace );
576         echo "Cleaning up broken links for namespace $ns... ";
578         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
579         $name = $wgContLang->getNsText( $ns );
580         $prefix = $wgDatabase->strencode( $name );
581         $likeprefix = str_replace( '_', '\\_', $prefix);
583         $sql = "UPDATE $pagelinks
584                    SET pl_namespace=$ns,
585                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
586                  WHERE pl_namespace=0
587                    AND pl_title LIKE '$likeprefix:%'";
589         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
590         echo "ok\n";
593 function do_drop_img_type() {
594         global $wgDatabase;
596         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
597                 echo "Dropping unused img_type field in image table... ";
598                 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
599                 echo "ok\n";
600         } else {
601                 echo "No img_type field in image table; Good.\n";
602         }
605 function do_old_links_update() {
606         global $wgDatabase;
607         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
608                 echo "Already have pagelinks; skipping old links table updates.\n";
609         } else {
610                 convertLinks(); flush();
611         }
614 function do_user_unique_update() {
615         global $wgDatabase;
616         $duper = new UserDupes( $wgDatabase );
617         if( $duper->hasUniqueIndex() ) {
618                 echo "Already have unique user_name index.\n";
619         } else {
620                 if( !$duper->clearDupes() ) {
621                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
622                 }
623                 echo "Adding unique index on user_name... ";
624                 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
625                 echo "ok\n";
626         }
629 function do_user_groups_update() {
630         $fname = 'do_user_groups_update';
631         global $wgDatabase;
633         if( $wgDatabase->tableExists( 'user_groups' ) ) {
634                 echo "...user_groups table already exists.\n";
635                 return do_user_groups_reformat();
636         }
638         echo "Adding user_groups table... ";
639         dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
640         echo "ok\n";
642         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
643                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
644                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
645                         dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
646                         echo "ok\n";
647                 } else {
648                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
649                         echo "*** You may need to manually configure some sysops by manipulating\n";
650                         echo "*** the user_groups table.\n";
651                         return;
652                 }
653         }
655         echo "Converting user_rights table to user_groups... ";
656         $result = $wgDatabase->select( 'user_rights',
657                 array( 'ur_user', 'ur_rights' ),
658                 array( "ur_rights != ''" ),
659                 $fname );
661         while( $row = $wgDatabase->fetchObject( $result ) ) {
662                 $groups = array_unique(
663                         array_map( 'trim',
664                                 explode( ',', $row->ur_rights ) ) );
666                 foreach( $groups as $group ) {
667                         $wgDatabase->insert( 'user_groups',
668                                 array(
669                                         'ug_user'  => $row->ur_user,
670                                         'ug_group' => $group ),
671                                 $fname );
672                 }
673         }
674         $wgDatabase->freeResult( $result );
675         echo "ok\n";
678 function do_user_groups_reformat() {
679         # Check for bogus formats from previous 1.5 alpha code.
680         global $wgDatabase;
681         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
683         if( $info->type() == 'int' ) {
684                 $oldug = $wgDatabase->tableName( 'user_groups' );
685                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
686                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
687                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
688                 echo "ok\n";
690                 echo "Re-adding fresh user_groups table... ";
691                 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
692                 echo "ok\n";
694                 echo "***\n";
695                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
696                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
697                 echo "***\n";
698         } else {
699                 echo "...user_groups is in current format.\n";
700         }
704 function do_watchlist_null() {
705         # Make sure wl_notificationtimestamp can be NULL,
706         # and update old broken items.
707         global $wgDatabase;
708         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
710         if( !$info->nullable() ) {
711                 echo "Making wl_notificationtimestamp nullable... ";
712                 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
713                 echo "ok\n";
714         } else {
715                 echo "...wl_notificationtimestamp is already nullable.\n";
716         }
721  * @bug 3946
722  */
723 function do_page_random_update() {
724         global $wgDatabase;
726         echo "Setting page_random to a random value on rows where it equals 0...";
728         $page = $wgDatabase->tableName( 'page' );
729         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
730         $rows = $wgDatabase->affectedRows();
732         echo "changed $rows rows\n";
735 function do_templatelinks_update() {
736         global $wgDatabase, $wgLoadBalancer;
737         $fname = 'do_templatelinks_update';
739         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
740                 echo "...templatelinks table already exists\n";
741                 return;
742         }
743         echo "Creating templatelinks table...\n";
744         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
745         echo "Populating...\n";
746         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
747                 // Slow, replication-friendly update
748                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
749                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
750                 $count = 0;
751                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
752                         $count = ($count + 1) % 100;
753                         if ( $count == 0 ) {
754                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
755                                         wfWaitForSlaves( 10 );
756                                 } else {
757                                         sleep( 1 );
758                                 }
759                         }
760                         $wgDatabase->insert( 'templatelinks',
761                                 array(
762                                         'tl_from' => $row->pl_from,
763                                         'tl_namespace' => $row->pl_namespace,
764                                         'tl_title' => $row->pl_title,
765                                 ), $fname
766                         );
768                 }
769                 $wgDatabase->freeResult( $res );
770         } else {
771                 // Fast update
772                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
773                         array(
774                                 'tl_from' => 'pl_from',
775                                 'tl_namespace' => 'pl_namespace',
776                                 'tl_title' => 'pl_title'
777                         ), array(
778                                 'pl_namespace' => 10
779                         ), $fname
780                 );
781         }
782         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
785 # July 2006
786 # Add ( rc_namespace, rc_user_text ) index [R. Church]
787 function do_rc_indices_update() {
788         global $wgDatabase;
789         echo( "Checking for additional recent changes indices...\n" );
790         # See if we can find the index we want
791         $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_ns_usertext', __METHOD__ );
792         if( !$info ) {
793                 # None, so create
794                 echo( "...index on ( rc_namespace, rc_user_text ) not found; creating\n" );
795                 dbsource( archive( 'patch-recentchanges-utindex.sql' ) );
796         } else {
797                 # Index seems to exist
798                 echo( "...index on ( rc_namespace, rc_user_text ) seems to be ok\n" );
799         }
801         #Add (rc_user_text, rc_timestamp) index [A. Garrett], November 2006
802         # See if we can find the index we want
803         $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_user_text', __METHOD__ );
804         if( !$info ) {
805                 # None, so create
806                 echo( "...index on ( rc_user_text, rc_timestamp ) not found; creating\n" );
807                 dbsource( archive( 'patch-rc_user_text-index.sql' ) );
808         } else {
809                 # Index seems to exist
810                 echo( "...index on ( rc_user_text, rc_timestamp ) seems to be ok\n" );
811         }
814 function index_has_field($table, $index, $field) {
815         global $wgDatabase;
816         echo( "Checking if $table index $index includes field $field...\n" );
817         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
818         if( $info ) {
819                 foreach($info as $row) {
820                         if($row->Column_name == $field) {
821                                 echo( "...index $index on table $table seems to be ok\n" );
822                                 return true;
823                         }
824                 }
825         }
826         echo( "...index $index on table $table has no field $field; adding\n" );
827         return false;
830 function do_backlinking_indices_update() {
831         echo( "Checking for backlinking indices...\n" );
832         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
833                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
834                 !index_has_field('imagelinks', 'il_to', 'il_from'))
835         {       
836                 dbsource( archive( 'patch-backlinkindexes.sql' ) );
837         }
840 function do_categorylinks_indices_update() {
841         echo( "Checking for categorylinks indices...\n" );
842         if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
843         {       
844                 dbsource( archive( 'patch-categorylinksindex.sql' ) );
845         }
848 function do_stats_init() {
849         // Sometimes site_stats table is not properly populated.
850         global $wgDatabase;
851         echo "Checking site_stats row...";
852         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
853         if( $row === false ) {
854                 echo "data is missing! rebuilding...\n";
855                 
856                 global $IP;
857                 require_once "$IP/maintenance/initStats.inc";
858                 wfInitStats();
859         } else {
860                 echo "ok.\n";
861         }
864 function purge_cache() {
865         global $wgDatabase;
866         # We can't guarantee that the user will be able to use TRUNCATE,
867         # but we know that DELETE is available to us
868         echo( "Purging caches..." );
869         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
870         echo( "done.\n" );
873 function do_all_updates( $shared = false, $purge = true ) {
874         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
876         $doUser = !$wgSharedDB || $shared;
878         if ($wgDBtype === 'postgres') {
879                 do_postgres_updates();
880                 return;
881         }
883         # Rename tables
884         foreach ( $wgRenamedTables as $tableRecord ) {
885                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
886         }
888         # Add missing tables
889         foreach ( $wgNewTables as $tableRecord ) {
890                 add_table( $tableRecord[0], $tableRecord[1] );
891                 flush();
892         }
894         # Add missing fields
895         foreach ( $wgNewFields as $fieldRecord ) {
896                 if ( $fieldRecord[0] != 'user' || $doUser ) {
897                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
898                 }
899                 flush();
900         }
902         # Do schema updates which require special handling
903         do_interwiki_update(); flush();
904         do_index_update(); flush();
905         do_old_links_update(); flush();
906         do_image_name_unique_update(); flush();
907         do_watchlist_update(); flush();
908         if ( $doUser ) {
909                 do_user_update(); flush();
910         }
911 ######  do_copy_newtalk_to_watchlist(); flush();
912         do_logging_encoding(); flush();
914         do_schema_restructuring(); flush();
915         do_inverse_timestamp(); flush();
916         do_text_id(); flush();
917         do_namespace_size(); flush();
919         do_pagelinks_update(); flush();
920         do_templatelinks_update(); flush(); // after pagelinks
922         do_drop_img_type(); flush();
924         if ( $doUser ) {
925                 do_user_unique_update(); flush();
926         }
927         do_user_groups_update(); flush();
929         do_watchlist_null(); flush();
931         //do_image_index_update(); flush();
933         do_logging_timestamp_index(); flush();
935         do_page_random_update(); flush();
936         
937         do_rc_indices_update(); flush();
939         add_table( 'redirect', 'patch-redirect.sql' );
941         do_backlinking_indices_update(); flush();
943         do_categorylinks_indices_update(); flush();
945         do_restrictions_update(); flush ();
947         echo "Deleting old default messages (this may take a long time!)..."; flush();
948         deleteDefaultMessages();
949         echo "Done\n"; flush();
950         
951         do_stats_init(); flush();
952         
953         if( $purge ) {
954                 purge_cache();
955                 flush();
956         }
959 function archive($name) {
960         global $wgDBtype, $IP;
961         switch ($wgDBtype) {
962         case "postgres":
963                 return "$IP/maintenance/postgres/archives/$name";
964         default:
965                 return "$IP/maintenance/archives/$name";
966         }
969 function do_restrictions_update() {
970         # Adding page_restrictions table, obsoleting page.page_restrictions.
971         #  Migrating old restrictions to new table
972         # -- Andrew Garrett, January 2007.
974         global $wgDatabase;
976         $name = 'page_restrictions';
977         $patch = 'patch-page_restrictions.sql';
978         $patch2 = 'patch-page_restrictions_sortkey.sql';
980         if ( $wgDatabase->tableExists( $name ) ) {
981                 echo "...$name table already exists.\n";
982         } else {
983                 echo "Creating $name table...";
984                 dbsource( archive($patch), $wgDatabase );
985                 dbsource( archive($patch2), $wgDatabase );
986                 echo "ok\n";
988                 echo "Migrating old restrictions to new table...";
990                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
992                 $count = 0;
994                 while ($row = $wgDatabase->fetchObject($res) ) {
995                         $count = ($count + 1) % 100;
997                         if ($count == 0) {
998                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
999                                         wfWaitForSlaves( 10 );
1000                                 } else {
1001                                         sleep( 1 );
1002                                 }
1003                         }
1005                         # Figure out what the restrictions are..
1006                         $id = $row->page_id;
1007                         $flatrestrictions = explode( ':', $row->page_restrictions );
1009                         $restrictions = array ();
1010                         foreach( $flatrestrictions as $restriction ) {
1011                                 $thisrestriction = explode( '=', $restriction, 2 );
1012                                 if( count( $thisrestriction ) == 1 ) {
1013                                         // Compatibility with old protections from before
1014                                         // separate move protection was added.
1015                                         list( $level ) = $thisrestriction;
1016                                         if( $level ) {
1017                                                 $restrictions['edit'] = $level;
1018                                                 $restrictions['move'] = $level;
1019                                         }
1020                                 } else {
1021                                         list( $type, $level ) = $thisrestriction;
1022                                         if( $level ) {
1023                                                 $restrictions[$type] = $level;
1024                                         }
1025                                 }
1027                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1029                         }
1030                         
1031                         foreach( $restrictions as $type => $level ) {
1032                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1033                                                                                         'pr_type' => $type,
1034                                                                                         'pr_level' => $level,
1035                                                                                         'pr_cascade' => 0,
1036                                                                                         'pr_expiry' => 'infinity' ),
1037                                                                                         __METHOD__ );
1038                         }
1039                 }
1040                 print "ok\n";
1041         }
1042         
1045 function
1046 pg_describe_table($table)
1048 global  $wgDatabase, $wgDBmwschema;
1049         $q = <<<END
1050 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1051         WHERE pg_class.relnamespace = pg_namespace.oid 
1052           AND attrelid=pg_class.oid AND attnum > 0
1053           AND relname=%s AND nspname=%s
1054 END;
1055         $res = $wgDatabase->query(sprintf($q,
1056                         $wgDatabase->addQuotes($table),
1057                         $wgDatabase->addQuotes($wgDBmwschema)));
1058         if (!$res)
1059                 return null;
1061         $cols = array();
1062         while ($r = $wgDatabase->fetchRow($res)) {
1063                 $cols[] = array(        
1064                                 "name" => $r[0],
1065                                 "ord" => $r[1],
1066                         );
1067         }
1068         return $cols;
1071 function
1072 pg_describe_index($idx)
1074 global  $wgDatabase, $wgDBmwschema;
1076         // first fetch the key (which is a list of columns ords) and
1077         // the table the index applies to (an oid)
1078         $q = <<<END
1079 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1080         WHERE nspname=%s
1081           AND pg_class.relnamespace = pg_namespace.oid
1082           AND relname=%s
1083           AND indexrelid=pg_class.oid
1084 END;
1085         $res = $wgDatabase->query(sprintf($q,
1086                         $wgDatabase->addQuotes($wgDBmwschema),
1087                         $wgDatabase->addQuotes($idx)));
1088         if (!$res)
1089                 return null;
1090         if (!($r = $wgDatabase->fetchRow($res))) {
1091                 $wgDatabase->freeResult($res);
1092                 return null;
1093         }
1095         $indkey = $r[0];
1096         $relid = intval($r[1]);
1097         $indkeys = explode(" ", $indkey);
1098         $wgDatabase->freeResult($res);
1100         $colnames = array();
1101         foreach ($indkeys as $rid) {
1102                 $query = <<<END
1103 SELECT attname FROM pg_class, pg_attribute
1104         WHERE attrelid=$relid
1105           AND attnum=%d
1106           AND attrelid=pg_class.oid
1107 END;
1108                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1109                 if (!$r2)
1110                         return null;
1111                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1112                         $wgDatabase->freeResult($r2);
1113                         return null;
1114                 }
1115                 $colnames[] = $row2[0];
1116                 $wgDatabase->freeResult($r2);
1117         }
1119         return $colnames;
1122 function
1123 pg_index_exists($table, $index)
1125 global  $wgDatabase, $wgDBmwschema;
1126         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1127                         array(  "indexname" => $index,
1128                                 "tablename" => $table,
1129                                 "schemaname" => $wgDBmwschema));
1130         return $exists === $index;
1133 function
1134 pg_fkey_deltype($fkey)
1136 global  $wgDatabase, $wgDBmwschema;
1137         $q = <<<END
1138 SELECT confdeltype FROM pg_constraint, pg_namespace
1139         WHERE connamespace=pg_namespace.oid
1140           AND nspname=%s
1141           AND conname=%s;
1142 END;
1143         $r = $wgDatabase->query(sprintf($q,
1144                 $wgDatabase->addQuotes($wgDBmwschema),
1145                 $wgDatabase->addQuotes($fkey)));
1146         if (!($row = $wgDatabase->fetchRow($r)))
1147                 return null;
1148         return $row[0];
1151 function
1152 pg_rule_def($table, $rule)
1154 global  $wgDatabase, $wgDBmwschema;
1155         $q = <<<END
1156 SELECT definition FROM pg_rules
1157         WHERE schemaname = %s
1158           AND tablename = %s
1159           AND rulename = %s
1160 END;
1161         $r = $wgDatabase->query(sprintf($q,
1162                         $wgDatabase->addQuotes($wgDBmwschema),
1163                         $wgDatabase->addQuotes($table),
1164                         $wgDatabase->addQuotes($rule)));
1165         $row = $wgDatabase->fetchRow($r);
1166         if (!$row)
1167                 return null;
1168         $d = $row[0];
1169         $wgDatabase->freeResult($r);
1170         return $d;
1173 function do_postgres_updates() {
1174         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1176         $wgShowExceptionDetails = 1;
1178         # Just in case their LocalSettings.php does not have this:
1179         if ( !isset( $wgDBmwschema ))
1180                 $wgDBmwschema = 'mediawiki';
1182         # Verify that this user is configured correctly
1183         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1184         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_user WHERE usename = $safeuser";
1185         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1186         $conf = array();
1187         foreach( explode( '*', $config ) as $c ) {
1188                 list( $x,$y ) = explode( '=', $c );
1189                 $conf[$x] = $y;
1190         }
1191         $newpath = array();
1192         if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBmwschema ) === false ) {
1193                 print "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1194                 $newpath[$wgDBmwschema] = 1;
1195         }
1196         if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBts2schema ) === false ) {
1197                 print "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1198                 $newpath[$wgDBts2schema] = 1;
1199         }
1200         $searchpath = implode( ',', array_keys( $newpath ) );
1201         if( strlen( $searchpath ) ) {
1202                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $searchpath" );
1203         }
1204         $goodconf = array(
1205                 'client_min_messages' => 'error',
1206                 'DateStyle'           => 'ISO, YMD',
1207                 'TimeZone'            => 'GMT'
1208         );
1209         foreach( array_keys( $goodconf ) AS $key ) {
1210                 $value = $goodconf[$key];
1211                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1212                         print "Setting $key to '$value' for user \"$wgDBuser\"\n";
1213                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1214                 }
1215         }
1217         $newsequences = array(
1218                 "log_log_id_seq",
1219                 "pr_id_val",
1220         );
1222         $newtables = array(
1223                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1224                 array("mwuser",            "patch-mwuser.sql"),
1225                 array("pagecontent",       "patch-pagecontent.sql"),
1226                 array("querycachetwo",     "patch-querycachetwo.sql"),
1227                 array("page_restrictions", "patch-page_restrictions.sql"),
1228                 array("profiling",         "patch-profiling.sql"),
1229                 array("redirect",          "patch-redirect.sql"),
1230         );
1232         $newcols = array(
1233                 array("archive",       "ar_len",               "INTEGER"),
1234                 array("ipblocks",      "ipb_anon_only",        "CHAR NOT NULL DEFAULT '0'"),
1235                 array("ipblocks",      "ipb_block_email",      "CHAR NOT NULL DEFAULT '0'"),
1236                 array("ipblocks",      "ipb_create_account",   "CHAR NOT NULL DEFAULT '1'"),
1237                 array("ipblocks",      "ipb_deleted",          "INTEGER NOT NULL DEFAULT 0"),
1238                 array("ipblocks",      "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1239                 array("filearchive",   "fa_deleted",           "INTEGER NOT NULL DEFAULT 0"),
1240                 array("logging",       "log_deleted",          "INTEGER NOT NULL DEFAULT 0"),
1241                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1242                 array("logging",       "log_params",           "TEXT"),
1243                 array("mwuser",        "user_editcount",       "INTEGER"),
1244                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1245                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1246                 array("recentchanges", "rc_deleted",           "INTEGER NOT NULL DEFAULT 0"),
1247                 array("recentchanges", "rc_log_action",        "TEXT"),
1248         array("recentchanges", "rc_log_type",          "TEXT"),
1249         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1250                 array("recentchanges", "rc_new_len",           "INTEGER"),
1251                 array("recentchanges", "rc_old_len",           "INTEGER"),
1252                 array("recentchanges", "rc_params",            "TEXT"),
1253                 array("revision",      "rev_len",              "INTEGER"),
1254         );
1257         # table, column, desired type, USING clause if needed
1258         $typechanges = array(
1259                 array("image",        "img_size",        "int4",  ""),
1260                 array("image",        "img_width",       "int4",  ""),
1261                 array("image",        "img_height",      "int4",  ""),
1262                 array("ipblocks",     "ipb_address",     "text", "ipb_address::text"),
1263                 array("math",         "math_inputhash",  "bytea", "decode(math_inputhash,'escape')"),
1264                 array("math",         "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1265                 array("oldimage",     "oi_size",         "int4",  ""),
1266                 array("oldimage",     "oi_width",        "int4",  ""),
1267                 array("oldimage",     "oi_height",       "int4",  ""),
1268                 array("user_newtalk", "user_ip",         "text", "host(user_ip)"),
1269         );
1271         $newindexes = array(
1272                 array("revision", "rev_text_id_idx", "patch-rev_text_id_idx.sql")
1273         );
1275         $newrules = array(
1276         );
1278         foreach ($newsequences as $ns) {
1279                 if ($wgDatabase->sequenceExists($ns)) {
1280                         echo "... sequence $ns already exists\n";
1281                         continue;
1282                 }
1284                 echo "... create sequence $ns\n";
1285                 $wgDatabase->query("CREATE SEQUENCE $ns");
1286         }
1288         foreach ($newtables as $nt) {
1289                 if ($wgDatabase->tableExists($nt[0])) {
1290                         echo "... table $nt[0] already exists\n";
1291                         continue;
1292                 }
1294                 echo "... create table $nt[0]\n";
1295                 dbsource(archive($nt[1]));
1296         }
1298         ## Needed before newcols
1299         if ($wgDatabase->tableExists("archive2")) {
1300                 echo "... convert archive2 back to normal archive table\n";
1301                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1302                         echo "...   drop rule archive_insert\n";
1303                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1304                 }
1305                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1306                         echo "...   drop rule archive_delete\n";
1307                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1308                 }
1310                 dbsource(archive("patch-remove-archive2.sql"));
1311         } else
1312                 echo "... obsolete archive2 not present\n";
1314         foreach ($newcols as $nc) {
1315                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1316                 if (!is_null($fi)) {
1317                         echo "... column $nc[0].$nc[1] already exists\n";
1318                         continue;
1319                 }
1321                 echo "... add column $nc[0].$nc[1]\n";
1322                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1323         }
1325         foreach ($typechanges as $tc) {
1326                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1327                 if (is_null($fi)) {
1328                         echo "... error: expected column $tc[0].$tc[1] to exist\n";
1329                         exit(1);
1330                 }
1332                 if ($fi->type() === $tc[2])
1333                         echo "... $tc[0].$tc[1] is already $tc[2]\n";
1334                 else {
1335                         echo "... change $tc[0].$tc[1] from {$fi->type()} to $tc[2]\n";
1336                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1337                         if (strlen($tc[3])) {
1338                                 $sql .= " USING $tc[3]";
1339                         }
1340                         $sql .= ";\nCOMMIT;\n";
1341                         $wgDatabase->query($sql);
1342                 }
1343         }
1345         foreach ($newindexes as $ni) {
1346                 if (pg_index_exists($ni[0], $ni[1])) {
1347                         echo "... index $ni[1] on $ni[0] already exists\n";
1348                         continue;
1349                 }
1350                 dbsource(archive($ni[2]));
1351         }
1353         foreach ($newrules as $nr) {
1354                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1355                         echo "... rule $nr[1] on $nr[0] already exists\n";
1356                         continue;
1357                 }
1358                 dbsource(archive($nr[2]));
1359         }
1361         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1362                 echo "... create page_deleted trigger\n";
1363                 dbsource(archive('patch-page_deleted.sql'));
1364         }
1366         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1367         if (!$fi->nullable()) {
1368                 echo "... remove NOT NULL constraint on recentchanges.rc_cur_id\n";
1369                 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1370         }
1372         $pu = pg_describe_index("pagelink_unique");
1373         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1374                 echo "... dropping obsolete pagelink_unique index\n";
1375                 $wgDatabase->query("DROP INDEX pagelink_unique");
1376                 $pu = null;
1377         } else
1378                 echo "... obsolete pagelink_unique index not present\n";
1380         if (is_null($pu)) {
1381                 echo "... adding new pagelink_unique index\n";
1382                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1383         } else
1384                 echo "... already have current pagelink_unique index\n";
1386         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1387                 echo "... revision_rev_user_fkey is already ON DELETE RESTRICT\n";
1388         } else {
1389                 echo "... change revision_rev_user_fkey to ON DELETE RESTRICT\n";
1390                 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1391         }
1393         if (is_null($wgDatabase->fieldInfo("archive", "ar_deleted"))) {
1394                 echo "... add archive.ar_deleted\n";
1395                 dbsource(archive("patch-archive-ar_deleted.sql"));
1396         } else
1397                 echo "... archive.ar_deleted already exists\n";
1399         return;