mw.Map: add ability to map over an existing object other than 'window'
[mediawiki.git] / maintenance / backupTextPass.inc
blobc515c6fec9ada737af0d047ee38ce67cb8d9f979
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(
488                                                 'revision',
489                                                 array( 'rev_len', 'rev_content_model' ),
490                                                 array( 'rev_id' => $revID ),
491                                                 __METHOD__
492                                         );
493                                         if ( $row ) {
494                                                 // only check the length for the wikitext content handler,
495                                                 // it's a wasted (and failed) check otherwise
496                                                 if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
497                                                         $revLength = $row->rev_len;
498                                                 }
499                                         }
501                                 }
502                                 else {
503                                         $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
504                                 }
506                                 if ( strlen( $text ) == $revLength ) {
507                                         if ( $tryIsPrefetch ) {
508                                                 $this->prefetchCount++;
509                                         }
510                                         return $text;
511                                 }
513                                 $text = false;
514                                 throw new MWException( "Received text is unplausible for id " . $id );
516                         } catch ( Exception $e ) {
517                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
518                                 if ( $failures + 1 < $this->maxFailures ) {
519                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
520                                 }
521                                 $this->progress( $msg );
522                         }
524                         // Something went wrong; we did not a text that was plausible :(
525                         $failures++;
527                         // A failure in a prefetch hit does not warrant resetting db connection etc.
528                         if ( ! $tryIsPrefetch ) {
529                                 // After backing off for some time, we try to reboot the whole process as
530                                 // much as possible to not carry over failures from one part to the other
531                                 // parts
532                                 sleep( $this->failureTimeout );
533                                 try {
534                                         $this->rotateDb();
535                                         if ( $this->spawn ) {
536                                                 $this->closeSpawn();
537                                                 $this->openSpawn();
538                                         }
539                                 } catch ( Exception $e ) {
540                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
541                                                 " Trying to continue anyways" );
542                                 }
543                         }
544                 }
546                 // Retirieving a good text for $id failed (at least) maxFailures times.
547                 // We abort for this $id.
549                 // Restoring the consecutive failures, and maybe aborting, if the dump
550                 // is too broken.
551                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
552                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
553                         throw new MWException( "Graceful storage failure" );
554                 }
556                 return "";
557         }
560         /**
561          * May throw a database error if, say, the server dies during query.
562          * @param $id
563          * @return bool|string
564          * @throws MWException
565          */
566         private function getTextDb( $id ) {
567                 global $wgContLang;
568                 if ( ! isset( $this->db ) ) {
569                         throw new MWException( __METHOD__ . "No database available" );
570                 }
571                 $row = $this->db->selectRow( 'text',
572                         array( 'old_text', 'old_flags' ),
573                         array( 'old_id' => $id ),
574                         __METHOD__ );
575                 $text = Revision::getRevisionText( $row );
576                 if ( $text === false ) {
577                         return false;
578                 }
579                 $stripped = str_replace( "\r", "", $text );
580                 $normalized = $wgContLang->normalize( $stripped );
581                 return $normalized;
582         }
584         private function getTextSpawned( $id ) {
585                 wfSuppressWarnings();
586                 if ( !$this->spawnProc ) {
587                         // First time?
588                         $this->openSpawn();
589                 }
590                 $text = $this->getTextSpawnedOnce( $id );
591                 wfRestoreWarnings();
592                 return $text;
593         }
595         function openSpawn() {
596                 global $IP;
598                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
599                         $cmd = implode( " ",
600                                 array_map( 'wfEscapeShellArg',
601                                         array(
602                                                 $this->php,
603                                                 "$IP/../multiversion/MWScript.php",
604                                                 "fetchText.php",
605                                                 '--wiki', wfWikiID() ) ) );
606                 }
607                 else {
608                         $cmd = implode( " ",
609                                 array_map( 'wfEscapeShellArg',
610                                         array(
611                                                 $this->php,
612                                                 "$IP/maintenance/fetchText.php",
613                                                 '--wiki', wfWikiID() ) ) );
614                 }
615                 $spec = array(
616                         0 => array( "pipe", "r" ),
617                         1 => array( "pipe", "w" ),
618                         2 => array( "file", "/dev/null", "a" ) );
619                 $pipes = array();
621                 $this->progress( "Spawning database subprocess: $cmd" );
622                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
623                 if ( !$this->spawnProc ) {
624                         // shit
625                         $this->progress( "Subprocess spawn failed." );
626                         return false;
627                 }
628                 list(
629                         $this->spawnWrite, // -> stdin
630                         $this->spawnRead,  // <- stdout
631                 ) = $pipes;
633                 return true;
634         }
636         private function closeSpawn() {
637                 wfSuppressWarnings();
638                 if ( $this->spawnRead ) {
639                         fclose( $this->spawnRead );
640                 }
641                 $this->spawnRead = false;
642                 if ( $this->spawnWrite ) {
643                         fclose( $this->spawnWrite );
644                 }
645                 $this->spawnWrite = false;
646                 if ( $this->spawnErr ) {
647                         fclose( $this->spawnErr );
648                 }
649                 $this->spawnErr = false;
650                 if ( $this->spawnProc ) {
651                         pclose( $this->spawnProc );
652                 }
653                 $this->spawnProc = false;
654                 wfRestoreWarnings();
655         }
657         private function getTextSpawnedOnce( $id ) {
658                 global $wgContLang;
660                 $ok = fwrite( $this->spawnWrite, "$id\n" );
661                 // $this->progress( ">> $id" );
662                 if ( !$ok ) {
663                         return false;
664                 }
666                 $ok = fflush( $this->spawnWrite );
667                 // $this->progress( ">> [flush]" );
668                 if ( !$ok ) {
669                         return false;
670                 }
672                 // check that the text id they are sending is the one we asked for
673                 // this avoids out of sync revision text errors we have encountered in the past
674                 $newId = fgets( $this->spawnRead );
675                 if ( $newId === false ) {
676                         return false;
677                 }
678                 if ( $id != intval( $newId ) ) {
679                         return false;
680                 }
682                 $len = fgets( $this->spawnRead );
683                 // $this->progress( "<< " . trim( $len ) );
684                 if ( $len === false ) {
685                         return false;
686                 }
688                 $nbytes = intval( $len );
689                 // actual error, not zero-length text
690                 if ( $nbytes < 0 ) {
691                         return false;
692                 }
694                 $text = "";
696                 // Subprocess may not send everything at once, we have to loop.
697                 while ( $nbytes > strlen( $text ) ) {
698                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
699                         if ( $buffer === false ) {
700                                 break;
701                         }
702                         $text .= $buffer;
703                 }
705                 $gotbytes = strlen( $text );
706                 if ( $gotbytes != $nbytes ) {
707                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
708                         return false;
709                 }
711                 // Do normalization in the dump thread...
712                 $stripped = str_replace( "\r", "", $text );
713                 $normalized = $wgContLang->normalize( $stripped );
714                 return $normalized;
715         }
717         function startElement( $parser, $name, $attribs ) {
718                 $this->checkpointJustWritten = false;
720                 $this->clearOpenElement( null );
721                 $this->lastName = $name;
723                 if ( $name == 'revision' ) {
724                         $this->state = $name;
725                         $this->egress->writeOpenPage( null, $this->buffer );
726                         $this->buffer = "";
727                 } elseif ( $name == 'page' ) {
728                         $this->state = $name;
729                         if ( $this->atStart ) {
730                                 $this->egress->writeOpenStream( $this->buffer );
731                                 $this->buffer = "";
732                                 $this->atStart = false;
733                         }
734                 }
736                 if ( $name == "text" && isset( $attribs['id'] ) ) {
737                         $text = $this->getText( $attribs['id'] );
738                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
739                         if ( strlen( $text ) > 0 ) {
740                                 $this->characterData( $parser, $text );
741                         }
742                 } else {
743                         $this->openElement = array( $name, $attribs );
744                 }
745         }
747         function endElement( $parser, $name ) {
748                 $this->checkpointJustWritten = false;
750                 if ( $this->openElement ) {
751                         $this->clearOpenElement( "" );
752                 } else {
753                         $this->buffer .= "</$name>";
754                 }
756                 if ( $name == 'revision' ) {
757                         $this->egress->writeRevision( null, $this->buffer );
758                         $this->buffer = "";
759                         $this->thisRev = "";
760                 } elseif ( $name == 'page' ) {
761                         if ( ! $this->firstPageWritten ) {
762                                 $this->firstPageWritten = trim( $this->thisPage );
763                         }
764                         $this->lastPageWritten = trim( $this->thisPage );
765                         if ( $this->timeExceeded ) {
766                                 $this->egress->writeClosePage( $this->buffer );
767                                 // nasty hack, we can't just write the chardata after the
768                                 // page tag, it will include leading blanks from the next line
769                                 $this->egress->sink->write( "\n" );
771                                 $this->buffer = $this->xmlwriterobj->closeStream();
772                                 $this->egress->writeCloseStream( $this->buffer );
774                                 $this->buffer = "";
775                                 $this->thisPage = "";
776                                 // this could be more than one file if we had more than one output arg
778                                 $filenameList = (array)$this->egress->getFilenames();
779                                 $newFilenames = array();
780                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
781                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
782                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
783                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
784                                         $fileinfo = pathinfo( $filenameList[$i] );
785                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
786                                 }
787                                 $this->egress->closeRenameAndReopen( $newFilenames );
788                                 $this->buffer = $this->xmlwriterobj->openStream();
789                                 $this->timeExceeded = false;
790                                 $this->timeOfCheckpoint = $this->lastTime;
791                                 $this->firstPageWritten = false;
792                                 $this->checkpointJustWritten = true;
793                         }
794                         else {
795                                 $this->egress->writeClosePage( $this->buffer );
796                                 $this->buffer = "";
797                                 $this->thisPage = "";
798                         }
800                 } elseif ( $name == 'mediawiki' ) {
801                         $this->egress->writeCloseStream( $this->buffer );
802                         $this->buffer = "";
803                 }
804         }
806         function characterData( $parser, $data ) {
807                 $this->clearOpenElement( null );
808                 if ( $this->lastName == "id" ) {
809                         if ( $this->state == "revision" ) {
810                                 $this->thisRev .= $data;
811                         } elseif ( $this->state == "page" ) {
812                                 $this->thisPage .= $data;
813                         }
814                 }
815                 // have to skip the newline left over from closepagetag line of
816                 // end of checkpoint files. nasty hack!!
817                 if ( $this->checkpointJustWritten ) {
818                         if ( $data[0] == "\n" ) {
819                                 $data = substr( $data, 1 );
820                         }
821                         $this->checkpointJustWritten = false;
822                 }
823                 $this->buffer .= htmlspecialchars( $data );
824         }
826         function clearOpenElement( $style ) {
827                 if ( $this->openElement ) {
828                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
829                         $this->openElement = false;
830                 }
831         }