]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - maintenance/dumpTextPass.php
MediaWiki 1.11.0-scripts
[autoinstalls/mediawiki.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         function dump() {
109                 # This shouldn't happen if on console... ;)
110                 header( 'Content-type: text/html; charset=UTF-8' );
111
112                 # Notice messages will foul up your XML output even if they're
113                 # relatively harmless.
114 //              ini_set( 'display_errors', false );
115
116                 $this->initProgress( $this->history );
117
118                 $this->db = $this->backupDb();
119
120                 $this->egress = new ExportProgressFilter( $this->sink, $this );
121
122                 $input = fopen( $this->input, "rt" );
123                 $result = $this->readDump( $input );
124
125                 if( WikiError::isError( $result ) ) {
126                         wfDie( $result->getMessage() );
127                 }
128
129                 $this->report( true );
130         }
131
132         function processOption( $opt, $val, $param ) {
133                 $url = $this->processFileOpt( $val, $param );
134                 
135                 switch( $opt ) {
136                 case 'prefetch':
137                         require_once 'maintenance/backupPrefetch.inc';
138                         $this->prefetch = new BaseDump( $url );
139                         break;
140                 case 'stub':
141                         $this->input = $url;
142                         break;
143                 case 'current':
144                         $this->history = WikiExporter::CURRENT;
145                         break;
146                 case 'full':
147                         $this->history = WikiExporter::FULL;
148                         break;
149                 }
150         }
151         
152         function processFileOpt( $val, $param ) {
153                 switch( $val ) {
154                 case "file":
155                         return $param;
156                 case "gzip":
157                         return "compress.zlib://$param";
158                 case "bzip2":
159                         return "compress.bzip2://$param";
160                 case "7zip":
161                         return "mediawiki.compress.7z://$param";
162                 default:
163                         return $val;
164                 }
165         }
166
167         /**
168          * Overridden to include prefetch ratio if enabled.
169          */
170         function showReport() {
171                 if( !$this->prefetch ) {
172                         return parent::showReport();
173                 }
174                 
175                 if( $this->reporting ) {
176                         $delta = wfTime() - $this->startTime;
177                         $now = wfTimestamp( TS_DB );
178                         if( $delta ) {
179                                 $rate = $this->pageCount / $delta;
180                                 $revrate = $this->revCount / $delta;
181                                 $portion = $this->revCount / $this->maxCount;
182                                 $eta = $this->startTime + $delta / $portion;
183                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
184                                 $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
185                         } else {
186                                 $rate = '-';
187                                 $revrate = '-';
188                                 $etats = '-';
189                                 $fetchrate = '-';
190                         }
191                         $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
192                                 $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
193                 }
194         }
195
196         function readDump( $input ) {
197                 $this->buffer = "";
198                 $this->openElement = false;
199                 $this->atStart = true;
200                 $this->state = "";
201                 $this->lastName = "";
202                 $this->thisPage = 0;
203                 $this->thisRev = 0;
204
205                 $parser = xml_parser_create( "UTF-8" );
206                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
207
208                 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
209                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
210
211                 $offset = 0; // for context extraction on error reporting
212                 $bufferSize = 512 * 1024;
213                 do {
214                         $chunk = fread( $input, $bufferSize );
215                         if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
216                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
217                                 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
218                         }
219                         $offset += strlen( $chunk );
220                 } while( $chunk !== false && !feof( $input ) );
221                 xml_parser_free( $parser );
222                 
223                 return true;
224         }
225
226         function getText( $id ) {
227                 $this->fetchCount++;
228                 if( isset( $this->prefetch ) ) {
229                         $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
230                         if( $text === null ) {
231                                 // Entry missing from prefetch dump
232                         } elseif( $text === "" ) {
233                                 // Blank entries may indicate that the prior dump was broken.
234                                 // To be safe, reload it.
235                         } else {
236                                 $this->prefetchCount++;
237                                 return $text;
238                         }
239                 }
240                 while( true ) {
241                         try {
242                                 $text = $this->doGetText( $id );
243                                 $ex = new MWException("Graceful storage failure");
244                         } catch (DBQueryError $ex) {
245                                 $text = false;
246                         }
247                         if( $text === false ) {
248                                 $this->failures++;
249                                 if( $this->failures > $this->maxFailures ) {
250                                         throw $ex;
251                                 } else {
252                                         $this->progress( "Database failure $this->failures " .
253                                                 "of allowed $this->maxFailures for revision $id! " .
254                                                 "Pausing $this->failureTimeout seconds..." );
255                                         sleep( $this->failureTimeout );
256                                 }
257                         } else {
258                                 return $text;
259                         }
260                 }
261         }
262         
263         /**
264          * May throw a database error if, say, the server dies during query.
265          */
266         private function doGetText( $id ) {
267                 $id = intval( $id );
268                 $row = $this->db->selectRow( 'text',
269                         array( 'old_text', 'old_flags' ),
270                         array( 'old_id' => $id ),
271                         'TextPassDumper::getText' );
272                 $text = Revision::getRevisionText( $row );
273                 if( $text === false ) {
274                         return false;
275                 }
276                 $stripped = str_replace( "\r", "", $text );
277                 $normalized = UtfNormal::cleanUp( $stripped );
278                 return $normalized;
279         }
280
281         function startElement( $parser, $name, $attribs ) {
282                 $this->clearOpenElement( null );
283                 $this->lastName = $name;
284
285                 if( $name == 'revision' ) {
286                         $this->state = $name;
287                         $this->egress->writeOpenPage( null, $this->buffer );
288                         $this->buffer = "";
289                 } elseif( $name == 'page' ) {
290                         $this->state = $name;
291                         if( $this->atStart ) {
292                                 $this->egress->writeOpenStream( $this->buffer );
293                                 $this->buffer = "";
294                                 $this->atStart = false;
295                         }
296                 }
297
298                 if( $name == "text" && isset( $attribs['id'] ) ) {
299                         $text = $this->getText( $attribs['id'] );
300                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
301                         if( strlen( $text ) > 0 ) {
302                                 $this->characterData( $parser, $text );
303                         }
304                 } else {
305                         $this->openElement = array( $name, $attribs );
306                 }
307         }
308
309         function endElement( $parser, $name ) {
310                 if( $this->openElement ) {
311                         $this->clearOpenElement( "" );
312                 } else {
313                         $this->buffer .= "</$name>";
314                 }
315
316                 if( $name == 'revision' ) {
317                         $this->egress->writeRevision( null, $this->buffer );
318                         $this->buffer = "";
319                         $this->thisRev = "";
320                 } elseif( $name == 'page' ) {
321                         $this->egress->writeClosePage( $this->buffer );
322                         $this->buffer = "";
323                         $this->thisPage = "";
324                 } elseif( $name == 'mediawiki' ) {
325                         $this->egress->writeCloseStream( $this->buffer );
326                         $this->buffer = "";
327                 }
328         }
329
330         function characterData( $parser, $data ) {
331                 $this->clearOpenElement( null );
332                 if( $this->lastName == "id" ) {
333                         if( $this->state == "revision" ) {
334                                 $this->thisRev .= $data;
335                         } elseif( $this->state == "page" ) {
336                                 $this->thisPage .= $data;
337                         }
338                 }
339                 $this->buffer .= htmlspecialchars( $data );
340         }
341
342         function clearOpenElement( $style ) {
343                 if( $this->openElement ) {
344                         $this->buffer .= wfElement( $this->openElement[0], $this->openElement[1], $style );
345                         $this->openElement = false;
346                 }
347         }
348 }
349
350
351 $dumper = new TextPassDumper( $argv );
352
353 if( true ) {
354         $dumper->dump();
355 } else {
356         $dumper->progress( <<<END
357 This script postprocesses XML dumps from dumpBackup.php to add
358 page text which was stubbed out (using --stub).
359
360 XML input is accepted on stdin.
361 XML output is sent to stdout; progress reports are sent to stderr.
362
363 Usage: php dumpTextPass.php [<options>]
364 Options:
365   --stub=<type>:<file> To load a compressed stub dump instead of stdin
366   --prefetch=<type>:<file> Use a prior dump file as a text source, to save
367               pressure on the database.
368               (Requires PHP 5.0+ and the XMLReader PECL extension)
369   --quiet     Don't dump status reports to stderr.
370   --report=n  Report position and speed after every n pages processed.
371               (Default: 100)
372   --server=h  Force reading from MySQL server h
373   --current   Base ETA on number of pages in database instead of all revisions
374 END
375 );
376 }
377
378