Convert image table:
[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 require_once( 'commandLine.inc' );
16 require_once( 'cleanupDupes.inc' );
17 require_once( 'userDupes.inc' );
18 require_once( 'updaters.inc' );
19
20 $upgrade = new FiveUpgrade();
21 $upgrade->upgrade();
22
23 class FiveUpgrade {
24 function FiveUpgrade() {
25 global $wgDatabase;
26 $this->conversionTables = $this->prepareWindows1252();
27 $this->dbw =& $this->newConnection();
28 $this->dbr =& $this->newConnection();
29 $this->dbr->bufferResults( false );
30 }
31
32 function upgrade() {
33 $this->upgradePage();
34 $this->upgradeLinks();
35 $this->upgradeUser();
36 $this->upgradeImage();
37 #$this->upgradeOldImage();
38 }
39
40
41 /**
42 * Open a second connection to the master server, with buffering off.
43 * This will let us stream large datasets in and write in chunks on the
44 * other end.
45 * @return Database
46 * @access private
47 */
48 function &newConnection() {
49 global $wgDBadminuser, $wgDBadminpassword;
50 global $wgDBserver, $wgDBname;
51 $db =& new Database( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
52 return $db;
53 }
54
55 /**
56 * Prepare a conversion array for converting Windows Code Page 1252 to
57 * UTF-8. This should provide proper conversion of text that was miscoded
58 * as Windows-1252 by naughty user-agents, and doesn't rely on an outside
59 * iconv library.
60 *
61 * @return array
62 * @access private
63 */
64 function prepareWindows1252() {
65 # Mappings from:
66 # http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
67 static $cp1252 = array(
68 0x80 => 0x20AC, #EURO SIGN
69 0x81 => UNICODE_REPLACEMENT,
70 0x82 => 0x201A, #SINGLE LOW-9 QUOTATION MARK
71 0x83 => 0x0192, #LATIN SMALL LETTER F WITH HOOK
72 0x84 => 0x201E, #DOUBLE LOW-9 QUOTATION MARK
73 0x85 => 0x2026, #HORIZONTAL ELLIPSIS
74 0x86 => 0x2020, #DAGGER
75 0x87 => 0x2021, #DOUBLE DAGGER
76 0x88 => 0x02C6, #MODIFIER LETTER CIRCUMFLEX ACCENT
77 0x89 => 0x2030, #PER MILLE SIGN
78 0x8A => 0x0160, #LATIN CAPITAL LETTER S WITH CARON
79 0x8B => 0x2039, #SINGLE LEFT-POINTING ANGLE QUOTATION MARK
80 0x8C => 0x0152, #LATIN CAPITAL LIGATURE OE
81 0x8D => UNICODE_REPLACEMENT,
82 0x8E => 0x017D, #LATIN CAPITAL LETTER Z WITH CARON
83 0x8F => UNICODE_REPLACEMENT,
84 0x90 => UNICODE_REPLACEMENT,
85 0x91 => 0x2018, #LEFT SINGLE QUOTATION MARK
86 0x92 => 0x2019, #RIGHT SINGLE QUOTATION MARK
87 0x93 => 0x201C, #LEFT DOUBLE QUOTATION MARK
88 0x94 => 0x201D, #RIGHT DOUBLE QUOTATION MARK
89 0x95 => 0x2022, #BULLET
90 0x96 => 0x2013, #EN DASH
91 0x97 => 0x2014, #EM DASH
92 0x98 => 0x02DC, #SMALL TILDE
93 0x99 => 0x2122, #TRADE MARK SIGN
94 0x9A => 0x0161, #LATIN SMALL LETTER S WITH CARON
95 0x9B => 0x203A, #SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
96 0x9C => 0x0153, #LATIN SMALL LIGATURE OE
97 0x9D => UNICODE_REPLACEMENT,
98 0x9E => 0x017E, #LATIN SMALL LETTER Z WITH CARON
99 0x9F => 0x0178, #LATIN CAPITAL LETTER Y WITH DIAERESIS
100 );
101 $pairs = array();
102 for( $i = 0; $i < 0x100; $i++ ) {
103 $unicode = isset( $cp1252[$i] ) ? $cp1252[$i] : $i;
104 $pairs[chr( $i )] = codepointToUtf8( $unicode );
105 }
106 return $pairs;
107 }
108
109 /**
110 * Convert from 8-bit Windows-1252 to UTF-8 if necessary.
111 * @param string $text
112 * @return string
113 * @access private
114 */
115 function conv( $text ) {
116 global $wgUseLatin1;
117 if( $wgUseLatin1 ) {
118 return strtr( $text, $this->conversionTables );
119 } else {
120 return $text;
121 }
122 }
123
124 /**
125 * Dump timestamp and message to output
126 * @param string $message
127 * @access private
128 */
129 function log( $message ) {
130 echo wfTimestamp( TS_DB ) . ': ' . $message . "\n";
131 flush();
132 }
133
134 /**
135 * Initialize the chunked-insert system.
136 * Rows will be inserted in chunks of the given number, rather
137 * than in a giant INSERT...SELECT query, to keep the serialized
138 * MySQL database replication from getting hung up. This way other
139 * things can be going on during conversion without waiting for
140 * slaves to catch up as badly.
141 *
142 * @param int $chunksize Number of rows to insert at once
143 * @param int $final Total expected number of rows / id of last row,
144 * used for progress reports.
145 * @param string $table to insert on
146 * @param string $fname function name to report in SQL
147 * @access private
148 */
149 function setChunkScale( $chunksize, $final, $table, $fname ) {
150 $this->chunkSize = $chunksize;
151 $this->chunkFinal = $final;
152 $this->chunkCount = 0;
153 $this->chunkStartTime = wfTime();
154 $this->chunkOptions = array();
155 $this->chunkTable = $table;
156 $this->chunkFunction = $fname;
157 }
158
159 /**
160 * Chunked inserts: perform an insert if we've reached the chunk limit.
161 * Prints a progress report with estimated completion time.
162 * @param array &$chunk -- This will be emptied if an insert is done.
163 * @param int $key A key identifier to use in progress estimation in
164 * place of the number of rows inserted. Use this if
165 * you provided a max key number instead of a count
166 * as the final chunk number in setChunkScale()
167 * @access private
168 */
169 function addChunk( &$chunk, $key = null ) {
170 if( count( $chunk ) >= $this->chunkSize ) {
171 $this->insertChunk( $chunk );
172
173 $this->chunkCount += count( $chunk );
174 $now = wfTime();
175 $delta = $now - $this->chunkStartTime;
176 $rate = $this->chunkCount / $delta;
177
178 if( is_null( $key ) ) {
179 $completed = $this->chunkCount;
180 } else {
181 $completed = $key;
182 }
183 $portion = $completed / $this->chunkFinal;
184
185 $estimatedTotalTime = $delta / $portion;
186 $eta = $this->chunkStartTime + $estimatedTotalTime;
187
188 printf( "%s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec\n",
189 wfTimestamp( TS_DB, intval( $now ) ),
190 $portion * 100.0,
191 $this->chunkTable,
192 wfTimestamp( TS_DB, intval( $eta ) ),
193 $completed,
194 $this->chunkFinal,
195 $rate );
196 flush();
197
198 $chunk = array();
199 }
200 }
201
202 /**
203 * Chunked inserts: perform an insert unconditionally, at the end, and log.
204 * @param array &$chunk -- This will be emptied if an insert is done.
205 * @access private
206 */
207 function lastChunk( &$chunk ) {
208 $n = count( $chunk );
209 if( $n > 0 ) {
210 $this->insertChunk( $chunk );
211 }
212 $this->log( "100.00% done on $this->chunkTable (last chunk $n rows)." );
213 }
214
215 /**
216 * Chunked inserts: perform an insert.
217 * @param array &$chunk -- This will be emptied if an insert is done.
218 * @access private
219 */
220 function insertChunk( &$chunk ) {
221 $this->dbw->insert( $this->chunkTable, $chunk, $this->chunkFunction, $this->chunkOptions );
222 }
223
224
225 function upgradePage() {
226 $fname = "FiveUpgrade::upgradePage";
227 $chunksize = 100;
228
229
230 $this->log( "Checking cur table for unique title index and applying if necessary" );
231 checkDupes( true );
232
233 $this->log( "...converting from cur/old to page/revision/text DB structure." );
234
235 extract( $this->dbw->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
236
237 $this->log( "Creating page and revision tables..." );
238 $this->dbw->query("CREATE TABLE $page (
239 page_id int(8) unsigned NOT NULL auto_increment,
240 page_namespace int NOT NULL,
241 page_title varchar(255) binary NOT NULL,
242 page_restrictions tinyblob NOT NULL default '',
243 page_counter bigint(20) unsigned NOT NULL default '0',
244 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
245 page_is_new tinyint(1) unsigned NOT NULL default '0',
246 page_random real unsigned NOT NULL,
247 page_touched char(14) binary NOT NULL default '',
248 page_latest int(8) unsigned NOT NULL,
249 page_len int(8) unsigned NOT NULL,
250
251 PRIMARY KEY page_id (page_id),
252 UNIQUE INDEX name_title (page_namespace,page_title),
253 INDEX (page_random),
254 INDEX (page_len)
255 ) TYPE=InnoDB", $fname );
256 $this->dbw->query("CREATE TABLE $revision (
257 rev_id int(8) unsigned NOT NULL auto_increment,
258 rev_page int(8) unsigned NOT NULL,
259 rev_comment tinyblob NOT NULL default '',
260 rev_user int(5) unsigned NOT NULL default '0',
261 rev_user_text varchar(255) binary NOT NULL default '',
262 rev_timestamp char(14) binary NOT NULL default '',
263 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
264 rev_deleted tinyint(1) unsigned NOT NULL default '0',
265
266 PRIMARY KEY rev_page_id (rev_page, rev_id),
267 UNIQUE INDEX rev_id (rev_id),
268 INDEX rev_timestamp (rev_timestamp),
269 INDEX page_timestamp (rev_page,rev_timestamp),
270 INDEX user_timestamp (rev_user,rev_timestamp),
271 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
272 ) TYPE=InnoDB", $fname );
273
274 $maxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
275 $this->log( "Last old record is {$maxold}" );
276
277 global $wgLegacySchemaConversion;
278 if( $wgLegacySchemaConversion ) {
279 // Create HistoryBlobCurStub entries.
280 // Text will be pulled from the leftover 'cur' table at runtime.
281 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
282 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
283 $cur_flags = "'object'";
284 } else {
285 // Copy all cur text in immediately: this may take longer but avoids
286 // having to keep an extra table around.
287 echo "......Moving text from cur.\n";
288 $cur_text = 'cur_text';
289 $cur_flags = "''";
290 }
291
292 $maxcur = $this->dbw->selectField( 'cur', 'max(cur_id)', '', $fname );
293 $this->log( "Last cur entry is $maxcur" );
294
295 /**
296 * Copy placeholder records for each page's current version into old
297 * Don't do any conversion here; text records are converted at runtime
298 * based on the flags (and may be originally binary!) while the meta
299 * fields will be converted in the old -> rev and cur -> page steps.
300 */
301 $this->setChunkScale( $chunksize, $maxcur, 'old', $fname );
302 $result = $this->dbr->query(
303 "SELECT cur_id, cur_namespace, cur_title, $cur_text AS text, cur_comment,
304 cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags AS flags
305 FROM $cur
306 ORDER BY cur_id", $fname );
307 $add = array();
308 while( $row = $this->dbr->fetchObject( $result ) ) {
309 $add[] = array(
310 'old_namespace' => $row->cur_namespace,
311 'old_title' => $row->cur_title,
312 'old_text' => $row->text,
313 'old_comment' => $row->cur_comment,
314 'old_user' => $row->cur_user,
315 'old_user_text' => $row->cur_user_text,
316 'old_timestamp' => $row->cur_timestamp,
317 'old_minor_edit' => $row->cur_minor_edit,
318 'old_flags' => $row->flags );
319 $this->addChunk( $add, $row->cur_id );
320 }
321 $this->lastChunk( $add );
322 $this->dbr->freeResult( $result );
323
324 /**
325 * Copy revision metadata from old into revision.
326 * We'll also do UTF-8 conversion of usernames and comments.
327 */
328 #$newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
329 #$this->setChunkScale( $chunksize, $newmaxold, 'revision', $fname );
330 $countold = $this->dbw->selectField( 'old', 'count(old_id)', '', $fname );
331 $this->setChunkScale( $chunksize, $countold, 'revision', $fname );
332
333 $this->log( "......Setting up revision table." );
334 $result = $this->dbr->query(
335 "SELECT old_id, cur_id, old_comment, old_user, old_user_text,
336 old_timestamp, old_minor_edit
337 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title",
338 $fname );
339
340 $add = array();
341 while( $row = $this->dbr->fetchObject( $result ) ) {
342 $add[] = array(
343 'rev_id' => $row->old_id,
344 'rev_page' => $row->cur_id,
345 'rev_comment' => $this->conv( $row->old_comment ),
346 'rev_user' => $row->old_user,
347 'rev_user_text' => $this->conv( $row->old_user_text ),
348 'rev_timestamp' => $row->old_timestamp,
349 'rev_minor_edit' => $row->old_minor_edit );
350 $this->addChunk( $add );
351 }
352 $this->lastChunk( $add );
353 $this->dbr->freeResult( $result );
354
355
356 /**
357 * Copy page metadata from cur into page.
358 * We'll also do UTF-8 conversion of titles.
359 */
360 $this->log( "......Setting up page table." );
361 $this->setChunkScale( $chunksize, $maxcur, 'page', $fname );
362 $result = $this->dbr->query( "
363 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
364 cur_random, cur_touched, rev_id, LENGTH(cur_text) AS len
365 FROM $cur,$revision
366 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}
367 ORDER BY cur_id", $fname );
368 $add = array();
369 while( $row = $this->dbr->fetchObject( $result ) ) {
370 $add[] = array(
371 'page_id' => $row->cur_id,
372 'page_namespace' => $row->cur_namespace,
373 'page_title' => $this->conv( $row->cur_title ),
374 'page_restrictions' => $row->cur_restrictions,
375 'page_counter' => $row->cur_counter,
376 'page_is_redirect' => $row->cur_is_redirect,
377 'page_is_new' => $row->cur_is_new,
378 'page_random' => $row->cur_random,
379 'page_touched' => $this->dbw->timestamp(),
380 'page_latest' => $row->rev_id,
381 'page_len' => $row->len );
382 $this->addChunk( $add, $row->cur_id );
383 }
384 $this->lastChunk( $add );
385 $this->dbr->freeResult( $result );
386
387 $this->log( "......Renaming old." );
388 $this->dbw->query( "ALTER TABLE $old RENAME TO $text", $fname );
389
390 $this->log( "...done." );
391 }
392
393 function upgradeLinks() {
394 $fname = 'FiveUpgrade::upgradeLinks';
395 $chunksize = 200;
396 extract( $this->dbw->tableNames( 'links', 'brokenlinks', 'pagelinks', 'page' ) );
397
398 $this->log( 'Creating pagelinks table...' );
399 $this->dbw->query( "
400 CREATE TABLE $pagelinks (
401 -- Key to the page_id of the page containing the link.
402 pl_from int(8) unsigned NOT NULL default '0',
403
404 -- Key to page_namespace/page_title of the target page.
405 -- The target page may or may not exist, and due to renames
406 -- and deletions may refer to different page records as time
407 -- goes by.
408 pl_namespace int NOT NULL default '0',
409 pl_title varchar(255) binary NOT NULL default '',
410
411 UNIQUE KEY pl_from(pl_from,pl_namespace,pl_title),
412 KEY (pl_namespace,pl_title)
413
414 ) TYPE=InnoDB" );
415
416 $this->log( 'Importing live links -> pagelinks' );
417 $nlinks = $this->dbw->selectField( 'links', 'count(*)', '', $fname );
418 if( $nlinks ) {
419 $this->setChunkScale( $chunksize, $nlinks, 'pagelinks', $fname );
420 $result = $this->dbr->query( "
421 SELECT l_from,page_namespace,page_title
422 FROM $links, $page
423 WHERE l_to=page_id", $fname );
424 $add = array();
425 while( $row = $this->dbr->fetchObject( $result ) ) {
426 $add[] = array(
427 'pl_from' => $row->l_from,
428 'pl_namespace' => $row->page_namespace,
429 'pl_title' => $row->page_title );
430 $this->addChunk( $add );
431 }
432 $this->lastChunk( $add );
433 } else {
434 $this->log( 'no links!' );
435 }
436
437 $this->log( 'Importing brokenlinks -> pagelinks' );
438 $nbrokenlinks = $this->dbw->selectField( 'brokenlinks', 'count(*)', '', $fname );
439 if( $nbrokenlinks ) {
440 $this->setChunkScale( $chunksize, $nbrokenlinks, 'pagelinks', $fname );
441 $this->chunkOptions = array( 'IGNORE' );
442 $result = $this->dbr->query(
443 "SELECT bl_from, bl_to FROM $brokenlinks",
444 $fname );
445 $add = array();
446 while( $row = $this->dbr->fetchObject( $result ) ) {
447 $pagename = $this->conv( $row->bl_to );
448 $title = Title::newFromText( $pagename );
449 if( is_null( $title ) ) {
450 $this->log( "** invalid brokenlink: $row->bl_from -> '$pagename' (converted from '$row->bl_to')" );
451 } else {
452 $add[] = array(
453 'pl_from' => $row->bl_from,
454 'pl_namespace' => $title->getNamespace(),
455 'pl_title' => $title->getDBkey() );
456 $this->addChunk( $add );
457 }
458 }
459 $this->lastChunk( $add );
460 } else {
461 $this->log( 'no brokenlinks!' );
462 }
463
464 $this->log( 'Done with links.' );
465 }
466
467 function upgradeUser() {
468 $fname = 'FiveUpgrade::upgradeUser';
469 $chunksize = 100;
470 $preauth = 0;
471
472 // Apply unique index, if necessary:
473 $duper = new UserDupes( $this->dbw );
474 if( $duper->hasUniqueIndex() ) {
475 $this->log( "Already have unique user_name index." );
476 } else {
477 $this->log( "Clearing user duplicates..." );
478 if( !$duper->clearDupes() ) {
479 $this->log( "WARNING: Duplicate user accounts, may explode!" );
480 }
481 }
482
483 /** Convert encoding on options, etc */
484 extract( $this->dbw->tableNames( 'user', 'user_temp', 'user_old' ) );
485
486 $this->log( 'Migrating user table to user_temp...' );
487 $this->dbw->query( "CREATE TABLE $user_temp (
488 user_id int(5) unsigned NOT NULL auto_increment,
489 user_name varchar(255) binary NOT NULL default '',
490 user_real_name varchar(255) binary NOT NULL default '',
491 user_password tinyblob NOT NULL default '',
492 user_newpassword tinyblob NOT NULL default '',
493 user_email tinytext NOT NULL default '',
494 user_options blob NOT NULL default '',
495 user_touched char(14) binary NOT NULL default '',
496 user_token char(32) binary NOT NULL default '',
497 user_email_authenticated CHAR(14) BINARY,
498 user_email_token CHAR(32) BINARY,
499 user_email_token_expires CHAR(14) BINARY,
500
501 PRIMARY KEY user_id (user_id),
502 UNIQUE INDEX user_name (user_name),
503 INDEX (user_email_token)
504
505 ) TYPE=InnoDB", $fname );
506
507 // Fix encoding for Latin-1 upgrades, and add some fields.
508 $numusers = $this->dbw->selectField( 'user', 'count(*)', '', $fname );
509 $this->setChunkScale( $chunksize, $numusers, 'user_temp', $fname );
510 $result = $this->dbr->select( 'user',
511 array(
512 'user_id',
513 'user_name',
514 'user_real_name',
515 'user_password',
516 'user_newpassword',
517 'user_email',
518 'user_options',
519 'user_touched',
520 'user_token' ),
521 '',
522 $fname );
523 $add = array();
524 while( $row = $this->dbr->fetchObject( $result ) ) {
525 $now = $this->dbw->timestamp();
526 $add[] = array(
527 'user_id' => $row->user_id,
528 'user_name' => $this->conv( $row->user_name ),
529 'user_real_name' => $this->conv( $row->user_real_name ),
530 'user_password' => $row->user_password,
531 'user_newpassword' => $row->user_newpassword,
532 'user_email' => $this->conv( $row->user_email ),
533 'user_options' => $this->conv( $row->user_options ),
534 'user_touched' => $now,
535 'user_token' => $row->user_token,
536 'user_email_authenticated' => $preauth ? $now : null,
537 'user_email_token' => null,
538 'user_email_token_expires' => null );
539 $this->addChunk( $add );
540 }
541 $this->lastChunk( $add );
542 $this->dbr->freeResult( $result );
543
544 $this->log( 'Renaming user to user_old and user_temp to user...' );
545 $this->dbw->query( "ALTER TABLE $user RENAME TO $user_old" );
546 $this->dbw->query( "ALTER TABLE $user_temp RENAME TO $user" );
547 }
548
549 function upgradeImage() {
550 $fname = 'FiveUpgrade::upgradeImage';
551 $chunksize = 100;
552
553 extract( $this->dbw->tableNames( 'image', 'image_temp', 'image_old' ) );
554 $this->log( 'Creating temporary image_temp to merge into...' );
555 $this->dbw->query( <<<END
556 CREATE TABLE $image_temp (
557 img_name varchar(255) binary NOT NULL default '',
558 img_size int(8) unsigned NOT NULL default '0',
559 img_width int(5) NOT NULL default '0',
560 img_height int(5) NOT NULL default '0',
561 img_metadata mediumblob NOT NULL,
562 img_bits int(3) NOT NULL default '0',
563 img_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL,
564 img_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown",
565 img_minor_mime varchar(32) NOT NULL default "unknown",
566 img_description tinyblob NOT NULL default '',
567 img_user int(5) unsigned NOT NULL default '0',
568 img_user_text varchar(255) binary NOT NULL default '',
569 img_timestamp char(14) binary NOT NULL default '',
570
571 PRIMARY KEY img_name (img_name),
572 INDEX img_size (img_size),
573 INDEX img_timestamp (img_timestamp)
574 ) TYPE=InnoDB
575 END
576 , $fname);
577
578 $numimages = $this->dbw->selectField( 'image', 'count(*)', '', $fname );
579 $result = $this->dbr->select( 'image',
580 array(
581 'img_name',
582 'img_size',
583 'img_description',
584 'img_user',
585 'img_user_text',
586 'img_timestamp' ),
587 '',
588 $fname );
589 $add = array();
590 $this->setChunkScale( $chunksize, $numimages, 'image_temp', $fname );
591 while( $row = $this->dbr->fetchObject( $result ) ) {
592 // Fill in the new image info fields
593 $info = $this->imageInfo( $row->img_name );
594
595 // Update and convert encoding
596 $add[] = array(
597 'img_name' => $this->conv( $row->img_name ),
598 'img_size' => $row->img_size,
599 'img_width' => $info['width'],
600 'img_height' => $info['height'],
601 'img_metadata' => "", // loaded on-demand
602 'img_bits' => $info['bits'],
603 'img_media_type' => $info['media'],
604 'img_major_mime' => $info['major'],
605 'img_minor_mime' => $info['minor'],
606 'img_description' => $this->conv( $row->img_description ),
607 'img_user' => $row->img_user,
608 'img_user_text' => $this->conv( $row->img_user_text ),
609 'img_timestamp' => $row->img_timestamp );
610
611 // If doing UTF8 conversion the file must be renamed
612 $this->renameFile( $row->img_name, 'wfImageDir' );
613 }
614 $this->lastChunk( $add );
615
616 $this->log( 'Renaming image to image_old and image_temp to image...' );
617 $this->dbw->query( "ALTER TABLE $image RENAME TO $image_old" );
618 $this->dbw->query( "ALTER TABLE $image_temp RENAME TO $image" );
619
620 $this->log( 'done with image table.' );
621 }
622
623 function imageInfo( $name ) {
624 $filename = wfImageDir( $name ) . '/' . $name;
625 $info = array(
626 'width' => 0,
627 'height' => 0,
628 'bits' => 0,
629 'media' => '',
630 'major' => '',
631 'minor' => '' );
632
633 $magic =& wfGetMimeMagic();
634 $mime = $magic->guessMimeType( $filename, true );
635 list( $info['major'], $info['minor'] ) = explode( '/', $mime );
636
637 $info['media'] = $magic->getMediaType( $filename, $mime );
638
639 # Height and width
640 $gis = false;
641 if( $mime == 'image/svg' ) {
642 $gis = wfGetSVGsize( $this->imagePath );
643 } elseif( $magic->isPHPImageType( $mime ) ) {
644 $gis = getimagesize( $filename );
645 } else {
646 $this->log( "Surprising mime type: $mime" );
647 }
648 if( $gis ) {
649 $info['width' ] = $gis[0];
650 $info['height'] = $gis[1];
651 }
652 if( isset( $gis['bits'] ) ) {
653 $info['bits'] = $gis['bits'];
654 }
655
656 return $info;
657 }
658
659
660 /**
661 * Truncate a table.
662 * @param string $table The table name to be truncated
663 */
664 function clearTable( $table ) {
665 print "Clearing $table...\n";
666 $tableName = $this->db->tableName( $table );
667 $this->db->query( 'TRUNCATE $tableName' );
668 }
669
670 /**
671 * Rename a given image or archived image file to the converted filename,
672 * leaving a symlink for URL compatibility.
673 *
674 * @param string $oldname pre-conversion filename
675 * @param callable $subdirCallback a function to generate hashed directories
676 * @access private
677 */
678 function renameFile( $oldname, $subdirCallback ) {
679 $newname = $this->conv( $oldname );
680 if( $newname == $oldname ) {
681 // No need to rename; another field triggered this row.
682 return;
683 }
684
685 $oldpath = call_user_func( $subdirCallback, $oldname ) . '/' . $oldname;
686 $newpath = call_user_func( $subdirCallback, $newname ) . '/' . $newname;
687
688 $this->log( "$oldpath -> $newpath" );
689 if( rename( $oldpath, $newpath ) ) {
690 $relpath = $this->relativize( $newpath, dirname( $oldpath ) );
691 if( !symlink( $relpath, $oldpath ) ) {
692 $this->log( "... symlink failed!" );
693 }
694 } else {
695 $this->log( "... rename failed!" );
696 }
697 }
698
699 /**
700 * Generate a relative path name to the given file.
701 * Assumes Unix-style paths, separators, and semantics.
702 *
703 * @param string $path Absolute destination path including target filename
704 * @param string $from Absolute source path, directory only
705 * @return string
706 * @access private
707 * @static
708 */
709 function relativize( $path, $from ) {
710 $pieces = explode( '/', dirname( $path ) );
711 $against = explode( '/', $from );
712
713 // Trim off common prefix
714 while( count( $pieces ) && count( $against )
715 && $pieces[0] == $against[0] ) {
716 array_shift( $pieces );
717 array_shift( $against );
718 }
719
720 // relative dots to bump us to the parent
721 while( count( $against ) ) {
722 array_unshift( $pieces, '..' );
723 array_shift( $against );
724 }
725
726 array_push( $pieces, basename( $path ) );
727
728 return implode( '/', $pieces );
729 }
730
731
732 }
733
734 ?>