Populate rc_deleted
[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 global $IP;
150 require_once "$IP/maintenance/backupPrefetch.inc";
151 $this->prefetch = new BaseDump( $url );
152 break;
153 case 'stub':
154 $this->input = $url;
155 break;
156 case 'current':
157 $this->history = WikiExporter::CURRENT;
158 break;
159 case 'full':
160 $this->history = WikiExporter::FULL;
161 break;
162 case 'spawn':
163 $this->spawn = true;
164 if( $val ) {
165 $this->php = $val;
166 }
167 break;
168 }
169 }
170
171 function processFileOpt( $val, $param ) {
172 switch( $val ) {
173 case "file":
174 return $param;
175 case "gzip":
176 return "compress.zlib://$param";
177 case "bzip2":
178 return "compress.bzip2://$param";
179 case "7zip":
180 return "mediawiki.compress.7z://$param";
181 default:
182 return $val;
183 }
184 }
185
186 /**
187 * Overridden to include prefetch ratio if enabled.
188 */
189 function showReport() {
190 if( !$this->prefetch ) {
191 return parent::showReport();
192 }
193
194 if( $this->reporting ) {
195 $delta = wfTime() - $this->startTime;
196 $now = wfTimestamp( TS_DB );
197 if( $delta ) {
198 $rate = $this->pageCount / $delta;
199 $revrate = $this->revCount / $delta;
200 $portion = $this->revCount / $this->maxCount;
201 $eta = $this->startTime + $delta / $portion;
202 $etats = wfTimestamp( TS_DB, intval( $eta ) );
203 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
204 } else {
205 $rate = '-';
206 $revrate = '-';
207 $etats = '-';
208 $fetchrate = '-';
209 }
210 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
211 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
212 }
213 }
214
215 function readDump( $input ) {
216 $this->buffer = "";
217 $this->openElement = false;
218 $this->atStart = true;
219 $this->state = "";
220 $this->lastName = "";
221 $this->thisPage = 0;
222 $this->thisRev = 0;
223
224 $parser = xml_parser_create( "UTF-8" );
225 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
226
227 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
228 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
229
230 $offset = 0; // for context extraction on error reporting
231 $bufferSize = 512 * 1024;
232 do {
233 $chunk = fread( $input, $bufferSize );
234 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
235 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
236 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
237 }
238 $offset += strlen( $chunk );
239 } while( $chunk !== false && !feof( $input ) );
240 xml_parser_free( $parser );
241
242 return true;
243 }
244
245 function getText( $id ) {
246 $this->fetchCount++;
247 if( isset( $this->prefetch ) ) {
248 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
249 if( $text === null ) {
250 // Entry missing from prefetch dump
251 } elseif( $text === "" ) {
252 // Blank entries may indicate that the prior dump was broken.
253 // To be safe, reload it.
254 } else {
255 $this->prefetchCount++;
256 return $text;
257 }
258 }
259 return $this->doGetText( $id );
260 }
261
262 private function doGetText( $id ) {
263 if( $this->spawn ) {
264 return $this->getTextSpawned( $id );
265 } else {
266 return $this->getTextDbSafe( $id );
267 }
268 }
269
270 /**
271 * Fetch a text revision from the database, retrying in case of failure.
272 * This may survive some transitory errors by reconnecting, but
273 * may not survive a long-term server outage.
274 */
275 private function getTextDbSafe( $id ) {
276 while( true ) {
277 try {
278 $text = $this->getTextDb( $id );
279 $ex = new MWException("Graceful storage failure");
280 } catch (DBQueryError $ex) {
281 $text = false;
282 }
283 if( $text === false ) {
284 $this->failures++;
285 if( $this->failures > $this->maxFailures ) {
286 throw $ex;
287 } else {
288 $this->progress( "Database failure $this->failures " .
289 "of allowed $this->maxFailures for revision $id! " .
290 "Pausing $this->failureTimeout seconds..." );
291 sleep( $this->failureTimeout );
292 }
293 } else {
294 return $text;
295 }
296 }
297 }
298
299 /**
300 * May throw a database error if, say, the server dies during query.
301 */
302 private function getTextDb( $id ) {
303 $id = intval( $id );
304 $row = $this->db->selectRow( 'text',
305 array( 'old_text', 'old_flags' ),
306 array( 'old_id' => $id ),
307 'TextPassDumper::getText' );
308 $text = Revision::getRevisionText( $row );
309 if( $text === false ) {
310 return false;
311 }
312 $stripped = str_replace( "\r", "", $text );
313 $normalized = UtfNormal::cleanUp( $stripped );
314 return $normalized;
315 }
316
317 private function getTextSpawned( $id ) {
318 wfSuppressWarnings();
319 if( !$this->spawnProc ) {
320 // First time?
321 $this->openSpawn();
322 }
323 while( true ) {
324
325 $text = $this->getTextSpawnedOnce( $id );
326 if( !is_string( $text ) ) {
327 $this->progress("Database subprocess failed. Respawning...");
328
329 $this->closeSpawn();
330 sleep( $this->failureTimeout );
331 $this->openSpawn();
332
333 continue;
334 }
335 wfRestoreWarnings();
336 return $text;
337 }
338 }
339
340 function openSpawn() {
341 global $IP, $wgDBname;
342
343 $cmd = implode( " ",
344 array_map( 'wfEscapeShellArg',
345 array(
346 $this->php,
347 "$IP/maintenance/fetchText.php",
348 $wgDBname ) ) );
349 $spec = array(
350 0 => array( "pipe", "r" ),
351 1 => array( "pipe", "w" ),
352 2 => array( "file", "/dev/null", "a" ) );
353 $pipes = array();
354
355 $this->progress( "Spawning database subprocess: $cmd" );
356 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
357 if( !$this->spawnProc ) {
358 // shit
359 $this->progress( "Subprocess spawn failed." );
360 return false;
361 }
362 list(
363 $this->spawnWrite, // -> stdin
364 $this->spawnRead, // <- stdout
365 ) = $pipes;
366
367 return true;
368 }
369
370 private function closeSpawn() {
371 wfSuppressWarnings();
372 if( $this->spawnRead )
373 fclose( $this->spawnRead );
374 $this->spawnRead = false;
375 if( $this->spawnWrite )
376 fclose( $this->spawnWrite );
377 $this->spawnWrite = false;
378 if( $this->spawnErr )
379 fclose( $this->spawnErr );
380 $this->spawnErr = false;
381 if( $this->spawnProc )
382 pclose( $this->spawnProc );
383 $this->spawnProc = false;
384 wfRestoreWarnings();
385 }
386
387 private function getTextSpawnedOnce( $id ) {
388 $ok = fwrite( $this->spawnWrite, "$id\n" );
389 //$this->progress( ">> $id" );
390 if( !$ok ) return false;
391
392 $ok = fflush( $this->spawnWrite );
393 //$this->progress( ">> [flush]" );
394 if( !$ok ) return false;
395
396 $len = fgets( $this->spawnRead );
397 //$this->progress( "<< " . trim( $len ) );
398 if( $len === false ) return false;
399
400 $nbytes = intval( $len );
401 $text = "";
402
403 // Subprocess may not send everything at once, we have to loop.
404 while( $nbytes > strlen( $text ) ) {
405 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
406 if( $text === false ) break;
407 $text .= $buffer;
408 }
409
410 $gotbytes = strlen( $text );
411 if( $gotbytes != $nbytes ) {
412 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
413 return false;
414 }
415
416 // Do normalization in the dump thread...
417 $stripped = str_replace( "\r", "", $text );
418 $normalized = UtfNormal::cleanUp( $stripped );
419 return $normalized;
420 }
421
422 function startElement( $parser, $name, $attribs ) {
423 $this->clearOpenElement( null );
424 $this->lastName = $name;
425
426 if( $name == 'revision' ) {
427 $this->state = $name;
428 $this->egress->writeOpenPage( null, $this->buffer );
429 $this->buffer = "";
430 } elseif( $name == 'page' ) {
431 $this->state = $name;
432 if( $this->atStart ) {
433 $this->egress->writeOpenStream( $this->buffer );
434 $this->buffer = "";
435 $this->atStart = false;
436 }
437 }
438
439 if( $name == "text" && isset( $attribs['id'] ) ) {
440 $text = $this->getText( $attribs['id'] );
441 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
442 if( strlen( $text ) > 0 ) {
443 $this->characterData( $parser, $text );
444 }
445 } else {
446 $this->openElement = array( $name, $attribs );
447 }
448 }
449
450 function endElement( $parser, $name ) {
451 if( $this->openElement ) {
452 $this->clearOpenElement( "" );
453 } else {
454 $this->buffer .= "</$name>";
455 }
456
457 if( $name == 'revision' ) {
458 $this->egress->writeRevision( null, $this->buffer );
459 $this->buffer = "";
460 $this->thisRev = "";
461 } elseif( $name == 'page' ) {
462 $this->egress->writeClosePage( $this->buffer );
463 $this->buffer = "";
464 $this->thisPage = "";
465 } elseif( $name == 'mediawiki' ) {
466 $this->egress->writeCloseStream( $this->buffer );
467 $this->buffer = "";
468 }
469 }
470
471 function characterData( $parser, $data ) {
472 $this->clearOpenElement( null );
473 if( $this->lastName == "id" ) {
474 if( $this->state == "revision" ) {
475 $this->thisRev .= $data;
476 } elseif( $this->state == "page" ) {
477 $this->thisPage .= $data;
478 }
479 }
480 $this->buffer .= htmlspecialchars( $data );
481 }
482
483 function clearOpenElement( $style ) {
484 if( $this->openElement ) {
485 $this->buffer .= wfElement( $this->openElement[0], $this->openElement[1], $style );
486 $this->openElement = false;
487 }
488 }
489 }
490
491
492 $dumper = new TextPassDumper( $argv );
493
494 if( true ) {
495 $dumper->dump();
496 } else {
497 $dumper->progress( <<<END
498 This script postprocesses XML dumps from dumpBackup.php to add
499 page text which was stubbed out (using --stub).
500
501 XML input is accepted on stdin.
502 XML output is sent to stdout; progress reports are sent to stderr.
503
504 Usage: php dumpTextPass.php [<options>]
505 Options:
506 --stub=<type>:<file> To load a compressed stub dump instead of stdin
507 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
508 pressure on the database.
509 (Requires PHP 5.0+ and the XMLReader PECL extension)
510 --quiet Don't dump status reports to stderr.
511 --report=n Report position and speed after every n pages processed.
512 (Default: 100)
513 --server=h Force reading from MySQL server h
514 --current Base ETA on number of pages in database instead of all revisions
515 --spawn Spawn a subprocess for loading text records
516 END
517 );
518 }
519
520