* (bug 13130) Moved edit token and autosummary fields above edit tools to
[mediawiki.git] / maintenance / updaters.inc
blob86e87014d5589aa2a994c9d2108d91f303fce1f1
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';
16 # Extension updates
17 require_once( "$IP/includes/Hooks.php" );
19 $wgRenamedTables = array(
20 #           from             to                  patch file
21 #       array( 'group',         'groups',           'patch-rename-group.sql' ),
24 $wgNewTables = array(
25 #            table          patch file (in maintenance/archives)
26         array( 'hitcounter',       'patch-hitcounter.sql' ),
27         array( 'querycache',       'patch-querycache.sql' ),
28         array( 'objectcache',      'patch-objectcache.sql' ),
29         array( 'categorylinks',    'patch-categorylinks.sql' ),
30         array( 'logging',          'patch-logging.sql' ),
31         array( 'user_newtalk',     'patch-usernewtalk2.sql' ),
32         array( 'transcache',       'patch-transcache.sql' ),
33         array( 'trackbacks',       'patch-trackbacks.sql' ),
34         array( 'externallinks',    'patch-externallinks.sql' ),
35         array( 'job',              'patch-job.sql' ),
36         array( 'langlinks',        'patch-langlinks.sql' ),
37         array( 'querycache_info',  'patch-querycacheinfo.sql' ),
38         array( 'filearchive',      'patch-filearchive.sql' ),
39         array( 'querycachetwo',    'patch-querycachetwo.sql' ),
40         array( 'redirect',         'patch-redirect.sql' ),
41         array( 'protected_titles', 'patch-protected_titles.sql' ),
42         array( 'page_props',       'patch-page_props.sql' ),
45 $wgNewFields = array(
46 #           table            field             patch file (in maintenance/archives)
47         array( 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
48         array( 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
49         array( 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
50         array( 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
51         array( 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
52         array( 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
53         array( 'recentchanges', 'rc_old_len',       'patch-rc_len.sql' ),
54         array( 'user',          'user_real_name',   'patch-user-realname.sql' ),
55         array( 'user',          'user_token',       'patch-user_token.sql' ),
56         array( 'user',          'user_email_token', 'patch-user_email_token.sql' ),
57         array( 'user',          'user_registration','patch-user_registration.sql' ),
58         array( 'logging',       'log_params',       'patch-log_params.sql' ),
59         array( 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
60         array( 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
61         array( 'page',          'page_len',         'patch-page_len.sql' ),
62         array( 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
63         array( 'image',         'img_width',        'patch-img_width.sql' ),
64         array( 'image',         'img_metadata',     'patch-img_metadata.sql' ),
65         array( 'image',         'img_media_type',   'patch-img_media_type.sql' ),
66         array( 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
67         array( 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
68         array( 'ipblocks',      'ipb_range_start',  'patch-ipb_range_start.sql' ),
69         array( 'site_stats',    'ss_images',        'patch-ss_images.sql' ),
70         array( 'ipblocks',      'ipb_anon_only',    'patch-ipb_anon_only.sql' ),
71         array( 'ipblocks',              'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
72         array( 'user',          'user_newpass_time','patch-user_newpass_time.sql' ),
73         array( 'user',          'user_editcount',   'patch-user_editcount.sql' ),
74         array( 'recentchanges', 'rc_deleted',           'patch-rc_deleted.sql' ),
75         array( 'logging',               'log_id',                       'patch-log_id.sql' ),
76         array( 'logging',               'log_deleted',          'patch-log_deleted.sql' ),
77         array( 'archive',               'ar_deleted',           'patch-ar_deleted.sql' ),
78         array( 'ipblocks',              'ipb_deleted',          'patch-ipb_deleted.sql' ),
79         array( 'filearchive',   'fa_deleted',           'patch-fa_deleted.sql' ),
80         array( 'revision',          'rev_len',          'patch-rev_len.sql' ),
81         array( 'archive',           'ar_len',           'patch-ar_len.sql' ),
82         array( 'revision',          'rev_parent_id',    'patch-rev_parent_id.sql' ),
83         array( 'page_restrictions', 'pr_id',            'patch-page_restrictions_sortkey.sql' ),
84         array( 'ipblocks',      'ipb_block_email',  'patch-ipb_emailban.sql' ),
85         array( 'oldimage',      'oi_metadata',      'patch-oi_metadata.sql'),
86         array( 'archive',       'ar_page_id',       'patch-archive-page_id.sql'),
87         array( 'image',         'img_sha1',         'patch-img_sha1.sql' ),
88         array( 'ipblocks',      'ipb_by_text',      'patch-ipb_by_text.sql' ),
91 # For extensions only, should be populated via hooks
92 # $wgDBtype should be checked to specifiy the proper file
93 $wgExtNewTables = array(); // table, dir
94 $wgExtNewFields = array(); // table, column, dir
95 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
96 $wgExtNewIndexes = array(); // table, index, dir
98 function rename_table( $from, $to, $patch ) {
99         global $wgDatabase;
100         if ( $wgDatabase->tableExists( $from ) ) {
101                 if ( $wgDatabase->tableExists( $to ) ) {
102                         echo "...can't move table $from to $to, $to already exists.\n";
103                 } else {
104                         echo "Moving table $from to $to...";
105                         dbsource( archive($patch), $wgDatabase );
106                         echo "ok\n";
107                 }
108         } else {
109                 // Source table does not exist
110                 // Renames are done before creations, so this is typical for a new installation
111                 // Ignore silently
112         }
115 function add_table( $name, $patch, $fullpath=false ) {
116         global $wgDatabase;
117         if ( $wgDatabase->tableExists( $name ) ) {
118                 echo "...$name table already exists.\n";
119         } else {
120                 echo "Creating $name table...";
121                 if( $fullpath ) {
122                         dbsource( $patch, $wgDatabase );
123                 } else {
124                         dbsource( archive($patch), $wgDatabase );
125                 }
126                 echo "ok\n";
127         }
130 function add_field( $table, $field, $patch, $fullpath=false ) {
131         global $wgDatabase;
132         if ( !$wgDatabase->tableExists( $table ) ) {
133                 echo "...$table table does not exist, skipping new field patch\n";
134         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
135                 echo "...have $field field in $table table.\n";
136         } else {
137                 echo "Adding $field field to table $table...";
138                 if( $fullpath ) {
139                         dbsource( $patch, $wgDatabase );
140                 } else {
141                         dbsource( archive($patch), $wgDatabase );
142                 }
143                 echo "ok\n";
144         }
147 function add_index( $table, $index, $patch, $fullpath=false ) {
148         global $wgDatabase;
149         if( $wgDatabase->indexExists( $table, $index ) ) {
150                 echo "...$index key already set on $table table.\n";
151         } else {
152                 echo "Adding $index key to table $table... ";
153                 if( $fullpath ) {
154                         dbsource( $patch, $wgDatabase );
155                 } else {
156                         dbsource( archive($patch), $wgDatabase );
157                 }
158                 echo "ok\n";
159         }
162 function do_revision_updates() {
163         global $wgSoftwareRevision;
164         if ( $wgSoftwareRevision < 1001 ) {
165                 update_passwords();
166         }
169 function update_passwords() {
170         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
172         global $wgDatabase;
173         $fname = "Update script: update_passwords()";
174         print "\nIt appears that you need to update the user passwords in your\n" .
175           "database. If you have already done this (if you've run this update\n" .
176           "script once before, for example), doing so again will make all your\n" .
177           "user accounts inaccessible, so be sure you only do this once.\n" .
178           "Update user passwords? (yes/no)";
180         $resp = readconsole();
181     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
183         $sql = "SELECT user_id,user_password FROM user";
184         $source = $wgDatabase->query( $sql, $fname );
186         while ( $row = $wgDatabase->fetchObject( $source ) ) {
187                 $id = $row->user_id;
188                 $oldpass = $row->user_password;
189                 $newpass = md5( "{$id}-{$oldpass}" );
191                 $sql = "UPDATE user SET user_password='{$newpass}' " .
192                   "WHERE user_id={$id}";
193                 $wgDatabase->query( $sql, $fname );
194         }
197 function do_interwiki_update() {
198         # Check that interwiki table exists; if it doesn't source it
199         global $wgDatabase, $IP;
200         if( $wgDatabase->tableExists( "interwiki" ) ) {
201                 echo "...already have interwiki table\n";
202                 return true;
203         }
204         echo "Creating interwiki table: ";
205         dbsource( archive("patch-interwiki.sql") );
206         echo "ok\n";
207         echo "Adding default interwiki definitions: ";
208         dbsource( "$IP/maintenance/interwiki.sql" );
209         echo "ok\n";
212 function do_index_update() {
213         # Check that proper indexes are in place
214         global $wgDatabase;
215         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
216         if( !$meta->isMultipleKey() ) {
217                 echo "Updating indexes to 20031107: ";
218                 dbsource( archive("patch-indexes.sql") );
219                 echo "ok\n";
220                 return true;
221         }
222         echo "...indexes seem up to 20031107 standards\n";
223         return false;
226 function do_image_index_update() {
227         global $wgDatabase;
229         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
230         if( !$meta->isMultipleKey() ) {
231                 echo "Updating indexes to 20050912: ";
232                 dbsource( archive("patch-mimesearch-indexes.sql") );
233                 echo "ok\n";
234                 return true;
235         }
236         echo "...indexes seem up to 20050912 standards\n";
237         return false;
240 function do_image_name_unique_update() {
241         global $wgDatabase;
242         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
243                 echo "...image primary key already set.\n";
244         } else {
245                 echo "Making img_name the primary key... ";
246                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
247                 echo "ok\n";
248         }
251 function do_logging_timestamp_index() {
252         global $wgDatabase;
253         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
254                 echo "...timestamp key on logging already exists.\n";
255         } else {
256                 echo "Adding timestamp key on logging table... ";
257                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
258                 echo "ok\n";
259         }
262 function do_archive_user_index() {
263         global $wgDatabase;
264         if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
265                 echo "...usertext,timestamp key on archive already exists.\n";
266         } else {
267                 echo "Adding usertext,timestamp key on archive table... ";
268                 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
269                 echo "ok\n";
270         }
273 function do_image_user_index() {
274         global $wgDatabase;
275         if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
276                 echo "...usertext,timestamp key on image already exists.\n";
277         } else {
278                 echo "Adding usertext,timestamp key on image table... ";
279                 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
280                 echo "ok\n";
281         }
284 function do_oldimage_user_index() {
285         global $wgDatabase;
286         if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
287                 echo "...usertext,timestamp key on oldimage already exists.\n";
288         } else {
289                 echo "Adding usertext,timestamp key on oldimage table... ";
290                 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
291                 echo "ok\n";
292         }
295 function do_watchlist_update() {
296         global $wgDatabase;
297         $fname = 'do_watchlist_update';
298         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
299                 echo "The watchlist table is already set up for email notification.\n";
300         } else {
301                 echo "Adding wl_notificationtimestamp field for email notification management.";
302                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
303                 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
304                 echo "ok\n";
305         }
306         # Check if we need to add talk page rows to the watchlist
307         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
308         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
309         if ( $talk != $nontalk ) {
310                 echo "Adding missing watchlist talk page rows... ";
311                 flush();
313                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
314                         array(
315                                 'wl_user' => 'wl_user',
316                                 'wl_namespace' => 'wl_namespace | 1',
317                                 'wl_title' => 'wl_title',
318                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
319                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
320                 echo "ok\n";
321         } else {
322                 echo "...watchlist talk page rows already present\n";
323         }
326 function do_copy_newtalk_to_watchlist() {
327         global $wgDatabase;
328         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
330         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
331                 $wgDatabase->tableName( 'user_newtalk' ) );
332         $num_newtalks=$wgDatabase->numRows($res);
333         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
335         $user = new User();
336         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
337                 $wluser = $wgDatabase->fetchObject( $res );
338                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
339                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
340                                 $wgDatabase->replace( 'watchlist',
341                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
342                                           array('wl_user'                       => 0,
343                                                 'wl_namespace'                  => NS_USER_TALK,
344                                                 'wl_title'                      => $wluser->user_ip,
345                                                 'wl_notificationtimestamp'      => '19700101000000'
346                                                 ), 'updaters.inc::do_watchlist_update2'
347                                         );
348                         }
349                 } else { # normal users ... have user_ids
350                         $user->setID($wluser->user_id);
351                         $wgDatabase->replace( 'watchlist',
352                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
353                                   array('wl_user'                       => $user->getID(),
354                                         'wl_namespace'                  => NS_USER_TALK,
355                                         'wl_title'                      => $user->getName(),
356                                         'wl_notificationtimestamp'      => '19700101000000'
357                                         ), 'updaters.inc::do_watchlist_update3'
358                                 );
359                 }
360         }
361         echo "Done.\n";
365 function do_user_update() {
366         global $wgDatabase;
367         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
368                 echo "User table contains old email authentication field. Dropping... ";
369                 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
370                 echo "ok\n";
371         } else {
372                 echo "...user table does not contain old email authentication field.\n";
373         }
377  * 1.4 betas were missing the 'binary' marker from logging.log_title,
378  * which causes a collation mismatch error on joins in MySQL 4.1.
379  */
380 function do_logging_encoding() {
381         global $wgDatabase, $wgDBtype;
382         if ($wgDBtype != 'mysql')
383                 return;
384         $logging = $wgDatabase->tableName( 'logging' );
385         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
386         $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
387         $wgDatabase->freeResult( $res );
389         if( in_array( 'binary', $flags ) ) {
390                 echo "Logging table has correct title encoding.\n";
391         } else {
392                 echo "Fixing title encoding on logging table... ";
393                 dbsource( archive( 'patch-logging-title.sql' ), $wgDatabase );
394                 echo "ok\n";
395         }
398 function do_schema_restructuring() {
399         global $wgDatabase;
400         $fname="do_schema_restructuring";
401         if ( $wgDatabase->tableExists( 'page' ) ) {
402                 echo "...page table already exists.\n";
403         } else {
404                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
405                 echo wfTimestamp( TS_DB );
406                 echo "......checking for duplicate entries.\n"; flush();
408                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
410                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
411                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
413                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
414                         echo wfTimestamp( TS_DB );
415                         echo "......<b>Found duplicate entries</b>\n";
416                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
417                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
418                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
419                                         $duplicate[$row->cur_namespace] = array();
420                                 }
421                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
422                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
423                         }
424                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
425                         $firstCond = true;
426                         foreach ( $duplicate as $ns => $titles ) {
427                                 if ( $firstCond ) {
428                                         $firstCond = false;
429                                 } else {
430                                         $sql .= ' OR ';
431                                 }
432                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
433                                 $first = true;
434                                 foreach ( $titles as $t ) {
435                                         if ( $first ) {
436                                                 $sql .= $wgDatabase->addQuotes( $t );
437                                                 $first = false;
438                                         } else {
439                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
440                                         }
441                                 }
442                                 $sql .= ") ) \n";
443                         }
444                         # By sorting descending, the most recent entry will be the first in the list.
445                         # All following entries will be deleted by the next while-loop.
446                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
448                         $rows = $wgDatabase->query( $sql, $fname );
450                         $prev_title = $prev_namespace = false;
451                         $deleteId = array();
453                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
454                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
455                                         $deleteId[] = $row->cur_id;
456                                 }
457                                 $prev_title     = $row->cur_title;
458                                 $prev_namespace = $row->cur_namespace;
459                         }
460                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
461                         $rows = $wgDatabase->query( $sql, $fname );
462                         echo wfTimestamp( TS_DB );
463                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
464                 }
467                 echo wfTimestamp( TS_DB );
468                 echo "......Creating tables.\n";
469                 $wgDatabase->query("CREATE TABLE $page (
470                         page_id int(8) unsigned NOT NULL auto_increment,
471                         page_namespace int NOT NULL,
472                         page_title varchar(255) binary NOT NULL,
473                         page_restrictions tinyblob NOT NULL,
474                         page_counter bigint(20) unsigned NOT NULL default '0',
475                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
476                         page_is_new tinyint(1) unsigned NOT NULL default '0',
477                         page_random real unsigned NOT NULL,
478                         page_touched char(14) binary NOT NULL default '',
479                         page_latest int(8) unsigned NOT NULL,
480                         page_len int(8) unsigned NOT NULL,
482                         PRIMARY KEY page_id (page_id),
483                         UNIQUE INDEX name_title (page_namespace,page_title),
484                         INDEX (page_random),
485                         INDEX (page_len)
486                         ) TYPE=InnoDB", $fname );
487                 $wgDatabase->query("CREATE TABLE $revision (
488                         rev_id int(8) unsigned NOT NULL auto_increment,
489                         rev_page int(8) unsigned NOT NULL,
490                         rev_comment tinyblob NOT NULL,
491                         rev_user int(5) unsigned NOT NULL default '0',
492                         rev_user_text varchar(255) binary NOT NULL default '',
493                         rev_timestamp char(14) binary NOT NULL default '',
494                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
495                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
496                         rev_len int(8) unsigned,
497                         rev_parent_id int(8) unsigned default NULL,
498                         PRIMARY KEY rev_page_id (rev_page, rev_id),
499                         UNIQUE INDEX rev_id (rev_id),
500                         INDEX rev_timestamp (rev_timestamp),
501                         INDEX page_timestamp (rev_page,rev_timestamp),
502                         INDEX user_timestamp (rev_user,rev_timestamp),
503                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
504                         ) TYPE=InnoDB", $fname );
506                 echo wfTimestamp( TS_DB );
507                 echo "......Locking tables.\n";
508                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
510                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
511                 echo wfTimestamp( TS_DB );
512                 echo "......maxold is {$maxold}\n";
514                 echo wfTimestamp( TS_DB );
515                 global $wgLegacySchemaConversion;
516                 if( $wgLegacySchemaConversion ) {
517                         // Create HistoryBlobCurStub entries.
518                         // Text will be pulled from the leftover 'cur' table at runtime.
519                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
520                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
521                         $cur_flags = "'object'";
522                 } else {
523                         // Copy all cur text in immediately: this may take longer but avoids
524                         // having to keep an extra table around.
525                         echo "......Moving text from cur.\n";
526                         $cur_text = 'cur_text';
527                         $cur_flags = "''";
528                 }
529                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
530                                 old_timestamp, old_minor_edit, old_flags)
531                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
532                         FROM $cur", $fname );
534                 echo wfTimestamp( TS_DB );
535                 echo "......Setting up revision table.\n";
536                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
537                                 rev_minor_edit)
538                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
539                                 old_timestamp, old_minor_edit
540                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
542                 echo wfTimestamp( TS_DB );
543                 echo "......Setting up page table.\n";
544                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
545                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
546                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
547                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
548                         FROM $cur,$revision
549                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
551                 echo wfTimestamp( TS_DB );
552                 echo "......Unlocking tables.\n";
553                 $wgDatabase->query( "UNLOCK TABLES", $fname );
555                 echo wfTimestamp( TS_DB );
556                 echo "......Renaming old.\n";
557                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
559                 echo wfTimestamp( TS_DB );
560                 echo "...done.\n";
561         }
564 function do_inverse_timestamp() {
565         global $wgDatabase;
566         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
567                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
568                 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
569                 echo "ok\n";
570         } else {
571                 echo "revision timestamp indexes already up to 2005-03-13\n";
572         }
575 function do_text_id() {
576         global $wgDatabase;
577         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
578                 echo "...rev_text_id already in place.\n";
579         } else {
580                 echo "Adding rev_text_id field... ";
581                 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
582                 echo "ok\n";
583         }
586 function do_namespace_size() {
587         $tables = array(
588                 'page'          => 'page',
589                 'archive'       => 'ar',
590                 'recentchanges' => 'rc',
591                 'watchlist'     => 'wl',
592                 'querycache'    => 'qc',
593                 'logging'       => 'log',
594         );
595         foreach( $tables as $table => $prefix ) {
596                 do_namespace_size_on( $table, $prefix );
597                 flush();
598         }
601 function do_namespace_size_on( $table, $prefix ) {
602         global $wgDatabase, $wgDBtype;
603         if ($wgDBtype != 'mysql')
604                 return;
605         $field = $prefix . '_namespace';
607         $tablename = $wgDatabase->tableName( $table );
608         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
609         $info = $wgDatabase->fetchObject( $result );
610         $wgDatabase->freeResult( $result );
612         if( substr( $info->Type, 0, 3 ) == 'int' ) {
613                 echo "...$field is already a full int ($info->Type).\n";
614         } else {
615                 echo "Promoting $field from $info->Type to int... ";
617                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
618                 $wgDatabase->query( $sql );
620                 echo "ok\n";
621         }
624 function do_pagelinks_update() {
625         global $wgDatabase;
626         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
627                 echo "...already have pagelinks table.\n";
628         } else {
629                 echo "Converting links and brokenlinks tables to pagelinks... ";
630                 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
631                 echo "ok\n";
632                 flush();
634                 global $wgCanonicalNamespaceNames;
635                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
636                         if( $ns != 0 ) {
637                                 do_pagelinks_namespace( $ns );
638                         }
639                 }
640         }
643 function do_pagelinks_namespace( $namespace ) {
644         global $wgDatabase, $wgContLang;
646         $ns = intval( $namespace );
647         echo "Cleaning up broken links for namespace $ns... ";
649         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
650         $name = $wgContLang->getNsText( $ns );
651         $prefix = $wgDatabase->strencode( $name );
652         $likeprefix = str_replace( '_', '\\_', $prefix);
654         $sql = "UPDATE $pagelinks
655                    SET pl_namespace=$ns,
656                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
657                  WHERE pl_namespace=0
658                    AND pl_title LIKE '$likeprefix:%'";
660         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
661         echo "ok\n";
664 function do_drop_img_type() {
665         global $wgDatabase;
667         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
668                 echo "Dropping unused img_type field in image table... ";
669                 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
670                 echo "ok\n";
671         } else {
672                 echo "No img_type field in image table; Good.\n";
673         }
676 function do_old_links_update() {
677         global $wgDatabase;
678         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
679                 echo "Already have pagelinks; skipping old links table updates.\n";
680         } else {
681                 convertLinks(); flush();
682         }
685 function do_user_unique_update() {
686         global $wgDatabase;
687         $duper = new UserDupes( $wgDatabase );
688         if( $duper->hasUniqueIndex() ) {
689                 echo "Already have unique user_name index.\n";
690         } else {
691                 if( !$duper->clearDupes() ) {
692                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
693                 }
694                 echo "Adding unique index on user_name... ";
695                 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
696                 echo "ok\n";
697         }
700 function do_user_groups_update() {
701         $fname = 'do_user_groups_update';
702         global $wgDatabase;
704         if( $wgDatabase->tableExists( 'user_groups' ) ) {
705                 echo "...user_groups table already exists.\n";
706                 return do_user_groups_reformat();
707         }
709         echo "Adding user_groups table... ";
710         dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
711         echo "ok\n";
713         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
714                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
715                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
716                         dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
717                         echo "ok\n";
718                 } else {
719                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
720                         echo "*** You may need to manually configure some sysops by manipulating\n";
721                         echo "*** the user_groups table.\n";
722                         return;
723                 }
724         }
726         echo "Converting user_rights table to user_groups... ";
727         $result = $wgDatabase->select( 'user_rights',
728                 array( 'ur_user', 'ur_rights' ),
729                 array( "ur_rights != ''" ),
730                 $fname );
732         while( $row = $wgDatabase->fetchObject( $result ) ) {
733                 $groups = array_unique(
734                         array_map( 'trim',
735                                 explode( ',', $row->ur_rights ) ) );
737                 foreach( $groups as $group ) {
738                         $wgDatabase->insert( 'user_groups',
739                                 array(
740                                         'ug_user'  => $row->ur_user,
741                                         'ug_group' => $group ),
742                                 $fname );
743                 }
744         }
745         $wgDatabase->freeResult( $result );
746         echo "ok\n";
749 function do_user_groups_reformat() {
750         # Check for bogus formats from previous 1.5 alpha code.
751         global $wgDatabase;
752         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
754         if( $info->type() == 'int' ) {
755                 $oldug = $wgDatabase->tableName( 'user_groups' );
756                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
757                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
758                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
759                 echo "ok\n";
761                 echo "Re-adding fresh user_groups table... ";
762                 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
763                 echo "ok\n";
765                 echo "***\n";
766                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
767                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
768                 echo "***\n";
769         } else {
770                 echo "...user_groups is in current format.\n";
771         }
775 function do_watchlist_null() {
776         # Make sure wl_notificationtimestamp can be NULL,
777         # and update old broken items.
778         global $wgDatabase;
779         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
781         if( !$info->nullable() ) {
782                 echo "Making wl_notificationtimestamp nullable... ";
783                 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
784                 echo "ok\n";
785         } else {
786                 echo "...wl_notificationtimestamp is already nullable.\n";
787         }
792  * @bug 3946
793  */
794 function do_page_random_update() {
795         global $wgDatabase;
797         echo "Setting page_random to a random value on rows where it equals 0...";
799         $page = $wgDatabase->tableName( 'page' );
800         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
801         $rows = $wgDatabase->affectedRows();
803         echo "changed $rows rows\n";
806 function do_templatelinks_update() {
807         global $wgDatabase, $wgLoadBalancer;
808         $fname = 'do_templatelinks_update';
810         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
811                 echo "...templatelinks table already exists\n";
812                 return;
813         }
814         echo "Creating templatelinks table...\n";
815         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
816         echo "Populating...\n";
817         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
818                 // Slow, replication-friendly update
819                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
820                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
821                 $count = 0;
822                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
823                         $count = ($count + 1) % 100;
824                         if ( $count == 0 ) {
825                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
826                                         wfWaitForSlaves( 10 );
827                                 } else {
828                                         sleep( 1 );
829                                 }
830                         }
831                         $wgDatabase->insert( 'templatelinks',
832                                 array(
833                                         'tl_from' => $row->pl_from,
834                                         'tl_namespace' => $row->pl_namespace,
835                                         'tl_title' => $row->pl_title,
836                                 ), $fname
837                         );
839                 }
840                 $wgDatabase->freeResult( $res );
841         } else {
842                 // Fast update
843                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
844                         array(
845                                 'tl_from' => 'pl_from',
846                                 'tl_namespace' => 'pl_namespace',
847                                 'tl_title' => 'pl_title'
848                         ), array(
849                                 'pl_namespace' => 10
850                         ), $fname
851                 );
852         }
853         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
856 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
857 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
858 function do_rc_indices_update() {
859         global $wgDatabase;
860         echo( "Checking for additional recent changes indices...\n" );
862         $indexes = array(
863                 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
864                 'rc_user_text' => 'patch-rc_user_text-index.sql',
865         );
866         
867         foreach( $indexes as $index => $patch ) {
868                 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
869                 if( !$info ) {
870                         echo( "...index `{$index}` not found; adding..." );
871                         dbsource( archive( $patch ) );
872                         echo( "done.\n" );
873                 } else {
874                         echo( "...index `{$index}` seems ok.\n" );
875                 }
876         }
879 function index_has_field($table, $index, $field) {
880         global $wgDatabase;
881         echo( "Checking if $table index $index includes field $field...\n" );
882         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
883         if( $info ) {
884                 foreach($info as $row) {
885                         if($row->Column_name == $field) {
886                                 echo( "...index $index on table $table seems to be ok\n" );
887                                 return true;
888                         }
889                 }
890         }
891         echo( "...index $index on table $table has no field $field; adding\n" );
892         return false;
895 function do_backlinking_indices_update() {
896         echo( "Checking for backlinking indices...\n" );
897         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
898                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
899                 !index_has_field('imagelinks', 'il_to', 'il_from'))
900         {       
901                 dbsource( archive( 'patch-backlinkindexes.sql' ) );
902         }
905 function do_categorylinks_indices_update() {
906         echo( "Checking for categorylinks indices...\n" );
907         if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
908         {       
909                 dbsource( archive( 'patch-categorylinksindex.sql' ) );
910         }
913 function do_stats_init() {
914         // Sometimes site_stats table is not properly populated.
915         global $wgDatabase;
916         echo "Checking site_stats row...";
917         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
918         if( $row === false ) {
919                 echo "data is missing! rebuilding...\n";
920                 
921                 global $IP;
922                 require_once "$IP/maintenance/initStats.inc";
923                 wfInitStats();
924         } else {
925                 echo "ok.\n";
926         }
929 function purge_cache() {
930         global $wgDatabase;
931         # We can't guarantee that the user will be able to use TRUNCATE,
932         # but we know that DELETE is available to us
933         echo( "Purging caches..." );
934         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
935         echo( "done.\n" );
938 function do_all_updates( $shared = false, $purge = true ) {
939         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
941         wfRunHooks('LoadExtensionSchemaUpdates');
943         $doUser = !$wgSharedDB || $shared;
945         if ($wgDBtype === 'postgres') {
946                 do_postgres_updates();
947                 return;
948         }
950         # Rename tables
951         foreach ( $wgRenamedTables as $tableRecord ) {
952                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
953         }
955         # Add missing tables
956         foreach ( $wgNewTables as $tableRecord ) {
957                 add_table( $tableRecord[0], $tableRecord[1] );
958                 flush();
959         }
961         # Add missing fields
962         foreach ( $wgNewFields as $fieldRecord ) {
963                 if ( $fieldRecord[0] != 'user' || $doUser ) {
964                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
965                 }
966                 flush();
967         }
968         
969         global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
970         # Add missing extension tables
971         foreach ( $wgExtNewTables as $tableRecord ) {
972                 add_table( $tableRecord[0], $tableRecord[1], true );
973                 flush();
974         }
975         # Add missing extension fields
976         foreach ( $wgExtNewFields as $fieldRecord ) {
977                 if ( $fieldRecord[0] != 'user' || $doUser ) {
978                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
979                 }
980                 flush();
981         }
982         # Add missing extension indexes
983         foreach ( $wgExtNewIndexes as $fieldRecord ) {
984                 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
985                 flush();
986         }
988         # Do schema updates which require special handling
989         do_interwiki_update(); flush();
990         do_index_update(); flush();
991         do_old_links_update(); flush();
992         do_image_name_unique_update(); flush();
993         do_watchlist_update(); flush();
994         if ( $doUser ) {
995                 do_user_update(); flush();
996         }
997 ######  do_copy_newtalk_to_watchlist(); flush();
998         do_logging_encoding(); flush();
1000         do_schema_restructuring(); flush();
1001         do_inverse_timestamp(); flush();
1002         do_text_id(); flush();
1003         do_namespace_size(); flush();
1005         do_pagelinks_update(); flush();
1006         do_templatelinks_update(); flush(); // after pagelinks
1008         do_drop_img_type(); flush();
1010         if ( $doUser ) {
1011                 do_user_unique_update(); flush();
1012         }
1013         do_user_groups_update(); flush();
1015         do_watchlist_null(); flush();
1017         //do_image_index_update(); flush();
1019         do_logging_timestamp_index(); flush();
1021         do_page_random_update(); flush();
1022         
1023         do_rc_indices_update(); flush();
1025         do_backlinking_indices_update(); flush();
1027         do_categorylinks_indices_update(); flush();
1029         do_restrictions_update(); flush ();
1030         
1031         do_archive_user_index(); flush ();
1032         
1033         do_image_user_index(); flush ();
1034         
1035         do_oldimage_user_index(); flush ();
1037         echo "Deleting old default messages (this may take a long time!)..."; flush();
1038         deleteDefaultMessages();
1039         echo "Done\n"; flush();
1040         
1041         do_stats_init(); flush();
1042         
1043         if( $purge ) {
1044                 purge_cache();
1045                 flush();
1046         }
1049 function archive($name) {
1050         global $wgDBtype, $IP;
1051         switch ($wgDBtype) {
1052         case "postgres":
1053                 return "$IP/maintenance/postgres/archives/$name";
1054         default:
1055                 return "$IP/maintenance/archives/$name";
1056         }
1059 function do_restrictions_update() {
1060         # Adding page_restrictions table, obsoleting page.page_restrictions.
1061         #  Migrating old restrictions to new table
1062         # -- Andrew Garrett, January 2007.
1064         global $wgDatabase;
1066         $name = 'page_restrictions';
1067         $patch = 'patch-page_restrictions.sql';
1068         $patch2 = 'patch-page_restrictions_sortkey.sql';
1070         if ( $wgDatabase->tableExists( $name ) ) {
1071                 echo "...$name table already exists.\n";
1072         } else {
1073                 echo "Creating $name table...";
1074                 dbsource( archive($patch), $wgDatabase );
1075                 dbsource( archive($patch2), $wgDatabase );
1076                 echo "ok\n";
1078                 echo "Migrating old restrictions to new table...";
1080                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1082                 $count = 0;
1084                 while ($row = $wgDatabase->fetchObject($res) ) {
1085                         $count = ($count + 1) % 100;
1087                         if ($count == 0) {
1088                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
1089                                         wfWaitForSlaves( 10 );
1090                                 } else {
1091                                         sleep( 1 );
1092                                 }
1093                         }
1095                         # Figure out what the restrictions are..
1096                         $id = $row->page_id;
1097                         $flatrestrictions = explode( ':', $row->page_restrictions );
1099                         $restrictions = array ();
1100                         foreach( $flatrestrictions as $restriction ) {
1101                                 $thisrestriction = explode( '=', $restriction, 2 );
1102                                 if( count( $thisrestriction ) == 1 ) {
1103                                         // Compatibility with old protections from before
1104                                         // separate move protection was added.
1105                                         list( $level ) = $thisrestriction;
1106                                         if( $level ) {
1107                                                 $restrictions['edit'] = $level;
1108                                                 $restrictions['move'] = $level;
1109                                         }
1110                                 } else {
1111                                         list( $type, $level ) = $thisrestriction;
1112                                         if( $level ) {
1113                                                 $restrictions[$type] = $level;
1114                                         }
1115                                 }
1117                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1119                         }
1120                         
1121                         foreach( $restrictions as $type => $level ) {
1122                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1123                                                                                         'pr_type' => $type,
1124                                                                                         'pr_level' => $level,
1125                                                                                         'pr_cascade' => 0,
1126                                                                                         'pr_expiry' => 'infinity' ),
1127                                                                                         __METHOD__ );
1128                         }
1129                 }
1130                 print "ok\n";
1131         }
1132         
1135 function
1136 pg_describe_table($table)
1138 global  $wgDatabase, $wgDBmwschema;
1139         $q = <<<END
1140 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1141         WHERE pg_class.relnamespace = pg_namespace.oid 
1142           AND attrelid=pg_class.oid AND attnum > 0
1143           AND relname=%s AND nspname=%s
1144 END;
1145         $res = $wgDatabase->query(sprintf($q,
1146                         $wgDatabase->addQuotes($table),
1147                         $wgDatabase->addQuotes($wgDBmwschema)));
1148         if (!$res)
1149                 return null;
1151         $cols = array();
1152         while ($r = $wgDatabase->fetchRow($res)) {
1153                 $cols[] = array(        
1154                                 "name" => $r[0],
1155                                 "ord" => $r[1],
1156                         );
1157         }
1158         return $cols;
1161 function
1162 pg_describe_index($idx)
1164 global  $wgDatabase, $wgDBmwschema;
1166         // first fetch the key (which is a list of columns ords) and
1167         // the table the index applies to (an oid)
1168         $q = <<<END
1169 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1170         WHERE nspname=%s
1171           AND pg_class.relnamespace = pg_namespace.oid
1172           AND relname=%s
1173           AND indexrelid=pg_class.oid
1174 END;
1175         $res = $wgDatabase->query(sprintf($q,
1176                         $wgDatabase->addQuotes($wgDBmwschema),
1177                         $wgDatabase->addQuotes($idx)));
1178         if (!$res)
1179                 return null;
1180         if (!($r = $wgDatabase->fetchRow($res))) {
1181                 $wgDatabase->freeResult($res);
1182                 return null;
1183         }
1185         $indkey = $r[0];
1186         $relid = intval($r[1]);
1187         $indkeys = explode(" ", $indkey);
1188         $wgDatabase->freeResult($res);
1190         $colnames = array();
1191         foreach ($indkeys as $rid) {
1192                 $query = <<<END
1193 SELECT attname FROM pg_class, pg_attribute
1194         WHERE attrelid=$relid
1195           AND attnum=%d
1196           AND attrelid=pg_class.oid
1197 END;
1198                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1199                 if (!$r2)
1200                         return null;
1201                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1202                         $wgDatabase->freeResult($r2);
1203                         return null;
1204                 }
1205                 $colnames[] = $row2[0];
1206                 $wgDatabase->freeResult($r2);
1207         }
1209         return $colnames;
1212 function
1213 pg_index_exists($table, $index)
1215 global  $wgDatabase, $wgDBmwschema;
1216         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1217                         array(  "indexname" => $index,
1218                                 "tablename" => $table,
1219                                 "schemaname" => $wgDBmwschema));
1220         return $exists === $index;
1223 function
1224 pg_fkey_deltype($fkey)
1226 global  $wgDatabase, $wgDBmwschema;
1227         $q = <<<END
1228 SELECT confdeltype FROM pg_constraint, pg_namespace
1229         WHERE connamespace=pg_namespace.oid
1230           AND nspname=%s
1231           AND conname=%s;
1232 END;
1233         $r = $wgDatabase->query(sprintf($q,
1234                 $wgDatabase->addQuotes($wgDBmwschema),
1235                 $wgDatabase->addQuotes($fkey)));
1236         if (!($row = $wgDatabase->fetchRow($r)))
1237                 return null;
1238         return $row[0];
1241 function
1242 pg_rule_def($table, $rule)
1244 global  $wgDatabase, $wgDBmwschema;
1245         $q = <<<END
1246 SELECT definition FROM pg_rules
1247         WHERE schemaname = %s
1248           AND tablename = %s
1249           AND rulename = %s
1250 END;
1251         $r = $wgDatabase->query(sprintf($q,
1252                         $wgDatabase->addQuotes($wgDBmwschema),
1253                         $wgDatabase->addQuotes($table),
1254                         $wgDatabase->addQuotes($rule)));
1255         $row = $wgDatabase->fetchRow($r);
1256         if (!$row)
1257                 return null;
1258         $d = $row[0];
1259         $wgDatabase->freeResult($r);
1260         return $d;
1263 function do_postgres_updates() {
1264         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1266         ## Gather version numbers in case we need them
1267         $version = $wgDatabase->getServerVersion(); ## long string
1268         $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1270         $wgShowExceptionDetails = 1;
1272         # Just in case their LocalSettings.php does not have this:
1273         if ( !isset( $wgDBmwschema ))
1274                 $wgDBmwschema = 'mediawiki';
1276         # Verify that this user is configured correctly
1277         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1278         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1279         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1280         $conf = array();
1281         foreach( explode( '*', $config ) as $c ) {
1282                 list( $x,$y ) = explode( '=', $c );
1283                 $conf[$x] = $y;
1284         }
1285         $newpath = array();
1286         if( $wgDBmwschema === 'mediawiki' ) {
1287                 if (!array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBmwschema ) === false ) {
1288                         echo "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1289                         $newpath[$wgDBmwschema] = 1;
1290                 }
1291         }
1292         if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBts2schema ) === false ) {
1293                 echo "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1294                 $newpath[$wgDBts2schema] = 1;
1295         }
1296         $searchpath = implode( ',', array_keys( $newpath ) );
1297         if( strlen( $searchpath ) ) {
1298                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $searchpath" );
1299                 $wgDatabase->doQuery( "SET search_path = $searchpath" );
1300         }
1301         else {
1302                 $path = $conf['search_path'];
1303                 echo "... search_path for user \"$wgDBuser\" looks correct ($path)\n";
1304         }
1305         $goodconf = array(
1306                 'client_min_messages' => 'error',
1307                 'DateStyle'           => 'ISO, YMD',
1308                 'TimeZone'            => 'GMT'
1309         );
1310         foreach( array_keys( $goodconf ) AS $key ) {
1311                 $value = $goodconf[$key];
1312                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1313                         echo "Setting $key to '$value' for user \"$wgDBuser\"\n";
1314                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1315                         $wgDatabase->doQuery( "SET $key = '$value'" );
1316                 }
1317                 else {
1318                         echo "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n";
1319                 }
1320         }
1322         $newsequences = array(
1323                 "log_log_id_seq",
1324                 "pr_id_val",
1325         );
1327         $newtables = array(
1328                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1329                 array("mwuser",            "patch-mwuser.sql"),
1330                 array("pagecontent",       "patch-pagecontent.sql"),
1331                 array("querycachetwo",     "patch-querycachetwo.sql"),
1332                 array("page_props",        "patch-page_props.sql"),
1333                 array("page_restrictions", "patch-page_restrictions.sql"),
1334                 array("profiling",         "patch-profiling.sql"),
1335                 array("protected_titles",  "patch-protected_titles.sql"),
1336                 array("redirect",          "patch-redirect.sql"),
1337         );
1339         $newcols = array(
1340                 array("archive",       "ar_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1341                 array("archive",       "ar_len",               "INTEGER"),
1342                 array("archive",       "ar_page_id",           "INTEGER"),
1343                 array("image",         "img_sha1",             "TEXT NOT NULL DEFAULT ''"),
1344                 array("ipblocks",      "ipb_anon_only",        "CHAR NOT NULL DEFAULT '0'"),
1345                 array("ipblocks",      "ipb_by_text",          "TEXT NOT NULL DEFAULT ''"),
1346                 array("ipblocks",      "ipb_block_email",      "CHAR NOT NULL DEFAULT '0'"),
1347                 array("ipblocks",      "ipb_create_account",   "CHAR NOT NULL DEFAULT '1'"),
1348                 array("ipblocks",      "ipb_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1349                 array("ipblocks",      "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1350                 array("filearchive",   "fa_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1351                 array("logging",       "log_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1352                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1353                 array("logging",       "log_params",           "TEXT"),
1354                 array("mwuser",        "user_editcount",       "INTEGER"),
1355                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1356                 array("oldimage",      "oi_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1357                 array("oldimage",      "oi_metadata",          "BYTEA NOT NULL DEFAULT ''"),
1358                 array("oldimage",      "oi_media_type",        "TEXT"),
1359                 array("oldimage",      "oi_major_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1360                 array("oldimage",      "oi_minor_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1361                 array("oldimage",      "oi_sha1",              "TEXT NOT NULL DEFAULT ''"),
1362                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1363                 array("recentchanges", "rc_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1364                 array("recentchanges", "rc_log_action",        "TEXT"),
1365         array("recentchanges", "rc_log_type",          "TEXT"),
1366         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1367                 array("recentchanges", "rc_new_len",           "INTEGER"),
1368                 array("recentchanges", "rc_old_len",           "INTEGER"),
1369                 array("recentchanges", "rc_params",            "TEXT"),
1370                 array("revision",      "rev_len",              "INTEGER"),
1371                 array("revision",      "rev_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1372         );
1375         # table, column, desired type, USING clause if needed (with new default if needed)
1376         $typechanges = array(
1377                 array("archive",      "ar_deleted",      "smallint", ""),
1378                 array("archive",      "ar_minor_edit",   "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1379                 array("filearchive",  "fa_deleted",      "smallint", ""),
1380                 array("filearchive",  "fa_height",       "integer",  ""),
1381                 array("filearchive",  "fa_metadata",     "bytea",    "decode(fa_metadata,'escape')"),
1382                 array("filearchive",  "fa_size",         "integer",  ""),
1383                 array("filearchive",  "fa_width",        "integer",  ""),
1384                 array("filearchive",  "fa_storage_group","text",     ""),
1385                 array("filearchive",  "fa_storage_key",  "text",     ""),
1386                 array("image",        "img_metadata",    "bytea",    "decode(img_metadata,'escape')"),
1387                 array("image",        "img_size",        "integer",  ""),
1388                 array("image",        "img_width",       "integer",  ""),
1389                 array("image",        "img_height",      "integer",  ""),
1390                 array("interwiki",    "iw_local",        "smallint", "iw_local::smallint DEFAULT 0"),
1391                 array("interwiki",    "iw_trans",        "smallint", "iw_trans::smallint DEFAULT 0"),
1392                 array("ipblocks",     "ipb_auto",        "smallint", "ipb_auto::smallint DEFAULT 0"),
1393                 array("ipblocks",     "ipb_anon_only",        "smallint", "ipb_anon_only::smallint DEFAULT 0"),
1394                 array("ipblocks",     "ipb_create_account",        "smallint", "ipb_create_account::smallint DEFAULT 1"),
1395                 array("ipblocks",     "ipb_enable_autoblock",        "smallint", "ipb_enable_autoblock::smallint DEFAULT 1"),
1396                 array("ipblocks",     "ipb_block_email",        "smallint", "ipb_block_email::smallint DEFAULT 0"),
1397                 array("ipblocks",     "ipb_address",     "text",     "ipb_address::text"),
1398                 array("ipblocks",     "ipb_deleted",     "smallint", ""),
1399                 array("math",         "math_inputhash",  "bytea",    "decode(math_inputhash,'escape')"),
1400                 array("math",         "math_outputhash", "bytea",    "decode(math_outputhash,'escape')"),
1401                 array("mwuser",       "user_token",      "text",     ""),
1402                 array("mwuser",       "user_email_token","text",     ""),
1403                 array("objectcache",  "keyname",         "text",     ""),
1404                 array("oldimage",     "oi_height",       "integer",  ""),
1405                 array("oldimage",     "oi_size",         "integer",  ""),
1406                 array("oldimage",     "oi_width",        "integer",  ""),
1407                 array("page",         "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1408                 array("page",         "page_is_new",     "smallint", "page_is_new::smallint DEFAULT 0"),
1409                 array("querycache",   "qc_value",        "integer",  ""),
1410                 array("querycachetwo","qcc_value",       "integer",  ""),
1411                 array("recentchanges","rc_bot",          "smallint", "rc_bot::smallint DEFAULT 0"),
1412                 array("recentchanges","rc_deleted",      "smallint", ""),
1413                 array("recentchanges","rc_minor",        "smallint", "rc_minor::smallint DEFAULT 0"),
1414                 array("recentchanges","rc_new",          "smallint", "rc_new::smallint DEFAULT 0"),
1415                 array("recentchanges","rc_type",         "smallint", "rc_type::smallint DEFAULT 0"),
1416                 array("recentchanges","rc_patrolled",    "smallint", "rc_patrolled::smallint DEFAULT 0"),
1417                 array("revision",     "rev_minor_edit",  "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1418                 array("templatelinks","tl_namespace",    "smallint", "tl_namespace::smallint"),
1419                 array("user_newtalk", "user_ip",         "text",     "host(user_ip)"),
1420         );
1422         $newindexes = array(
1423                 array("archive",       "archive_user_text", "(ar_user_text)"),
1424                 array("image",         "img_sha1",          "(img_sha1)"),
1425                 array("oldimage",      "oi_sha1",           "(oi_sha1)"),
1426                 array("revision",      "rev_text_id_idx",   "(rev_text_id)"),
1427         );
1429         $newrules = array(
1430         );
1432         foreach ($newsequences as $ns) {
1433                 if ($wgDatabase->sequenceExists($ns)) {
1434                         echo "... sequence \"$ns\" already exists\n";
1435                         continue;
1436                 }
1438                 echo "Creating sequence \"$ns\"\n";
1439                 $wgDatabase->query("CREATE SEQUENCE $ns");
1440         }
1442         foreach ($newtables as $nt) {
1443                 if ($wgDatabase->tableExists($nt[0])) {
1444                         echo "... table \"$nt[0]\" already exists\n";
1445                         continue;
1446                 }
1448                 echo "Creating table \"$nt[0]\"\n";
1449                 dbsource(archive($nt[1]));
1450         }
1452         ## Needed before newcols
1453         if ($wgDatabase->tableExists("archive2")) {
1454                 echo "Converting \"archive2\" back to normal archive table\n";
1455                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1456                         echo "Dropping rule \"archive_insert\"\n";
1457                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1458                 }
1459                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1460                         echo "Dropping rule \"archive_delete\"\n";
1461                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1462                 }
1463                 dbsource(archive("patch-remove-archive2.sql"));
1464         }
1465         else
1466                 echo "... obsolete table \"archive2\" does not exist\n";
1468         foreach ($newcols as $nc) {
1469                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1470                 if (!is_null($fi)) {
1471                         echo "... column \"$nc[0].$nc[1]\" already exists\n";
1472                         continue;
1473                 }
1475                 echo "Adding column \"$nc[0].$nc[1]\"\n";
1476                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1477         }
1479         foreach ($typechanges as $tc) {
1480                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1481                 if (is_null($fi)) {
1482                         echo "... error: expected column $tc[0].$tc[1] to exist\n";
1483                         exit(1);
1484                 }
1486                 if ($fi->type() === $tc[2])
1487                         echo "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n";
1488                 else {
1489                         echo "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n";
1490                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1491                         if (strlen($tc[3])) {
1492                                 $default = array();
1493                                 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1494                                         $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1495                                         $wgDatabase->query($sqldef);
1496                                         $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1497                                 }
1498                                 $sql .= " USING $tc[3]";
1499                         }
1500                         $sql .= ";\nCOMMIT;\n";
1501                         $wgDatabase->query($sql);
1502                 }
1503         }
1505         if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1506                 echo "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n";
1507                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1508                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1509                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1510         }
1511         else
1512                 echo "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n";
1515         foreach ($newindexes as $ni) {
1516                 if (pg_index_exists($ni[0], $ni[1])) {
1517                         echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1518                         continue;
1519                 }
1520                 echo "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n";
1521                 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1522         }
1524         foreach ($newrules as $nr) {
1525                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1526                         echo "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n";
1527                         continue;
1528                 }
1529                 echo "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n";
1530                 dbsource(archive($nr[2]));
1531         }
1533         if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1534                 echo "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n";
1535                 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1536                 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1537                         "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1538         }
1539         else
1540                 echo "... table \"oldimage\" has correct cascade delete foreign key to image\n";
1542         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1543                 echo "Adding function and trigger \"page_deleted\" to table \"page\"\n";
1544                 dbsource(archive('patch-page_deleted.sql'));
1545         }
1546         else
1547                 echo "... table \"page\" has \"page_deleted\" trigger\n";
1549         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1550         if (!$fi->nullable()) {
1551                 echo "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n";
1552                 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1553         }
1554         else
1555                 echo "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n";
1557         $pu = pg_describe_index("pagelink_unique");
1558         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1559                 echo "Dropping obsolete version of index \"pagelink_unique index\"\n";
1560                 $wgDatabase->query("DROP INDEX pagelink_unique");
1561                 $pu = null;
1562         }
1563         else
1564                 echo "... obsolete version of index \"pagelink_unique index\" does not exist\n";
1566         if (is_null($pu)) {
1567                 echo "Creating index \"pagelink_unique index\"\n";
1568                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1569         }
1570         else
1571                 echo "... index \"pagelink_unique_index\" aready exists\n";
1573         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1574                 echo "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n";
1575         }
1576         else {
1577                 echo "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n";
1578                 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1579         }
1581         global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1582         # Add missing extension tables
1583         foreach ( $wgExtNewTables as $nt ) {
1584                 if ($wgDatabase->tableExists($nt[0])) {
1585                         echo "... table \"$nt[0]\" already exists\n";
1586                         continue;
1587                 }
1588                 echo "Creating table \"$nt[0]\"\n";
1589                 dbsource($nt[1]);
1590         }
1591         # Add missing extension fields
1592         foreach ( $wgExtPGNewFields as $nc ) {
1593                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1594                 if (!is_null($fi)) {
1595                         echo "... column \"$nc[0].$nc[1]\" already exists\n";
1596                         continue;
1597                 }
1598                 echo "Adding column \"$nc[0].$nc[1]\"\n";
1599                 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1600         }
1601         # Add missing extension indexes
1602         foreach ( $wgExtNewIndexes as $ni ) {
1603                 if (pg_index_exists($ni[0], $ni[1])) {
1604                         echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1605                         continue;
1606                 }
1607                 echo "Creating index \"$ni[1]\" on table \"$ni[0]\"\n";
1608                 dbsource($ni[2]);
1609         }
1611         # Tweak the page_title tsearch2 trigger to filter out slashes
1612         # This is create or replace, so harmless to call if not needed
1613         dbsource(archive('patch-ts2pagetitle.sql'));
1615         ## If the server is 8.3 or higher, rewrite teh tsearch2 triggers
1616         ## in case they have the old 'default' versions
1617         if ( $numver >= 8.3 )
1618                 dbsource(archive('patch-tsearch2funcs.sql'));
1620         return;