]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - maintenance/upgrade1_5.php
MediaWiki 1.17.1-scripts
[autoinstalls/mediawiki.git] / maintenance / upgrade1_5.php
1 <?php
2 /**
3  * Alternate 1.4 -> 1.5 schema upgrade.
4  * This does only the main tables + UTF-8 and is designed to allow upgrades to
5  * interleave with other updates on the replication stream so that large wikis
6  * can be upgraded without disrupting other services.
7  *
8  * Note: this script DOES NOT apply every update, nor will it probably handle
9  * much older versions, etc.
10  * Run this, FOLLOWED BY update.php, for upgrading from 1.4.5 release to 1.5.
11  *
12  * @file
13  * @ingroup Maintenance
14  */
15
16 require_once( dirname( __FILE__ ) . '/Maintenance.php' );
17
18 define( 'MW_UPGRADE_COPY',     false );
19 define( 'MW_UPGRADE_ENCODE',   true  );
20 define( 'MW_UPGRADE_NULL',     null  );
21 define( 'MW_UPGRADE_CALLBACK', null  ); // for self-documentation only
22
23 /**
24  * @ingroup Maintenance
25  */
26 class FiveUpgrade extends Maintenance {
27         function __construct() {
28                 parent::__construct();
29
30                 $this->mDescription = 'Script for upgrades from 1.4 to 1.5 (NOT 1.15) in very special cases.';
31
32                 $this->addOption( 'upgrade', 'Really run the script' );
33                 $this->addOption( 'noimage', '' );
34                 $this->addOption( 'step', 'Only do a specific step', false, true );
35         }
36
37         public function getDbType() {
38                 return Maintenance::DB_ADMIN;
39         }
40
41         public function execute() {
42                 $this->output( "ATTENTION: This script is for upgrades from 1.4 to 1.5 (NOT 1.15) in very special cases.\n" );
43                 $this->output( "Use update.php for usual updates.\n" );
44
45                 if ( !$this->hasOption( 'upgrade' ) ) {
46                         $this->output( "Please run this script with --upgrade key to actually run the updater.\n" );
47                         return;
48                 }
49
50                 $this->setMembers();
51
52                 $tables = array(
53                         'page',
54                         'links',
55                         'user',
56                         'image',
57                         'oldimage',
58                         'watchlist',
59                         'logging',
60                         'archive',
61                         'imagelinks',
62                         'categorylinks',
63                         'ipblocks',
64                         'recentchanges',
65                         'querycache'
66                 );
67
68                 foreach ( $tables as $table ) {
69                         if ( $this->doing( $table ) ) {
70                                 $method = 'upgrade' . ucfirst( $table );
71                                 $this->$method();
72                         }
73                 }
74
75                 if ( $this->doing( 'cleanup' ) ) {
76                         $this->upgradeCleanup();
77                 }
78         }
79
80         protected function setMembers() {
81                 $this->conversionTables = $this->prepareWindows1252();
82
83                 $this->loadBalancers = array();
84                 $this->dbw = wfGetDB( DB_MASTER );
85                 $this->dbr = $this->streamConnection();
86
87                 $this->cleanupSwaps = array();
88                 $this->emailAuth = false; # don't preauthenticate emails
89                 $this->maxLag    = 10; # if slaves are lagged more than 10 secs, wait
90                 $this->step      = $this->getOption( 'step', null );
91         }
92
93         function doing( $step ) {
94                 return is_null( $this->step ) || $step == $this->step;
95         }
96
97         /**
98          * Open a connection to the master server with the admin rights.
99          * @return Database
100          * @access private
101          */
102         function newConnection() {
103                 $lb = wfGetLBFactory()->newMainLB();
104                 $db = $lb->getConnection( DB_MASTER );
105
106                 $this->loadBalancers[] = $lb;
107                 return $db;
108         }
109
110         /**
111          * Commit transactions and close the connections when we're done...
112          */
113         function close() {
114                 foreach ( $this->loadBalancers as $lb ) {
115                         $lb->commitMasterChanges();
116                         $lb->closeAll();
117                 }
118         }
119
120         /**
121          * Open a second connection to the master server, with buffering off.
122          * This will let us stream large datasets in and write in chunks on the
123          * other end.
124          * @return Database
125          * @access private
126          */
127         function streamConnection() {
128                 global $wgDBtype;
129
130                 $timeout = 3600 * 24;
131                 $db = $this->newConnection();
132                 $db->bufferResults( false );
133                 if ( $wgDBtype == 'mysql' ) {
134                         $db->query( "SET net_read_timeout=$timeout" );
135                         $db->query( "SET net_write_timeout=$timeout" );
136                 }
137                 return $db;
138         }
139
140         /**
141          * Prepare a conversion array for converting Windows Code Page 1252 to
142          * UTF-8. This should provide proper conversion of text that was miscoded
143          * as Windows-1252 by naughty user-agents, and doesn't rely on an outside
144          * iconv library.
145          *
146          * @return array
147          * @access private
148          */
149         function prepareWindows1252() {
150                 # Mappings from:
151                 # http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
152                 static $cp1252 = array(
153                         0x80 => 0x20AC, # EURO SIGN
154                         0x81 => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
155                         0x82 => 0x201A, # SINGLE LOW-9 QUOTATION MARK
156                         0x83 => 0x0192, # LATIN SMALL LETTER F WITH HOOK
157                         0x84 => 0x201E, # DOUBLE LOW-9 QUOTATION MARK
158                         0x85 => 0x2026, # HORIZONTAL ELLIPSIS
159                         0x86 => 0x2020, # DAGGER
160                         0x87 => 0x2021, # DOUBLE DAGGER
161                         0x88 => 0x02C6, # MODIFIER LETTER CIRCUMFLEX ACCENT
162                         0x89 => 0x2030, # PER MILLE SIGN
163                         0x8A => 0x0160, # LATIN CAPITAL LETTER S WITH CARON
164                         0x8B => 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
165                         0x8C => 0x0152, # LATIN CAPITAL LIGATURE OE
166                         0x8D => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
167                         0x8E => 0x017D, # LATIN CAPITAL LETTER Z WITH CARON
168                         0x8F => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
169                         0x90 => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
170                         0x91 => 0x2018, # LEFT SINGLE QUOTATION MARK
171                         0x92 => 0x2019, # RIGHT SINGLE QUOTATION MARK
172                         0x93 => 0x201C, # LEFT DOUBLE QUOTATION MARK
173                         0x94 => 0x201D, # RIGHT DOUBLE QUOTATION MARK
174                         0x95 => 0x2022, # BULLET
175                         0x96 => 0x2013, # EN DASH
176                         0x97 => 0x2014, # EM DASH
177                         0x98 => 0x02DC, # SMALL TILDE
178                         0x99 => 0x2122, # TRADE MARK SIGN
179                         0x9A => 0x0161, # LATIN SMALL LETTER S WITH CARON
180                         0x9B => 0x203A, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
181                         0x9C => 0x0153, # LATIN SMALL LIGATURE OE
182                         0x9D => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
183                         0x9E => 0x017E, # LATIN SMALL LETTER Z WITH CARON
184                         0x9F => 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS
185                         );
186                 $pairs = array();
187                 for ( $i = 0; $i < 0x100; $i++ ) {
188                         $unicode = isset( $cp1252[$i] ) ? $cp1252[$i] : $i;
189                         $pairs[chr( $i )] = codepointToUtf8( $unicode );
190                 }
191                 return $pairs;
192         }
193
194         /**
195          * Convert from 8-bit Windows-1252 to UTF-8 if necessary.
196          * @param string $text
197          * @return string
198          * @access private
199          */
200         function conv( $text ) {
201                 global $wgUseLatin1;
202                 return is_null( $text )
203                         ? null
204                         : ( $wgUseLatin1
205                                 ? strtr( $text, $this->conversionTables )
206                                 : $text );
207         }
208
209         /**
210          * Dump timestamp and message to output
211          * @param $message String
212          * @access private
213          */
214         function log( $message ) {
215                 $this->output( wfWikiID() . ' ' . wfTimestamp( TS_DB ) . ': ' . $message . "\n" );
216         }
217
218         /**
219          * Initialize the chunked-insert system.
220          * Rows will be inserted in chunks of the given number, rather
221          * than in a giant INSERT...SELECT query, to keep the serialized
222          * MySQL database replication from getting hung up. This way other
223          * things can be going on during conversion without waiting for
224          * slaves to catch up as badly.
225          *
226          * @param int $chunksize Number of rows to insert at once
227          * @param int $final Total expected number of rows / id of last row,
228          *                   used for progress reports.
229          * @param string $table to insert on
230          * @param string $fname function name to report in SQL
231          * @access private
232          */
233         function setChunkScale( $chunksize, $final, $table, $fname ) {
234                 $this->chunkSize  = $chunksize;
235                 $this->chunkFinal = $final;
236                 $this->chunkCount = 0;
237                 $this->chunkStartTime = wfTime();
238                 $this->chunkOptions = array( 'IGNORE' );
239                 $this->chunkTable = $table;
240                 $this->chunkFunction = $fname;
241         }
242
243         /**
244          * Chunked inserts: perform an insert if we've reached the chunk limit.
245          * Prints a progress report with estimated completion time.
246          * @param array &$chunk -- This will be emptied if an insert is done.
247          * @param int $key A key identifier to use in progress estimation in
248          *                 place of the number of rows inserted. Use this if
249          *                 you provided a max key number instead of a count
250          *                 as the final chunk number in setChunkScale()
251          * @access private
252          */
253         function addChunk( &$chunk, $key = null ) {
254                 if ( count( $chunk ) >= $this->chunkSize ) {
255                         $this->insertChunk( $chunk );
256
257                         $this->chunkCount += count( $chunk );
258                         $now = wfTime();
259                         $delta = $now - $this->chunkStartTime;
260                         $rate = $this->chunkCount / $delta;
261
262                         if ( is_null( $key ) ) {
263                                 $completed = $this->chunkCount;
264                         } else {
265                                 $completed = $key;
266                         }
267                         $portion = $completed / $this->chunkFinal;
268
269                         $estimatedTotalTime = $delta / $portion;
270                         $eta = $this->chunkStartTime + $estimatedTotalTime;
271
272                         printf( "%s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec\n",
273                                 wfTimestamp( TS_DB, intval( $now ) ),
274                                 $portion * 100.0,
275                                 $this->chunkTable,
276                                 wfTimestamp( TS_DB, intval( $eta ) ),
277                                 $completed,
278                                 $this->chunkFinal,
279                                 $rate );
280                         flush();
281
282                         $chunk = array();
283                 }
284         }
285
286         /**
287          * Chunked inserts: perform an insert unconditionally, at the end, and log.
288          * @param array &$chunk -- This will be emptied if an insert is done.
289          * @access private
290          */
291         function lastChunk( &$chunk ) {
292                 $n = count( $chunk );
293                 if ( $n > 0 ) {
294                         $this->insertChunk( $chunk );
295                 }
296                 $this->log( "100.00% done on $this->chunkTable (last chunk $n rows)." );
297         }
298
299         /**
300          * Chunked inserts: perform an insert.
301          * @param array &$chunk -- This will be emptied if an insert is done.
302          * @access private
303          */
304         function insertChunk( &$chunk ) {
305                 // Give slaves a chance to catch up
306                 wfWaitForSlaves( $this->maxLag );
307                 $this->dbw->insert( $this->chunkTable, $chunk, $this->chunkFunction, $this->chunkOptions );
308         }
309
310
311         /**
312          * Copy and transcode a table to table_temp.
313          * @param string $name Base name of the source table
314          * @param string $tabledef CREATE TABLE definition, w/ $1 for the name
315          * @param array $fields set of destination fields to these constants:
316          *              MW_UPGRADE_COPY   - straight copy
317          *              MW_UPGRADE_ENCODE - for old Latin1 wikis, conv to UTF-8
318          *              MW_UPGRADE_NULL   - just put NULL
319          * @param callable $callback An optional callback to modify the data
320          *                           or perform other processing. Func should be
321          *                           ( object $row, array $copy ) and return $copy
322          * @access private
323          */
324         function copyTable( $name, $tabledef, $fields, $callback = null ) {
325                 $name_temp = $name . '_temp';
326                 $this->log( "Migrating $name table to $name_temp..." );
327
328                 $table_temp = $this->dbw->tableName( $name_temp );
329
330                 // Create temporary table; we're going to copy everything in there,
331                 // then at the end rename the final tables into place.
332                 $def = str_replace( '$1', $table_temp, $tabledef );
333                 $this->dbw->query( $def, __METHOD__ );
334
335                 $numRecords = $this->dbw->selectField( $name, 'COUNT(*)', '', __METHOD__ );
336                 $this->setChunkScale( 100, $numRecords, $name_temp, __METHOD__ );
337
338                 // Pull all records from the second, streaming database connection.
339                 $sourceFields = array_keys( array_filter( $fields,
340                         create_function( '$x', 'return $x !== MW_UPGRADE_NULL;' ) ) );
341                 $result = $this->dbr->select( $name,
342                         $sourceFields,
343                         '',
344                         __METHOD__ );
345
346                 $add = array();
347                 foreach ( $result as $row ) {
348                         $copy = array();
349                         foreach ( $fields as $field => $source ) {
350                                 if ( $source === MW_UPGRADE_COPY ) {
351                                         $copy[$field] = $row->$field;
352                                 } elseif ( $source === MW_UPGRADE_ENCODE ) {
353                                         $copy[$field] = $this->conv( $row->$field );
354                                 } elseif ( $source === MW_UPGRADE_NULL ) {
355                                         $copy[$field] = null;
356                                 } else {
357                                         $this->log( "Unknown field copy type: $field => $source" );
358                                 }
359                         }
360                         if ( is_callable( $callback ) ) {
361                                 $copy = call_user_func( $callback, $row, $copy );
362                         }
363                         $add[] = $copy;
364                         $this->addChunk( $add );
365                 }
366                 $this->lastChunk( $add );
367
368                 $this->log( "Done converting $name." );
369                 $this->cleanupSwaps[] = $name;
370         }
371
372         function upgradePage() {
373                 $chunksize = 100;
374
375                 if ( $this->dbw->tableExists( 'page' ) ) {
376                         $this->error( 'Page table already exists.', true );
377                 }
378
379                 $this->log( "Checking cur table for unique title index and applying if necessary" );
380                 $this->checkDupes();
381
382                 $this->log( "...converting from cur/old to page/revision/text DB structure." );
383
384                 list ( $cur, $old, $page, $revision, $text ) = $this->dbw->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
385
386                 $this->log( "Creating page and revision tables..." );
387                 $this->dbw->query( "CREATE TABLE $page (
388                         page_id int(8) unsigned NOT NULL auto_increment,
389                         page_namespace int NOT NULL,
390                         page_title varchar(255) binary NOT NULL,
391                         page_restrictions tinyblob NOT NULL default '',
392                         page_counter bigint(20) unsigned NOT NULL default '0',
393                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
394                         page_is_new tinyint(1) unsigned NOT NULL default '0',
395                         page_random real unsigned NOT NULL,
396                         page_touched char(14) binary NOT NULL default '',
397                         page_latest int(8) unsigned NOT NULL,
398                         page_len int(8) unsigned NOT NULL,
399
400                         PRIMARY KEY page_id (page_id),
401                         UNIQUE INDEX name_title (page_namespace,page_title),
402                         INDEX (page_random),
403                         INDEX (page_len)
404                         ) TYPE=InnoDB", __METHOD__ );
405                 $this->dbw->query( "CREATE TABLE $revision (
406                         rev_id int(8) unsigned NOT NULL auto_increment,
407                         rev_page int(8) unsigned NOT NULL,
408                         rev_text_id int(8) unsigned NOT NULL,
409                         rev_comment tinyblob NOT NULL default '',
410                         rev_user int(5) unsigned NOT NULL default '0',
411                         rev_user_text varchar(255) binary NOT NULL default '',
412                         rev_timestamp char(14) binary NOT NULL default '',
413                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
414                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
415
416                         PRIMARY KEY rev_page_id (rev_page, rev_id),
417                         UNIQUE INDEX rev_id (rev_id),
418                         INDEX rev_timestamp (rev_timestamp),
419                         INDEX page_timestamp (rev_page,rev_timestamp),
420                         INDEX user_timestamp (rev_user,rev_timestamp),
421                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
422                         ) TYPE=InnoDB", __METHOD__ );
423
424                 $maxold = intval( $this->dbw->selectField( 'old', 'max(old_id)', '', __METHOD__ ) );
425                 $this->log( "Last old record is {$maxold}" );
426
427                 global $wgLegacySchemaConversion;
428                 if ( $wgLegacySchemaConversion ) {
429                         // Create HistoryBlobCurStub entries.
430                         // Text will be pulled from the leftover 'cur' table at runtime.
431                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
432                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
433                         $cur_flags = "'object'";
434                 } else {
435                         // Copy all cur text in immediately: this may take longer but avoids
436                         // having to keep an extra table around.
437                         echo "......Moving text from cur.\n";
438                         $cur_text = 'cur_text';
439                         $cur_flags = "''";
440                 }
441
442                 $maxcur = $this->dbw->selectField( 'cur', 'max(cur_id)', '', __METHOD__ );
443                 $this->log( "Last cur entry is $maxcur" );
444
445                 /**
446                  * Copy placeholder records for each page's current version into old
447                  * Don't do any conversion here; text records are converted at runtime
448                  * based on the flags (and may be originally binary!) while the meta
449                  * fields will be converted in the old -> rev and cur -> page steps.
450                  */
451                 $this->setChunkScale( $chunksize, $maxcur, 'old', __METHOD__ );
452                 $result = $this->dbr->query(
453                         "SELECT cur_id, cur_namespace, cur_title, $cur_text AS text, cur_comment,
454                         cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags AS flags
455                         FROM $cur
456                         ORDER BY cur_id", __METHOD__ );
457                 $add = array();
458                 foreach ( $result as $row ) {
459                         $add[] = array(
460                                 'old_namespace'  => $row->cur_namespace,
461                                 'old_title'      => $row->cur_title,
462                                 'old_text'       => $row->text,
463                                 'old_comment'    => $row->cur_comment,
464                                 'old_user'       => $row->cur_user,
465                                 'old_user_text'  => $row->cur_user_text,
466                                 'old_timestamp'  => $row->cur_timestamp,
467                                 'old_minor_edit' => $row->cur_minor_edit,
468                                 'old_flags'      => $row->flags );
469                         $this->addChunk( $add, $row->cur_id );
470                 }
471                 $this->lastChunk( $add );
472
473                 /**
474                  * Copy revision metadata from old into revision.
475                  * We'll also do UTF-8 conversion of usernames and comments.
476                  */
477                 # $newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', __METHOD__ );
478                 # $this->setChunkScale( $chunksize, $newmaxold, 'revision', __METHOD__ );
479                 # $countold = $this->dbw->selectField( 'old', 'count(old_id)', '', __METHOD__ );
480                 $countold = $this->dbw->selectField( 'old', 'max(old_id)', '', __METHOD__ );
481                 $this->setChunkScale( $chunksize, $countold, 'revision', __METHOD__ );
482
483                 $this->log( "......Setting up revision table." );
484                 $result = $this->dbr->query(
485                         "SELECT old_id, cur_id, old_comment, old_user, old_user_text,
486                         old_timestamp, old_minor_edit
487                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title",
488                         __METHOD__ );
489
490                 $add = array();
491                 foreach ( $result as $row ) {
492                         $add[] = array(
493                                 'rev_id'         =>              $row->old_id,
494                                 'rev_page'       =>              $row->cur_id,
495                                 'rev_text_id'    =>              $row->old_id,
496                                 'rev_comment'    => $this->conv( $row->old_comment ),
497                                 'rev_user'       =>              $row->old_user,
498                                 'rev_user_text'  => $this->conv( $row->old_user_text ),
499                                 'rev_timestamp'  =>              $row->old_timestamp,
500                                 'rev_minor_edit' =>              $row->old_minor_edit );
501                         $this->addChunk( $add );
502                 }
503                 $this->lastChunk( $add );
504
505
506                 /**
507                  * Copy page metadata from cur into page.
508                  * We'll also do UTF-8 conversion of titles.
509                  */
510                 $this->log( "......Setting up page table." );
511                 $this->setChunkScale( $chunksize, $maxcur, 'page', __METHOD__ );
512                 $result = $this->dbr->query( "
513                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
514                                         cur_random, cur_touched, rev_id, LENGTH(cur_text) AS len
515                         FROM $cur,$revision
516                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}
517                         ORDER BY cur_id", __METHOD__ );
518                 $add = array();
519                 foreach ( $result as $row ) {
520                         $add[] = array(
521                                 'page_id'           =>              $row->cur_id,
522                                 'page_namespace'    =>              $row->cur_namespace,
523                                 'page_title'        => $this->conv( $row->cur_title ),
524                                 'page_restrictions' =>              $row->cur_restrictions,
525                                 'page_counter'      =>              $row->cur_counter,
526                                 'page_is_redirect'  =>              $row->cur_is_redirect,
527                                 'page_is_new'       =>              $row->cur_is_new,
528                                 'page_random'       =>              $row->cur_random,
529                                 'page_touched'      =>              $this->dbw->timestamp(),
530                                 'page_latest'       =>              $row->rev_id,
531                                 'page_len'          =>              $row->len );
532                         # $this->addChunk( $add, $row->cur_id );
533                         $this->addChunk( $add );
534                 }
535                 $this->lastChunk( $add );
536
537                 $this->log( "...done with cur/old -> page/revision." );
538         }
539
540         function upgradeLinks() {
541                 $chunksize = 200;
542                 list ( $links, $brokenlinks, $pagelinks, $cur ) = $this->dbw->tableNamesN( 'links', 'brokenlinks', 'pagelinks', 'cur' );
543
544                 $this->log( 'Checking for interwiki table change in case of bogus items...' );
545                 if ( $this->dbw->fieldExists( 'interwiki', 'iw_trans' ) ) {
546                         $this->log( 'interwiki has iw_trans.' );
547                 } else {
548                         global $IP;
549                         $this->log( 'adding iw_trans...' );
550                         $this->dbw->sourceFile( $IP . '/maintenance/archives/patch-interwiki-trans.sql' );
551                         $this->log( 'added iw_trans.' );
552                 }
553
554                 $this->log( 'Creating pagelinks table...' );
555                 $this->dbw->query( "
556 CREATE TABLE $pagelinks (
557   -- Key to the page_id of the page containing the link.
558   pl_from int(8) unsigned NOT NULL default '0',
559
560   -- Key to page_namespace/page_title of the target page.
561   -- The target page may or may not exist, and due to renames
562   -- and deletions may refer to different page records as time
563   -- goes by.
564   pl_namespace int NOT NULL default '0',
565   pl_title varchar(255) binary NOT NULL default '',
566
567   UNIQUE KEY pl_from(pl_from,pl_namespace,pl_title),
568   KEY (pl_namespace,pl_title)
569
570 ) TYPE=InnoDB" );
571
572                 $this->log( 'Importing live links -> pagelinks' );
573                 $nlinks = $this->dbw->selectField( 'links', 'count(*)', '', __METHOD__ );
574                 if ( $nlinks ) {
575                         $this->setChunkScale( $chunksize, $nlinks, 'pagelinks', __METHOD__ );
576                         $result = $this->dbr->query( "
577                           SELECT l_from,cur_namespace,cur_title
578                                 FROM $links, $cur
579                                 WHERE l_to=cur_id", __METHOD__ );
580                         $add = array();
581                         foreach ( $result as $row ) {
582                                 $add[] = array(
583                                         'pl_from'      =>              $row->l_from,
584                                         'pl_namespace' =>              $row->cur_namespace,
585                                         'pl_title'     => $this->conv( $row->cur_title ) );
586                                 $this->addChunk( $add );
587                         }
588                         $this->lastChunk( $add );
589                 } else {
590                         $this->log( 'no links!' );
591                 }
592
593                 $this->log( 'Importing brokenlinks -> pagelinks' );
594                 $nbrokenlinks = $this->dbw->selectField( 'brokenlinks', 'count(*)', '', __METHOD__ );
595                 if ( $nbrokenlinks ) {
596                         $this->setChunkScale( $chunksize, $nbrokenlinks, 'pagelinks', __METHOD__ );
597                         $result = $this->dbr->query(
598                                 "SELECT bl_from, bl_to FROM $brokenlinks",
599                                 __METHOD__ );
600                         $add = array();
601                         foreach ( $result as $row ) {
602                                 $pagename = $this->conv( $row->bl_to );
603                                 $title = Title::newFromText( $pagename );
604                                 if ( is_null( $title ) ) {
605                                         $this->log( "** invalid brokenlink: $row->bl_from -> '$pagename' (converted from '$row->bl_to')" );
606                                 } else {
607                                         $add[] = array(
608                                                 'pl_from'      => $row->bl_from,
609                                                 'pl_namespace' => $title->getNamespace(),
610                                                 'pl_title'     => $title->getDBkey() );
611                                         $this->addChunk( $add );
612                                 }
613                         }
614                         $this->lastChunk( $add );
615                 } else {
616                         $this->log( 'no brokenlinks!' );
617                 }
618
619                 $this->log( 'Done with links.' );
620         }
621
622         function userDupeCallback( $str ) {
623                 echo $str;
624         }
625
626         function upgradeUser() {
627                 // Apply unique index, if necessary:
628                 $duper = new UserDupes( $this->dbw, array( $this, 'userDupeCallback' ) );
629                 if ( $duper->hasUniqueIndex() ) {
630                         $this->log( "Already have unique user_name index." );
631                 } else {
632                         $this->log( "Clearing user duplicates..." );
633                         if ( !$duper->clearDupes() ) {
634                                 $this->log( "WARNING: Duplicate user accounts, may explode!" );
635                         }
636                 }
637
638                 $tabledef = <<<END
639 CREATE TABLE $1 (
640   user_id int(5) unsigned NOT NULL auto_increment,
641   user_name varchar(255) binary NOT NULL default '',
642   user_real_name varchar(255) binary NOT NULL default '',
643   user_password tinyblob NOT NULL default '',
644   user_newpassword tinyblob NOT NULL default '',
645   user_email tinytext NOT NULL default '',
646   user_options blob NOT NULL default '',
647   user_touched char(14) binary NOT NULL default '',
648   user_token char(32) binary NOT NULL default '',
649   user_email_authenticated CHAR(14) BINARY,
650   user_email_token CHAR(32) BINARY,
651   user_email_token_expires CHAR(14) BINARY,
652
653   PRIMARY KEY user_id (user_id),
654   UNIQUE INDEX user_name (user_name),
655   INDEX (user_email_token)
656
657 ) TYPE=InnoDB
658 END;
659                 $fields = array(
660                         'user_id'                  => MW_UPGRADE_COPY,
661                         'user_name'                => MW_UPGRADE_ENCODE,
662                         'user_real_name'           => MW_UPGRADE_ENCODE,
663                         'user_password'            => MW_UPGRADE_COPY,
664                         'user_newpassword'         => MW_UPGRADE_COPY,
665                         'user_email'               => MW_UPGRADE_ENCODE,
666                         'user_options'             => MW_UPGRADE_ENCODE,
667                         'user_touched'             => MW_UPGRADE_CALLBACK,
668                         'user_token'               => MW_UPGRADE_COPY,
669                         'user_email_authenticated' => MW_UPGRADE_CALLBACK,
670                         'user_email_token'         => MW_UPGRADE_NULL,
671                         'user_email_token_expires' => MW_UPGRADE_NULL );
672                 $this->copyTable( 'user', $tabledef, $fields,
673                         array( &$this, 'userCallback' ) );
674         }
675
676         function userCallback( $row, $copy ) {
677                 $now = $this->dbw->timestamp();
678                 $copy['user_touched'] = $now;
679                 $copy['user_email_authenticated'] = $this->emailAuth ? $now : null;
680                 return $copy;
681         }
682
683         function upgradeImage() {
684                 $tabledef = <<<END
685 CREATE TABLE $1 (
686   img_name varchar(255) binary NOT NULL default '',
687   img_size int(8) unsigned NOT NULL default '0',
688   img_width int(5)  NOT NULL default '0',
689   img_height int(5)  NOT NULL default '0',
690   img_metadata mediumblob NOT NULL,
691   img_bits int(3)  NOT NULL default '0',
692   img_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL,
693   img_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown",
694   img_minor_mime varchar(32) NOT NULL default "unknown",
695   img_description tinyblob NOT NULL default '',
696   img_user int(5) unsigned NOT NULL default '0',
697   img_user_text varchar(255) binary NOT NULL default '',
698   img_timestamp char(14) binary NOT NULL default '',
699
700   PRIMARY KEY img_name (img_name),
701   INDEX img_size (img_size),
702   INDEX img_timestamp (img_timestamp)
703 ) TYPE=InnoDB
704 END;
705                 $fields = array(
706                         'img_name'        => MW_UPGRADE_ENCODE,
707                         'img_size'        => MW_UPGRADE_COPY,
708                         'img_width'       => MW_UPGRADE_CALLBACK,
709                         'img_height'      => MW_UPGRADE_CALLBACK,
710                         'img_metadata'    => MW_UPGRADE_CALLBACK,
711                         'img_bits'        => MW_UPGRADE_CALLBACK,
712                         'img_media_type'  => MW_UPGRADE_CALLBACK,
713                         'img_major_mime'  => MW_UPGRADE_CALLBACK,
714                         'img_minor_mime'  => MW_UPGRADE_CALLBACK,
715                         'img_description' => MW_UPGRADE_ENCODE,
716                         'img_user'        => MW_UPGRADE_COPY,
717                         'img_user_text'   => MW_UPGRADE_ENCODE,
718                         'img_timestamp'   => MW_UPGRADE_COPY );
719                 $this->copyTable( 'image', $tabledef, $fields,
720                         array( &$this, 'imageCallback' ) );
721         }
722
723         function imageCallback( $row, $copy ) {
724                 if ( !$this->hasOption( 'noimage' ) ) {
725                         // Fill in the new image info fields
726                         $info = $this->imageInfo( $row->img_name );
727
728                         $copy['img_width'     ] = $info['width'];
729                         $copy['img_height'    ] = $info['height'];
730                         $copy['img_metadata'  ] = ""; // loaded on-demand
731                         $copy['img_bits'      ] = $info['bits'];
732                         $copy['img_media_type'] = $info['media'];
733                         $copy['img_major_mime'] = $info['major'];
734                         $copy['img_minor_mime'] = $info['minor'];
735                 }
736
737                 // If doing UTF8 conversion the file must be renamed
738                 $this->renameFile( $row->img_name, 'wfImageDir' );
739
740                 return $copy;
741         }
742
743         function imageInfo( $filename ) {
744                 $info = array(
745                         'width'  => 0,
746                         'height' => 0,
747                         'bits'   => 0,
748                         'media'  => '',
749                         'major'  => '',
750                         'minor'  => '' );
751
752                 $magic = MimeMagic::singleton();
753                 $mime = $magic->guessMimeType( $filename, true );
754                 list( $info['major'], $info['minor'] ) = explode( '/', $mime );
755
756                 $info['media'] = $magic->getMediaType( $filename, $mime );
757
758                 $image = UnregisteredLocalFile::newFromPath( $filename, $mime );
759
760                 $info['width'] = $image->getWidth();
761                 $info['height'] = $image->getHeight();
762
763                 $gis = $image->getImageSize( $filename );
764                 if ( isset( $gis['bits'] ) ) {
765                         $info['bits'] = $gis['bits'];
766                 }
767
768                 return $info;
769         }
770
771
772         /**
773          * Truncate a table.
774          * @param string $table The table name to be truncated
775          */
776         function clearTable( $table ) {
777                 print "Clearing $table...\n";
778                 $tableName = $this->db->tableName( $table );
779                 $this->db->query( "TRUNCATE $tableName" );
780         }
781
782         /**
783          * Rename a given image or archived image file to the converted filename,
784          * leaving a symlink for URL compatibility.
785          *
786          * @param string $oldname pre-conversion filename
787          * @param string $basename pre-conversion base filename for dir hashing, if an archive
788          * @access private
789          */
790         function renameFile( $oldname, $subdirCallback = 'wfImageDir', $basename = null ) {
791                 $newname = $this->conv( $oldname );
792                 if ( $newname == $oldname ) {
793                         // No need to rename; another field triggered this row.
794                         return false;
795                 }
796
797                 if ( is_null( $basename ) ) $basename = $oldname;
798                 $ubasename = $this->conv( $basename );
799                 $oldpath = call_user_func( $subdirCallback, $basename ) . '/' . $oldname;
800                 $newpath = call_user_func( $subdirCallback, $ubasename ) . '/' . $newname;
801
802                 $this->log( "$oldpath -> $newpath" );
803                 if ( rename( $oldpath, $newpath ) ) {
804                         $relpath = wfRelativePath( $newpath, dirname( $oldpath ) );
805                         if ( !symlink( $relpath, $oldpath ) ) {
806                                 $this->log( "... symlink failed!" );
807                         }
808                         return $newname;
809                 } else {
810                         $this->log( "... rename failed!" );
811                         return false;
812                 }
813         }
814
815         function upgradeOldImage() {
816                 $tabledef = <<<END
817 CREATE TABLE $1 (
818   -- Base filename: key to image.img_name
819   oi_name varchar(255) binary NOT NULL default '',
820
821   -- Filename of the archived file.
822   -- This is generally a timestamp and '!' prepended to the base name.
823   oi_archive_name varchar(255) binary NOT NULL default '',
824
825   -- Other fields as in image...
826   oi_size int(8) unsigned NOT NULL default 0,
827   oi_width int(5) NOT NULL default 0,
828   oi_height int(5) NOT NULL default 0,
829   oi_bits int(3) NOT NULL default 0,
830   oi_description tinyblob NOT NULL default '',
831   oi_user int(5) unsigned NOT NULL default '0',
832   oi_user_text varchar(255) binary NOT NULL default '',
833   oi_timestamp char(14) binary NOT NULL default '',
834
835   INDEX oi_name (oi_name(10))
836
837 ) TYPE=InnoDB;
838 END;
839                 $fields = array(
840                         'oi_name'         => MW_UPGRADE_ENCODE,
841                         'oi_archive_name' => MW_UPGRADE_ENCODE,
842                         'oi_size'         => MW_UPGRADE_COPY,
843                         'oi_width'        => MW_UPGRADE_CALLBACK,
844                         'oi_height'       => MW_UPGRADE_CALLBACK,
845                         'oi_bits'         => MW_UPGRADE_CALLBACK,
846                         'oi_description'  => MW_UPGRADE_ENCODE,
847                         'oi_user'         => MW_UPGRADE_COPY,
848                         'oi_user_text'    => MW_UPGRADE_ENCODE,
849                         'oi_timestamp'    => MW_UPGRADE_COPY );
850                 $this->copyTable( 'oldimage', $tabledef, $fields,
851                         array( &$this, 'oldimageCallback' ) );
852         }
853
854         function oldimageCallback( $row, $copy ) {
855                 global $options;
856                 if ( !isset( $options['noimage'] ) ) {
857                         // Fill in the new image info fields
858                         $info = $this->imageInfo( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
859                         $copy['oi_width' ] = $info['width' ];
860                         $copy['oi_height'] = $info['height'];
861                         $copy['oi_bits'  ] = $info['bits'  ];
862                 }
863
864                 // If doing UTF8 conversion the file must be renamed
865                 $this->renameFile( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
866
867                 return $copy;
868         }
869
870
871         function upgradeWatchlist() {
872                 $chunksize = 100;
873
874                 list ( $watchlist, $watchlist_temp ) = $this->dbw->tableNamesN( 'watchlist', 'watchlist_temp' );
875
876                 $this->log( 'Migrating watchlist table to watchlist_temp...' );
877                 $this->dbw->query(
878 "CREATE TABLE $watchlist_temp (
879   -- Key to user_id
880   wl_user int(5) unsigned NOT NULL,
881
882   -- Key to page_namespace/page_title
883   -- Note that users may watch patches which do not exist yet,
884   -- or existed in the past but have been deleted.
885   wl_namespace int NOT NULL default '0',
886   wl_title varchar(255) binary NOT NULL default '',
887
888   -- Timestamp when user was last sent a notification e-mail;
889   -- cleared when the user visits the page.
890   -- FIXME: add proper null support etc
891   wl_notificationtimestamp varchar(14) binary NOT NULL default '0',
892
893   UNIQUE KEY (wl_user, wl_namespace, wl_title),
894   KEY namespace_title (wl_namespace,wl_title)
895
896 ) TYPE=InnoDB;", __METHOD__ );
897
898                 // Fix encoding for Latin-1 upgrades, add some fields,
899                 // and double article to article+talk pairs
900                 $numwatched = $this->dbw->selectField( 'watchlist', 'count(*)', '', __METHOD__ );
901
902                 $this->setChunkScale( $chunksize, $numwatched * 2, 'watchlist_temp', __METHOD__ );
903                 $result = $this->dbr->select( 'watchlist',
904                         array(
905                                 'wl_user',
906                                 'wl_namespace',
907                                 'wl_title' ),
908                         '',
909                         __METHOD__ );
910
911                 $add = array();
912                 foreach ( $result as $row ) {
913                         $add[] = array(
914                                 'wl_user'      =>                          $row->wl_user,
915                                 'wl_namespace' => MWNamespace::getSubject( $row->wl_namespace ),
916                                 'wl_title'     =>             $this->conv( $row->wl_title ),
917                                 'wl_notificationtimestamp' =>              '0' );
918                         $this->addChunk( $add );
919
920                         $add[] = array(
921                                 'wl_user'      =>                          $row->wl_user,
922                                 'wl_namespace' =>    MWNamespace::getTalk( $row->wl_namespace ),
923                                 'wl_title'     =>             $this->conv( $row->wl_title ),
924                                 'wl_notificationtimestamp' =>              '0' );
925                         $this->addChunk( $add );
926                 }
927                 $this->lastChunk( $add );
928
929                 $this->log( 'Done converting watchlist.' );
930                 $this->cleanupSwaps[] = 'watchlist';
931         }
932
933         function upgradeLogging() {
934                 $tabledef = <<<ENDS
935 CREATE TABLE $1 (
936   -- Symbolic keys for the general log type and the action type
937   -- within the log. The output format will be controlled by the
938   -- action field, but only the type controls categorization.
939   log_type char(10) NOT NULL default '',
940   log_action char(10) NOT NULL default '',
941
942   -- Timestamp. Duh.
943   log_timestamp char(14) NOT NULL default '19700101000000',
944
945   -- The user who performed this action; key to user_id
946   log_user int unsigned NOT NULL default 0,
947
948   -- Key to the page affected. Where a user is the target,
949   -- this will point to the user page.
950   log_namespace int NOT NULL default 0,
951   log_title varchar(255) binary NOT NULL default '',
952
953   -- Freeform text. Interpreted as edit history comments.
954   log_comment varchar(255) NOT NULL default '',
955
956   -- LF separated list of miscellaneous parameters
957   log_params blob NOT NULL default '',
958
959   KEY type_time (log_type, log_timestamp),
960   KEY user_time (log_user, log_timestamp),
961   KEY page_time (log_namespace, log_title, log_timestamp)
962
963 ) TYPE=InnoDB
964 ENDS;
965                 $fields = array(
966                         'log_type'      => MW_UPGRADE_COPY,
967                         'log_action'    => MW_UPGRADE_COPY,
968                         'log_timestamp' => MW_UPGRADE_COPY,
969                         'log_user'      => MW_UPGRADE_COPY,
970                         'log_namespace' => MW_UPGRADE_COPY,
971                         'log_title'     => MW_UPGRADE_ENCODE,
972                         'log_comment'   => MW_UPGRADE_ENCODE,
973                         'log_params'    => MW_UPGRADE_ENCODE );
974                 $this->copyTable( 'logging', $tabledef, $fields );
975         }
976
977         function upgradeArchive() {
978                 $tabledef = <<<ENDS
979 CREATE TABLE $1 (
980   ar_namespace int NOT NULL default '0',
981   ar_title varchar(255) binary NOT NULL default '',
982   ar_text mediumblob NOT NULL default '',
983
984   ar_comment tinyblob NOT NULL default '',
985   ar_user int(5) unsigned NOT NULL default '0',
986   ar_user_text varchar(255) binary NOT NULL,
987   ar_timestamp char(14) binary NOT NULL default '',
988   ar_minor_edit tinyint(1) NOT NULL default '0',
989
990   ar_flags tinyblob NOT NULL default '',
991
992   ar_rev_id int(8) unsigned,
993   ar_text_id int(8) unsigned,
994
995   KEY name_title_timestamp (ar_namespace,ar_title,ar_timestamp)
996
997 ) TYPE=InnoDB
998 ENDS;
999                 $fields = array(
1000                         'ar_namespace'  => MW_UPGRADE_COPY,
1001                         'ar_title'      => MW_UPGRADE_ENCODE,
1002                         'ar_text'       => MW_UPGRADE_COPY,
1003                         'ar_comment'    => MW_UPGRADE_ENCODE,
1004                         'ar_user'       => MW_UPGRADE_COPY,
1005                         'ar_user_text'  => MW_UPGRADE_ENCODE,
1006                         'ar_timestamp'  => MW_UPGRADE_COPY,
1007                         'ar_minor_edit' => MW_UPGRADE_COPY,
1008                         'ar_flags'      => MW_UPGRADE_COPY,
1009                         'ar_rev_id'     => MW_UPGRADE_NULL,
1010                         'ar_text_id'    => MW_UPGRADE_NULL );
1011                 $this->copyTable( 'archive', $tabledef, $fields );
1012         }
1013
1014         function upgradeImagelinks() {
1015                 global $wgUseLatin1;
1016                 if ( $wgUseLatin1 ) {
1017                         $tabledef = <<<ENDS
1018 CREATE TABLE $1 (
1019   -- Key to page_id of the page containing the image / media link.
1020   il_from int(8) unsigned NOT NULL default '0',
1021
1022   -- Filename of target image.
1023   -- This is also the page_title of the file's description page;
1024   -- all such pages are in namespace 6 (NS_FILE).
1025   il_to varchar(255) binary NOT NULL default '',
1026
1027   UNIQUE KEY il_from(il_from,il_to),
1028   KEY (il_to)
1029
1030 ) TYPE=InnoDB
1031 ENDS;
1032                         $fields = array(
1033                                 'il_from' => MW_UPGRADE_COPY,
1034                                 'il_to'   => MW_UPGRADE_ENCODE );
1035                         $this->copyTable( 'imagelinks', $tabledef, $fields );
1036                 }
1037         }
1038
1039         function upgradeCategorylinks() {
1040                 global $wgUseLatin1;
1041                 if ( $wgUseLatin1 ) {
1042                         $tabledef = <<<ENDS
1043 CREATE TABLE $1 (
1044   cl_from int(8) unsigned NOT NULL default '0',
1045   cl_to varchar(255) binary NOT NULL default '',
1046   cl_sortkey varchar(86) binary NOT NULL default '',
1047   cl_timestamp timestamp NOT NULL,
1048
1049   UNIQUE KEY cl_from(cl_from,cl_to),
1050   KEY cl_sortkey(cl_to,cl_sortkey),
1051   KEY cl_timestamp(cl_to,cl_timestamp)
1052 ) TYPE=InnoDB
1053 ENDS;
1054                         $fields = array(
1055                                 'cl_from'      => MW_UPGRADE_COPY,
1056                                 'cl_to'        => MW_UPGRADE_ENCODE,
1057                                 'cl_sortkey'   => MW_UPGRADE_ENCODE,
1058                                 'cl_timestamp' => MW_UPGRADE_COPY );
1059                         $this->copyTable( 'categorylinks', $tabledef, $fields );
1060                 }
1061         }
1062
1063         function upgradeIpblocks() {
1064                 global $wgUseLatin1;
1065                 if ( $wgUseLatin1 ) {
1066                         $tabledef = <<<ENDS
1067 CREATE TABLE $1 (
1068   ipb_id int(8) NOT NULL auto_increment,
1069   ipb_address varchar(40) binary NOT NULL default '',
1070   ipb_user int(8) unsigned NOT NULL default '0',
1071   ipb_by int(8) unsigned NOT NULL default '0',
1072   ipb_reason tinyblob NOT NULL default '',
1073   ipb_timestamp char(14) binary NOT NULL default '',
1074   ipb_auto tinyint(1) NOT NULL default '0',
1075   ipb_expiry char(14) binary NOT NULL default '',
1076
1077   PRIMARY KEY ipb_id (ipb_id),
1078   INDEX ipb_address (ipb_address),
1079   INDEX ipb_user (ipb_user)
1080
1081 ) TYPE=InnoDB
1082 ENDS;
1083                         $fields = array(
1084                                 'ipb_id'        => MW_UPGRADE_COPY,
1085                                 'ipb_address'   => MW_UPGRADE_COPY,
1086                                 'ipb_user'      => MW_UPGRADE_COPY,
1087                                 'ipb_by'        => MW_UPGRADE_COPY,
1088                                 'ipb_reason'    => MW_UPGRADE_ENCODE,
1089                                 'ipb_timestamp' => MW_UPGRADE_COPY,
1090                                 'ipb_auto'      => MW_UPGRADE_COPY,
1091                                 'ipb_expiry'    => MW_UPGRADE_COPY );
1092                         $this->copyTable( 'ipblocks', $tabledef, $fields );
1093                 }
1094         }
1095
1096         function upgradeRecentchanges() {
1097                 // There's a format change in the namespace field
1098                 $tabledef = <<<ENDS
1099 CREATE TABLE $1 (
1100   rc_id int(8) NOT NULL auto_increment,
1101   rc_timestamp varchar(14) binary NOT NULL default '',
1102   rc_cur_time varchar(14) binary NOT NULL default '',
1103
1104   rc_user int(10) unsigned NOT NULL default '0',
1105   rc_user_text varchar(255) binary NOT NULL default '',
1106
1107   rc_namespace int NOT NULL default '0',
1108   rc_title varchar(255) binary NOT NULL default '',
1109
1110   rc_comment varchar(255) binary NOT NULL default '',
1111   rc_minor tinyint(3) unsigned NOT NULL default '0',
1112
1113   rc_bot tinyint(3) unsigned NOT NULL default '0',
1114   rc_new tinyint(3) unsigned NOT NULL default '0',
1115
1116   rc_cur_id int(10) unsigned NOT NULL default '0',
1117   rc_this_oldid int(10) unsigned NOT NULL default '0',
1118   rc_last_oldid int(10) unsigned NOT NULL default '0',
1119
1120   rc_type tinyint(3) unsigned NOT NULL default '0',
1121   rc_moved_to_ns tinyint(3) unsigned NOT NULL default '0',
1122   rc_moved_to_title varchar(255) binary NOT NULL default '',
1123
1124   rc_patrolled tinyint(3) unsigned NOT NULL default '0',
1125
1126   rc_ip char(15) NOT NULL default '',
1127
1128   PRIMARY KEY rc_id (rc_id),
1129   INDEX rc_timestamp (rc_timestamp),
1130   INDEX rc_namespace_title (rc_namespace, rc_title),
1131   INDEX rc_cur_id (rc_cur_id),
1132   INDEX new_name_timestamp(rc_new,rc_namespace,rc_timestamp),
1133   INDEX rc_ip (rc_ip)
1134
1135 ) TYPE=InnoDB
1136 ENDS;
1137                 $fields = array(
1138                         'rc_id'             => MW_UPGRADE_COPY,
1139                         'rc_timestamp'      => MW_UPGRADE_COPY,
1140                         'rc_cur_time'       => MW_UPGRADE_COPY,
1141                         'rc_user'           => MW_UPGRADE_COPY,
1142                         'rc_user_text'      => MW_UPGRADE_ENCODE,
1143                         'rc_namespace'      => MW_UPGRADE_COPY,
1144                         'rc_title'          => MW_UPGRADE_ENCODE,
1145                         'rc_comment'        => MW_UPGRADE_ENCODE,
1146                         'rc_minor'          => MW_UPGRADE_COPY,
1147                         'rc_bot'            => MW_UPGRADE_COPY,
1148                         'rc_new'            => MW_UPGRADE_COPY,
1149                         'rc_cur_id'         => MW_UPGRADE_COPY,
1150                         'rc_this_oldid'     => MW_UPGRADE_COPY,
1151                         'rc_last_oldid'     => MW_UPGRADE_COPY,
1152                         'rc_type'           => MW_UPGRADE_COPY,
1153                         'rc_moved_to_ns'    => MW_UPGRADE_COPY,
1154                         'rc_moved_to_title' => MW_UPGRADE_ENCODE,
1155                         'rc_patrolled'      => MW_UPGRADE_COPY,
1156                         'rc_ip'             => MW_UPGRADE_COPY );
1157                 $this->copyTable( 'recentchanges', $tabledef, $fields );
1158         }
1159
1160         function upgradeQuerycache() {
1161                 // There's a format change in the namespace field
1162                 $tabledef = <<<ENDS
1163 CREATE TABLE $1 (
1164   -- A key name, generally the base name of of the special page.
1165   qc_type char(32) NOT NULL,
1166
1167   -- Some sort of stored value. Sizes, counts...
1168   qc_value int(5) unsigned NOT NULL default '0',
1169
1170   -- Target namespace+title
1171   qc_namespace int NOT NULL default '0',
1172   qc_title char(255) binary NOT NULL default '',
1173
1174   KEY (qc_type,qc_value)
1175
1176 ) TYPE=InnoDB
1177 ENDS;
1178                 $fields = array(
1179                         'qc_type'      => MW_UPGRADE_COPY,
1180                         'qc_value'     => MW_UPGRADE_COPY,
1181                         'qc_namespace' => MW_UPGRADE_COPY,
1182                         'qc_title'     => MW_UPGRADE_ENCODE );
1183                 $this->copyTable( 'querycache', $tabledef, $fields );
1184         }
1185
1186         /**
1187          * Check for duplicate rows in "cur" table and move duplicates entries in
1188          * "old" table.
1189          *
1190          * This was in cleanupDupes.inc before.
1191          */
1192         function checkDupes() {
1193                 $dbw = wfGetDB( DB_MASTER );
1194                 if ( $dbw->indexExists( 'cur', 'name_title' ) &&
1195                         $dbw->indexUnique( 'cur', 'name_title' ) ) {
1196                         echo wfWikiID() . ": cur table has the current unique index; no duplicate entries.\n";
1197                         return;
1198                 } elseif ( $dbw->indexExists( 'cur', 'name_title_dup_prevention' ) ) {
1199                         echo wfWikiID() . ": cur table has a temporary name_title_dup_prevention unique index; no duplicate entries.\n";
1200                         return;
1201                 }
1202
1203                 echo wfWikiID() . ": cur table has the old non-unique index and may have duplicate entries.\n";
1204
1205                 $dbw = wfGetDB( DB_MASTER );
1206                 $cur = $dbw->tableName( 'cur' );
1207                 $old = $dbw->tableName( 'old' );
1208                 $dbw->query( "LOCK TABLES $cur WRITE, $old WRITE" );
1209                 echo "Checking for duplicate cur table entries... (this may take a while on a large wiki)\n";
1210                 $res = $dbw->query( <<<END
1211 SELECT cur_namespace,cur_title,count(*) as c,min(cur_id) as id
1212   FROM $cur
1213  GROUP BY cur_namespace,cur_title
1214 HAVING c > 1
1215 END
1216                 );
1217                 $n = $dbw->numRows( $res );
1218                 echo "Found $n titles with duplicate entries.\n";
1219                 if ( $n > 0 ) {
1220                         echo "Correcting...\n";
1221                         foreach ( $res as $row ) {
1222                                 $ns = intval( $row->cur_namespace );
1223                                 $title = $dbw->addQuotes( $row->cur_title );
1224
1225                                 # Get the first responding ID; that'll be the one we keep.
1226                                 $id = $dbw->selectField( 'cur', 'cur_id', array(
1227                                         'cur_namespace' => $row->cur_namespace,
1228                                         'cur_title'     => $row->cur_title ) );
1229
1230                                 echo "$ns:$row->cur_title (canonical ID $id)\n";
1231                                 if ( $id != $row->id ) {
1232                                         echo "  ** minimum ID $row->id; ";
1233                                         $timeMin = $dbw->selectField( 'cur', 'cur_timestamp', array(
1234                                                 'cur_id' => $row->id ) );
1235                                         $timeFirst = $dbw->selectField( 'cur', 'cur_timestamp', array(
1236                                                 'cur_id' => $id ) );
1237                                         if ( $timeMin == $timeFirst ) {
1238                                                 echo "timestamps match at $timeFirst; ok\n";
1239                                         } else {
1240                                                 echo "timestamps don't match! min: $timeMin, first: $timeFirst; ";
1241                                                 if ( $timeMin > $timeFirst ) {
1242                                                         $id = $row->id;
1243                                                         echo "keeping minimum: $id\n";
1244                                                 } else {
1245                                                         echo "keeping first: $id\n";
1246                                                 }
1247                                         }
1248                                 }
1249
1250                                 $dbw->query( <<<END
1251 INSERT
1252   INTO $old
1253           (old_namespace, old_title,      old_text,
1254            old_comment,   old_user,       old_user_text,
1255            old_timestamp, old_minor_edit, old_flags,
1256            inverse_timestamp)
1257 SELECT cur_namespace, cur_title,      cur_text,
1258            cur_comment,   cur_user,       cur_user_text,
1259            cur_timestamp, cur_minor_edit, '',
1260            inverse_timestamp
1261   FROM $cur
1262  WHERE cur_namespace=$ns
1263    AND cur_title=$title
1264    AND cur_id != $id
1265 END
1266                                 );
1267                                 $dbw->query( <<<END
1268 DELETE
1269   FROM $cur
1270  WHERE cur_namespace=$ns
1271    AND cur_title=$title
1272    AND cur_id != $id
1273 END
1274                                         );
1275                         }
1276                 }
1277                 $dbw->query( 'UNLOCK TABLES' );
1278                 echo "Done.\n";
1279         }
1280
1281         /**
1282          * Rename all our temporary tables into final place.
1283          * We've left things in place so a read-only wiki can continue running
1284          * on the old code during all this.
1285          */
1286         function upgradeCleanup() {
1287                 $this->renameTable( 'old', 'text' );
1288
1289                 foreach ( $this->cleanupSwaps as $table ) {
1290                         $this->swap( $table );
1291                 }
1292         }
1293
1294         function renameTable( $from, $to ) {
1295                 $this->log( "Renaming $from to $to..." );
1296
1297                 $fromtable = $this->dbw->tableName( $from );
1298                 $totable   = $this->dbw->tableName( $to );
1299                 $this->dbw->query( "ALTER TABLE $fromtable RENAME TO $totable" );
1300         }
1301
1302         function swap( $base ) {
1303                 $this->renameTable( $base, "{$base}_old" );
1304                 $this->renameTable( "{$base}_temp", $base );
1305         }
1306
1307 }
1308
1309 $maintClass = 'FiveUpgrade';
1310 require_once( RUN_MAINTENANCE_IF_MAIN );