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