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