Remove annoying `s from the definition of the protected_titles table.
[lhc/web/wiklou.git] / maintenance / dumpTextPass.php
1 <?php
2 /**
3 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
4 * http://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @addtogroup SpecialPage
22 */
23
24 $originalDir = getcwd();
25
26 require_once( 'commandLine.inc' );
27 require_once( 'backup.inc' );
28
29 /**
30 * Stream wrapper around 7za filter program.
31 * Required since we can't pass an open file resource to XMLReader->open()
32 * which is used for the text prefetch.
33 */
34 class SevenZipStream {
35 var $stream;
36
37 private function stripPath( $path ) {
38 $prefix = 'mediawiki.compress.7z://';
39 return substr( $path, strlen( $prefix ) );
40 }
41
42 function stream_open( $path, $mode, $options, &$opened_path ) {
43 if( $mode{0} == 'r' ) {
44 $options = 'e -bd -so';
45 } elseif( $mode{0} == 'w' ) {
46 $options = 'a -bd -si';
47 } else {
48 return false;
49 }
50 $arg = wfEscapeShellArg( $this->stripPath( $path ) );
51 $command = "7za $options $arg";
52 if( !wfIsWindows() ) {
53 // Suppress the stupid messages on stderr
54 $command .= ' 2>/dev/null';
55 }
56 $this->stream = popen( $command, $mode );
57 return ($this->stream !== false);
58 }
59
60 function url_stat( $path, $flags ) {
61 return stat( $this->stripPath( $path ) );
62 }
63
64 // This is all so lame; there should be a default class we can extend
65
66 function stream_close() {
67 return fclose( $this->stream );
68 }
69
70 function stream_flush() {
71 return fflush( $this->stream );
72 }
73
74 function stream_read( $count ) {
75 return fread( $this->stream, $count );
76 }
77
78 function stream_write( $data ) {
79 return fwrite( $this->stream, $data );
80 }
81
82 function stream_tell() {
83 return ftell( $this->stream );
84 }
85
86 function stream_eof() {
87 return feof( $this->stream );
88 }
89
90 function stream_seek( $offset, $whence ) {
91 return fseek( $this->stream, $offset, $whence );
92 }
93 }
94 stream_wrapper_register( 'mediawiki.compress.7z', 'SevenZipStream' );
95
96
97 class TextPassDumper extends BackupDumper {
98 var $prefetch = null;
99 var $input = "php://stdin";
100 var $history = WikiExporter::FULL;
101 var $fetchCount = 0;
102 var $prefetchCount = 0;
103
104 var $failures = 0;
105 var $maxFailures = 200;
106 var $failureTimeout = 5; // Seconds to sleep after db failure
107
108 var $php = "php";
109 var $spawn = false;
110 var $spawnProc = false;
111 var $spawnWrite = false;
112 var $spawnRead = false;
113 var $spawnErr = false;
114
115 function dump() {
116 # This shouldn't happen if on console... ;)
117 header( 'Content-type: text/html; charset=UTF-8' );
118
119 # Notice messages will foul up your XML output even if they're
120 # relatively harmless.
121 if( ini_get( 'display_errors' ) )
122 ini_set( 'display_errors', 'stderr' );
123
124 $this->initProgress( $this->history );
125
126 $this->db = $this->backupDb();
127
128 $this->egress = new ExportProgressFilter( $this->sink, $this );
129
130 $input = fopen( $this->input, "rt" );
131 $result = $this->readDump( $input );
132
133 if( WikiError::isError( $result ) ) {
134 wfDie( $result->getMessage() );
135 }
136
137 if( $this->spawnProc ) {
138 $this->closeSpawn();
139 }
140
141 $this->report( true );
142 }
143
144 function processOption( $opt, $val, $param ) {
145 $url = $this->processFileOpt( $val, $param );
146
147 switch( $opt ) {
148 case 'prefetch':
149 require_once 'maintenance/backupPrefetch.inc';
150 $this->prefetch = new BaseDump( $url );
151 break;
152 case 'stub':
153 $this->input = $url;
154 break;
155 case 'current':
156 $this->history = WikiExporter::CURRENT;
157 break;
158 case 'full':
159 $this->history = WikiExporter::FULL;
160 break;
161 case 'spawn':
162 $this->spawn = true;
163 if( $val ) {
164 $this->php = $val;
165 }
166 break;
167 }
168 }
169
170 function processFileOpt( $val, $param ) {
171 switch( $val ) {
172 case "file":
173 return $param;
174 case "gzip":
175 return "compress.zlib://$param";
176 case "bzip2":
177 return "compress.bzip2://$param";
178 case "7zip":
179 return "mediawiki.compress.7z://$param";
180 default:
181 return $val;
182 }
183 }
184
185 /**
186 * Overridden to include prefetch ratio if enabled.
187 */
188 function showReport() {
189 if( !$this->prefetch ) {
190 return parent::showReport();
191 }
192
193 if( $this->reporting ) {
194 $delta = wfTime() - $this->startTime;
195 $now = wfTimestamp( TS_DB );
196 if( $delta ) {
197 $rate = $this->pageCount / $delta;
198 $revrate = $this->revCount / $delta;
199 $portion = $this->revCount / $this->maxCount;
200 $eta = $this->startTime + $delta / $portion;
201 $etats = wfTimestamp( TS_DB, intval( $eta ) );
202 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
203 } else {
204 $rate = '-';
205 $revrate = '-';
206 $etats = '-';
207 $fetchrate = '-';
208 }
209 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
210 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
211 }
212 }
213
214 function readDump( $input ) {
215 $this->buffer = "";
216 $this->openElement = false;
217 $this->atStart = true;
218 $this->state = "";
219 $this->lastName = "";
220 $this->thisPage = 0;
221 $this->thisRev = 0;
222
223 $parser = xml_parser_create( "UTF-8" );
224 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
225
226 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
227 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
228
229 $offset = 0; // for context extraction on error reporting
230 $bufferSize = 512 * 1024;
231 do {
232 $chunk = fread( $input, $bufferSize );
233 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
234 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
235 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
236 }
237 $offset += strlen( $chunk );
238 } while( $chunk !== false && !feof( $input ) );
239 xml_parser_free( $parser );
240
241 return true;
242 }
243
244 function getText( $id ) {
245 $this->fetchCount++;
246 if( isset( $this->prefetch ) ) {
247 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
248 if( $text === null ) {
249 // Entry missing from prefetch dump
250 } elseif( $text === "" ) {
251 // Blank entries may indicate that the prior dump was broken.
252 // To be safe, reload it.
253 } else {
254 $this->prefetchCount++;
255 return $text;
256 }
257 }
258 return $this->doGetText( $id );
259 }
260
261 private function doGetText( $id ) {
262 if( $this->spawn ) {
263 return $this->getTextSpawned( $id );
264 } else {
265 return $this->getTextDbSafe( $id );
266 }
267 }
268
269 /**
270 * Fetch a text revision from the database, retrying in case of failure.
271 * This may survive some transitory errors by reconnecting, but
272 * may not survive a long-term server outage.
273 */
274 private function getTextDbSafe( $id ) {
275 while( true ) {
276 try {
277 $text = $this->getTextDb( $id );
278 $ex = new MWException("Graceful storage failure");
279 } catch (DBQueryError $ex) {
280 $text = false;
281 }
282 if( $text === false ) {
283 $this->failures++;
284 if( $this->failures > $this->maxFailures ) {
285 throw $ex;
286 } else {
287 $this->progress( "Database failure $this->failures " .
288 "of allowed $this->maxFailures for revision $id! " .
289 "Pausing $this->failureTimeout seconds..." );
290 sleep( $this->failureTimeout );
291 }
292 } else {
293 return $text;
294 }
295 }
296 }
297
298 /**
299 * May throw a database error if, say, the server dies during query.
300 */
301 private function getTextDb( $id ) {
302 $id = intval( $id );
303 $row = $this->db->selectRow( 'text',
304 array( 'old_text', 'old_flags' ),
305 array( 'old_id' => $id ),
306 'TextPassDumper::getText' );
307 $text = Revision::getRevisionText( $row );
308 if( $text === false ) {
309 return false;
310 }
311 $stripped = str_replace( "\r", "", $text );
312 $normalized = UtfNormal::cleanUp( $stripped );
313 return $normalized;
314 }
315
316 private function getTextSpawned( $id ) {
317 wfSuppressWarnings();
318 if( !$this->spawnProc ) {
319 // First time?
320 $this->openSpawn();
321 }
322 while( true ) {
323
324 $text = $this->getTextSpawnedOnce( $id );
325 if( !is_string( $text ) ) {
326 $this->progress("Database subprocess failed. Respawning...");
327
328 $this->closeSpawn();
329 sleep( $this->failureTimeout );
330 $this->openSpawn();
331
332 continue;
333 }
334 wfRestoreWarnings();
335 return $text;
336 }
337 }
338
339 function openSpawn() {
340 global $IP, $wgDBname;
341
342 $cmd = implode( " ",
343 array_map( 'wfEscapeShellArg',
344 array(
345 $this->php,
346 "$IP/maintenance/fetchText.php",
347 $wgDBname ) ) );
348 $spec = array(
349 0 => array( "pipe", "r" ),
350 1 => array( "pipe", "w" ),
351 2 => array( "file", "/dev/null", "a" ) );
352 $pipes = array();
353
354 $this->progress( "Spawning database subprocess: $cmd" );
355 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
356 if( !$this->spawnProc ) {
357 // shit
358 $this->progress( "Subprocess spawn failed." );
359 return false;
360 }
361 list(
362 $this->spawnWrite, // -> stdin
363 $this->spawnRead, // <- stdout
364 ) = $pipes;
365
366 return true;
367 }
368
369 private function closeSpawn() {
370 wfSuppressWarnings();
371 if( $this->spawnRead )
372 fclose( $this->spawnRead );
373 $this->spawnRead = false;
374 if( $this->spawnWrite )
375 fclose( $this->spawnWrite );
376 $this->spawnWrite = false;
377 if( $this->spawnErr )
378 fclose( $this->spawnErr );
379 $this->spawnErr = false;
380 if( $this->spawnProc )
381 pclose( $this->spawnProc );
382 $this->spawnProc = false;
383 wfRestoreWarnings();
384 }
385
386 private function getTextSpawnedOnce( $id ) {
387 $ok = fwrite( $this->spawnWrite, "$id\n" );
388 //$this->progress( ">> $id" );
389 if( !$ok ) return false;
390
391 $ok = fflush( $this->spawnWrite );
392 //$this->progress( ">> [flush]" );
393 if( !$ok ) return false;
394
395 $len = fgets( $this->spawnRead );
396 //$this->progress( "<< " . trim( $len ) );
397 if( $len === false ) return false;
398
399 $nbytes = intval( $len );
400 $text = "";
401
402 // Subprocess may not send everything at once, we have to loop.
403 while( $nbytes > strlen( $text ) ) {
404 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
405 if( $text === false ) break;
406 $text .= $buffer;
407 }
408
409 $gotbytes = strlen( $text );
410 if( $gotbytes != $nbytes ) {
411 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
412 return false;
413 }
414
415 // Do normalization in the dump thread...
416 $stripped = str_replace( "\r", "", $text );
417 $normalized = UtfNormal::cleanUp( $stripped );
418 return $normalized;
419 }
420
421 function startElement( $parser, $name, $attribs ) {
422 $this->clearOpenElement( null );
423 $this->lastName = $name;
424
425 if( $name == 'revision' ) {
426 $this->state = $name;
427 $this->egress->writeOpenPage( null, $this->buffer );
428 $this->buffer = "";
429 } elseif( $name == 'page' ) {
430 $this->state = $name;
431 if( $this->atStart ) {
432 $this->egress->writeOpenStream( $this->buffer );
433 $this->buffer = "";
434 $this->atStart = false;
435 }
436 }
437
438 if( $name == "text" && isset( $attribs['id'] ) ) {
439 $text = $this->getText( $attribs['id'] );
440 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
441 if( strlen( $text ) > 0 ) {
442 $this->characterData( $parser, $text );
443 }
444 } else {
445 $this->openElement = array( $name, $attribs );
446 }
447 }
448
449 function endElement( $parser, $name ) {
450 if( $this->openElement ) {
451 $this->clearOpenElement( "" );
452 } else {
453 $this->buffer .= "</$name>";
454 }
455
456 if( $name == 'revision' ) {
457 $this->egress->writeRevision( null, $this->buffer );
458 $this->buffer = "";
459 $this->thisRev = "";
460 } elseif( $name == 'page' ) {
461 $this->egress->writeClosePage( $this->buffer );
462 $this->buffer = "";
463 $this->thisPage = "";
464 } elseif( $name == 'mediawiki' ) {
465 $this->egress->writeCloseStream( $this->buffer );
466 $this->buffer = "";
467 }
468 }
469
470 function characterData( $parser, $data ) {
471 $this->clearOpenElement( null );
472 if( $this->lastName == "id" ) {
473 if( $this->state == "revision" ) {
474 $this->thisRev .= $data;
475 } elseif( $this->state == "page" ) {
476 $this->thisPage .= $data;
477 }
478 }
479 $this->buffer .= htmlspecialchars( $data );
480 }
481
482 function clearOpenElement( $style ) {
483 if( $this->openElement ) {
484 $this->buffer .= wfElement( $this->openElement[0], $this->openElement[1], $style );
485 $this->openElement = false;
486 }
487 }
488 }
489
490
491 $dumper = new TextPassDumper( $argv );
492
493 if( true ) {
494 $dumper->dump();
495 } else {
496 $dumper->progress( <<<END
497 This script postprocesses XML dumps from dumpBackup.php to add
498 page text which was stubbed out (using --stub).
499
500 XML input is accepted on stdin.
501 XML output is sent to stdout; progress reports are sent to stderr.
502
503 Usage: php dumpTextPass.php [<options>]
504 Options:
505 --stub=<type>:<file> To load a compressed stub dump instead of stdin
506 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
507 pressure on the database.
508 (Requires PHP 5.0+ and the XMLReader PECL extension)
509 --quiet Don't dump status reports to stderr.
510 --report=n Report position and speed after every n pages processed.
511 (Default: 100)
512 --server=h Force reading from MySQL server h
513 --current Base ETA on number of pages in database instead of all revisions
514 --spawn Spawn a subprocess for loading text records
515 END
516 );
517 }
518
519