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