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