Merge "Make update.php file executable"
[mediawiki.git] / maintenance / backupTextPass.inc
blob7fca377335a8e9771bd9e6228aa4591145fd2231
1 <?php
2 /**
3  * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
4  *
5  * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6  * https://www.mediawiki.org/
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  * http://www.gnu.org/copyleft/gpl.html
22  *
23  * @file
24  * @ingroup Maintenance
25  */
27 require_once __DIR__ . '/backup.inc';
29 /**
30  * @ingroup Maintenance
31  */
32 class TextPassDumper extends BackupDumper {
33         public $prefetch = null;
35         // when we spend more than maxTimeAllowed seconds on this run, we continue
36         // processing until we write out the next complete page, then save output file(s),
37         // rename it/them and open new one(s)
38         public $maxTimeAllowed = 0; // 0 = no limit
40         protected $input = "php://stdin";
41         protected $history = WikiExporter::FULL;
42         protected $fetchCount = 0;
43         protected $prefetchCount = 0;
44         protected $prefetchCountLast = 0;
45         protected $fetchCountLast = 0;
47         protected $maxFailures = 5;
48         protected $maxConsecutiveFailedTextRetrievals = 200;
49         protected $failureTimeout = 5; // Seconds to sleep after db failure
51         protected $php = "php";
52         protected $spawn = false;
54         /**
55          * @var bool|resource
56          */
57         protected $spawnProc = false;
59         /**
60          * @var bool|resource
61          */
62         protected $spawnWrite = false;
64         /**
65          * @var bool|resource
66          */
67         protected $spawnRead = false;
69         /**
70          * @var bool|resource
71          */
72         protected $spawnErr = false;
74         protected $xmlwriterobj = false;
76         protected $timeExceeded = false;
77         protected $firstPageWritten = false;
78         protected $lastPageWritten = false;
79         protected $checkpointJustWritten = false;
80         protected $checkpointFiles = array();
82         /**
83          * @var DatabaseBase
84          */
85         protected $db;
87         /**
88          * Drop the database connection $this->db and try to get a new one.
89          *
90          * This function tries to get a /different/ connection if this is
91          * possible. Hence, (if this is possible) it switches to a different
92          * failover upon each call.
93          *
94          * This function resets $this->lb and closes all connections on it.
95          *
96          * @throws MWException
97          */
98         function rotateDb() {
99                 // Cleaning up old connections
100                 if ( isset( $this->lb ) ) {
101                         $this->lb->closeAll();
102                         unset( $this->lb );
103                 }
105                 if ( $this->forcedDb !== null ) {
106                         $this->db = $this->forcedDb;
108                         return;
109                 }
111                 if ( isset( $this->db ) && $this->db->isOpen() ) {
112                         throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
113                 }
115                 unset( $this->db );
117                 // Trying to set up new connection.
118                 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
119                 // individually retrying at different layers of code.
121                 // 1. The LoadBalancer.
122                 try {
123                         $this->lb = wfGetLBFactory()->newMainLB();
124                 } catch ( Exception $e ) {
125                         throw new MWException( __METHOD__
126                                 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
127                 }
129                 // 2. The Connection, through the load balancer.
130                 try {
131                         $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
132                 } catch ( Exception $e ) {
133                         throw new MWException( __METHOD__
134                                 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
135                 }
136         }
138         function initProgress( $history = WikiExporter::FULL ) {
139                 parent::initProgress();
140                 $this->timeOfCheckpoint = $this->startTime;
141         }
143         function dump( $history, $text = WikiExporter::TEXT ) {
144                 // Notice messages will foul up your XML output even if they're
145                 // relatively harmless.
146                 if ( ini_get( 'display_errors' ) ) {
147                         ini_set( 'display_errors', 'stderr' );
148                 }
150                 $this->initProgress( $this->history );
152                 // We are trying to get an initial database connection to avoid that the
153                 // first try of this request's first call to getText fails. However, if
154                 // obtaining a good DB connection fails it's not a serious issue, as
155                 // getText does retry upon failure and can start without having a working
156                 // DB connection.
157                 try {
158                         $this->rotateDb();
159                 } catch ( Exception $e ) {
160                         // We do not even count this as failure. Just let eventual
161                         // watchdogs know.
162                         $this->progress( "Getting initial DB connection failed (" .
163                                 $e->getMessage() . ")" );
164                 }
166                 $this->egress = new ExportProgressFilter( $this->sink, $this );
168                 // it would be nice to do it in the constructor, oh well. need egress set
169                 $this->finalOptionCheck();
171                 // we only want this so we know how to close a stream :-P
172                 $this->xmlwriterobj = new XmlDumpWriter();
174                 $input = fopen( $this->input, "rt" );
175                 $this->readDump( $input );
177                 if ( $this->spawnProc ) {
178                         $this->closeSpawn();
179                 }
181                 $this->report( true );
182         }
184         function processOption( $opt, $val, $param ) {
185                 global $IP;
186                 $url = $this->processFileOpt( $val, $param );
188                 switch ( $opt ) {
189                         case 'prefetch':
190                                 require_once "$IP/maintenance/backupPrefetch.inc";
191                                 $this->prefetch = new BaseDump( $url );
192                                 break;
193                         case 'stub':
194                                 $this->input = $url;
195                                 break;
196                         case 'maxtime':
197                                 $this->maxTimeAllowed = intval( $val ) * 60;
198                                 break;
199                         case 'checkpointfile':
200                                 $this->checkpointFiles[] = $val;
201                                 break;
202                         case 'current':
203                                 $this->history = WikiExporter::CURRENT;
204                                 break;
205                         case 'full':
206                                 $this->history = WikiExporter::FULL;
207                                 break;
208                         case 'spawn':
209                                 $this->spawn = true;
210                                 if ( $val ) {
211                                         $this->php = $val;
212                                 }
213                                 break;
214                 }
215         }
217         function processFileOpt( $val, $param ) {
218                 $fileURIs = explode( ';', $param );
219                 foreach ( $fileURIs as $URI ) {
220                         switch ( $val ) {
221                                 case "file":
222                                         $newURI = $URI;
223                                         break;
224                                 case "gzip":
225                                         $newURI = "compress.zlib://$URI";
226                                         break;
227                                 case "bzip2":
228                                         $newURI = "compress.bzip2://$URI";
229                                         break;
230                                 case "7zip":
231                                         $newURI = "mediawiki.compress.7z://$URI";
232                                         break;
233                                 default:
234                                         $newURI = $URI;
235                         }
236                         $newFileURIs[] = $newURI;
237                 }
238                 $val = implode( ';', $newFileURIs );
240                 return $val;
241         }
243         /**
244          * Overridden to include prefetch ratio if enabled.
245          */
246         function showReport() {
247                 if ( !$this->prefetch ) {
248                         parent::showReport();
250                         return;
251                 }
253                 if ( $this->reporting ) {
254                         $now = wfTimestamp( TS_DB );
255                         $nowts = microtime( true );
256                         $deltaAll = $nowts - $this->startTime;
257                         $deltaPart = $nowts - $this->lastTime;
258                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
259                         $this->revCountPart = $this->revCount - $this->revCountLast;
261                         if ( $deltaAll ) {
262                                 $portion = $this->revCount / $this->maxCount;
263                                 $eta = $this->startTime + $deltaAll / $portion;
264                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
265                                 if ( $this->fetchCount ) {
266                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
267                                 } else {
268                                         $fetchRate = '-';
269                                 }
270                                 $pageRate = $this->pageCount / $deltaAll;
271                                 $revRate = $this->revCount / $deltaAll;
272                         } else {
273                                 $pageRate = '-';
274                                 $revRate = '-';
275                                 $etats = '-';
276                                 $fetchRate = '-';
277                         }
278                         if ( $deltaPart ) {
279                                 if ( $this->fetchCountLast ) {
280                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
281                                 } else {
282                                         $fetchRatePart = '-';
283                                 }
284                                 $pageRatePart = $this->pageCountPart / $deltaPart;
285                                 $revRatePart = $this->revCountPart / $deltaPart;
286                         } else {
287                                 $fetchRatePart = '-';
288                                 $pageRatePart = '-';
289                                 $revRatePart = '-';
290                         }
291                         $this->progress( sprintf(
292                                 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
293                                         . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
294                                         . "prefetched (all|curr), ETA %s [max %d]",
295                                 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
296                                 $pageRatePart, $this->revCount, $revRate, $revRatePart,
297                                 $fetchRate, $fetchRatePart, $etats, $this->maxCount
298                         ) );
299                         $this->lastTime = $nowts;
300                         $this->revCountLast = $this->revCount;
301                         $this->prefetchCountLast = $this->prefetchCount;
302                         $this->fetchCountLast = $this->fetchCount;
303                 }
304         }
306         function setTimeExceeded() {
307                 $this->timeExceeded = true;
308         }
310         function checkIfTimeExceeded() {
311                 if ( $this->maxTimeAllowed
312                         && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
313                 ) {
314                         return true;
315                 }
317                 return false;
318         }
320         function finalOptionCheck() {
321                 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
322                         || ( $this->maxTimeAllowed && !$this->checkpointFiles )
323                 ) {
324                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
325                 }
326                 foreach ( $this->checkpointFiles as $checkpointFile ) {
327                         $count = substr_count( $checkpointFile, "%s" );
328                         if ( $count != 2 ) {
329                                 throw new MWException( "Option checkpointfile must contain two '%s' "
330                                         . "for substitution of first and last pageids, count is $count instead, "
331                                         . "file is $checkpointFile.\n" );
332                         }
333                 }
335                 if ( $this->checkpointFiles ) {
336                         $filenameList = (array)$this->egress->getFilenames();
337                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
338                                 throw new MWException( "One checkpointfile must be specified "
339                                         . "for each output option, if maxtime is used.\n" );
340                         }
341                 }
342         }
344         /**
345          * @throws MWException Failure to parse XML input
346          * @return bool
347          */
348         function readDump( $input ) {
349                 $this->buffer = "";
350                 $this->openElement = false;
351                 $this->atStart = true;
352                 $this->state = "";
353                 $this->lastName = "";
354                 $this->thisPage = 0;
355                 $this->thisRev = 0;
357                 $parser = xml_parser_create( "UTF-8" );
358                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
360                 xml_set_element_handler(
361                         $parser,
362                         array( &$this, 'startElement' ),
363                         array( &$this, 'endElement' )
364                 );
365                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
367                 $offset = 0; // for context extraction on error reporting
368                 $bufferSize = 512 * 1024;
369                 do {
370                         if ( $this->checkIfTimeExceeded() ) {
371                                 $this->setTimeExceeded();
372                         }
373                         $chunk = fread( $input, $bufferSize );
374                         if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
375                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
377                                 $byte = xml_get_current_byte_index( $parser );
378                                 $msg = wfMessage( 'xml-error-string',
379                                         'XML import parse failure',
380                                         xml_get_current_line_number( $parser ),
381                                         xml_get_current_column_number( $parser ),
382                                         $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
383                                         xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
385                                 xml_parser_free( $parser );
387                                 throw new MWException( $msg );
388                         }
389                         $offset += strlen( $chunk );
390                 } while ( $chunk !== false && !feof( $input ) );
391                 if ( $this->maxTimeAllowed ) {
392                         $filenameList = (array)$this->egress->getFilenames();
393                         // we wrote some stuff after last checkpoint that needs renamed
394                         if ( file_exists( $filenameList[0] ) ) {
395                                 $newFilenames = array();
396                                 # we might have just written the header and footer and had no
397                                 # pages or revisions written... perhaps they were all deleted
398                                 # there's no pageID 0 so we use that. the caller is responsible
399                                 # for deciding what to do with a file containing only the
400                                 # siteinfo information and the mw tags.
401                                 if ( !$this->firstPageWritten ) {
402                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
403                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
404                                 } else {
405                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
406                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
407                                 }
409                                 $filenameCount = count( $filenameList );
410                                 for ( $i = 0; $i < $filenameCount; $i++ ) {
411                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
412                                         $fileinfo = pathinfo( $filenameList[$i] );
413                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
414                                 }
415                                 $this->egress->closeAndRename( $newFilenames );
416                         }
417                 }
418                 xml_parser_free( $parser );
420                 return true;
421         }
423         /**
424          * Tries to get the revision text for a revision id.
425          *
426          * Upon errors, retries (Up to $this->maxFailures tries each call).
427          * If still no good revision get could be found even after this retrying, "" is returned.
428          * If no good revision text could be returned for
429          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
430          * is thrown.
431          *
432          * @param string $id The revision id to get the text for
433          *
434          * @return string The revision text for $id, or ""
435          * @throws MWException
436          */
437         function getText( $id ) {
438                 global $wgContentHandlerUseDB;
440                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
441                 $text = false; // The candidate for a good text. false if no proper value.
442                 $failures = 0; // The number of times, this invocation of getText already failed.
444                 // The number of times getText failed without yielding a good text in between.
445                 static $consecutiveFailedTextRetrievals = 0;
447                 $this->fetchCount++;
449                 // To allow to simply return on success and do not have to worry about book keeping,
450                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
451                 // the old value, so we can restore it, if problems occur (See after the while loop).
452                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
453                 $consecutiveFailedTextRetrievals = 0;
455                 while ( $failures < $this->maxFailures ) {
457                         // As soon as we found a good text for the $id, we will return immediately.
458                         // Hence, if we make it past the try catch block, we know that we did not
459                         // find a good text.
461                         try {
462                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
463                                 //         for plausibility failed)
465                                 // Trying to get prefetch, if it has not been tried before
466                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
467                                         $prefetchNotTried = false;
468                                         $tryIsPrefetch = true;
469                                         $text = $this->prefetch->prefetch( intval( $this->thisPage ),
470                                                 intval( $this->thisRev ) );
471                                         if ( $text === null ) {
472                                                 $text = false;
473                                         }
474                                 }
476                                 if ( $text === false ) {
477                                         // Fallback to asking the database
478                                         $tryIsPrefetch = false;
479                                         if ( $this->spawn ) {
480                                                 $text = $this->getTextSpawned( $id );
481                                         } else {
482                                                 $text = $this->getTextDb( $id );
483                                         }
485                                         // No more checks for texts from DB for now.
486                                         // If we received something that is not false,
487                                         // We treat it as good text, regardless of whether it actually is or is not
488                                         if ( $text !== false ) {
489                                                 return $text;
490                                         }
491                                 }
493                                 if ( $text === false ) {
494                                         throw new MWException( "Generic error while obtaining text for id " . $id );
495                                 }
497                                 // We received a good candidate for the text of $id via some method
499                                 // Step 2: Checking for plausibility and return the text if it is
500                                 //         plausible
501                                 $revID = intval( $this->thisRev );
502                                 if ( !isset( $this->db ) ) {
503                                         throw new MWException( "No database available" );
504                                 }
506                                 $revLength = strlen( $text );
507                                 if ( $wgContentHandlerUseDB ) {
508                                         $row = $this->db->selectRow(
509                                                 'revision',
510                                                 array( 'rev_len', 'rev_content_model' ),
511                                                 array( 'rev_id' => $revID ),
512                                                 __METHOD__
513                                         );
514                                         if ( $row ) {
515                                                 // only check the length for the wikitext content handler,
516                                                 // it's a wasted (and failed) check otherwise
517                                                 if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
518                                                         $revLength = $row->rev_len;
519                                                 }
520                                         }
521                                 } else {
522                                         $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
523                                 }
525                                 if ( strlen( $text ) == $revLength ) {
526                                         if ( $tryIsPrefetch ) {
527                                                 $this->prefetchCount++;
528                                         }
530                                         return $text;
531                                 }
533                                 $text = false;
534                                 throw new MWException( "Received text is unplausible for id " . $id );
535                         } catch ( Exception $e ) {
536                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
537                                 if ( $failures + 1 < $this->maxFailures ) {
538                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
539                                 }
540                                 $this->progress( $msg );
541                         }
543                         // Something went wrong; we did not a text that was plausible :(
544                         $failures++;
546                         // A failure in a prefetch hit does not warrant resetting db connection etc.
547                         if ( !$tryIsPrefetch ) {
548                                 // After backing off for some time, we try to reboot the whole process as
549                                 // much as possible to not carry over failures from one part to the other
550                                 // parts
551                                 sleep( $this->failureTimeout );
552                                 try {
553                                         $this->rotateDb();
554                                         if ( $this->spawn ) {
555                                                 $this->closeSpawn();
556                                                 $this->openSpawn();
557                                         }
558                                 } catch ( Exception $e ) {
559                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
560                                                 " Trying to continue anyways" );
561                                 }
562                         }
563                 }
565                 // Retirieving a good text for $id failed (at least) maxFailures times.
566                 // We abort for this $id.
568                 // Restoring the consecutive failures, and maybe aborting, if the dump
569                 // is too broken.
570                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
571                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
572                         throw new MWException( "Graceful storage failure" );
573                 }
575                 return "";
576         }
578         /**
579          * May throw a database error if, say, the server dies during query.
580          * @param int $id
581          * @return bool|string
582          * @throws MWException
583          */
584         private function getTextDb( $id ) {
585                 global $wgContLang;
586                 if ( !isset( $this->db ) ) {
587                         throw new MWException( __METHOD__ . "No database available" );
588                 }
589                 $row = $this->db->selectRow( 'text',
590                         array( 'old_text', 'old_flags' ),
591                         array( 'old_id' => $id ),
592                         __METHOD__ );
593                 $text = Revision::getRevisionText( $row );
594                 if ( $text === false ) {
595                         return false;
596                 }
597                 $stripped = str_replace( "\r", "", $text );
598                 $normalized = $wgContLang->normalize( $stripped );
600                 return $normalized;
601         }
603         private function getTextSpawned( $id ) {
604                 wfSuppressWarnings();
605                 if ( !$this->spawnProc ) {
606                         // First time?
607                         $this->openSpawn();
608                 }
609                 $text = $this->getTextSpawnedOnce( $id );
610                 wfRestoreWarnings();
612                 return $text;
613         }
615         function openSpawn() {
616                 global $IP;
618                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
619                         $cmd = implode( " ",
620                                 array_map( 'wfEscapeShellArg',
621                                         array(
622                                                 $this->php,
623                                                 "$IP/../multiversion/MWScript.php",
624                                                 "fetchText.php",
625                                                 '--wiki', wfWikiID() ) ) );
626                 } else {
627                         $cmd = implode( " ",
628                                 array_map( 'wfEscapeShellArg',
629                                         array(
630                                                 $this->php,
631                                                 "$IP/maintenance/fetchText.php",
632                                                 '--wiki', wfWikiID() ) ) );
633                 }
634                 $spec = array(
635                         0 => array( "pipe", "r" ),
636                         1 => array( "pipe", "w" ),
637                         2 => array( "file", "/dev/null", "a" ) );
638                 $pipes = array();
640                 $this->progress( "Spawning database subprocess: $cmd" );
641                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
642                 if ( !$this->spawnProc ) {
643                         // shit
644                         $this->progress( "Subprocess spawn failed." );
646                         return false;
647                 }
648                 list(
649                         $this->spawnWrite, // -> stdin
650                         $this->spawnRead, // <- stdout
651                 ) = $pipes;
653                 return true;
654         }
656         private function closeSpawn() {
657                 wfSuppressWarnings();
658                 if ( $this->spawnRead ) {
659                         fclose( $this->spawnRead );
660                 }
661                 $this->spawnRead = false;
662                 if ( $this->spawnWrite ) {
663                         fclose( $this->spawnWrite );
664                 }
665                 $this->spawnWrite = false;
666                 if ( $this->spawnErr ) {
667                         fclose( $this->spawnErr );
668                 }
669                 $this->spawnErr = false;
670                 if ( $this->spawnProc ) {
671                         pclose( $this->spawnProc );
672                 }
673                 $this->spawnProc = false;
674                 wfRestoreWarnings();
675         }
677         private function getTextSpawnedOnce( $id ) {
678                 global $wgContLang;
680                 $ok = fwrite( $this->spawnWrite, "$id\n" );
681                 // $this->progress( ">> $id" );
682                 if ( !$ok ) {
683                         return false;
684                 }
686                 $ok = fflush( $this->spawnWrite );
687                 // $this->progress( ">> [flush]" );
688                 if ( !$ok ) {
689                         return false;
690                 }
692                 // check that the text id they are sending is the one we asked for
693                 // this avoids out of sync revision text errors we have encountered in the past
694                 $newId = fgets( $this->spawnRead );
695                 if ( $newId === false ) {
696                         return false;
697                 }
698                 if ( $id != intval( $newId ) ) {
699                         return false;
700                 }
702                 $len = fgets( $this->spawnRead );
703                 // $this->progress( "<< " . trim( $len ) );
704                 if ( $len === false ) {
705                         return false;
706                 }
708                 $nbytes = intval( $len );
709                 // actual error, not zero-length text
710                 if ( $nbytes < 0 ) {
711                         return false;
712                 }
714                 $text = "";
716                 // Subprocess may not send everything at once, we have to loop.
717                 while ( $nbytes > strlen( $text ) ) {
718                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
719                         if ( $buffer === false ) {
720                                 break;
721                         }
722                         $text .= $buffer;
723                 }
725                 $gotbytes = strlen( $text );
726                 if ( $gotbytes != $nbytes ) {
727                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
729                         return false;
730                 }
732                 // Do normalization in the dump thread...
733                 $stripped = str_replace( "\r", "", $text );
734                 $normalized = $wgContLang->normalize( $stripped );
736                 return $normalized;
737         }
739         function startElement( $parser, $name, $attribs ) {
740                 $this->checkpointJustWritten = false;
742                 $this->clearOpenElement( null );
743                 $this->lastName = $name;
745                 if ( $name == 'revision' ) {
746                         $this->state = $name;
747                         $this->egress->writeOpenPage( null, $this->buffer );
748                         $this->buffer = "";
749                 } elseif ( $name == 'page' ) {
750                         $this->state = $name;
751                         if ( $this->atStart ) {
752                                 $this->egress->writeOpenStream( $this->buffer );
753                                 $this->buffer = "";
754                                 $this->atStart = false;
755                         }
756                 }
758                 if ( $name == "text" && isset( $attribs['id'] ) ) {
759                         $text = $this->getText( $attribs['id'] );
760                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
761                         if ( strlen( $text ) > 0 ) {
762                                 $this->characterData( $parser, $text );
763                         }
764                 } else {
765                         $this->openElement = array( $name, $attribs );
766                 }
767         }
769         function endElement( $parser, $name ) {
770                 $this->checkpointJustWritten = false;
772                 if ( $this->openElement ) {
773                         $this->clearOpenElement( "" );
774                 } else {
775                         $this->buffer .= "</$name>";
776                 }
778                 if ( $name == 'revision' ) {
779                         $this->egress->writeRevision( null, $this->buffer );
780                         $this->buffer = "";
781                         $this->thisRev = "";
782                 } elseif ( $name == 'page' ) {
783                         if ( !$this->firstPageWritten ) {
784                                 $this->firstPageWritten = trim( $this->thisPage );
785                         }
786                         $this->lastPageWritten = trim( $this->thisPage );
787                         if ( $this->timeExceeded ) {
788                                 $this->egress->writeClosePage( $this->buffer );
789                                 // nasty hack, we can't just write the chardata after the
790                                 // page tag, it will include leading blanks from the next line
791                                 $this->egress->sink->write( "\n" );
793                                 $this->buffer = $this->xmlwriterobj->closeStream();
794                                 $this->egress->writeCloseStream( $this->buffer );
796                                 $this->buffer = "";
797                                 $this->thisPage = "";
798                                 // this could be more than one file if we had more than one output arg
800                                 $filenameList = (array)$this->egress->getFilenames();
801                                 $newFilenames = array();
802                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
803                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
804                                 $filenamesCount = count( $filenameList );
805                                 for ( $i = 0; $i < $filenamesCount; $i++ ) {
806                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
807                                         $fileinfo = pathinfo( $filenameList[$i] );
808                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
809                                 }
810                                 $this->egress->closeRenameAndReopen( $newFilenames );
811                                 $this->buffer = $this->xmlwriterobj->openStream();
812                                 $this->timeExceeded = false;
813                                 $this->timeOfCheckpoint = $this->lastTime;
814                                 $this->firstPageWritten = false;
815                                 $this->checkpointJustWritten = true;
816                         } else {
817                                 $this->egress->writeClosePage( $this->buffer );
818                                 $this->buffer = "";
819                                 $this->thisPage = "";
820                         }
821                 } elseif ( $name == 'mediawiki' ) {
822                         $this->egress->writeCloseStream( $this->buffer );
823                         $this->buffer = "";
824                 }
825         }
827         function characterData( $parser, $data ) {
828                 $this->clearOpenElement( null );
829                 if ( $this->lastName == "id" ) {
830                         if ( $this->state == "revision" ) {
831                                 $this->thisRev .= $data;
832                         } elseif ( $this->state == "page" ) {
833                                 $this->thisPage .= $data;
834                         }
835                 }
836                 // have to skip the newline left over from closepagetag line of
837                 // end of checkpoint files. nasty hack!!
838                 if ( $this->checkpointJustWritten ) {
839                         if ( $data[0] == "\n" ) {
840                                 $data = substr( $data, 1 );
841                         }
842                         $this->checkpointJustWritten = false;
843                 }
844                 $this->buffer .= htmlspecialchars( $data );
845         }
847         function clearOpenElement( $style ) {
848                 if ( $this->openElement ) {
849                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
850                         $this->openElement = false;
851                 }
852         }