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