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