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