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