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