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