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