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