fixed bug
[mediawiki.git] / maintenance / updaters.inc
blob7d64aee8b24bc3c3bfda55a8722daf3d7825aaa2
1 <?php
2 /**
3  * @package MediaWiki
4  * @subpackage Maintenance
5  */
7  /** */
9 require_once 'convertLinks.inc';
10 require_once 'InitialiseMessages.inc';
11 require_once 'userDupes.inc';
13 $wgRenamedTables = array(
14 #           from             to                  patch file
15 #       array( 'group',         'groups',           'patch-rename-group.sql' ),
18 $wgNewTables = array(
19 #            table          patch file (in maintenance/archives)
20         array( 'hitcounter',    'patch-hitcounter.sql' ),
21         array( 'querycache',    'patch-querycache.sql' ),
22         array( 'objectcache',   'patch-objectcache.sql' ),
23         array( 'categorylinks', 'patch-categorylinks.sql' ),
24         array( 'logging',       'patch-logging.sql' ),
25         array( 'validate',      'patch-validate.sql' ),
26         array( 'user_newtalk',  'patch-usernewtalk2.sql' ),
27         array( 'transcache',    'patch-transcache.sql' ),
28         array( 'trackbacks',    'patch-trackbacks.sql' ),
31 $wgNewFields = array(
32 #           table            field             patch file (in maintenance/archives)
33         array( 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
34         array( 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
35         array( 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
36         array( 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
37         array( 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
38         array( 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
39         array( 'user',          'user_real_name',   'patch-user-realname.sql' ),
40         array( 'user',          'user_token',       'patch-user_token.sql' ),
41         array( 'user',          'user_email_token', 'patch-user_email_token.sql' ),
42         array( 'user',          'user_registration','patch-user_registration.sql' ),
43         array( 'logging',       'log_params',       'patch-log_params.sql' ),
44         array( 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
45         array( 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
46         array( 'page',          'page_len',         'patch-page_len.sql' ),
47         array( 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
48         array( 'image',         'img_width',        'patch-img_width.sql' ),
49         array( 'image',         'img_metadata',     'patch-img_metadata.sql' ),
50         array( 'image',         'img_media_type',   'patch-img_media_type.sql' ),
51         array( 'validate',      'val_ip',           'patch-val_ip.sql' ),
52         array( 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
53         array( 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
54         array( 'ipblocks',      'ipb_range_start',  'patch-ipb_range_start.sql' ),
57 function rename_table( $from, $to, $patch ) {
58         global $wgDatabase;
59         if ( $wgDatabase->tableExists( $from ) ) {
60                 if ( $wgDatabase->tableExists( $to ) ) {
61                         echo "...can't move table $from to $to, $to already exists.\n";
62                 } else {
63                         echo "Moving table $from to $to...";
64                         dbsource( archive($patch), $wgDatabase );
65                         echo "ok\n";
66                 }
67         } else {
68                 // Source table does not exist
69                 // Renames are done before creations, so this is typical for a new installation
70                 // Ignore silently
71         }
74 function add_table( $name, $patch ) {
75         global $wgDatabase;
76         if ( $wgDatabase->tableExists( $name ) ) {
77                 echo "...$name table already exists.\n";
78         } else {
79                 echo "Creating $name table...";
80                 dbsource( archive($patch), $wgDatabase );
81                 echo "ok\n";
82         }
85 function add_field( $table, $field, $patch ) {
86         global $wgDatabase;
87         if ( !$wgDatabase->tableExists( $table ) ) {
88                 echo "...$table table does not exist, skipping new field patch\n";
89         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
90                 echo "...have $field field in $table table.\n";
91         } else {
92                 echo "Adding $field field to table $table...";
93                 dbsource( archive($patch) , $wgDatabase );
94                 echo "ok\n";
95         }
98 function do_revision_updates() {
99         global $wgSoftwareRevision;
100         if ( $wgSoftwareRevision < 1001 ) {
101                 update_passwords();
102         }
105 function update_passwords() {
106         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
108         global $wgDatabase;
109         $fname = "Update script: update_passwords()";
110         print "\nIt appears that you need to update the user passwords in your\n" .
111           "database. If you have already done this (if you've run this update\n" .
112           "script once before, for example), doing so again will make all your\n" .
113           "user accounts inaccessible, so be sure you only do this once.\n" .
114           "Update user passwords? (yes/no)";
116         $resp = readconsole();
117     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
119         $sql = "SELECT user_id,user_password FROM user";
120         $source = $wgDatabase->query( $sql, $fname );
122         while ( $row = $wgDatabase->fetchObject( $source ) ) {
123                 $id = $row->user_id;
124                 $oldpass = $row->user_password;
125                 $newpass = md5( "{$id}-{$oldpass}" );
127                 $sql = "UPDATE user SET user_password='{$newpass}' " .
128                   "WHERE user_id={$id}";
129                 $wgDatabase->query( $sql, $fname );
130         }
133 function do_interwiki_update() {
134         # Check that interwiki table exists; if it doesn't source it
135         global $wgDatabase;
136         if( $wgDatabase->tableExists( "interwiki" ) ) {
137                 echo "...already have interwiki table\n";
138                 return true;
139         }
140         echo "Creating interwiki table: ";
141         dbsource( archive("patch-interwiki.sql") );
142         echo "ok\n";
143         echo "Adding default interwiki definitions: ";
144         dbsource( "maintenance/interwiki.sql" );
145         echo "ok\n";
148 function do_index_update() {
149         # Check that proper indexes are in place
150         global $wgDatabase;
151         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
152         if( $meta->multiple_key == 0 ) {
153                 echo "Updating indexes to 20031107: ";
154                 dbsource( archive("patch-indexes.sql") );
155                 echo "ok\n";
156                 return true;
157         }
158         echo "...indexes seem up to 20031107 standards\n";
159         return false;
162 function do_image_index_update() {
163         global $wgDatabase;
164         
165         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
166         if( $meta->multiple_key == 0 ) {
167                 echo "Updating indexes to 20050912: ";
168                 dbsource( archive("patch-mimesearch-indexes.sql") );
169                 echo "ok\n";
170                 return true;
171         }
172         echo "...indexes seem up to 20050912 standards\n";
173         return false;
176 function do_image_name_unique_update() {
177         global $wgDatabase;
178         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
179                 echo "...image primary key already set.\n";
180         } else {
181                 echo "Making img_name the primary key... ";
182                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
183                 echo "ok\n";
184         }
187 function do_logging_timestamp_index() {
188         global $wgDatabase;
189         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
190                 echo "...timestamp key on logging already exists.\n";
191         } else {
192                 echo "Adding timestamp key on logging table... ";
193                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
194                 echo "ok\n";
195         }
199 function do_watchlist_update() {
200         global $wgDatabase;
201         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
202                 echo "The watchlist table is already set up for email notification.\n";
203         } else {
204                 echo "Adding wl_notificationtimestamp field for email notification management.";
205                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
206                 dbsource( "maintenance/archives/patch-email-notification.sql", $wgDatabase );
207                 echo "ok\n";
208         }
211 function do_copy_newtalk_to_watchlist() {
212         global $wgDatabase;
213         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
215         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
216                 $wgDatabase->tableName( 'user_newtalk' ) );
217         $num_newtalks=$wgDatabase->numRows($res);
218         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
220         $user = new User();
221         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
222                 $wluser = $wgDatabase->fetchObject( $res );
223                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
224                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
225                                 $wgDatabase->replace( 'watchlist',
226                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
227                                           array('wl_user'                       => 0,
228                                                 'wl_namespace'                  => NS_USER_TALK,
229                                                 'wl_title'                      => $wluser->user_ip,
230                                                 'wl_notificationtimestamp'      => '19700101000000'
231                                                 ), 'updaters.inc::do_watchlist_update2'
232                                         );
233                         }
234                 } else { # normal users ... have user_ids
235                         $user->setID($wluser->user_id);
236                         $wgDatabase->replace( 'watchlist',
237                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
238                                   array('wl_user'                       => $user->getID(),
239                                         'wl_namespace'                  => NS_USER_TALK,
240                                         'wl_title'                      => $user->getName(),
241                                         'wl_notificationtimestamp'      => '19700101000000'
242                                         ), 'updaters.inc::do_watchlist_update3'
243                                 );
244                 }
245         }
246         echo "Done.\n";
250 function do_user_update() {
251         global $wgDatabase;
252         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
253                 echo "User table contains old email authentication field. Dropping... ";
254                 dbsource( "maintenance/archives/patch-email-authentication.sql", $wgDatabase );
255                 echo "ok\n";
256         } else {
257                 echo "...user table does not contain old email authentication field.\n";
258         }
262  * 1.4 betas were missing the 'binary' marker from logging.log_title,
263  * which causes a collation mismatch error on joins in MySQL 4.1.
264  */
265 function do_logging_encoding() {
266         global $wgDatabase, $wgDBtype;
267         if ($wgDBtype != 'mysql')
268                 return;
269         $logging = $wgDatabase->tableName( 'logging' );
270         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
271         $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
272         $wgDatabase->freeResult( $res );
274         if( in_array( 'binary', $flags ) ) {
275                 echo "Logging table has correct title encoding.\n";
276         } else {
277                 echo "Fixing title encoding on logging table... ";
278                 dbsource( 'maintenance/archives/patch-logging-title.sql', $wgDatabase );
279                 echo "ok\n";
280         }
283 function do_schema_restructuring() {
284         global $wgDatabase;
285         $fname="do_schema_restructuring";
286         if ( $wgDatabase->tableExists( 'page' ) ) {
287                 echo "...page table already exists.\n";
288         } else {
289                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
290                 echo wfTimestamp();
291                 echo "......checking for duplicate entries.\n"; flush();
293                 extract( $wgDatabase->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
295                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
296                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
298                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
299                         echo wfTimestamp();
300                         echo "......<b>Found duplicate entries</b>\n";
301                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
302                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
303                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
304                                         $duplicate[$row->cur_namespace] = array();
305                                 }
306                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
307                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
308                         }
309                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
310                         $firstCond = true;
311                         foreach ( $duplicate as $ns => $titles ) {
312                                 if ( $firstCond ) {
313                                         $firstCond = false;
314                                 } else {
315                                         $sql .= ' OR ';
316                                 }
317                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
318                                 $first = true;
319                                 foreach ( $titles as $t ) {
320                                         if ( $first ) {
321                                                 $sql .= $wgDatabase->addQuotes( $t );
322                                                 $first = false;
323                                         } else {
324                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
325                                         }
326                                 }
327                                 $sql .= ") ) \n";
328                         }
329                         # By sorting descending, the most recent entry will be the first in the list.
330                         # All following entries will be deleted by the next while-loop.
331                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
333                         $rows = $wgDatabase->query( $sql, $fname );
335                         $prev_title = $prev_namespace = false;
336                         $deleteId = array();
338                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
339                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
340                                         $deleteId[] = $row->cur_id;
341                                 }
342                                 $prev_title     = $row->cur_title;
343                                 $prev_namespace = $row->cur_namespace;
344                         }
345                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
346                         $rows = $wgDatabase->query( $sql, $fname );
347                         echo wfTimestamp();
348                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
349                 }
352                 echo wfTimestamp();
353                 echo "......Creating tables.\n";
354                 $wgDatabase->query("CREATE TABLE $page (
355                         page_id int(8) unsigned NOT NULL auto_increment,
356                         page_namespace int NOT NULL,
357                         page_title varchar(255) binary NOT NULL,
358                         page_restrictions tinyblob NOT NULL default '',
359                         page_counter bigint(20) unsigned NOT NULL default '0',
360                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
361                         page_is_new tinyint(1) unsigned NOT NULL default '0',
362                         page_random real unsigned NOT NULL,
363                         page_touched char(14) binary NOT NULL default '',
364                         page_latest int(8) unsigned NOT NULL,
365                         page_len int(8) unsigned NOT NULL,
367                         PRIMARY KEY page_id (page_id),
368                         UNIQUE INDEX name_title (page_namespace,page_title),
369                         INDEX (page_random),
370                         INDEX (page_len)
371                         ) TYPE=InnoDB", $fname );
372                 $wgDatabase->query("CREATE TABLE $revision (
373                         rev_id int(8) unsigned NOT NULL auto_increment,
374                         rev_page int(8) unsigned NOT NULL,
375                         rev_comment tinyblob NOT NULL default '',
376                         rev_user int(5) unsigned NOT NULL default '0',
377                         rev_user_text varchar(255) binary NOT NULL default '',
378                         rev_timestamp char(14) binary NOT NULL default '',
379                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
380                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
382                         PRIMARY KEY rev_page_id (rev_page, rev_id),
383                         UNIQUE INDEX rev_id (rev_id),
384                         INDEX rev_timestamp (rev_timestamp),
385                         INDEX page_timestamp (rev_page,rev_timestamp),
386                         INDEX user_timestamp (rev_user,rev_timestamp),
387                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
388                         ) TYPE=InnoDB", $fname );
390                 echo wfTimestamp();
391                 echo "......Locking tables.\n";
392                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
394                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
395                 echo wfTimestamp();
396                 echo "......maxold is {$maxold}\n";
398                 echo wfTimestamp();
399                 global $wgLegacySchemaConversion;
400                 if( $wgLegacySchemaConversion ) {
401                         // Create HistoryBlobCurStub entries.
402                         // Text will be pulled from the leftover 'cur' table at runtime.
403                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
404                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
405                         $cur_flags = "'object'";
406                 } else {
407                         // Copy all cur text in immediately: this may take longer but avoids
408                         // having to keep an extra table around.
409                         echo "......Moving text from cur.\n";
410                         $cur_text = 'cur_text';
411                         $cur_flags = "''";
412                 }
413                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
414                                 old_timestamp, old_minor_edit, old_flags)
415                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
416                         FROM $cur", $fname );
418                 echo wfTimestamp();
419                 echo "......Setting up revision table.\n";
420                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
421                                 rev_minor_edit)
422                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
423                                 old_timestamp, old_minor_edit
424                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
426                 echo wfTimestamp();
427                 echo "......Setting up page table.\n";
428                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
429                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
430                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
431                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
432                         FROM $cur,$revision
433                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
435                 echo wfTimestamp();
436                 echo "......Unlocking tables.\n";
437                 $wgDatabase->query( "UNLOCK TABLES", $fname );
439                 echo wfTimestamp();
440                 echo "......Renaming old.\n";
441                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
443                 echo wfTimestamp();
444                 echo "...done.\n";
445         }
448 function do_inverse_timestamp() {
449         global $wgDatabase;
450         $fname="do_schema_restructuring";
451         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
452                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
453                 dbsource( 'maintenance/archives/patch-inverse_timestamp.sql', $wgDatabase );
454                 echo "ok\n";
455         } else {
456                 echo "revision timestamp indexes already up to 2005-03-13\n";
457         }
460 function do_text_id() {
461         global $wgDatabase;
462         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
463                 echo "...rev_text_id already in place.\n";
464         } else {
465                 echo "Adding rev_text_id field... ";
466                 dbsource( 'maintenance/archives/patch-rev_text_id.sql', $wgDatabase );
467                 echo "ok\n";
468         }
471 function do_namespace_size() {
472         $tables = array(
473                 'page'          => 'page',
474                 'archive'       => 'ar',
475                 'recentchanges' => 'rc',
476                 'watchlist'     => 'wl',
477                 'querycache'    => 'qc',
478                 'logging'       => 'log',
479         );
480         foreach( $tables as $table => $prefix ) {
481                 do_namespace_size_on( $table, $prefix );
482                 flush();
483         }
486 function do_namespace_size_on( $table, $prefix ) {
487         global $wgDatabase, $wgDBtype;
488         if ($wgDBtype != 'mysql')
489                 return;
490         $field = $prefix . '_namespace';
492         $tablename = $wgDatabase->tableName( $table );
493         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
494         $info = $wgDatabase->fetchObject( $result );
495         $wgDatabase->freeResult( $result );
497         if( substr( $info->Type, 0, 3 ) == 'int' ) {
498                 echo "...$field is already a full int ($info->Type).\n";
499         } else {
500                 echo "Promoting $field from $info->Type to int... ";
502                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
503                 $wgDatabase->query( $sql );
505                 echo "ok\n";
506         }
509 function do_pagelinks_update() {
510         global $wgDatabase;
511         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
512                 echo "...already have pagelinks table.\n";
513         } else {
514                 echo "Converting links and brokenlinks tables to pagelinks... ";
515                 dbsource( "maintenance/archives/patch-pagelinks.sql", $wgDatabase );
516                 echo "ok\n";
517                 flush();
519                 global $wgCanonicalNamespaceNames;
520                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
521                         if( $ns != 0 ) {
522                                 do_pagelinks_namespace( $ns );
523                         }
524                 }
525         }
528 function do_pagelinks_namespace( $namespace ) {
529         global $wgDatabase, $wgContLang;
531         $ns = intval( $namespace );
532         echo "Cleaning up broken links for namespace $ns... ";
534         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
535         $name = $wgContLang->getNsText( $ns );
536         $prefix = $wgDatabase->strencode( $name );
537         $likeprefix = str_replace( '_', '\\_', $prefix);
539         $sql = "UPDATE $pagelinks
540                    SET pl_namespace=$ns,
541                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
542                  WHERE pl_namespace=0
543                    AND pl_title LIKE '$likeprefix:%'";
545         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
546         echo "ok\n";
549 function do_drop_img_type() {
550         global $wgDatabase;
552         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
553                 echo "Dropping unused img_type field in image table... ";
554                 dbsource( "maintenance/archives/patch-drop_img_type.sql", $wgDatabase );
555                 echo "ok\n";
556         } else {
557                 echo "No img_type field in image table; Good.\n";
558         }
561 function do_old_links_update() {
562         global $wgDatabase;
563         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
564                 echo "Already have pagelinks; skipping old links table updates.\n";
565         } else {
566                 convertLinks(); flush();
567         }
570 function do_user_unique_update() {
571         global $wgDatabase;
572         $duper = new UserDupes( $wgDatabase );
573         if( $duper->hasUniqueIndex() ) {
574                 echo "Already have unique user_name index.\n";
575         } else {
576                 if( !$duper->clearDupes() ) {
577                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
578                 }
579                 echo "Adding unique index on user_name... ";
580                 dbsource( 'maintenance/archives/patch-user_nameindex.sql', $wgDatabase );
581                 echo "ok\n";
582         }
585 function do_user_groups_update() {
586         $fname = 'do_user_groups_update';
587         global $wgDatabase;
589         if( $wgDatabase->tableExists( 'user_groups' ) ) {
590                 echo "...user_groups table already exists.\n";
591                 return do_user_groups_reformat();
592         }
594         echo "Adding user_groups table... ";
595         dbsource( 'maintenance/archives/patch-user_groups.sql', $wgDatabase );
596         echo "ok\n";
598         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
599                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
600                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
601                         dbsource( 'maintenance/archives/patch-user_rights.sql', $wgDatabase );
602                         echo "ok\n";
603                 } else {
604                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
605                         echo "*** You may need to manually configure some sysops by manipulating\n";
606                         echo "*** the user_groups table.\n";
607                         return;
608                 }
609         }
611         echo "Converting user_rights table to user_groups... ";
612         $result = $wgDatabase->select( 'user_rights',
613                 array( 'ur_user', 'ur_rights' ),
614                 array( "ur_rights != ''" ),
615                 $fname );
617         while( $row = $wgDatabase->fetchObject( $result ) ) {
618                 $groups = array_unique(
619                         array_map( 'trim',
620                                 explode( ',', $row->ur_rights ) ) );
622                 foreach( $groups as $group ) {
623                         $wgDatabase->insert( 'user_groups',
624                                 array(
625                                         'ug_user'  => $row->ur_user,
626                                         'ug_group' => $group ),
627                                 $fname );
628                 }
629         }
630         $wgDatabase->freeResult( $result );
631         echo "ok\n";
634 function do_user_groups_reformat() {
635         # Check for bogus formats from previous 1.5 alpha code.
636         global $wgDatabase;
637         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
639         if( $info->type == 'int' ) {
640                 $oldug = $wgDatabase->tableName( 'user_groups' );
641                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
642                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
643                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
644                 echo "ok\n";
646                 echo "Re-adding fresh user_groups table... ";
647                 dbsource( 'maintenance/archives/patch-user_groups.sql', $wgDatabase );
648                 echo "ok\n";
650                 echo "***\n";
651                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
652                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
653                 echo "***\n";
654         } else {
655                 echo "...user_groups is in current format.\n";
656         }
660 function do_watchlist_null() {
661         # Make sure wl_notificationtimestamp can be NULL,
662         # and update old broken items.
663         global $wgDatabase;
664         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
665         
666         if( $info->not_null ) {
667                 echo "Making wl_notificationtimestamp nullable... ";
668                 dbsource( 'maintenance/archives/patch-watchlist-null.sql', $wgDatabase );
669                 echo "ok\n";
670         } else {
671                 echo "...wl_notificationtimestamp is already nullable.\n";
672         }
677  * @bug 3946
678  */
679 function do_page_random_update() {
680         global $wgDatabase;
682         echo "Setting page_random to a random value on rows where it equals 0...";
684         $page = $wgDatabase->tableName( 'page' );
685         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
686         $rows = $wgDatabase->affectedRows();
687         
688         echo "changed $rows rows\n";
691 function do_templatelinks_update() {
692         global $wgDatabase, $wgLoadBalancer;
693         $fname = 'do_templatelinks_update';
694         
695         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
696                 echo "...templatelinks table already exists\n";
697                 return;
698         }
699         echo "Creating templatelinks table...\n";
700         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
701         echo "Populating...\n";
702         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
703                 // Slow, replication-friendly update
704                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
705                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
706                 $count = 0;
707                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
708                         $count = ($count + 1) % 100;
709                         if ( $count == 0 ) {
710                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
711                                         wfWaitForSlaves( 10 );
712                                 } else {
713                                         sleep( 1 );
714                                 }
715                         }
716                         $wgDatabase->insert( 'templatelinks', 
717                                 array( 
718                                         'tl_from' => $row->pl_from,
719                                         'tl_namespace' => $row->pl_namespace,
720                                         'tl_title' => $row->pl_title,
721                                 ), $fname
722                         );
723                                 
724                 }
725                 $wgDatabase->freeResult( $res );
726         } else {
727                 // Fast update
728                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks', 
729                         array( 
730                                 'tl_from' => 'pl_from',
731                                 'tl_namespace' => 'pl_namespace', 
732                                 'tl_title' => 'pl_title' 
733                         ), array(
734                                 'pl_namespace' => 10
735                         ), $fname
736                 );
737         }
738         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
741 function do_all_updates() {
742         global $wgNewTables, $wgNewFields, $wgRenamedTables;
744         # Rename tables
745         foreach ( $wgRenamedTables as $tableRecord ) {
746                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
747         }
749         # Add missing tables
750         foreach ( $wgNewTables as $tableRecord ) {
751                 add_table( $tableRecord[0], $tableRecord[1] );
752                 flush();
753         }
755         # Add missing fields
756         foreach ( $wgNewFields as $fieldRecord ) {
757                 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
758                 flush();
759         }
761         # Do schema updates which require special handling
762         do_interwiki_update(); flush();
763         do_index_update(); flush();
764         do_old_links_update(); flush();
765         do_image_name_unique_update(); flush();
766         do_watchlist_update(); flush();
767         do_user_update(); flush();
768 ######  do_copy_newtalk_to_watchlist(); flush();
769         do_logging_encoding(); flush();
771         do_schema_restructuring(); flush();
772         do_inverse_timestamp(); flush();
773         do_text_id(); flush();
774         do_namespace_size(); flush();
776         do_pagelinks_update(); flush();
777         do_templatelinks_update(); flush(); // after pagelinks
778         
779         do_drop_img_type(); flush();
781         do_user_unique_update(); flush();
782         do_user_groups_update(); flush();
783         
784         do_watchlist_null(); flush();
786         //do_image_index_update(); flush();
788         do_logging_timestamp_index(); flush();
790         do_page_random_update(); flush();
792         initialiseMessages(); flush();
795 function archive($name) {
796         global $wgDBtype;
797         switch ($wgDBtype) {
798         case "oracle":
799                 return "maintenance/oracle/archives/$name";
800         default:
801                 return "maintenance/archives/$name";
802         }