obsolete, we have plenty of examples these days
[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 * @package MediaWiki
22 * @subpackage SpecialPage
23 */
24
25 $originalDir = getcwd();
26
27 require_once( 'commandLine.inc' );
28 require_once( 'SpecialExport.php' );
29 require_once( 'maintenance/backup.inc' );
30
31 /**
32 * Stream wrapper around 7za filter program.
33 * Required since we can't pass an open file resource to XMLReader->open()
34 * which is used for the text prefetch.
35 */
36 class SevenZipStream {
37 var $stream;
38
39 private function stripPath( $path ) {
40 $prefix = 'mediawiki.compress.7z://';
41 return substr( $path, strlen( $prefix ) );
42 }
43
44 function stream_open( $path, $mode, $options, &$opened_path ) {
45 if( $mode{0} == 'r' ) {
46 $options = 'e -bd -so';
47 } elseif( $mode{0} == 'w' ) {
48 $options = 'a -bd -si';
49 } else {
50 return false;
51 }
52 $arg = wfEscapeShellArg( $this->stripPath( $path ) );
53 $command = "7za $options $arg";
54 if( !wfIsWindows() ) {
55 // Suppress the stupid messages on stderr
56 $command .= ' 2>/dev/null';
57 }
58 $this->stream = popen( $command, $mode );
59 return ($this->stream !== false);
60 }
61
62 function url_stat( $path, $flags ) {
63 return stat( $this->stripPath( $path ) );
64 }
65
66 // This is all so lame; there should be a default class we can extend
67
68 function stream_close() {
69 return fclose( $this->stream );
70 }
71
72 function stream_flush() {
73 return fflush( $this->stream );
74 }
75
76 function stream_read( $count ) {
77 return fread( $this->stream, $count );
78 }
79
80 function stream_write( $data ) {
81 return fwrite( $this->stream, $data );
82 }
83
84 function stream_tell() {
85 return ftell( $this->stream );
86 }
87
88 function stream_eof() {
89 return feof( $this->stream );
90 }
91
92 function stream_seek( $offset, $whence ) {
93 return fseek( $this->stream, $offset, $whence );
94 }
95 }
96 stream_wrapper_register( 'mediawiki.compress.7z', 'SevenZipStream' );
97
98
99 class TextPassDumper extends BackupDumper {
100 var $prefetch = null;
101 var $input = "php://stdin";
102 var $history = WikiExporter::FULL;
103 var $fetchCount = 0;
104 var $prefetchCount = 0;
105
106 var $failures = 0;
107 var $maxFailures = 200;
108 var $failureTimeout = 5; // Seconds to sleep after db failure
109
110 function dump() {
111 # This shouldn't happen if on console... ;)
112 header( 'Content-type: text/html; charset=UTF-8' );
113
114 # Notice messages will foul up your XML output even if they're
115 # relatively harmless.
116 // ini_set( 'display_errors', false );
117
118 $this->initProgress( $this->history );
119
120 $this->db =& $this->backupDb();
121
122 $this->egress = new ExportProgressFilter( $this->sink, $this );
123
124 $input = fopen( $this->input, "rt" );
125 $result = $this->readDump( $input );
126
127 if( WikiError::isError( $result ) ) {
128 wfDie( $result->getMessage() );
129 }
130
131 $this->report( true );
132 }
133
134 function processOption( $opt, $val, $param ) {
135 $url = $this->processFileOpt( $val, $param );
136
137 switch( $opt ) {
138 case 'prefetch':
139 require_once 'maintenance/backupPrefetch.inc';
140 $this->prefetch = new BaseDump( $url );
141 break;
142 case 'stub':
143 $this->input = $url;
144 break;
145 case 'current':
146 $this->history = WikiExporter::CURRENT;
147 break;
148 case 'full':
149 $this->history = WikiExporter::FULL;
150 break;
151 }
152 }
153
154 function processFileOpt( $val, $param ) {
155 switch( $val ) {
156 case "file":
157 return $param;
158 case "gzip":
159 return "compress.zlib://$param";
160 case "bzip2":
161 return "compress.bzip2://$param";
162 case "7zip":
163 return "mediawiki.compress.7z://$param";
164 default:
165 return $val;
166 }
167 }
168
169 /**
170 * Overridden to include prefetch ratio if enabled.
171 */
172 function showReport() {
173 if( !$this->prefetch ) {
174 return parent::showReport();
175 }
176
177 if( $this->reporting ) {
178 $delta = wfTime() - $this->startTime;
179 $now = wfTimestamp( TS_DB );
180 if( $delta ) {
181 $rate = $this->pageCount / $delta;
182 $revrate = $this->revCount / $delta;
183 $portion = $this->revCount / $this->maxCount;
184 $eta = $this->startTime + $delta / $portion;
185 $etats = wfTimestamp( TS_DB, intval( $eta ) );
186 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
187 } else {
188 $rate = '-';
189 $revrate = '-';
190 $etats = '-';
191 $fetchrate = '-';
192 }
193 global $wgDBname;
194 $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
195 $now, $wgDBname, $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
196 }
197 }
198
199 function readDump( $input ) {
200 $this->buffer = "";
201 $this->openElement = false;
202 $this->atStart = true;
203 $this->state = "";
204 $this->lastName = "";
205 $this->thisPage = 0;
206 $this->thisRev = 0;
207
208 $parser = xml_parser_create( "UTF-8" );
209 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
210
211 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
212 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
213
214 $offset = 0; // for context extraction on error reporting
215 $bufferSize = 512 * 1024;
216 do {
217 $chunk = fread( $input, $bufferSize );
218 if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
219 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
220 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
221 }
222 $offset += strlen( $chunk );
223 } while( $chunk !== false && !feof( $input ) );
224 xml_parser_free( $parser );
225
226 return true;
227 }
228
229 function getText( $id ) {
230 $this->fetchCount++;
231 if( isset( $this->prefetch ) ) {
232 $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
233 if( $text === null ) {
234 // Entry missing from prefetch dump
235 } elseif( $text === "" ) {
236 // Blank entries may indicate that the prior dump was broken.
237 // To be safe, reload it.
238 } else {
239 $this->prefetchCount++;
240 return $text;
241 }
242 }
243 while( true ) {
244 try {
245 return $this->doGetText( $id );
246 } catch (DBQueryError $ex) {
247 $this->failures++;
248 if( $this->failures > $this->maxFailures ) {
249 throw $ex;
250 } else {
251 $this->progress( "Database failure $this->failures " .
252 "of allowed $this->maxFailures! " .
253 "Pausing $this->failureTimeout seconds..." );
254 sleep( $this->failureTimeout );
255 }
256 }
257 }
258 }
259
260 /**
261 * May throw a database error if, say, the server dies during query.
262 */
263 private function doGetText( $id ) {
264 $id = intval( $id );
265 $row = $this->db->selectRow( 'text',
266 array( 'old_text', 'old_flags' ),
267 array( 'old_id' => $id ),
268 'TextPassDumper::getText' );
269 $text = Revision::getRevisionText( $row );
270 $stripped = str_replace( "\r", "", $text );
271 $normalized = UtfNormal::cleanUp( $stripped );
272 return $normalized;
273 }
274
275 function startElement( $parser, $name, $attribs ) {
276 $this->clearOpenElement( null );
277 $this->lastName = $name;
278
279 if( $name == 'revision' ) {
280 $this->state = $name;
281 $this->egress->writeOpenPage( null, $this->buffer );
282 $this->buffer = "";
283 } elseif( $name == 'page' ) {
284 $this->state = $name;
285 if( $this->atStart ) {
286 $this->egress->writeOpenStream( $this->buffer );
287 $this->buffer = "";
288 $this->atStart = false;
289 }
290 }
291
292 if( $name == "text" && isset( $attribs['id'] ) ) {
293 $text = $this->getText( $attribs['id'] );
294 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
295 if( strlen( $text ) > 0 ) {
296 $this->characterData( $parser, $text );
297 }
298 } else {
299 $this->openElement = array( $name, $attribs );
300 }
301 }
302
303 function endElement( $parser, $name ) {
304 if( $this->openElement ) {
305 $this->clearOpenElement( "" );
306 } else {
307 $this->buffer .= "</$name>";
308 }
309
310 if( $name == 'revision' ) {
311 $this->egress->writeRevision( null, $this->buffer );
312 $this->buffer = "";
313 $this->thisRev = "";
314 } elseif( $name == 'page' ) {
315 $this->egress->writeClosePage( $this->buffer );
316 $this->buffer = "";
317 $this->thisPage = "";
318 } elseif( $name == 'mediawiki' ) {
319 $this->egress->writeCloseStream( $this->buffer );
320 $this->buffer = "";
321 }
322 }
323
324 function characterData( $parser, $data ) {
325 $this->clearOpenElement( null );
326 if( $this->lastName == "id" ) {
327 if( $this->state == "revision" ) {
328 $this->thisRev .= $data;
329 } elseif( $this->state == "page" ) {
330 $this->thisPage .= $data;
331 }
332 }
333 $this->buffer .= htmlspecialchars( $data );
334 }
335
336 function clearOpenElement( $style ) {
337 if( $this->openElement ) {
338 $this->buffer .= wfElement( $this->openElement[0], $this->openElement[1], $style );
339 $this->openElement = false;
340 }
341 }
342 }
343
344
345 $dumper = new TextPassDumper( $argv );
346
347 if( true ) {
348 $dumper->dump();
349 } else {
350 $dumper->progress( <<<END
351 This script postprocesses XML dumps from dumpBackup.php to add
352 page text which was stubbed out (using --stub).
353
354 XML input is accepted on stdin.
355 XML output is sent to stdout; progress reports are sent to stderr.
356
357 Usage: php dumpTextPass.php [<options>]
358 Options:
359 --stub=<type>:<file> To load a compressed stub dump instead of stdin
360 --prefetch=<type>:<file> Use a prior dump file as a text source, to save
361 pressure on the database.
362 (Requires PHP 5.0+ and the XMLReader PECL extension)
363 --quiet Don't dump status reports to stderr.
364 --report=n Report position and speed after every n pages processed.
365 (Default: 100)
366 --server=h Force reading from MySQL server h
367 --current Base ETA on number of pages in database instead of all revisions
368 END
369 );
370 }
371
372 ?>