3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
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.
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.
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
24 * @ingroup Maintenance
27 require_once __DIR__
. '/backup.inc';
28 require_once __DIR__
. '/../includes/export/WikiExporter.php';
31 * @ingroup Maintenance
33 class TextPassDumper
extends BackupDumper
{
34 public $prefetch = null;
36 // when we spend more than maxTimeAllowed seconds on this run, we continue
37 // processing until we write out the next complete page, then save output file(s),
38 // rename it/them and open new one(s)
39 public $maxTimeAllowed = 0; // 0 = no limit
41 protected $input = "php://stdin";
42 protected $history = WikiExporter
::FULL
;
43 protected $fetchCount = 0;
44 protected $prefetchCount = 0;
45 protected $prefetchCountLast = 0;
46 protected $fetchCountLast = 0;
48 protected $maxFailures = 5;
49 protected $maxConsecutiveFailedTextRetrievals = 200;
50 protected $failureTimeout = 5; // Seconds to sleep after db failure
52 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
54 protected $php = "php";
55 protected $spawn = false;
60 protected $spawnProc = false;
65 protected $spawnWrite = false;
70 protected $spawnRead = false;
75 protected $spawnErr = false;
77 protected $xmlwriterobj = false;
79 protected $timeExceeded = false;
80 protected $firstPageWritten = false;
81 protected $lastPageWritten = false;
82 protected $checkpointJustWritten = false;
83 protected $checkpointFiles = array();
91 * @param array $args For backward compatibility
93 function __construct( $args = null ) {
94 parent
::__construct();
96 $this->mDescription
= <<<TEXT
97 This script postprocesses XML dumps from dumpBackup.php to add
98 page text which was stubbed out (using --stub).
100 XML input is accepted on stdin.
101 XML output is sent to stdout; progress reports are sent to stderr.
103 $this->stderr
= fopen( "php://stderr", "wt" );
105 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
106 'Specify as --stub=<type>:<file>.', false, true );
107 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
108 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
110 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
111 'out complete page, closing xml file properly, and opening new one' .
112 'with header). This option requires the checkpointfile option.', false, true );
113 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
114 'first pageid written for the first %s (required) and the last pageid written for the ' .
115 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
116 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
117 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
118 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
119 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
120 '(Default: 512KB, Minimum: 4KB)', false, true );
123 $this->loadWithArgv( $args );
124 $this->processOptions();
129 $this->processOptions();
133 function processOptions() {
136 parent
::processOptions();
138 if ( $this->hasOption( 'buffersize' ) ) {
139 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
142 if ( $this->hasOption( 'prefetch' ) ) {
143 require_once "$IP/maintenance/backupPrefetch.inc";
144 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
145 $this->prefetch
= new BaseDump( $url );
148 if ( $this->hasOption( 'stub' ) ) {
149 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
152 if ( $this->hasOption( 'maxtime' ) ) {
153 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
156 if ( $this->hasOption( 'checkpointfile' ) ) {
157 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
160 if ( $this->hasOption( 'current' ) ) {
161 $this->history
= WikiExporter
::CURRENT
;
164 if ( $this->hasOption( 'full' ) ) {
165 $this->history
= WikiExporter
::FULL
;
168 if ( $this->hasOption( 'spawn' ) ) {
170 $val = $this->getOption( 'spawn' );
178 * Drop the database connection $this->db and try to get a new one.
180 * This function tries to get a /different/ connection if this is
181 * possible. Hence, (if this is possible) it switches to a different
182 * failover upon each call.
184 * This function resets $this->lb and closes all connections on it.
186 * @throws MWException
188 function rotateDb() {
189 // Cleaning up old connections
190 if ( isset( $this->lb
) ) {
191 $this->lb
->closeAll();
195 if ( $this->forcedDb
!== null ) {
196 $this->db
= $this->forcedDb
;
201 if ( isset( $this->db
) && $this->db
->isOpen() ) {
202 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
207 // Trying to set up new connection.
208 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
209 // individually retrying at different layers of code.
211 // 1. The LoadBalancer.
213 $this->lb
= wfGetLBFactory()->newMainLB();
214 } catch ( Exception
$e ) {
215 throw new MWException( __METHOD__
216 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
219 // 2. The Connection, through the load balancer.
221 $this->db
= $this->lb
->getConnection( DB_SLAVE
, 'dump' );
222 } catch ( Exception
$e ) {
223 throw new MWException( __METHOD__
224 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
228 function initProgress( $history = WikiExporter
::FULL
) {
229 parent
::initProgress();
230 $this->timeOfCheckpoint
= $this->startTime
;
233 function dump( $history, $text = WikiExporter
::TEXT
) {
234 // Notice messages will foul up your XML output even if they're
235 // relatively harmless.
236 if ( ini_get( 'display_errors' ) ) {
237 ini_set( 'display_errors', 'stderr' );
240 $this->initProgress( $this->history
);
242 // We are trying to get an initial database connection to avoid that the
243 // first try of this request's first call to getText fails. However, if
244 // obtaining a good DB connection fails it's not a serious issue, as
245 // getText does retry upon failure and can start without having a working
249 } catch ( Exception
$e ) {
250 // We do not even count this as failure. Just let eventual
252 $this->progress( "Getting initial DB connection failed (" .
253 $e->getMessage() . ")" );
256 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
258 // it would be nice to do it in the constructor, oh well. need egress set
259 $this->finalOptionCheck();
261 // we only want this so we know how to close a stream :-P
262 $this->xmlwriterobj
= new XmlDumpWriter();
264 $input = fopen( $this->input
, "rt" );
265 $this->readDump( $input );
267 if ( $this->spawnProc
) {
271 $this->report( true );
274 function processFileOpt( $opt ) {
275 $split = explode( ':', $opt, 2 );
278 if ( count( $split ) === 2 ) {
281 $fileURIs = explode( ';', $param );
282 foreach ( $fileURIs as $URI ) {
288 $newURI = "compress.zlib://$URI";
291 $newURI = "compress.bzip2://$URI";
294 $newURI = "mediawiki.compress.7z://$URI";
299 $newFileURIs[] = $newURI;
301 $val = implode( ';', $newFileURIs );
307 * Overridden to include prefetch ratio if enabled.
309 function showReport() {
310 if ( !$this->prefetch
) {
311 parent
::showReport();
316 if ( $this->reporting
) {
317 $now = wfTimestamp( TS_DB
);
318 $nowts = microtime( true );
319 $deltaAll = $nowts - $this->startTime
;
320 $deltaPart = $nowts - $this->lastTime
;
321 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
322 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
325 $portion = $this->revCount
/ $this->maxCount
;
326 $eta = $this->startTime +
$deltaAll / $portion;
327 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
328 if ( $this->fetchCount
) {
329 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
333 $pageRate = $this->pageCount
/ $deltaAll;
334 $revRate = $this->revCount
/ $deltaAll;
342 if ( $this->fetchCountLast
) {
343 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
345 $fetchRatePart = '-';
347 $pageRatePart = $this->pageCountPart
/ $deltaPart;
348 $revRatePart = $this->revCountPart
/ $deltaPart;
350 $fetchRatePart = '-';
354 $this->progress( sprintf(
355 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
356 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
357 . "prefetched (all|curr), ETA %s [max %d]",
358 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
359 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
360 $fetchRate, $fetchRatePart, $etats, $this->maxCount
362 $this->lastTime
= $nowts;
363 $this->revCountLast
= $this->revCount
;
364 $this->prefetchCountLast
= $this->prefetchCount
;
365 $this->fetchCountLast
= $this->fetchCount
;
369 function setTimeExceeded() {
370 $this->timeExceeded
= true;
373 function checkIfTimeExceeded() {
374 if ( $this->maxTimeAllowed
375 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
383 function finalOptionCheck() {
384 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
385 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
387 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
389 foreach ( $this->checkpointFiles
as $checkpointFile ) {
390 $count = substr_count( $checkpointFile, "%s" );
392 throw new MWException( "Option checkpointfile must contain two '%s' "
393 . "for substitution of first and last pageids, count is $count instead, "
394 . "file is $checkpointFile.\n" );
398 if ( $this->checkpointFiles
) {
399 $filenameList = (array)$this->egress
->getFilenames();
400 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
401 throw new MWException( "One checkpointfile must be specified "
402 . "for each output option, if maxtime is used.\n" );
408 * @throws MWException Failure to parse XML input
409 * @param string $input
412 function readDump( $input ) {
414 $this->openElement
= false;
415 $this->atStart
= true;
417 $this->lastName
= "";
420 $this->thisRevModel
= null;
421 $this->thisRevFormat
= null;
423 $parser = xml_parser_create( "UTF-8" );
424 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
426 xml_set_element_handler(
428 array( &$this, 'startElement' ),
429 array( &$this, 'endElement' )
431 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
433 $offset = 0; // for context extraction on error reporting
435 if ( $this->checkIfTimeExceeded() ) {
436 $this->setTimeExceeded();
438 $chunk = fread( $input, $this->bufferSize
);
439 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
440 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
442 $byte = xml_get_current_byte_index( $parser );
443 $msg = wfMessage( 'xml-error-string',
444 'XML import parse failure',
445 xml_get_current_line_number( $parser ),
446 xml_get_current_column_number( $parser ),
447 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
448 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
450 xml_parser_free( $parser );
452 throw new MWException( $msg );
454 $offset +
= strlen( $chunk );
455 } while ( $chunk !== false && !feof( $input ) );
456 if ( $this->maxTimeAllowed
) {
457 $filenameList = (array)$this->egress
->getFilenames();
458 // we wrote some stuff after last checkpoint that needs renamed
459 if ( file_exists( $filenameList[0] ) ) {
460 $newFilenames = array();
461 # we might have just written the header and footer and had no
462 # pages or revisions written... perhaps they were all deleted
463 # there's no pageID 0 so we use that. the caller is responsible
464 # for deciding what to do with a file containing only the
465 # siteinfo information and the mw tags.
466 if ( !$this->firstPageWritten
) {
467 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
468 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
470 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
471 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
474 $filenameCount = count( $filenameList );
475 for ( $i = 0; $i < $filenameCount; $i++
) {
476 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
477 $fileinfo = pathinfo( $filenameList[$i] );
478 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
480 $this->egress
->closeAndRename( $newFilenames );
483 xml_parser_free( $parser );
489 * Applies applicable export transformations to $text.
491 * @param string $text
492 * @param string $model
493 * @param string|null $format
497 private function exportTransform( $text, $model, $format = null ) {
499 $handler = ContentHandler
::getForModelID( $model );
500 $text = $handler->exportTransform( $text, $format );
502 catch ( MWException
$ex ) {
504 "Unable to apply export transformation for content model '$model': " .
513 * Tries to get the revision text for a revision id.
514 * Export transformations are applied if the content model can is given or can be
515 * determined from the database.
517 * Upon errors, retries (Up to $this->maxFailures tries each call).
518 * If still no good revision get could be found even after this retrying, "" is returned.
519 * If no good revision text could be returned for
520 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
523 * @param string $id The revision id to get the text for
524 * @param string|bool|null $model The content model used to determine
525 * applicable export transformations.
526 * If $model is null, it will be determined from the database.
527 * @param string|null $format The content format used when applying export transformations.
529 * @throws MWException
530 * @return string The revision text for $id, or ""
532 function getText( $id, $model = null, $format = null ) {
533 global $wgContentHandlerUseDB;
535 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
536 $text = false; // The candidate for a good text. false if no proper value.
537 $failures = 0; // The number of times, this invocation of getText already failed.
539 // The number of times getText failed without yielding a good text in between.
540 static $consecutiveFailedTextRetrievals = 0;
544 // To allow to simply return on success and do not have to worry about book keeping,
545 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
546 // the old value, so we can restore it, if problems occur (See after the while loop).
547 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
548 $consecutiveFailedTextRetrievals = 0;
550 if ( $model === null && $wgContentHandlerUseDB ) {
551 $row = $this->db
->selectRow(
553 array( 'rev_content_model', 'rev_content_format' ),
554 array( 'rev_id' => $this->thisRev
),
559 $model = $row->rev_content_model
;
560 $format = $row->rev_content_format
;
564 if ( $model === null ||
$model === '' ) {
568 while ( $failures < $this->maxFailures
) {
570 // As soon as we found a good text for the $id, we will return immediately.
571 // Hence, if we make it past the try catch block, we know that we did not
575 // Step 1: Get some text (or reuse from previous iteratuon if checking
576 // for plausibility failed)
578 // Trying to get prefetch, if it has not been tried before
579 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
580 $prefetchNotTried = false;
581 $tryIsPrefetch = true;
582 $text = $this->prefetch
->prefetch( intval( $this->thisPage
),
583 intval( $this->thisRev
) );
585 if ( $text === null ) {
589 if ( is_string( $text ) && $model !== false ) {
590 // Apply export transformation to text coming from an old dump.
591 // The purpose of this transformation is to convert up from legacy
592 // formats, which may still be used in the older dump that is used
593 // for pre-fetching. Applying the transformation again should not
594 // interfere with content that is already in the correct form.
595 $text = $this->exportTransform( $text, $model, $format );
599 if ( $text === false ) {
600 // Fallback to asking the database
601 $tryIsPrefetch = false;
602 if ( $this->spawn
) {
603 $text = $this->getTextSpawned( $id );
605 $text = $this->getTextDb( $id );
608 if ( $text !== false && $model !== false ) {
609 // Apply export transformation to text coming from the database.
610 // Prefetched text should already have transformations applied.
611 $text = $this->exportTransform( $text, $model, $format );
614 // No more checks for texts from DB for now.
615 // If we received something that is not false,
616 // We treat it as good text, regardless of whether it actually is or is not
617 if ( $text !== false ) {
622 if ( $text === false ) {
623 throw new MWException( "Generic error while obtaining text for id " . $id );
626 // We received a good candidate for the text of $id via some method
628 // Step 2: Checking for plausibility and return the text if it is
630 $revID = intval( $this->thisRev
);
631 if ( !isset( $this->db
) ) {
632 throw new MWException( "No database available" );
635 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
636 $revLength = strlen( $text );
638 $revLength = $this->db
->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
641 if ( strlen( $text ) == $revLength ) {
642 if ( $tryIsPrefetch ) {
643 $this->prefetchCount++
;
650 throw new MWException( "Received text is unplausible for id " . $id );
651 } catch ( Exception
$e ) {
652 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
653 if ( $failures +
1 < $this->maxFailures
) {
654 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
656 $this->progress( $msg );
659 // Something went wrong; we did not a text that was plausible :(
662 // A failure in a prefetch hit does not warrant resetting db connection etc.
663 if ( !$tryIsPrefetch ) {
664 // After backing off for some time, we try to reboot the whole process as
665 // much as possible to not carry over failures from one part to the other
667 sleep( $this->failureTimeout
);
670 if ( $this->spawn
) {
674 } catch ( Exception
$e ) {
675 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
676 " Trying to continue anyways" );
681 // Retirieving a good text for $id failed (at least) maxFailures times.
682 // We abort for this $id.
684 // Restoring the consecutive failures, and maybe aborting, if the dump
686 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
687 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
688 throw new MWException( "Graceful storage failure" );
695 * May throw a database error if, say, the server dies during query.
697 * @return bool|string
698 * @throws MWException
700 private function getTextDb( $id ) {
702 if ( !isset( $this->db
) ) {
703 throw new MWException( __METHOD__
. "No database available" );
705 $row = $this->db
->selectRow( 'text',
706 array( 'old_text', 'old_flags' ),
707 array( 'old_id' => $id ),
709 $text = Revision
::getRevisionText( $row );
710 if ( $text === false ) {
713 $stripped = str_replace( "\r", "", $text );
714 $normalized = $wgContLang->normalize( $stripped );
719 private function getTextSpawned( $id ) {
720 MediaWiki\
suppressWarnings();
721 if ( !$this->spawnProc
) {
725 $text = $this->getTextSpawnedOnce( $id );
726 MediaWiki\restoreWarnings
();
731 function openSpawn() {
734 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
736 array_map( 'wfEscapeShellArg',
739 "$IP/../multiversion/MWScript.php",
741 '--wiki', wfWikiID() ) ) );
744 array_map( 'wfEscapeShellArg',
747 "$IP/maintenance/fetchText.php",
748 '--wiki', wfWikiID() ) ) );
751 0 => array( "pipe", "r" ),
752 1 => array( "pipe", "w" ),
753 2 => array( "file", "/dev/null", "a" ) );
756 $this->progress( "Spawning database subprocess: $cmd" );
757 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
758 if ( !$this->spawnProc
) {
759 $this->progress( "Subprocess spawn failed." );
764 $this->spawnWrite
, // -> stdin
765 $this->spawnRead
, // <- stdout
771 private function closeSpawn() {
772 MediaWiki\
suppressWarnings();
773 if ( $this->spawnRead
) {
774 fclose( $this->spawnRead
);
776 $this->spawnRead
= false;
777 if ( $this->spawnWrite
) {
778 fclose( $this->spawnWrite
);
780 $this->spawnWrite
= false;
781 if ( $this->spawnErr
) {
782 fclose( $this->spawnErr
);
784 $this->spawnErr
= false;
785 if ( $this->spawnProc
) {
786 pclose( $this->spawnProc
);
788 $this->spawnProc
= false;
789 MediaWiki\restoreWarnings
();
792 private function getTextSpawnedOnce( $id ) {
795 $ok = fwrite( $this->spawnWrite
, "$id\n" );
796 // $this->progress( ">> $id" );
801 $ok = fflush( $this->spawnWrite
);
802 // $this->progress( ">> [flush]" );
807 // check that the text id they are sending is the one we asked for
808 // this avoids out of sync revision text errors we have encountered in the past
809 $newId = fgets( $this->spawnRead
);
810 if ( $newId === false ) {
813 if ( $id != intval( $newId ) ) {
817 $len = fgets( $this->spawnRead
);
818 // $this->progress( "<< " . trim( $len ) );
819 if ( $len === false ) {
823 $nbytes = intval( $len );
824 // actual error, not zero-length text
831 // Subprocess may not send everything at once, we have to loop.
832 while ( $nbytes > strlen( $text ) ) {
833 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
834 if ( $buffer === false ) {
840 $gotbytes = strlen( $text );
841 if ( $gotbytes != $nbytes ) {
842 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
847 // Do normalization in the dump thread...
848 $stripped = str_replace( "\r", "", $text );
849 $normalized = $wgContLang->normalize( $stripped );
854 function startElement( $parser, $name, $attribs ) {
855 $this->checkpointJustWritten
= false;
857 $this->clearOpenElement( null );
858 $this->lastName
= $name;
860 if ( $name == 'revision' ) {
861 $this->state
= $name;
862 $this->egress
->writeOpenPage( null, $this->buffer
);
864 } elseif ( $name == 'page' ) {
865 $this->state
= $name;
866 if ( $this->atStart
) {
867 $this->egress
->writeOpenStream( $this->buffer
);
869 $this->atStart
= false;
873 if ( $name == "text" && isset( $attribs['id'] ) ) {
874 $id = $attribs['id'];
875 $model = trim( $this->thisRevModel
);
876 $format = trim( $this->thisRevFormat
);
878 $model = $model === '' ?
null : $model;
879 $format = $format === '' ?
null : $format;
881 $text = $this->getText( $id, $model, $format );
882 $this->openElement
= array( $name, array( 'xml:space' => 'preserve' ) );
883 if ( strlen( $text ) > 0 ) {
884 $this->characterData( $parser, $text );
887 $this->openElement
= array( $name, $attribs );
891 function endElement( $parser, $name ) {
892 $this->checkpointJustWritten
= false;
894 if ( $this->openElement
) {
895 $this->clearOpenElement( "" );
897 $this->buffer
.= "</$name>";
900 if ( $name == 'revision' ) {
901 $this->egress
->writeRevision( null, $this->buffer
);
904 $this->thisRevModel
= null;
905 $this->thisRevFormat
= null;
906 } elseif ( $name == 'page' ) {
907 if ( !$this->firstPageWritten
) {
908 $this->firstPageWritten
= trim( $this->thisPage
);
910 $this->lastPageWritten
= trim( $this->thisPage
);
911 if ( $this->timeExceeded
) {
912 $this->egress
->writeClosePage( $this->buffer
);
913 // nasty hack, we can't just write the chardata after the
914 // page tag, it will include leading blanks from the next line
915 $this->egress
->sink
->write( "\n" );
917 $this->buffer
= $this->xmlwriterobj
->closeStream();
918 $this->egress
->writeCloseStream( $this->buffer
);
921 $this->thisPage
= "";
922 // this could be more than one file if we had more than one output arg
924 $filenameList = (array)$this->egress
->getFilenames();
925 $newFilenames = array();
926 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
927 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
928 $filenamesCount = count( $filenameList );
929 for ( $i = 0; $i < $filenamesCount; $i++
) {
930 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
931 $fileinfo = pathinfo( $filenameList[$i] );
932 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
934 $this->egress
->closeRenameAndReopen( $newFilenames );
935 $this->buffer
= $this->xmlwriterobj
->openStream();
936 $this->timeExceeded
= false;
937 $this->timeOfCheckpoint
= $this->lastTime
;
938 $this->firstPageWritten
= false;
939 $this->checkpointJustWritten
= true;
941 $this->egress
->writeClosePage( $this->buffer
);
943 $this->thisPage
= "";
945 } elseif ( $name == 'mediawiki' ) {
946 $this->egress
->writeCloseStream( $this->buffer
);
951 function characterData( $parser, $data ) {
952 $this->clearOpenElement( null );
953 if ( $this->lastName
== "id" ) {
954 if ( $this->state
== "revision" ) {
955 $this->thisRev
.= $data;
956 } elseif ( $this->state
== "page" ) {
957 $this->thisPage
.= $data;
959 } elseif ( $this->lastName
== "model" ) {
960 $this->thisRevModel
.= $data;
961 } elseif ( $this->lastName
== "format" ) {
962 $this->thisRevFormat
.= $data;
965 // have to skip the newline left over from closepagetag line of
966 // end of checkpoint files. nasty hack!!
967 if ( $this->checkpointJustWritten
) {
968 if ( $data[0] == "\n" ) {
969 $data = substr( $data, 1 );
971 $this->checkpointJustWritten
= false;
973 $this->buffer
.= htmlspecialchars( $data );
976 function clearOpenElement( $style ) {
977 if ( $this->openElement
) {
978 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
979 $this->openElement
= false;
984 $maintClass = 'TextPassDumper';
985 require_once RUN_MAINTENANCE_IF_MAIN
;