Commit the transaction after an upload is recorded and logged, to avoid losing images...
[mediawiki.git] / maintenance / FiveUpgrade.inc
blob8f172c904fb41e75cc17e8f26634809c31386286
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                 global $wgDBname;
163                 echo $wgDBname . ' ' . wfTimestamp( TS_DB ) . ': ' . $message . "\n";
164                 flush();
165         }
167         /**
168          * Initialize the chunked-insert system.
169          * Rows will be inserted in chunks of the given number, rather
170          * than in a giant INSERT...SELECT query, to keep the serialized
171          * MySQL database replication from getting hung up. This way other
172          * things can be going on during conversion without waiting for
173          * slaves to catch up as badly.
174          *
175          * @param int $chunksize Number of rows to insert at once
176          * @param int $final Total expected number of rows / id of last row,
177          *                   used for progress reports.
178          * @param string $table to insert on
179          * @param string $fname function name to report in SQL
180          * @access private
181          */
182         function setChunkScale( $chunksize, $final, $table, $fname ) {
183                 $this->chunkSize  = $chunksize;
184                 $this->chunkFinal = $final;
185                 $this->chunkCount = 0;
186                 $this->chunkStartTime = wfTime();
187                 $this->chunkOptions = array( 'IGNORE' );
188                 $this->chunkTable = $table;
189                 $this->chunkFunction = $fname;
190         }
192         /**
193          * Chunked inserts: perform an insert if we've reached the chunk limit.
194          * Prints a progress report with estimated completion time.
195          * @param array &$chunk -- This will be emptied if an insert is done.
196          * @param int $key A key identifier to use in progress estimation in
197          *                 place of the number of rows inserted. Use this if
198          *                 you provided a max key number instead of a count
199          *                 as the final chunk number in setChunkScale()
200          * @access private
201          */
202         function addChunk( &$chunk, $key = null ) {
203                 if( count( $chunk ) >= $this->chunkSize ) {
204                         $this->insertChunk( $chunk );
206                         $this->chunkCount += count( $chunk );
207                         $now = wfTime();
208                         $delta = $now - $this->chunkStartTime;
209                         $rate = $this->chunkCount / $delta;
211                         if( is_null( $key ) ) {
212                                 $completed = $this->chunkCount;
213                         } else {
214                                 $completed = $key;
215                         }
216                         $portion = $completed / $this->chunkFinal;
218                         $estimatedTotalTime = $delta / $portion;
219                         $eta = $this->chunkStartTime + $estimatedTotalTime;
221                         printf( "%s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec\n",
222                                 wfTimestamp( TS_DB, intval( $now ) ),
223                                 $portion * 100.0,
224                                 $this->chunkTable,
225                                 wfTimestamp( TS_DB, intval( $eta ) ),
226                                 $completed,
227                                 $this->chunkFinal,
228                                 $rate );
229                         flush();
231                         $chunk = array();
232                 }
233         }
235         /**
236          * Chunked inserts: perform an insert unconditionally, at the end, and log.
237          * @param array &$chunk -- This will be emptied if an insert is done.
238          * @access private
239          */
240         function lastChunk( &$chunk ) {
241                 $n = count( $chunk );
242                 if( $n > 0 ) {
243                         $this->insertChunk( $chunk );
244                 }
245                 $this->log( "100.00% done on $this->chunkTable (last chunk $n rows)." );
246         }
248         /**
249          * Chunked inserts: perform an insert.
250          * @param array &$chunk -- This will be emptied if an insert is done.
251          * @access private
252          */
253         function insertChunk( &$chunk ) {
254                 // Give slaves a chance to catch up
255                 wfWaitForSlaves( $this->maxLag );
256                 $this->dbw->insert( $this->chunkTable, $chunk, $this->chunkFunction, $this->chunkOptions );
257         }
260         /**
261          * Copy and transcode a table to table_temp.
262          * @param string $name Base name of the source table
263          * @param string $tabledef CREATE TABLE definition, w/ $1 for the name
264          * @param array $fields set of destination fields to these constants:
265          *              MW_UPGRADE_COPY   - straight copy
266          *              MW_UPGRADE_ENCODE - for old Latin1 wikis, conv to UTF-8
267          *              MW_UPGRADE_NULL   - just put NULL
268          * @param callable $callback An optional callback to modify the data
269          *                           or perform other processing. Func should be
270          *                           ( object $row, array $copy ) and return $copy
271          * @access private
272          */
273         function copyTable( $name, $tabledef, $fields, $callback = null ) {
274                 $fname = 'FiveUpgrade::copyTable';
276                 $name_temp = $name . '_temp';
277                 $this->log( "Migrating $name table to $name_temp..." );
279                 $table      = $this->dbw->tableName( $name );
280                 $table_temp = $this->dbw->tableName( $name_temp );
282                 // Create temporary table; we're going to copy everything in there,
283                 // then at the end rename the final tables into place.
284                 $def = str_replace( '$1', $table_temp, $tabledef );
285                 $this->dbw->query( $def, $fname );
287                 $numRecords = $this->dbw->selectField( $name, 'COUNT(*)', '', $fname );
288                 $this->setChunkScale( 100, $numRecords, $name_temp, $fname );
290                 // Pull all records from the second, streaming database connection.
291                 $sourceFields = array_keys( array_filter( $fields,
292                         create_function( '$x', 'return $x !== MW_UPGRADE_NULL;' ) ) );
293                 $result = $this->dbr->select( $name,
294                         $sourceFields,
295                         '',
296                         $fname );
298                 $add = array();
299                 while( $row = $this->dbr->fetchObject( $result ) ) {
300                         $copy = array();
301                         foreach( $fields as $field => $source ) {
302                                 if( $source === MW_UPGRADE_COPY ) {
303                                         $copy[$field] = $row->$field;
304                                 } elseif( $source === MW_UPGRADE_ENCODE ) {
305                                         $copy[$field] = $this->conv( $row->$field );
306                                 } elseif( $source === MW_UPGRADE_NULL ) {
307                                         $copy[$field] = null;
308                                 } else {
309                                         $this->log( "Unknown field copy type: $field => $source" );
310                                 }
311                         }
312                         if( is_callable( $callback ) ) {
313                                 $copy = call_user_func( $callback, $row, $copy );
314                         }
315                         $add[] = $copy;
316                         $this->addChunk( $add );
317                 }
318                 $this->lastChunk( $add );
319                 $this->dbr->freeResult( $result );
321                 $this->log( "Done converting $name." );
322                 $this->cleanupSwaps[] = $name;
323         }
325         function upgradePage() {
326                 $fname = "FiveUpgrade::upgradePage";
327                 $chunksize = 100;
329                 if( $this->dbw->tableExists( 'page' ) ) {
330                         $this->log( 'Page table already exists; aborting.' );
331                         die( -1 );
332                 }
334                 $this->log( "Checking cur table for unique title index and applying if necessary" );
335                 checkDupes( true );
337                 $this->log( "...converting from cur/old to page/revision/text DB structure." );
339                 extract( $this->dbw->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
341                 $this->log( "Creating page and revision tables..." );
342                 $this->dbw->query("CREATE TABLE $page (
343                         page_id int(8) unsigned NOT NULL auto_increment,
344                         page_namespace int NOT NULL,
345                         page_title varchar(255) binary NOT NULL,
346                         page_restrictions tinyblob NOT NULL default '',
347                         page_counter bigint(20) unsigned NOT NULL default '0',
348                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
349                         page_is_new tinyint(1) unsigned NOT NULL default '0',
350                         page_random real unsigned NOT NULL,
351                         page_touched char(14) binary NOT NULL default '',
352                         page_latest int(8) unsigned NOT NULL,
353                         page_len int(8) unsigned NOT NULL,
355                         PRIMARY KEY page_id (page_id),
356                         UNIQUE INDEX name_title (page_namespace,page_title),
357                         INDEX (page_random),
358                         INDEX (page_len)
359                         ) TYPE=InnoDB", $fname );
360                 $this->dbw->query("CREATE TABLE $revision (
361                         rev_id int(8) unsigned NOT NULL auto_increment,
362                         rev_page int(8) unsigned NOT NULL,
363                         rev_text_id int(8) unsigned NOT NULL,
364                         rev_comment tinyblob NOT NULL default '',
365                         rev_user int(5) unsigned NOT NULL default '0',
366                         rev_user_text varchar(255) binary NOT NULL default '',
367                         rev_timestamp char(14) binary NOT NULL default '',
368                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
369                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
371                         PRIMARY KEY rev_page_id (rev_page, rev_id),
372                         UNIQUE INDEX rev_id (rev_id),
373                         INDEX rev_timestamp (rev_timestamp),
374                         INDEX page_timestamp (rev_page,rev_timestamp),
375                         INDEX user_timestamp (rev_user,rev_timestamp),
376                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
377                         ) TYPE=InnoDB", $fname );
379                 $maxold = intval( $this->dbw->selectField( 'old', 'max(old_id)', '', $fname ) );
380                 $this->log( "Last old record is {$maxold}" );
382                 global $wgLegacySchemaConversion;
383                 if( $wgLegacySchemaConversion ) {
384                         // Create HistoryBlobCurStub entries.
385                         // Text will be pulled from the leftover 'cur' table at runtime.
386                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
387                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
388                         $cur_flags = "'object'";
389                 } else {
390                         // Copy all cur text in immediately: this may take longer but avoids
391                         // having to keep an extra table around.
392                         echo "......Moving text from cur.\n";
393                         $cur_text = 'cur_text';
394                         $cur_flags = "''";
395                 }
397                 $maxcur = $this->dbw->selectField( 'cur', 'max(cur_id)', '', $fname );
398                 $this->log( "Last cur entry is $maxcur" );
400                 /**
401                  * Copy placeholder records for each page's current version into old
402                  * Don't do any conversion here; text records are converted at runtime
403                  * based on the flags (and may be originally binary!) while the meta
404                  * fields will be converted in the old -> rev and cur -> page steps.
405                  */
406                 $this->setChunkScale( $chunksize, $maxcur, 'old', $fname );
407                 $result = $this->dbr->query(
408                         "SELECT cur_id, cur_namespace, cur_title, $cur_text AS text, cur_comment,
409                         cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags AS flags
410                         FROM $cur
411                         ORDER BY cur_id", $fname );
412                 $add = array();
413                 while( $row = $this->dbr->fetchObject( $result ) ) {
414                         $add[] = array(
415                                 'old_namespace'  => $row->cur_namespace,
416                                 'old_title'      => $row->cur_title,
417                                 'old_text'       => $row->text,
418                                 'old_comment'    => $row->cur_comment,
419                                 'old_user'       => $row->cur_user,
420                                 'old_user_text'  => $row->cur_user_text,
421                                 'old_timestamp'  => $row->cur_timestamp,
422                                 'old_minor_edit' => $row->cur_minor_edit,
423                                 'old_flags'      => $row->flags );
424                         $this->addChunk( $add, $row->cur_id );
425                 }
426                 $this->lastChunk( $add );
427                 $this->dbr->freeResult( $result );
429                 /**
430                  * Copy revision metadata from old into revision.
431                  * We'll also do UTF-8 conversion of usernames and comments.
432                  */
433                 #$newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
434                 #$this->setChunkScale( $chunksize, $newmaxold, 'revision', $fname );
435                 #$countold = $this->dbw->selectField( 'old', 'count(old_id)', '', $fname );
436                 $countold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
437                 $this->setChunkScale( $chunksize, $countold, 'revision', $fname );
439                 $this->log( "......Setting up revision table." );
440                 $result = $this->dbr->query(
441                         "SELECT old_id, cur_id, old_comment, old_user, old_user_text,
442                         old_timestamp, old_minor_edit
443                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title",
444                         $fname );
446                 $add = array();
447                 while( $row = $this->dbr->fetchObject( $result ) ) {
448                         $add[] = array(
449                                 'rev_id'         =>              $row->old_id,
450                                 'rev_page'       =>              $row->cur_id,
451                                 'rev_text_id'    =>              $row->old_id,
452                                 'rev_comment'    => $this->conv( $row->old_comment ),
453                                 'rev_user'       =>              $row->old_user,
454                                 'rev_user_text'  => $this->conv( $row->old_user_text ),
455                                 'rev_timestamp'  =>              $row->old_timestamp,
456                                 'rev_minor_edit' =>              $row->old_minor_edit );
457                         $this->addChunk( $add );
458                 }
459                 $this->lastChunk( $add );
460                 $this->dbr->freeResult( $result );
463                 /**
464                  * Copy page metadata from cur into page.
465                  * We'll also do UTF-8 conversion of titles.
466                  */
467                 $this->log( "......Setting up page table." );
468                 $this->setChunkScale( $chunksize, $maxcur, 'page', $fname );
469                 $result = $this->dbr->query( "
470                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
471                                 cur_random, cur_touched, rev_id, LENGTH(cur_text) AS len
472                         FROM $cur,$revision
473                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}
474                         ORDER BY cur_id", $fname );
475                 $add = array();
476                 while( $row = $this->dbr->fetchObject( $result ) ) {
477                         $add[] = array(
478                                 'page_id'           =>              $row->cur_id,
479                                 'page_namespace'    =>              $row->cur_namespace,
480                                 'page_title'        => $this->conv( $row->cur_title ),
481                                 'page_restrictions' =>              $row->cur_restrictions,
482                                 'page_counter'      =>              $row->cur_counter,
483                                 'page_is_redirect'  =>              $row->cur_is_redirect,
484                                 'page_is_new'       =>              $row->cur_is_new,
485                                 'page_random'       =>              $row->cur_random,
486                                 'page_touched'      =>              $this->dbw->timestamp(),
487                                 'page_latest'       =>              $row->rev_id,
488                                 'page_len'          =>              $row->len );
489                         #$this->addChunk( $add, $row->cur_id );
490                         $this->addChunk( $add );
491                 }
492                 $this->lastChunk( $add );
493                 $this->dbr->freeResult( $result );
495                 $this->log( "...done with cur/old -> page/revision." );
496         }
498         function upgradeLinks() {
499                 $fname = 'FiveUpgrade::upgradeLinks';
500                 $chunksize = 200;
501                 extract( $this->dbw->tableNames( 'links', 'brokenlinks', 'pagelinks', 'cur' ) );
503                 $this->log( 'Checking for interwiki table change in case of bogus items...' );
504                 if( $this->dbw->fieldExists( 'interwiki', 'iw_trans' ) ) {
505                         $this->log( 'interwiki has iw_trans.' );
506                 } else {
507                         $this->log( 'adding iw_trans...' );
508                         dbsource( 'maintenance/archives/patch-interwiki-trans.sql', $this->dbw );
509                         $this->log( 'added iw_trans.' );
510                 }
512                 $this->log( 'Creating pagelinks table...' );
513                 $this->dbw->query( "
514 CREATE TABLE $pagelinks (
515   -- Key to the page_id of the page containing the link.
516   pl_from int(8) unsigned NOT NULL default '0',
518   -- Key to page_namespace/page_title of the target page.
519   -- The target page may or may not exist, and due to renames
520   -- and deletions may refer to different page records as time
521   -- goes by.
522   pl_namespace int NOT NULL default '0',
523   pl_title varchar(255) binary NOT NULL default '',
525   UNIQUE KEY pl_from(pl_from,pl_namespace,pl_title),
526   KEY (pl_namespace,pl_title)
528 ) TYPE=InnoDB" );
530                 $this->log( 'Importing live links -> pagelinks' );
531                 $nlinks = $this->dbw->selectField( 'links', 'count(*)', '', $fname );
532                 if( $nlinks ) {
533                         $this->setChunkScale( $chunksize, $nlinks, 'pagelinks', $fname );
534                         $result = $this->dbr->query( "
535                           SELECT l_from,cur_namespace,cur_title
536                                 FROM $links, $cur
537                                 WHERE l_to=cur_id", $fname );
538                         $add = array();
539                         while( $row = $this->dbr->fetchObject( $result ) ) {
540                                 $add[] = array(
541                                         'pl_from'      =>              $row->l_from,
542                                         'pl_namespace' =>              $row->cur_namespace,
543                                         'pl_title'     => $this->conv( $row->cur_title ) );
544                                 $this->addChunk( $add );
545                         }
546                         $this->lastChunk( $add );
547                 } else {
548                         $this->log( 'no links!' );
549                 }
551                 $this->log( 'Importing brokenlinks -> pagelinks' );
552                 $nbrokenlinks = $this->dbw->selectField( 'brokenlinks', 'count(*)', '', $fname );
553                 if( $nbrokenlinks ) {
554                         $this->setChunkScale( $chunksize, $nbrokenlinks, 'pagelinks', $fname );
555                         $result = $this->dbr->query(
556                                 "SELECT bl_from, bl_to FROM $brokenlinks",
557                                 $fname );
558                         $add = array();
559                         while( $row = $this->dbr->fetchObject( $result ) ) {
560                                 $pagename = $this->conv( $row->bl_to );
561                                 $title = Title::newFromText( $pagename );
562                                 if( is_null( $title ) ) {
563                                         $this->log( "** invalid brokenlink: $row->bl_from -> '$pagename' (converted from '$row->bl_to')" );
564                                 } else {
565                                         $add[] = array(
566                                                 'pl_from'      => $row->bl_from,
567                                                 'pl_namespace' => $title->getNamespace(),
568                                                 'pl_title'     => $title->getDBkey() );
569                                         $this->addChunk( $add );
570                                 }
571                         }
572                         $this->lastChunk( $add );
573                 } else {
574                         $this->log( 'no brokenlinks!' );
575                 }
577                 $this->log( 'Done with links.' );
578         }
580         function upgradeUser() {
581                 // Apply unique index, if necessary:
582                 $duper = new UserDupes( $this->dbw );
583                 if( $duper->hasUniqueIndex() ) {
584                         $this->log( "Already have unique user_name index." );
585                 } else {
586                         $this->log( "Clearing user duplicates..." );
587                         if( !$duper->clearDupes() ) {
588                                 $this->log( "WARNING: Duplicate user accounts, may explode!" );
589                         }
590                 }
592                 $tabledef = <<<END
593 CREATE TABLE $1 (
594   user_id int(5) unsigned NOT NULL auto_increment,
595   user_name varchar(255) binary NOT NULL default '',
596   user_real_name varchar(255) binary NOT NULL default '',
597   user_password tinyblob NOT NULL default '',
598   user_newpassword tinyblob NOT NULL default '',
599   user_email tinytext NOT NULL default '',
600   user_options blob NOT NULL default '',
601   user_touched char(14) binary NOT NULL default '',
602   user_token char(32) binary NOT NULL default '',
603   user_email_authenticated CHAR(14) BINARY,
604   user_email_token CHAR(32) BINARY,
605   user_email_token_expires CHAR(14) BINARY,
607   PRIMARY KEY user_id (user_id),
608   UNIQUE INDEX user_name (user_name),
609   INDEX (user_email_token)
611 ) TYPE=InnoDB
612 END;
613                 $fields = array(
614                         'user_id'                  => MW_UPGRADE_COPY,
615                         'user_name'                => MW_UPGRADE_ENCODE,
616                         'user_real_name'           => MW_UPGRADE_ENCODE,
617                         'user_password'            => MW_UPGRADE_COPY,
618                         'user_newpassword'         => MW_UPGRADE_COPY,
619                         'user_email'               => MW_UPGRADE_ENCODE,
620                         'user_options'             => MW_UPGRADE_ENCODE,
621                         'user_touched'             => MW_UPGRADE_CALLBACK,
622                         'user_token'               => MW_UPGRADE_COPY,
623                         'user_email_authenticated' => MW_UPGRADE_CALLBACK,
624                         'user_email_token'         => MW_UPGRADE_NULL,
625                         'user_email_token_expires' => MW_UPGRADE_NULL );
626                 $this->copyTable( 'user', $tabledef, $fields,
627                         array( &$this, 'userCallback' ) );
628         }
630         function userCallback( $row, $copy ) {
631                 $now = $this->dbw->timestamp();
632                 $copy['user_touched'] = $now;
633                 $copy['user_email_authenticated'] = $this->emailAuth ? $now : null;
634                 return $copy;
635         }
637         function upgradeImage() {
638                 $tabledef = <<<END
639 CREATE TABLE $1 (
640   img_name varchar(255) binary NOT NULL default '',
641   img_size int(8) unsigned NOT NULL default '0',
642   img_width int(5)  NOT NULL default '0',
643   img_height int(5)  NOT NULL default '0',
644   img_metadata mediumblob NOT NULL,
645   img_bits int(3)  NOT NULL default '0',
646   img_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL,
647   img_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown",
648   img_minor_mime varchar(32) NOT NULL default "unknown",
649   img_description tinyblob NOT NULL default '',
650   img_user int(5) unsigned NOT NULL default '0',
651   img_user_text varchar(255) binary NOT NULL default '',
652   img_timestamp char(14) binary NOT NULL default '',
654   PRIMARY KEY img_name (img_name),
655   INDEX img_size (img_size),
656   INDEX img_timestamp (img_timestamp)
657 ) TYPE=InnoDB
658 END;
659                 $fields = array(
660                         'img_name'        => MW_UPGRADE_ENCODE,
661                         'img_size'        => MW_UPGRADE_COPY,
662                         'img_width'       => MW_UPGRADE_CALLBACK,
663                         'img_height'      => MW_UPGRADE_CALLBACK,
664                         'img_metadata'    => MW_UPGRADE_CALLBACK,
665                         'img_bits'        => MW_UPGRADE_CALLBACK,
666                         'img_media_type'  => MW_UPGRADE_CALLBACK,
667                         'img_major_mime'  => MW_UPGRADE_CALLBACK,
668                         'img_minor_mime'  => MW_UPGRADE_CALLBACK,
669                         'img_description' => MW_UPGRADE_ENCODE,
670                         'img_user'        => MW_UPGRADE_COPY,
671                         'img_user_text'   => MW_UPGRADE_ENCODE,
672                         'img_timestamp'   => MW_UPGRADE_COPY );
673                 $this->copyTable( 'image', $tabledef, $fields,
674                         array( &$this, 'imageCallback' ) );
675         }
677         function imageCallback( $row, $copy ) {
678                 global $options;
679                 if( !isset( $options['noimage'] ) ) {
680                         // Fill in the new image info fields
681                         $info = $this->imageInfo( $row->img_name );
683                         $copy['img_width'     ] = $info['width'];
684                         $copy['img_height'    ] = $info['height'];
685                         $copy['img_metadata'  ] = ""; // loaded on-demand
686                         $copy['img_bits'      ] = $info['bits'];
687                         $copy['img_media_type'] = $info['media'];
688                         $copy['img_major_mime'] = $info['major'];
689                         $copy['img_minor_mime'] = $info['minor'];
690                 }
692                 // If doing UTF8 conversion the file must be renamed
693                 $this->renameFile( $row->img_name, 'wfImageDir' );
695                 return $copy;
696         }
698         function imageInfo( $name, $subdirCallback='wfImageDir', $basename = null ) {
699                 if( is_null( $basename ) ) $basename = $name;
700                 $dir = call_user_func( $subdirCallback, $basename );
701                 $filename = $dir . '/' . $name;
702                 $info = array(
703                         'width'  => 0,
704                         'height' => 0,
705                         'bits'   => 0,
706                         'media'  => '',
707                         'major'  => '',
708                         'minor'  => '' );
710                 $magic =& wfGetMimeMagic();
711                 $mime = $magic->guessMimeType( $filename, true );
712                 list( $info['major'], $info['minor'] ) = explode( '/', $mime );
714                 $info['media'] = $magic->getMediaType( $filename, $mime );
716                 # Height and width
717                 $gis = false;
718                 if( $mime == 'image/svg' ) {
719                         $gis = wfGetSVGsize( $this->imagePath );
720                 } elseif( $magic->isPHPImageType( $mime ) ) {
721                         $gis = getimagesize( $filename );
722                 } else {
723                         $this->log( "Surprising mime type: $mime" );
724                 }
725                 if( $gis ) {
726                         $info['width' ] = $gis[0];
727                         $info['height'] = $gis[1];
728                 }
729                 if( isset( $gis['bits'] ) ) {
730                         $info['bits'] = $gis['bits'];
731                 }
733                 return $info;
734         }
737         /**
738          * Truncate a table.
739          * @param string $table The table name to be truncated
740          */
741         function clearTable( $table ) {
742                 print "Clearing $table...\n";
743                 $tableName = $this->db->tableName( $table );
744                 $this->db->query( 'TRUNCATE $tableName' );
745         }
747         /**
748          * Rename a given image or archived image file to the converted filename,
749          * leaving a symlink for URL compatibility.
750          *
751          * @param string $oldname pre-conversion filename
752          * @param string $basename pre-conversion base filename for dir hashing, if an archive
753          * @access private
754          */
755         function renameFile( $oldname, $subdirCallback='wfImageDir', $basename=null ) {
756                 $newname = $this->conv( $oldname );
757                 if( $newname == $oldname ) {
758                         // No need to rename; another field triggered this row.
759                         return false;
760                 }
762                 if( is_null( $basename ) ) $basename = $oldname;
763                 $ubasename = $this->conv( $basename );
764                 $oldpath = call_user_func( $subdirCallback, $basename ) . '/' . $oldname;
765                 $newpath = call_user_func( $subdirCallback, $ubasename ) . '/' . $newname;
767                 $this->log( "$oldpath -> $newpath" );
768                 if( rename( $oldpath, $newpath ) ) {
769                         $relpath = $this->relativize( $newpath, dirname( $oldpath ) );
770                         if( !symlink( $relpath, $oldpath ) ) {
771                                 $this->log( "... symlink failed!" );
772                         }
773                         return $newname;
774                 } else {
775                         $this->log( "... rename failed!" );
776                         return false;
777                 }
778         }
780         /**
781          * Generate a relative path name to the given file.
782          * Assumes Unix-style paths, separators, and semantics.
783          *
784          * @param string $path Absolute destination path including target filename
785          * @param string $from Absolute source path, directory only
786          * @return string
787          * @access private
788          * @static
789          */
790         function relativize( $path, $from ) {
791                 $pieces  = explode( '/', dirname( $path ) );
792                 $against = explode( '/', $from );
794                 // Trim off common prefix
795                 while( count( $pieces ) && count( $against )
796                         && $pieces[0] == $against[0] ) {
797                         array_shift( $pieces );
798                         array_shift( $against );
799                 }
801                 // relative dots to bump us to the parent
802                 while( count( $against ) ) {
803                         array_unshift( $pieces, '..' );
804                         array_shift( $against );
805                 }
807                 array_push( $pieces, basename( $path ) );
809                 return implode( '/', $pieces );
810         }
812         function upgradeOldImage() {
813                 $tabledef = <<<END
814 CREATE TABLE $1 (
815   -- Base filename: key to image.img_name
816   oi_name varchar(255) binary NOT NULL default '',
818   -- Filename of the archived file.
819   -- This is generally a timestamp and '!' prepended to the base name.
820   oi_archive_name varchar(255) binary NOT NULL default '',
822   -- Other fields as in image...
823   oi_size int(8) unsigned NOT NULL default 0,
824   oi_width int(5) NOT NULL default 0,
825   oi_height int(5) NOT NULL default 0,
826   oi_bits int(3) NOT NULL default 0,
827   oi_description tinyblob NOT NULL default '',
828   oi_user int(5) unsigned NOT NULL default '0',
829   oi_user_text varchar(255) binary NOT NULL default '',
830   oi_timestamp char(14) binary NOT NULL default '',
832   INDEX oi_name (oi_name(10))
834 ) TYPE=InnoDB;
835 END;
836                 $fields = array(
837                         'oi_name'         => MW_UPGRADE_ENCODE,
838                         'oi_archive_name' => MW_UPGRADE_ENCODE,
839                         'oi_size'         => MW_UPGRADE_COPY,
840                         'oi_width'        => MW_UPGRADE_CALLBACK,
841                         'oi_height'       => MW_UPGRADE_CALLBACK,
842                         'oi_bits'         => MW_UPGRADE_CALLBACK,
843                         'oi_description'  => MW_UPGRADE_ENCODE,
844                         'oi_user'         => MW_UPGRADE_COPY,
845                         'oi_user_text'    => MW_UPGRADE_ENCODE,
846                         'oi_timestamp'    => MW_UPGRADE_COPY );
847                 $this->copyTable( 'oldimage', $tabledef, $fields,
848                         array( &$this, 'oldimageCallback' ) );
849         }
851         function oldimageCallback( $row, $copy ) {
852                 global $options;
853                 if( !isset( $options['noimage'] ) ) {
854                         // Fill in the new image info fields
855                         $info = $this->imageInfo( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
856                         $copy['oi_width' ] = $info['width' ];
857                         $copy['oi_height'] = $info['height'];
858                         $copy['oi_bits'  ] = $info['bits'  ];
859                 }
861                 // If doing UTF8 conversion the file must be renamed
862                 $this->renameFile( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
864                 return $copy;
865         }
868         function upgradeWatchlist() {
869                 $fname = 'FiveUpgrade::upgradeWatchlist';
870                 $chunksize = 100;
872                 extract( $this->dbw->tableNames( 'watchlist', 'watchlist_temp' ) );
874                 $this->log( 'Migrating watchlist table to watchlist_temp...' );
875                 $this->dbw->query(
876 "CREATE TABLE $watchlist_temp (
877   -- Key to user_id
878   wl_user int(5) unsigned NOT NULL,
880   -- Key to page_namespace/page_title
881   -- Note that users may watch patches which do not exist yet,
882   -- or existed in the past but have been deleted.
883   wl_namespace int NOT NULL default '0',
884   wl_title varchar(255) binary NOT NULL default '',
886   -- Timestamp when user was last sent a notification e-mail;
887   -- cleared when the user visits the page.
888   -- FIXME: add proper null support etc
889   wl_notificationtimestamp varchar(14) binary NOT NULL default '0',
891   UNIQUE KEY (wl_user, wl_namespace, wl_title),
892   KEY namespace_title (wl_namespace,wl_title)
894 ) TYPE=InnoDB;", $fname );
896                 // Fix encoding for Latin-1 upgrades, add some fields,
897                 // and double article to article+talk pairs
898                 $numwatched = $this->dbw->selectField( 'watchlist', 'count(*)', '', $fname );
900                 $this->setChunkScale( $chunksize, $numwatched * 2, 'watchlist_temp', $fname );
901                 $result = $this->dbr->select( 'watchlist',
902                         array(
903                                 'wl_user',
904                                 'wl_namespace',
905                                 'wl_title' ),
906                         '',
907                         $fname );
909                 $add = array();
910                 while( $row = $this->dbr->fetchObject( $result ) ) {
911                         $now = $this->dbw->timestamp();
912                         $add[] = array(
913                                 'wl_user'      =>                        $row->wl_user,
914                                 'wl_namespace' => Namespace::getSubject( $row->wl_namespace ),
915                                 'wl_title'     =>           $this->conv( $row->wl_title ),
916                                 'wl_notificationtimestamp' =>            '0' );
917                         $this->addChunk( $add );
919                         $add[] = array(
920                                 'wl_user'      =>                        $row->wl_user,
921                                 'wl_namespace' =>    Namespace::getTalk( $row->wl_namespace ),
922                                 'wl_title'     =>           $this->conv( $row->wl_title ),
923                                 'wl_notificationtimestamp' =>            '0' );
924                         $this->addChunk( $add );
925                 }
926                 $this->lastChunk( $add );
927                 $this->dbr->freeResult( $result );
929                 $this->log( 'Done converting watchlist.' );
930                 $this->cleanupSwaps[] = 'watchlist';
931         }
933         function upgradeLogging() {
934                 $tabledef = <<<END
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 '',
942   -- Timestamp. Duh.
943   log_timestamp char(14) NOT NULL default '19700101000000',
945   -- The user who performed this action; key to user_id
946   log_user int unsigned NOT NULL default 0,
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 '',
953   -- Freeform text. Interpreted as edit history comments.
954   log_comment varchar(255) NOT NULL default '',
956   -- LF separated list of miscellaneous parameters
957   log_params blob NOT NULL default '',
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)
963 ) TYPE=InnoDB
964 END;
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         }
977         function upgradeArchive() {
978                 $tabledef = <<<END
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 '',
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',
990   ar_flags tinyblob NOT NULL default '',
992   ar_rev_id int(8) unsigned,
993   ar_text_id int(8) unsigned,
995   KEY name_title_timestamp (ar_namespace,ar_title,ar_timestamp)
997 ) TYPE=InnoDB
998 END;
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         }
1014         function upgradeImagelinks() {
1015                 global $wgUseLatin1;
1016                 if( $wgUseLatin1 ) {
1017                         $tabledef = <<<END
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',
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_IMAGE).
1025   il_to varchar(255) binary NOT NULL default '',
1027   UNIQUE KEY il_from(il_from,il_to),
1028   KEY (il_to)
1030 ) TYPE=InnoDB
1031 END;
1032                         $fields = array(
1033                                 'il_from' => MW_UPGRADE_COPY,
1034                                 'il_to'   => MW_UPGRADE_ENCODE );
1035                         $this->copyTable( 'imagelinks', $tabledef, $fields );
1036                 }
1037         }
1039         function upgradeCategorylinks() {
1040                 global $wgUseLatin1;
1041                 if( $wgUseLatin1 ) {
1042                         $tabledef = <<<END
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,
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 END;
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         }
1063         function upgradeIpblocks() {
1064                 global $wgUseLatin1;
1065                 if( $wgUseLatin1 ) {
1066                         $tabledef = <<<END
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 '',
1077   PRIMARY KEY ipb_id (ipb_id),
1078   INDEX ipb_address (ipb_address),
1079   INDEX ipb_user (ipb_user)
1081 ) TYPE=InnoDB
1082 END;
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         }
1096         function upgradeRecentchanges() {
1097                 // There's a format change in the namespace field
1098                 $tabledef = <<<END
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 '',
1104   rc_user int(10) unsigned NOT NULL default '0',
1105   rc_user_text varchar(255) binary NOT NULL default '',
1107   rc_namespace int NOT NULL default '0',
1108   rc_title varchar(255) binary NOT NULL default '',
1110   rc_comment varchar(255) binary NOT NULL default '',
1111   rc_minor tinyint(3) unsigned NOT NULL default '0',
1113   rc_bot tinyint(3) unsigned NOT NULL default '0',
1114   rc_new tinyint(3) unsigned NOT NULL default '0',
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',
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 '',
1124   rc_patrolled tinyint(3) unsigned NOT NULL default '0',
1126   rc_ip char(15) NOT NULL default '',
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)
1135 ) TYPE=InnoDB
1136 END;
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         }
1160         function upgradeQuerycache() {
1161                 // There's a format change in the namespace field
1162                 $tabledef = <<<END
1163 CREATE TABLE $1 (
1164   -- A key name, generally the base name of of the special page.
1165   qc_type char(32) NOT NULL,
1167   -- Some sort of stored value. Sizes, counts...
1168   qc_value int(5) unsigned NOT NULL default '0',
1170   -- Target namespace+title
1171   qc_namespace int NOT NULL default '0',
1172   qc_title char(255) binary NOT NULL default '',
1174   KEY (qc_type,qc_value)
1176 ) TYPE=InnoDB
1177 END;
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         }
1186         /**
1187          * Rename all our temporary tables into final place.
1188          * We've left things in place so a read-only wiki can continue running
1189          * on the old code during all this.
1190          */
1191         function upgradeCleanup() {
1192                 $this->renameTable( 'old', 'text' );
1194                 foreach( $this->cleanupSwaps as $table ) {
1195                         $this->swap( $table );
1196                 }
1197         }
1199         function renameTable( $from, $to ) {
1200                 $this->log( "Renaming $from to $to..." );
1202                 $fromtable = $this->dbw->tableName( $from );
1203                 $totable   = $this->dbw->tableName( $to );
1204                 $this->dbw->query( "ALTER TABLE $fromtable RENAME TO $totable" );
1205         }
1207         function swap( $base ) {
1208                 $this->renameTable( $base, "{$base}_old" );
1209                 $this->renameTable( "{$base}_temp", $base );
1210         }