ipblocks, recentchanges conversion
[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 foreach( $tables as $table ) {
60 if( $this->doing( $table ) ) {
61 $method = 'upgrade' . ucfirst( $table );
62 $this->$method();
63 }
64 }
65
66 if( $this->doing( 'cleanup' ) ) {
67 $this->upgradeCleanup();
68 }
69 }
70
71
72 /**
73 * Open a second connection to the master server, with buffering off.
74 * This will let us stream large datasets in and write in chunks on the
75 * other end.
76 * @return Database
77 * @access private
78 */
79 function &newConnection() {
80 global $wgDBadminuser, $wgDBadminpassword;
81 global $wgDBserver, $wgDBname;
82 $db =& new Database( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
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 => UNICODE_REPLACEMENT,
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 => UNICODE_REPLACEMENT,
113 0x8E => 0x017D, #LATIN CAPITAL LETTER Z WITH CARON
114 0x8F => UNICODE_REPLACEMENT,
115 0x90 => UNICODE_REPLACEMENT,
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 => UNICODE_REPLACEMENT,
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 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();
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 $this->dbw->insert( $this->chunkTable, $chunk, $this->chunkFunction, $this->chunkOptions );
253 }
254
255
256 /**
257 * Copy and transcode a table to table_temp.
258 * @param string $name Base name of the source table
259 * @param string $tabledef CREATE TABLE definition, w/ $1 for the name
260 * @param array $fields set of destination fields to these constants:
261 * MW_UPGRADE_COPY - straight copy
262 * MW_UPGRADE_ENCODE - for old Latin1 wikis, conv to UTF-8
263 * MW_UPGRADE_NULL - just put NULL
264 * @param callable $callback An optional callback to modify the data
265 * or perform other processing. Func should be
266 * ( object $row, array $copy ) and return $copy
267 * @access private
268 */
269 function copyTable( $name, $tabledef, $fields, $callback = null ) {
270 $fname = 'FiveUpgrade::copyTable';
271
272 $name_temp = $name . '_temp';
273 $this->log( "Migrating $name table to $name_temp..." );
274
275 $table = $this->dbw->tableName( $name );
276 $table_temp = $this->dbw->tableName( $name_temp );
277
278 // Create temporary table; we're going to copy everything in there,
279 // then at the end rename the final tables into place.
280 $def = str_replace( '$1', $table_temp, $tabledef );
281 $this->dbw->query( $def, $fname );
282
283 $numRecords = $this->dbw->selectField( $name, 'COUNT(*)', '', $fname );
284 $this->setChunkScale( 100, $numRecords, $name_temp, $fname );
285
286 // Pull all records from the second, streaming database connection.
287 $sourceFields = array_keys( array_filter( $fields,
288 create_function( '$x', 'return $x !== MW_UPGRADE_NULL;' ) ) );
289 $result = $this->dbr->select( $name,
290 $sourceFields,
291 '',
292 $fname );
293
294 $add = array();
295 while( $row = $this->dbr->fetchObject( $result ) ) {
296 $copy = array();
297 foreach( $fields as $field => $source ) {
298 if( $source === MW_UPGRADE_COPY ) {
299 $copy[$field] = $row->$field;
300 } elseif( $source === MW_UPGRADE_ENCODE ) {
301 $copy[$field] = $this->conv( $row->$field );
302 } elseif( $source === MW_UPGRADE_NULL ) {
303 $copy[$field] = null;
304 } else {
305 $this->log( "Unknown field copy type: $field => $source" );
306 }
307 }
308 if( is_callable( $callback ) ) {
309 $copy = call_user_func( $callback, $row, $copy );
310 }
311 $add[] = $copy;
312 $this->addChunk( $add );
313 }
314 $this->lastChunk( $add );
315 $this->dbr->freeResult( $result );
316
317 $this->log( "Done converting $name." );
318 $this->cleanupSwaps[] = $name;
319 }
320
321 function upgradePage() {
322 $fname = "FiveUpgrade::upgradePage";
323 $chunksize = 100;
324
325
326 $this->log( "Checking cur table for unique title index and applying if necessary" );
327 checkDupes( true );
328
329 $this->log( "...converting from cur/old to page/revision/text DB structure." );
330
331 extract( $this->dbw->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
332
333 $this->log( "Creating page and revision tables..." );
334 $this->dbw->query("CREATE TABLE $page (
335 page_id int(8) unsigned NOT NULL auto_increment,
336 page_namespace int NOT NULL,
337 page_title varchar(255) binary NOT NULL,
338 page_restrictions tinyblob NOT NULL default '',
339 page_counter bigint(20) unsigned NOT NULL default '0',
340 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
341 page_is_new tinyint(1) unsigned NOT NULL default '0',
342 page_random real unsigned NOT NULL,
343 page_touched char(14) binary NOT NULL default '',
344 page_latest int(8) unsigned NOT NULL,
345 page_len int(8) unsigned NOT NULL,
346
347 PRIMARY KEY page_id (page_id),
348 UNIQUE INDEX name_title (page_namespace,page_title),
349 INDEX (page_random),
350 INDEX (page_len)
351 ) TYPE=InnoDB", $fname );
352 $this->dbw->query("CREATE TABLE $revision (
353 rev_id int(8) unsigned NOT NULL auto_increment,
354 rev_page int(8) unsigned NOT NULL,
355 rev_comment tinyblob NOT NULL default '',
356 rev_user int(5) unsigned NOT NULL default '0',
357 rev_user_text varchar(255) binary NOT NULL default '',
358 rev_timestamp char(14) binary NOT NULL default '',
359 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
360 rev_deleted tinyint(1) unsigned NOT NULL default '0',
361
362 PRIMARY KEY rev_page_id (rev_page, rev_id),
363 UNIQUE INDEX rev_id (rev_id),
364 INDEX rev_timestamp (rev_timestamp),
365 INDEX page_timestamp (rev_page,rev_timestamp),
366 INDEX user_timestamp (rev_user,rev_timestamp),
367 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
368 ) TYPE=InnoDB", $fname );
369
370 $maxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
371 $this->log( "Last old record is {$maxold}" );
372
373 global $wgLegacySchemaConversion;
374 if( $wgLegacySchemaConversion ) {
375 // Create HistoryBlobCurStub entries.
376 // Text will be pulled from the leftover 'cur' table at runtime.
377 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
378 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
379 $cur_flags = "'object'";
380 } else {
381 // Copy all cur text in immediately: this may take longer but avoids
382 // having to keep an extra table around.
383 echo "......Moving text from cur.\n";
384 $cur_text = 'cur_text';
385 $cur_flags = "''";
386 }
387
388 $maxcur = $this->dbw->selectField( 'cur', 'max(cur_id)', '', $fname );
389 $this->log( "Last cur entry is $maxcur" );
390
391 /**
392 * Copy placeholder records for each page's current version into old
393 * Don't do any conversion here; text records are converted at runtime
394 * based on the flags (and may be originally binary!) while the meta
395 * fields will be converted in the old -> rev and cur -> page steps.
396 */
397 $this->setChunkScale( $chunksize, $maxcur, 'old', $fname );
398 $result = $this->dbr->query(
399 "SELECT cur_id, cur_namespace, cur_title, $cur_text AS text, cur_comment,
400 cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags AS flags
401 FROM $cur
402 ORDER BY cur_id", $fname );
403 $add = array();
404 while( $row = $this->dbr->fetchObject( $result ) ) {
405 $add[] = array(
406 'old_namespace' => $row->cur_namespace,
407 'old_title' => $row->cur_title,
408 'old_text' => $row->text,
409 'old_comment' => $row->cur_comment,
410 'old_user' => $row->cur_user,
411 'old_user_text' => $row->cur_user_text,
412 'old_timestamp' => $row->cur_timestamp,
413 'old_minor_edit' => $row->cur_minor_edit,
414 'old_flags' => $row->flags );
415 $this->addChunk( $add, $row->cur_id );
416 }
417 $this->lastChunk( $add );
418 $this->dbr->freeResult( $result );
419
420 /**
421 * Copy revision metadata from old into revision.
422 * We'll also do UTF-8 conversion of usernames and comments.
423 */
424 #$newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
425 #$this->setChunkScale( $chunksize, $newmaxold, 'revision', $fname );
426 $countold = $this->dbw->selectField( 'old', 'count(old_id)', '', $fname );
427 $this->setChunkScale( $chunksize, $countold, 'revision', $fname );
428
429 $this->log( "......Setting up revision table." );
430 $result = $this->dbr->query(
431 "SELECT old_id, cur_id, old_comment, old_user, old_user_text,
432 old_timestamp, old_minor_edit
433 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title",
434 $fname );
435
436 $add = array();
437 while( $row = $this->dbr->fetchObject( $result ) ) {
438 $add[] = array(
439 'rev_id' => $row->old_id,
440 'rev_page' => $row->cur_id,
441 'rev_comment' => $this->conv( $row->old_comment ),
442 'rev_user' => $row->old_user,
443 'rev_user_text' => $this->conv( $row->old_user_text ),
444 'rev_timestamp' => $row->old_timestamp,
445 'rev_minor_edit' => $row->old_minor_edit );
446 $this->addChunk( $add );
447 }
448 $this->lastChunk( $add );
449 $this->dbr->freeResult( $result );
450
451
452 /**
453 * Copy page metadata from cur into page.
454 * We'll also do UTF-8 conversion of titles.
455 */
456 $this->log( "......Setting up page table." );
457 $this->setChunkScale( $chunksize, $maxcur, 'page', $fname );
458 $result = $this->dbr->query( "
459 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
460 cur_random, cur_touched, rev_id, LENGTH(cur_text) AS len
461 FROM $cur,$revision
462 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}
463 ORDER BY cur_id", $fname );
464 $add = array();
465 while( $row = $this->dbr->fetchObject( $result ) ) {
466 $add[] = array(
467 'page_id' => $row->cur_id,
468 'page_namespace' => $row->cur_namespace,
469 'page_title' => $this->conv( $row->cur_title ),
470 'page_restrictions' => $row->cur_restrictions,
471 'page_counter' => $row->cur_counter,
472 'page_is_redirect' => $row->cur_is_redirect,
473 'page_is_new' => $row->cur_is_new,
474 'page_random' => $row->cur_random,
475 'page_touched' => $this->dbw->timestamp(),
476 'page_latest' => $row->rev_id,
477 'page_len' => $row->len );
478 $this->addChunk( $add, $row->cur_id );
479 }
480 $this->lastChunk( $add );
481 $this->dbr->freeResult( $result );
482
483 $this->log( "...done with cur/old -> page/revision." );
484 }
485
486 function upgradeLinks() {
487 $fname = 'FiveUpgrade::upgradeLinks';
488 $chunksize = 200;
489 extract( $this->dbw->tableNames( 'links', 'brokenlinks', 'pagelinks', 'page' ) );
490
491 $this->log( 'Creating pagelinks table...' );
492 $this->dbw->query( "
493 CREATE TABLE $pagelinks (
494 -- Key to the page_id of the page containing the link.
495 pl_from int(8) unsigned NOT NULL default '0',
496
497 -- Key to page_namespace/page_title of the target page.
498 -- The target page may or may not exist, and due to renames
499 -- and deletions may refer to different page records as time
500 -- goes by.
501 pl_namespace int NOT NULL default '0',
502 pl_title varchar(255) binary NOT NULL default '',
503
504 UNIQUE KEY pl_from(pl_from,pl_namespace,pl_title),
505 KEY (pl_namespace,pl_title)
506
507 ) TYPE=InnoDB" );
508
509 $this->log( 'Importing live links -> pagelinks' );
510 $nlinks = $this->dbw->selectField( 'links', 'count(*)', '', $fname );
511 if( $nlinks ) {
512 $this->setChunkScale( $chunksize, $nlinks, 'pagelinks', $fname );
513 $result = $this->dbr->query( "
514 SELECT l_from,page_namespace,page_title
515 FROM $links, $page
516 WHERE l_to=page_id", $fname );
517 $add = array();
518 while( $row = $this->dbr->fetchObject( $result ) ) {
519 $add[] = array(
520 'pl_from' => $row->l_from,
521 'pl_namespace' => $row->page_namespace,
522 'pl_title' => $row->page_title );
523 $this->addChunk( $add );
524 }
525 $this->lastChunk( $add );
526 } else {
527 $this->log( 'no links!' );
528 }
529
530 $this->log( 'Importing brokenlinks -> pagelinks' );
531 $nbrokenlinks = $this->dbw->selectField( 'brokenlinks', 'count(*)', '', $fname );
532 if( $nbrokenlinks ) {
533 $this->setChunkScale( $chunksize, $nbrokenlinks, 'pagelinks', $fname );
534 $this->chunkOptions = array( 'IGNORE' );
535 $result = $this->dbr->query(
536 "SELECT bl_from, bl_to FROM $brokenlinks",
537 $fname );
538 $add = array();
539 while( $row = $this->dbr->fetchObject( $result ) ) {
540 $pagename = $this->conv( $row->bl_to );
541 $title = Title::newFromText( $pagename );
542 if( is_null( $title ) ) {
543 $this->log( "** invalid brokenlink: $row->bl_from -> '$pagename' (converted from '$row->bl_to')" );
544 } else {
545 $add[] = array(
546 'pl_from' => $row->bl_from,
547 'pl_namespace' => $title->getNamespace(),
548 'pl_title' => $title->getDBkey() );
549 $this->addChunk( $add );
550 }
551 }
552 $this->lastChunk( $add );
553 } else {
554 $this->log( 'no brokenlinks!' );
555 }
556
557 $this->log( 'Done with links.' );
558 }
559
560 function upgradeUser() {
561 // Apply unique index, if necessary:
562 $duper = new UserDupes( $this->dbw );
563 if( $duper->hasUniqueIndex() ) {
564 $this->log( "Already have unique user_name index." );
565 } else {
566 $this->log( "Clearing user duplicates..." );
567 if( !$duper->clearDupes() ) {
568 $this->log( "WARNING: Duplicate user accounts, may explode!" );
569 }
570 }
571
572 $tabledef = <<<END
573 CREATE TABLE $1 (
574 user_id int(5) unsigned NOT NULL auto_increment,
575 user_name varchar(255) binary NOT NULL default '',
576 user_real_name varchar(255) binary NOT NULL default '',
577 user_password tinyblob NOT NULL default '',
578 user_newpassword tinyblob NOT NULL default '',
579 user_email tinytext NOT NULL default '',
580 user_options blob NOT NULL default '',
581 user_touched char(14) binary NOT NULL default '',
582 user_token char(32) binary NOT NULL default '',
583 user_email_authenticated CHAR(14) BINARY,
584 user_email_token CHAR(32) BINARY,
585 user_email_token_expires CHAR(14) BINARY,
586
587 PRIMARY KEY user_id (user_id),
588 UNIQUE INDEX user_name (user_name),
589 INDEX (user_email_token)
590
591 ) TYPE=InnoDB
592 END;
593 $fields = array(
594 'user_id' => MW_UPGRADE_COPY,
595 'user_name' => MW_UPGRADE_ENCODE,
596 'user_real_name' => MW_UPGRADE_ENCODE,
597 'user_password' => MW_UPGRADE_COPY,
598 'user_newpassword' => MW_UPGRADE_COPY,
599 'user_email' => MW_UPGRADE_ENCODE,
600 'user_options' => MW_UPGRADE_ENCODE,
601 'user_touched' => MW_UPGRADE_CALLBACK,
602 'user_token' => MW_UPGRADE_COPY,
603 'user_email_authenticated' => MW_UPGRADE_CALLBACK,
604 'user_email_token' => MW_UPGRADE_NULL,
605 'user_email_token_expires' => MW_UPGRADE_NULL );
606 $this->copyTable( 'user', $tabledef, $fields,
607 array( &$this, 'userCallback' ) );
608 }
609
610 function userCallback( $row, $copy ) {
611 $now = $this->dbw->timestamp();
612 $copy['user_touched'] = $now;
613 $copy['user_email_authenticated'] = $this->emailAuth ? $now : null;
614 return $copy;
615 }
616
617 function upgradeImage() {
618 $tabledef = <<<END
619 CREATE TABLE $1 (
620 img_name varchar(255) binary NOT NULL default '',
621 img_size int(8) unsigned NOT NULL default '0',
622 img_width int(5) NOT NULL default '0',
623 img_height int(5) NOT NULL default '0',
624 img_metadata mediumblob NOT NULL,
625 img_bits int(3) NOT NULL default '0',
626 img_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL,
627 img_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown",
628 img_minor_mime varchar(32) NOT NULL default "unknown",
629 img_description tinyblob NOT NULL default '',
630 img_user int(5) unsigned NOT NULL default '0',
631 img_user_text varchar(255) binary NOT NULL default '',
632 img_timestamp char(14) binary NOT NULL default '',
633
634 PRIMARY KEY img_name (img_name),
635 INDEX img_size (img_size),
636 INDEX img_timestamp (img_timestamp)
637 ) TYPE=InnoDB
638 END;
639 $fields = array(
640 'img_name' => MW_UPGRADE_ENCODE,
641 'img_size' => MW_UPGRADE_COPY,
642 'img_width' => MW_UPGRADE_CALLBACK,
643 'img_height' => MW_UPGRADE_CALLBACK,
644 'img_metadata' => MW_UPGRADE_CALLBACK,
645 'img_bits' => MW_UPGRADE_CALLBACK,
646 'img_media_type' => MW_UPGRADE_CALLBACK,
647 'img_major_mime' => MW_UPGRADE_CALLBACK,
648 'img_minor_mime' => MW_UPGRADE_CALLBACK,
649 'img_description' => MW_UPGRADE_ENCODE,
650 'img_user' => MW_UPGRADE_COPY,
651 'img_user_text' => MW_UPGRADE_ENCODE,
652 'img_timestamp' => MW_UPGRADE_COPY );
653 $this->copyTable( 'image', $tabledef, $fields,
654 array( &$this, 'imageCallback' ) );
655 }
656
657 function imageCallback( $row, $copy ) {
658 // Fill in the new image info fields
659 $info = $this->imageInfo( $row->img_name );
660
661 $copy['img_width' ] = $info['width'];
662 $copy['img_height' ] = $info['height'];
663 $copy['img_metadata' ] = ""; // loaded on-demand
664 $copy['img_bits' ] = $info['bits'];
665 $copy['img_media_type'] = $info['media'];
666 $copy['img_major_mime'] = $info['major'];
667 $copy['img_minor_mime'] = $info['minor'];
668
669 // If doing UTF8 conversion the file must be renamed
670 $this->renameFile( $row->img_name, 'wfImageDir' );
671
672 return $copy;
673 }
674
675 function imageInfo( $name, $subdirCallback='wfImageDir', $basename = null ) {
676 if( is_null( $basename ) ) $basename = $name;
677 $dir = call_user_func( $subdirCallback, $basename );
678 $filename = $dir . '/' . $name;
679 $info = array(
680 'width' => 0,
681 'height' => 0,
682 'bits' => 0,
683 'media' => '',
684 'major' => '',
685 'minor' => '' );
686
687 $magic =& wfGetMimeMagic();
688 $mime = $magic->guessMimeType( $filename, true );
689 list( $info['major'], $info['minor'] ) = explode( '/', $mime );
690
691 $info['media'] = $magic->getMediaType( $filename, $mime );
692
693 # Height and width
694 $gis = false;
695 if( $mime == 'image/svg' ) {
696 $gis = wfGetSVGsize( $this->imagePath );
697 } elseif( $magic->isPHPImageType( $mime ) ) {
698 $gis = getimagesize( $filename );
699 } else {
700 $this->log( "Surprising mime type: $mime" );
701 }
702 if( $gis ) {
703 $info['width' ] = $gis[0];
704 $info['height'] = $gis[1];
705 }
706 if( isset( $gis['bits'] ) ) {
707 $info['bits'] = $gis['bits'];
708 }
709
710 return $info;
711 }
712
713
714 /**
715 * Truncate a table.
716 * @param string $table The table name to be truncated
717 */
718 function clearTable( $table ) {
719 print "Clearing $table...\n";
720 $tableName = $this->db->tableName( $table );
721 $this->db->query( 'TRUNCATE $tableName' );
722 }
723
724 /**
725 * Rename a given image or archived image file to the converted filename,
726 * leaving a symlink for URL compatibility.
727 *
728 * @param string $oldname pre-conversion filename
729 * @param string $basename pre-conversion base filename for dir hashing, if an archive
730 * @access private
731 */
732 function renameFile( $oldname, $subdirCallback='wfImageDir', $basename=null ) {
733 $newname = $this->conv( $oldname );
734 if( $newname == $oldname ) {
735 // No need to rename; another field triggered this row.
736 return;
737 }
738
739 if( is_null( $basename ) ) $basename = $oldname;
740 $ubasename = $this->conv( $basename );
741 $oldpath = call_user_func( $subdirCallback, $basename ) . '/' . $oldname;
742 $newpath = call_user_func( $subdirCallback, $ubasename ) . '/' . $newname;
743
744 $this->log( "$oldpath -> $newpath" );
745 if( rename( $oldpath, $newpath ) ) {
746 $relpath = $this->relativize( $newpath, dirname( $oldpath ) );
747 if( !symlink( $relpath, $oldpath ) ) {
748 $this->log( "... symlink failed!" );
749 }
750 } else {
751 $this->log( "... rename failed!" );
752 }
753 }
754
755 /**
756 * Generate a relative path name to the given file.
757 * Assumes Unix-style paths, separators, and semantics.
758 *
759 * @param string $path Absolute destination path including target filename
760 * @param string $from Absolute source path, directory only
761 * @return string
762 * @access private
763 * @static
764 */
765 function relativize( $path, $from ) {
766 $pieces = explode( '/', dirname( $path ) );
767 $against = explode( '/', $from );
768
769 // Trim off common prefix
770 while( count( $pieces ) && count( $against )
771 && $pieces[0] == $against[0] ) {
772 array_shift( $pieces );
773 array_shift( $against );
774 }
775
776 // relative dots to bump us to the parent
777 while( count( $against ) ) {
778 array_unshift( $pieces, '..' );
779 array_shift( $against );
780 }
781
782 array_push( $pieces, basename( $path ) );
783
784 return implode( '/', $pieces );
785 }
786
787 function upgradeOldImage() {
788 $tabledef = <<<END
789 CREATE TABLE $1 (
790 -- Base filename: key to image.img_name
791 oi_name varchar(255) binary NOT NULL default '',
792
793 -- Filename of the archived file.
794 -- This is generally a timestamp and '!' prepended to the base name.
795 oi_archive_name varchar(255) binary NOT NULL default '',
796
797 -- Other fields as in image...
798 oi_size int(8) unsigned NOT NULL default 0,
799 oi_width int(5) NOT NULL default 0,
800 oi_height int(5) NOT NULL default 0,
801 oi_bits int(3) NOT NULL default 0,
802 oi_description tinyblob NOT NULL default '',
803 oi_user int(5) unsigned NOT NULL default '0',
804 oi_user_text varchar(255) binary NOT NULL default '',
805 oi_timestamp char(14) binary NOT NULL default '',
806
807 INDEX oi_name (oi_name(10))
808
809 ) TYPE=InnoDB;
810 END;
811 $fields = array(
812 'oi_name' => MW_UPGRADE_ENCODE,
813 'oi_archive_name' => MW_UPGRADE_ENCODE,
814 'oi_size' => MW_UPGRADE_COPY,
815 'oi_width' => MW_UPGRADE_CALLBACK,
816 'oi_height' => MW_UPGRADE_CALLBACK,
817 'oi_bits' => MW_UPGRADE_CALLBACK,
818 'oi_description' => MW_UPGRADE_ENCODE,
819 'oi_user' => MW_UPGRADE_COPY,
820 'oi_user_text' => MW_UPGRADE_ENCODE,
821 'oi_timestamp' => MW_UPGRADE_COPY );
822 $this->copyTable( 'oldimage', $tabledef, $fields,
823 array( &$this, 'oldimageCallback' ) );
824 }
825
826 function oldimageCallback( $row, $copy ) {
827 // Fill in the new image info fields
828 $info = $this->imageInfo( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
829 $copy['oi_width' ] = $info['width' ];
830 $copy['oi_height'] = $info['height'];
831 $copy['oi_bits' ] = $info['bits' ];
832
833 // If doing UTF8 conversion the file must be renamed
834 $this->renameFile( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
835
836 return $copy;
837 }
838
839
840 function upgradeWatchlist() {
841 $fname = 'FiveUpgrade::upgradeWatchlist';
842 $chunksize = 100;
843
844 extract( $this->dbw->tableNames( 'watchlist', 'watchlist_temp' ) );
845
846 $this->log( 'Migrating watchlist table to watchlist_temp...' );
847 $this->dbw->query(
848 "CREATE TABLE $watchlist_temp (
849 -- Key to user_id
850 wl_user int(5) unsigned NOT NULL,
851
852 -- Key to page_namespace/page_title
853 -- Note that users may watch patches which do not exist yet,
854 -- or existed in the past but have been deleted.
855 wl_namespace int NOT NULL default '0',
856 wl_title varchar(255) binary NOT NULL default '',
857
858 -- Timestamp when user was last sent a notification e-mail;
859 -- cleared when the user visits the page.
860 -- FIXME: add proper null support etc
861 wl_notificationtimestamp varchar(14) binary NOT NULL default '0',
862
863 UNIQUE KEY (wl_user, wl_namespace, wl_title),
864 KEY namespace_title (wl_namespace,wl_title)
865
866 ) TYPE=InnoDB;", $fname );
867
868 // Fix encoding for Latin-1 upgrades, add some fields,
869 // and double article to article+talk pairs
870 $numwatched = $this->dbw->selectField( 'watchlist', 'count(*)', '', $fname );
871
872 $this->setChunkScale( $chunksize, $numwatched * 2, 'watchlist_temp', $fname );
873 $result = $this->dbr->select( 'watchlist',
874 array(
875 'wl_user',
876 'wl_namespace',
877 'wl_title' ),
878 '',
879 $fname );
880
881 $add = array();
882 while( $row = $this->dbr->fetchObject( $result ) ) {
883 $now = $this->dbw->timestamp();
884 $add[] = array(
885 'wl_user' => $row->wl_user,
886 'wl_namespace' => Namespace::getSubject( $row->wl_namespace ),
887 'wl_title' => $this->conv( $row->wl_title ),
888 'wl_notificationtimestamp' => '0' );
889 $this->addChunk( $add );
890
891 $add[] = array(
892 'wl_user' => $row->wl_user,
893 'wl_namespace' => Namespace::getTalk( $row->wl_namespace ),
894 'wl_title' => $this->conv( $row->wl_title ),
895 'wl_notificationtimestamp' => '0' );
896 $this->addChunk( $add );
897 }
898 $this->lastChunk( $add );
899 $this->dbr->freeResult( $result );
900
901 $this->log( 'Done converting watchlist.' );
902 $this->cleanupSwaps[] = 'watchlist';
903 }
904
905 function upgradeLogging() {
906 $tabledef = <<<END
907 CREATE TABLE $1 (
908 -- Symbolic keys for the general log type and the action type
909 -- within the log. The output format will be controlled by the
910 -- action field, but only the type controls categorization.
911 log_type char(10) NOT NULL default '',
912 log_action char(10) NOT NULL default '',
913
914 -- Timestamp. Duh.
915 log_timestamp char(14) NOT NULL default '19700101000000',
916
917 -- The user who performed this action; key to user_id
918 log_user int unsigned NOT NULL default 0,
919
920 -- Key to the page affected. Where a user is the target,
921 -- this will point to the user page.
922 log_namespace int NOT NULL default 0,
923 log_title varchar(255) binary NOT NULL default '',
924
925 -- Freeform text. Interpreted as edit history comments.
926 log_comment varchar(255) NOT NULL default '',
927
928 -- LF separated list of miscellaneous parameters
929 log_params blob NOT NULL default '',
930
931 KEY type_time (log_type, log_timestamp),
932 KEY user_time (log_user, log_timestamp),
933 KEY page_time (log_namespace, log_title, log_timestamp)
934
935 ) TYPE=InnoDB
936 END;
937 $fields = array(
938 'log_type' => MW_UPGRADE_COPY,
939 'log_action' => MW_UPGRADE_COPY,
940 'log_timestamp' => MW_UPGRADE_COPY,
941 'log_user' => MW_UPGRADE_COPY,
942 'log_namespace' => MW_UPGRADE_COPY,
943 'log_title' => MW_UPGRADE_ENCODE,
944 'log_comment' => MW_UPGRADE_ENCODE,
945 'log_params' => MW_UPGRADE_ENCODE );
946 $this->copyTable( 'archive', $tabledef, $fields );
947 }
948
949 function upgradeArchive() {
950 $tabledef = <<<END
951 CREATE TABLE $1 (
952 ar_namespace int NOT NULL default '0',
953 ar_title varchar(255) binary NOT NULL default '',
954 ar_text mediumblob NOT NULL default '',
955
956 ar_comment tinyblob NOT NULL default '',
957 ar_user int(5) unsigned NOT NULL default '0',
958 ar_user_text varchar(255) binary NOT NULL,
959 ar_timestamp char(14) binary NOT NULL default '',
960 ar_minor_edit tinyint(1) NOT NULL default '0',
961
962 ar_flags tinyblob NOT NULL default '',
963
964 ar_rev_id int(8) unsigned,
965 ar_text_id int(8) unsigned,
966
967 KEY name_title_timestamp (ar_namespace,ar_title,ar_timestamp)
968
969 ) TYPE=InnoDB
970 END;
971 $fields = array(
972 'ar_namespace' => MW_UPGRADE_COPY,
973 'ar_title' => MW_UPGRADE_ENCODE,
974 'ar_text' => MW_UPGRADE_COPY,
975 'ar_comment' => MW_UPGRADE_ENCODE,
976 'ar_user' => MW_UPGRADE_COPY,
977 'ar_user_text' => MW_UPGRADE_ENCODE,
978 'ar_timestamp' => MW_UPGRADE_COPY,
979 'ar_minor_edit' => MW_UPGRADE_COPY,
980 'ar_flags' => MW_UPGRADE_COPY,
981 'ar_rev_id' => MW_UPGRADE_NULL,
982 'ar_text_id' => MW_UPGRADE_NULL );
983 $this->copyTable( 'archive', $tabledef, $fields );
984 }
985
986 function upgradeImagelinks() {
987 global $wgUseLatin1;
988 if( $wgUseLatin1 ) {
989 $tabledef = <<<END
990 CREATE TABLE $1 (
991 -- Key to page_id of the page containing the image / media link.
992 il_from int(8) unsigned NOT NULL default '0',
993
994 -- Filename of target image.
995 -- This is also the page_title of the file's description page;
996 -- all such pages are in namespace 6 (NS_IMAGE).
997 il_to varchar(255) binary NOT NULL default '',
998
999 UNIQUE KEY il_from(il_from,il_to),
1000 KEY (il_to)
1001
1002 ) TYPE=InnoDB
1003 END;
1004 $fields = array(
1005 'il_from' => MW_UPGRADE_COPY,
1006 'il_to' => MW_UPGRADE_ENCODE );
1007 $this->copyTable( 'imagelinks', $tabledef, $fields );
1008 }
1009 }
1010
1011 function upgradeCategorylinks() {
1012 global $wgUseLatin1;
1013 if( $wgUseLatin1 ) {
1014 $tabledef = <<<END
1015 CREATE TABLE $1 (
1016 cl_from int(8) unsigned NOT NULL default '0',
1017 cl_to varchar(255) binary NOT NULL default '',
1018 cl_sortkey varchar(86) binary NOT NULL default '',
1019 cl_timestamp timestamp NOT NULL,
1020
1021 UNIQUE KEY cl_from(cl_from,cl_to),
1022 KEY cl_sortkey(cl_to,cl_sortkey),
1023 KEY cl_timestamp(cl_to,cl_timestamp)
1024 ) TYPE=InnoDB
1025 END;
1026 $fields = array(
1027 'cl_from' => MW_UPGRADE_COPY,
1028 'cl_to' => MW_UPGRADE_ENCODE,
1029 'cl_sortkey' => MW_UPGRADE_ENCODE,
1030 'cl_timestamp' => MW_UPGRADE_COPY );
1031 $this->copyTable( 'categorylinks', $tabledef, $fields );
1032 }
1033 }
1034
1035 function upgradeIpblocks() {
1036 global $wgUseLatin1;
1037 if( $wgUseLatin1 ) {
1038 $tabledef = <<<END
1039 CREATE TABLE $1 (
1040 ipb_id int(8) NOT NULL auto_increment,
1041 ipb_address varchar(40) binary NOT NULL default '',
1042 ipb_user int(8) unsigned NOT NULL default '0',
1043 ipb_by int(8) unsigned NOT NULL default '0',
1044 ipb_reason tinyblob NOT NULL default '',
1045 ipb_timestamp char(14) binary NOT NULL default '',
1046 ipb_auto tinyint(1) NOT NULL default '0',
1047 ipb_expiry char(14) binary NOT NULL default '',
1048
1049 PRIMARY KEY ipb_id (ipb_id),
1050 INDEX ipb_address (ipb_address),
1051 INDEX ipb_user (ipb_user)
1052
1053 ) TYPE=InnoDB
1054 END;
1055 $fields = array(
1056 'ipb_id' => MW_UPGRADE_COPY,
1057 'ipb_address' => MW_UPGRADE_COPY,
1058 'ipb_user' => MW_UPGRADE_COPY,
1059 'ipb_by' => MW_UPGRADE_COPY,
1060 'ipb_reason' => MW_UPGRADE_ENCODE,
1061 'ipb_timestamp' => MW_UPGRADE_COPY,
1062 'ipb_auto' => MW_UPGRADE_COPY,
1063 'ipb_expiry' => MW_UPGRADE_COPY );
1064 $this->copyTable( 'ipblocks', $tabledef, $fields );
1065 }
1066 }
1067
1068 function upgradeRecentchanges() {
1069 // There's a format change in the namespace field
1070 $tabledef = <<<END
1071 CREATE TABLE $1 (
1072 rc_id int(8) NOT NULL auto_increment,
1073 rc_timestamp varchar(14) binary NOT NULL default '',
1074 rc_cur_time varchar(14) binary NOT NULL default '',
1075
1076 rc_user int(10) unsigned NOT NULL default '0',
1077 rc_user_text varchar(255) binary NOT NULL default '',
1078
1079 rc_namespace int NOT NULL default '0',
1080 rc_title varchar(255) binary NOT NULL default '',
1081
1082 rc_comment varchar(255) binary NOT NULL default '',
1083 rc_minor tinyint(3) unsigned NOT NULL default '0',
1084
1085 rc_bot tinyint(3) unsigned NOT NULL default '0',
1086 rc_new tinyint(3) unsigned NOT NULL default '0',
1087
1088 rc_cur_id int(10) unsigned NOT NULL default '0',
1089 rc_this_oldid int(10) unsigned NOT NULL default '0',
1090 rc_last_oldid int(10) unsigned NOT NULL default '0',
1091
1092 rc_type tinyint(3) unsigned NOT NULL default '0',
1093 rc_moved_to_ns tinyint(3) unsigned NOT NULL default '0',
1094 rc_moved_to_title varchar(255) binary NOT NULL default '',
1095
1096 rc_patrolled tinyint(3) unsigned NOT NULL default '0',
1097
1098 rc_ip char(15) NOT NULL default '',
1099
1100 PRIMARY KEY rc_id (rc_id),
1101 INDEX rc_timestamp (rc_timestamp),
1102 INDEX rc_namespace_title (rc_namespace, rc_title),
1103 INDEX rc_cur_id (rc_cur_id),
1104 INDEX new_name_timestamp(rc_new,rc_namespace,rc_timestamp),
1105 INDEX rc_ip (rc_ip)
1106
1107 ) TYPE=InnoDB
1108 END;
1109 $fields = array(
1110 'rc_id' => MW_UPGRADE_COPY,
1111 'rc_timestamp' => MW_UPGRADE_COPY,
1112 'rc_cur_time' => MW_UPGRADE_COPY,
1113 'rc_user' => MW_UPGRADE_COPY,
1114 'rc_user_text' => MW_UPGRADE_ENCODE,
1115 'rc_namespace' => MW_UPGRADE_COPY,
1116 'rc_title' => MW_UPGRADE_ENCODE,
1117 'rc_comment' => MW_UPGRADE_ENCODE,
1118 'rc_minor' => MW_UPGRADE_COPY,
1119 'rc_bot' => MW_UPGRADE_COPY,
1120 'rc_new' => MW_UPGRADE_COPY,
1121 'rc_cur_id' => MW_UPGRADE_COPY,
1122 'rc_this_oldid' => MW_UPGRADE_COPY,
1123 'rc_last_oldid' => MW_UPGRADE_COPY,
1124 'rc_type' => MW_UPGRADE_COPY,
1125 'rc_moved_to_ns' => MW_UPGRADE_COPY,
1126 'rc_moved_to_title' => MW_UPGRADE_ENCODE,
1127 'rc_patrolled' => MW_UPGRADE_COPY,
1128 'rc_ip' => MW_UPGRADE_COPY );
1129 $this->copyTable( 'recentchanges', $tabledef, $fields );
1130 }
1131
1132 /**
1133 * Rename all our temporary tables into final place.
1134 * We've left things in place so a read-only wiki can continue running
1135 * on the old code during all this.
1136 */
1137 function upgradeCleanup() {
1138 $this->renameTable( 'old', 'text' );
1139
1140 foreach( $this->cleanupSwaps as $table ) {
1141 $this->swap( $table );
1142 }
1143 }
1144
1145 function renameTable( $from, $to ) {
1146 $this->log( 'Renaming $from to $to...' );
1147
1148 $fromtable = $this->dbw->tableName( $from );
1149 $totable = $this->dbw->tableName( $to );
1150 $this->dbw->query( "ALTER TABLE $fromtable RENAME TO $totable" );
1151 }
1152
1153 function swap( $base ) {
1154 $this->renameTable( $base, "{$base}_old" );
1155 $this->renameTable( "{$base}_temp", $base );
1156 }
1157
1158 }
1159
1160 $upgrade = new FiveUpgrade();
1161 $step = isset( $options['step'] ) ? $options['step'] : null;
1162 $upgrade->upgrade( $step );
1163
1164 ?>