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