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