bug 21076: b/c, make 'undelete' work without 'deletedtext'
[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 * @file
22 * @ingroup Maintenance
23 */
24
25 $originalDir = getcwd();
26
27 require_once( dirname(__FILE__) . '/commandLine.inc' );
28 require_once( 'backup.inc' );
29
30 /**
31 * @ingroup Maintenance
32 */
33 class TextPassDumper extends BackupDumper {
34 var $prefetch = null;
35 var $input = "php://stdin";
36 var $history = WikiExporter::FULL;
37 var $fetchCount = 0;
38 var $prefetchCount = 0;
39
40 var $failures = 0;
41 var $maxFailures = 200;
42 var $failureTimeout = 5; // Seconds to sleep after db failure
43
44 var $php = "php";
45 var $spawn = false;
46 var $spawnProc = false;
47 var $spawnWrite = false;
48 var $spawnRead = false;
49 var $spawnErr = false;
50
51 function dump() {
52 # This shouldn't happen if on console... ;)
53 header( 'Content-type: text/html; charset=UTF-8' );
54
55 # Notice messages will foul up your XML output even if they're
56 # relatively harmless.
57 if( ini_get( 'display_errors' ) )
58 ini_set( 'display_errors', 'stderr' );
59
60 $this->initProgress( $this->history );
61
62 $this->db = $this->backupDb();
63
64 $this->egress = new ExportProgressFilter( $this->sink, $this );
65
66 $input = fopen( $this->input, "rt" );
67 $result = $this->readDump( $input );
68
69 if( WikiError::isError( $result ) ) {
70 wfDie( $result->getMessage() );
71 }
72
73 if( $this->spawnProc ) {
74 $this->closeSpawn();
75 }
76
77 $this->report( true );
78 }
79
80 function processOption( $opt, $val, $param ) {
81 $url = $this->processFileOpt( $val, $param );
82
83 switch( $opt ) {
84 case 'prefetch':
85 global $IP;
86 require_once "$IP/maintenance/backupPrefetch.inc";
87 $this->prefetch = new BaseDump( $url );
88 break;
89 case 'stub':
90 $this->input = $url;
91 break;
92 case 'current':
93 $this->history = WikiExporter::CURRENT;
94 break;
95 case 'full':
96 $this->history = WikiExporter::FULL;
97 break;
98 case 'spawn':
99 $this->spawn = true;
100 if( $val ) {
101 $this->php = $val;
102 }
103 break;
104 }
105 }
106
107 function processFileOpt( $val, $param ) {
108 switch( $val ) {
109 case "file":
110 return $param;
111 case "gzip":
112 return "compress.zlib://$param";
113 case "bzip2":
114 return "compress.bzip2://$param";
115 case "7zip":
116 return "mediawiki.compress.7z://$param";
117 default:
118 return $val;
119 }
120 }
121
122 /**
123 * Overridden to include prefetch ratio if enabled.
124 */
125 function showReport() {
126 if( !$this->prefetch ) {
127 return parent::showReport();
128 }
129
130 if( $this->reporting ) {
131 $delta = wfTime() - $this->startTime;
132 $now = wfTimestamp( TS_DB );
133 if( $delta ) {
134 $rate = $this->pageCount / $delta;
135 $revrate = $this->revCount / $delta;
136 $portion = $this->revCount / $this->maxCount;
137 $eta = $this->startTime + $delta / $portion;
138 $etats = wfTimestamp( TS_DB, intval( $eta ) );
139 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
140 } else {
141 $rate = '-';
142 $revrate = '-';
143 $etats = '-';
144 $fetchrate = '-';
145 }
146 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
147 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
148 }
149 }
150
151 function readDump( $input ) {
152 $this->buffer = "";
153 $this->openElement = false;
154 $this->atStart = true;
155 $this->state = "";
156 $this->lastName = "";
157 $this->thisPage = 0;
158 $this->thisRev = 0;
159
160 $parser = xml_parser_create( "UTF-8" );
161 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
162
163 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
164 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
165
166 $offset = 0; // for context extraction on error reporting
167 $bufferSize = 512 * 1024;
168 do {
169 $chunk = fread( $input, $bufferSize );
170 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
171 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
172 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
173 }
174 $offset += strlen( $chunk );
175 } while( $chunk !== false && !feof( $input ) );
176 xml_parser_free( $parser );
177
178 return true;
179 }
180
181 function getText( $id ) {
182 $this->fetchCount++;
183 if( isset( $this->prefetch ) ) {
184 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
185 if( $text === null ) {
186 // Entry missing from prefetch dump
187 } elseif( $text === "" ) {
188 // Blank entries may indicate that the prior dump was broken.
189 // To be safe, reload it.
190 } else {
191 $this->prefetchCount++;
192 return $text;
193 }
194 }
195 return $this->doGetText( $id );
196 }
197
198 private function doGetText( $id ) {
199 if( $this->spawn ) {
200 return $this->getTextSpawned( $id );
201 } else {
202 return $this->getTextDbSafe( $id );
203 }
204 }
205
206 /**
207 * Fetch a text revision from the database, retrying in case of failure.
208 * This may survive some transitory errors by reconnecting, but
209 * may not survive a long-term server outage.
210 */
211 private function getTextDbSafe( $id ) {
212 while( true ) {
213 try {
214 $text = $this->getTextDb( $id );
215 $ex = new MWException("Graceful storage failure");
216 } catch (DBQueryError $ex) {
217 $text = false;
218 }
219 if( $text === false ) {
220 $this->failures++;
221 if( $this->failures > $this->maxFailures ) {
222 throw $ex;
223 } else {
224 $this->progress( "Database failure $this->failures " .
225 "of allowed $this->maxFailures for revision $id! " .
226 "Pausing $this->failureTimeout seconds..." );
227 sleep( $this->failureTimeout );
228 }
229 } else {
230 return $text;
231 }
232 }
233 }
234
235 /**
236 * May throw a database error if, say, the server dies during query.
237 */
238 private function getTextDb( $id ) {
239 $id = intval( $id );
240 $row = $this->db->selectRow( 'text',
241 array( 'old_text', 'old_flags' ),
242 array( 'old_id' => $id ),
243 'TextPassDumper::getText' );
244 $text = Revision::getRevisionText( $row );
245 if( $text === false ) {
246 return false;
247 }
248 $stripped = str_replace( "\r", "", $text );
249 $normalized = UtfNormal::cleanUp( $stripped );
250 return $normalized;
251 }
252
253 private function getTextSpawned( $id ) {
254 wfSuppressWarnings();
255 if( !$this->spawnProc ) {
256 // First time?
257 $this->openSpawn();
258 }
259 while( true ) {
260
261 $text = $this->getTextSpawnedOnce( $id );
262 if( !is_string( $text ) ) {
263 $this->progress("Database subprocess failed. Respawning...");
264
265 $this->closeSpawn();
266 sleep( $this->failureTimeout );
267 $this->openSpawn();
268
269 continue;
270 }
271 wfRestoreWarnings();
272 return $text;
273 }
274 }
275
276 function openSpawn() {
277 global $IP, $wgDBname;
278
279 $cmd = implode( " ",
280 array_map( 'wfEscapeShellArg',
281 array(
282 $this->php,
283 "$IP/maintenance/fetchText.php",
284 $wgDBname ) ) );
285 $spec = array(
286 0 => array( "pipe", "r" ),
287 1 => array( "pipe", "w" ),
288 2 => array( "file", "/dev/null", "a" ) );
289 $pipes = array();
290
291 $this->progress( "Spawning database subprocess: $cmd" );
292 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
293 if( !$this->spawnProc ) {
294 // shit
295 $this->progress( "Subprocess spawn failed." );
296 return false;
297 }
298 list(
299 $this->spawnWrite, // -> stdin
300 $this->spawnRead, // <- stdout
301 ) = $pipes;
302
303 return true;
304 }
305
306 private function closeSpawn() {
307 wfSuppressWarnings();
308 if( $this->spawnRead )
309 fclose( $this->spawnRead );
310 $this->spawnRead = false;
311 if( $this->spawnWrite )
312 fclose( $this->spawnWrite );
313 $this->spawnWrite = false;
314 if( $this->spawnErr )
315 fclose( $this->spawnErr );
316 $this->spawnErr = false;
317 if( $this->spawnProc )
318 pclose( $this->spawnProc );
319 $this->spawnProc = false;
320 wfRestoreWarnings();
321 }
322
323 private function getTextSpawnedOnce( $id ) {
324 $ok = fwrite( $this->spawnWrite, "$id\n" );
325 //$this->progress( ">> $id" );
326 if( !$ok ) return false;
327
328 $ok = fflush( $this->spawnWrite );
329 //$this->progress( ">> [flush]" );
330 if( !$ok ) return false;
331
332 $len = fgets( $this->spawnRead );
333 //$this->progress( "<< " . trim( $len ) );
334 if( $len === false ) return false;
335
336 $nbytes = intval( $len );
337 $text = "";
338
339 // Subprocess may not send everything at once, we have to loop.
340 while( $nbytes > strlen( $text ) ) {
341 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
342 if( $buffer === false ) break;
343 $text .= $buffer;
344 }
345
346 $gotbytes = strlen( $text );
347 if( $gotbytes != $nbytes ) {
348 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
349 return false;
350 }
351
352 // Do normalization in the dump thread...
353 $stripped = str_replace( "\r", "", $text );
354 $normalized = UtfNormal::cleanUp( $stripped );
355 return $normalized;
356 }
357
358 function startElement( $parser, $name, $attribs ) {
359 $this->clearOpenElement( null );
360 $this->lastName = $name;
361
362 if( $name == 'revision' ) {
363 $this->state = $name;
364 $this->egress->writeOpenPage( null, $this->buffer );
365 $this->buffer = "";
366 } elseif( $name == 'page' ) {
367 $this->state = $name;
368 if( $this->atStart ) {
369 $this->egress->writeOpenStream( $this->buffer );
370 $this->buffer = "";
371 $this->atStart = false;
372 }
373 }
374
375 if( $name == "text" && isset( $attribs['id'] ) ) {
376 $text = $this->getText( $attribs['id'] );
377 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
378 if( strlen( $text ) > 0 ) {
379 $this->characterData( $parser, $text );
380 }
381 } else {
382 $this->openElement = array( $name, $attribs );
383 }
384 }
385
386 function endElement( $parser, $name ) {
387 if( $this->openElement ) {
388 $this->clearOpenElement( "" );
389 } else {
390 $this->buffer .= "</$name>";
391 }
392
393 if( $name == 'revision' ) {
394 $this->egress->writeRevision( null, $this->buffer );
395 $this->buffer = "";
396 $this->thisRev = "";
397 } elseif( $name == 'page' ) {
398 $this->egress->writeClosePage( $this->buffer );
399 $this->buffer = "";
400 $this->thisPage = "";
401 } elseif( $name == 'mediawiki' ) {
402 $this->egress->writeCloseStream( $this->buffer );
403 $this->buffer = "";
404 }
405 }
406
407 function characterData( $parser, $data ) {
408 $this->clearOpenElement( null );
409 if( $this->lastName == "id" ) {
410 if( $this->state == "revision" ) {
411 $this->thisRev .= $data;
412 } elseif( $this->state == "page" ) {
413 $this->thisPage .= $data;
414 }
415 }
416 $this->buffer .= htmlspecialchars( $data );
417 }
418
419 function clearOpenElement( $style ) {
420 if( $this->openElement ) {
421 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
422 $this->openElement = false;
423 }
424 }
425 }
426
427
428 $dumper = new TextPassDumper( $argv );
429
430 if( true ) {
431 $dumper->dump();
432 } else {
433 $dumper->progress( <<<ENDS
434 This script postprocesses XML dumps from dumpBackup.php to add
435 page text which was stubbed out (using --stub).
436
437 XML input is accepted on stdin.
438 XML output is sent to stdout; progress reports are sent to stderr.
439
440 Usage: php dumpTextPass.php [<options>]
441 Options:
442 --stub=<type>:<file> To load a compressed stub dump instead of stdin
443 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
444 pressure on the database.
445 (Requires PHP 5.0+ and the XMLReader PECL extension)
446 --quiet Don't dump status reports to stderr.
447 --report=n Report position and speed after every n pages processed.
448 (Default: 100)
449 --server=h Force reading from MySQL server h
450 --current Base ETA on number of pages in database instead of all revisions
451 --spawn Spawn a subprocess for loading text records
452 ENDS
453 );
454 }
455
456