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