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