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 = [];
91 * @param array $args For backward compatibility
93 function __construct( $args = null ) {
94 parent
::__construct();
96 $this->addDescription( <<<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.
104 $this->stderr
= fopen( "php://stderr", "wt" );
106 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
107 'Specify as --stub=<type>:<file>.', false, true );
108 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
109 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
111 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
112 'out complete page, closing xml file properly, and opening new one' .
113 'with header). This option requires the checkpointfile option.', false, true );
114 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
115 'first pageid written for the first %s (required) and the last pageid written for the ' .
116 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
117 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
118 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
119 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
120 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
121 '(Default: 512KB, Minimum: 4KB)', false, true );
124 $this->loadWithArgv( $args );
125 $this->processOptions();
130 $this->processOptions();
134 function processOptions() {
137 parent
::processOptions();
139 if ( $this->hasOption( 'buffersize' ) ) {
140 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
143 if ( $this->hasOption( 'prefetch' ) ) {
144 require_once "$IP/maintenance/backupPrefetch.inc";
145 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
146 $this->prefetch
= new BaseDump( $url );
149 if ( $this->hasOption( 'stub' ) ) {
150 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
153 if ( $this->hasOption( 'maxtime' ) ) {
154 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
157 if ( $this->hasOption( 'checkpointfile' ) ) {
158 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
161 if ( $this->hasOption( 'current' ) ) {
162 $this->history
= WikiExporter
::CURRENT
;
165 if ( $this->hasOption( 'full' ) ) {
166 $this->history
= WikiExporter
::FULL
;
169 if ( $this->hasOption( 'spawn' ) ) {
171 $val = $this->getOption( 'spawn' );
179 * Drop the database connection $this->db and try to get a new one.
181 * This function tries to get a /different/ connection if this is
182 * possible. Hence, (if this is possible) it switches to a different
183 * failover upon each call.
185 * This function resets $this->lb and closes all connections on it.
187 * @throws MWException
189 function rotateDb() {
190 // Cleaning up old connections
191 if ( isset( $this->lb
) ) {
192 $this->lb
->closeAll();
196 if ( $this->forcedDb
!== null ) {
197 $this->db
= $this->forcedDb
;
202 if ( isset( $this->db
) && $this->db
->isOpen() ) {
203 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
208 // Trying to set up new connection.
209 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
210 // individually retrying at different layers of code.
212 // 1. The LoadBalancer.
214 $this->lb
= wfGetLBFactory()->newMainLB();
215 } catch ( Exception
$e ) {
216 throw new MWException( __METHOD__
217 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
220 // 2. The Connection, through the load balancer.
222 $this->db
= $this->lb
->getConnection( DB_SLAVE
, 'dump' );
223 } catch ( Exception
$e ) {
224 throw new MWException( __METHOD__
225 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
229 function initProgress( $history = WikiExporter
::FULL
) {
230 parent
::initProgress();
231 $this->timeOfCheckpoint
= $this->startTime
;
234 function dump( $history, $text = WikiExporter
::TEXT
) {
235 // Notice messages will foul up your XML output even if they're
236 // relatively harmless.
237 if ( ini_get( 'display_errors' ) ) {
238 ini_set( 'display_errors', 'stderr' );
241 $this->initProgress( $this->history
);
243 // We are trying to get an initial database connection to avoid that the
244 // first try of this request's first call to getText fails. However, if
245 // obtaining a good DB connection fails it's not a serious issue, as
246 // getText does retry upon failure and can start without having a working
250 } catch ( Exception
$e ) {
251 // We do not even count this as failure. Just let eventual
253 $this->progress( "Getting initial DB connection failed (" .
254 $e->getMessage() . ")" );
257 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
259 // it would be nice to do it in the constructor, oh well. need egress set
260 $this->finalOptionCheck();
262 // we only want this so we know how to close a stream :-P
263 $this->xmlwriterobj
= new XmlDumpWriter();
265 $input = fopen( $this->input
, "rt" );
266 $this->readDump( $input );
268 if ( $this->spawnProc
) {
272 $this->report( true );
275 function processFileOpt( $opt ) {
276 $split = explode( ':', $opt, 2 );
279 if ( count( $split ) === 2 ) {
282 $fileURIs = explode( ';', $param );
283 foreach ( $fileURIs as $URI ) {
289 $newURI = "compress.zlib://$URI";
292 $newURI = "compress.bzip2://$URI";
295 $newURI = "mediawiki.compress.7z://$URI";
300 $newFileURIs[] = $newURI;
302 $val = implode( ';', $newFileURIs );
308 * Overridden to include prefetch ratio if enabled.
310 function showReport() {
311 if ( !$this->prefetch
) {
312 parent
::showReport();
317 if ( $this->reporting
) {
318 $now = wfTimestamp( TS_DB
);
319 $nowts = microtime( true );
320 $deltaAll = $nowts - $this->startTime
;
321 $deltaPart = $nowts - $this->lastTime
;
322 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
323 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
326 $portion = $this->revCount
/ $this->maxCount
;
327 $eta = $this->startTime +
$deltaAll / $portion;
328 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
329 if ( $this->fetchCount
) {
330 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
334 $pageRate = $this->pageCount
/ $deltaAll;
335 $revRate = $this->revCount
/ $deltaAll;
343 if ( $this->fetchCountLast
) {
344 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
346 $fetchRatePart = '-';
348 $pageRatePart = $this->pageCountPart
/ $deltaPart;
349 $revRatePart = $this->revCountPart
/ $deltaPart;
351 $fetchRatePart = '-';
355 $this->progress( sprintf(
356 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
357 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
358 . "prefetched (all|curr), ETA %s [max %d]",
359 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
360 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
361 $fetchRate, $fetchRatePart, $etats, $this->maxCount
363 $this->lastTime
= $nowts;
364 $this->revCountLast
= $this->revCount
;
365 $this->prefetchCountLast
= $this->prefetchCount
;
366 $this->fetchCountLast
= $this->fetchCount
;
370 function setTimeExceeded() {
371 $this->timeExceeded
= true;
374 function checkIfTimeExceeded() {
375 if ( $this->maxTimeAllowed
376 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
384 function finalOptionCheck() {
385 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
386 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
388 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
390 foreach ( $this->checkpointFiles
as $checkpointFile ) {
391 $count = substr_count( $checkpointFile, "%s" );
393 throw new MWException( "Option checkpointfile must contain two '%s' "
394 . "for substitution of first and last pageids, count is $count instead, "
395 . "file is $checkpointFile.\n" );
399 if ( $this->checkpointFiles
) {
400 $filenameList = (array)$this->egress
->getFilenames();
401 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
402 throw new MWException( "One checkpointfile must be specified "
403 . "for each output option, if maxtime is used.\n" );
409 * @throws MWException Failure to parse XML input
410 * @param string $input
413 function readDump( $input ) {
415 $this->openElement
= false;
416 $this->atStart
= true;
418 $this->lastName
= "";
421 $this->thisRevModel
= null;
422 $this->thisRevFormat
= null;
424 $parser = xml_parser_create( "UTF-8" );
425 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
427 xml_set_element_handler(
429 [ $this, 'startElement' ],
430 [ $this, 'endElement' ]
432 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
434 $offset = 0; // for context extraction on error reporting
436 if ( $this->checkIfTimeExceeded() ) {
437 $this->setTimeExceeded();
439 $chunk = fread( $input, $this->bufferSize
);
440 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
441 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
443 $byte = xml_get_current_byte_index( $parser );
444 $msg = wfMessage( 'xml-error-string',
445 'XML import parse failure',
446 xml_get_current_line_number( $parser ),
447 xml_get_current_column_number( $parser ),
448 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
449 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
451 xml_parser_free( $parser );
453 throw new MWException( $msg );
455 $offset +
= strlen( $chunk );
456 } while ( $chunk !== false && !feof( $input ) );
457 if ( $this->maxTimeAllowed
) {
458 $filenameList = (array)$this->egress
->getFilenames();
459 // we wrote some stuff after last checkpoint that needs renamed
460 if ( file_exists( $filenameList[0] ) ) {
462 # we might have just written the header and footer and had no
463 # pages or revisions written... perhaps they were all deleted
464 # there's no pageID 0 so we use that. the caller is responsible
465 # for deciding what to do with a file containing only the
466 # siteinfo information and the mw tags.
467 if ( !$this->firstPageWritten
) {
468 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
469 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
471 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
472 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
475 $filenameCount = count( $filenameList );
476 for ( $i = 0; $i < $filenameCount; $i++
) {
477 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
478 $fileinfo = pathinfo( $filenameList[$i] );
479 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
481 $this->egress
->closeAndRename( $newFilenames );
484 xml_parser_free( $parser );
490 * Applies applicable export transformations to $text.
492 * @param string $text
493 * @param string $model
494 * @param string|null $format
498 private function exportTransform( $text, $model, $format = null ) {
500 $handler = ContentHandler
::getForModelID( $model );
501 $text = $handler->exportTransform( $text, $format );
503 catch ( MWException
$ex ) {
505 "Unable to apply export transformation for content model '$model': " .
514 * Tries to get the revision text for a revision id.
515 * Export transformations are applied if the content model can is given or can be
516 * determined from the database.
518 * Upon errors, retries (Up to $this->maxFailures tries each call).
519 * If still no good revision get could be found even after this retrying, "" is returned.
520 * If no good revision text could be returned for
521 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
524 * @param string $id The revision id to get the text for
525 * @param string|bool|null $model The content model used to determine
526 * applicable export transformations.
527 * If $model is null, it will be determined from the database.
528 * @param string|null $format The content format used when applying export transformations.
530 * @throws MWException
531 * @return string The revision text for $id, or ""
533 function getText( $id, $model = null, $format = null ) {
534 global $wgContentHandlerUseDB;
536 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
537 $text = false; // The candidate for a good text. false if no proper value.
538 $failures = 0; // The number of times, this invocation of getText already failed.
540 // The number of times getText failed without yielding a good text in between.
541 static $consecutiveFailedTextRetrievals = 0;
545 // To allow to simply return on success and do not have to worry about book keeping,
546 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
547 // the old value, so we can restore it, if problems occur (See after the while loop).
548 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
549 $consecutiveFailedTextRetrievals = 0;
551 if ( $model === null && $wgContentHandlerUseDB ) {
552 $row = $this->db
->selectRow(
554 [ 'rev_content_model', 'rev_content_format' ],
555 [ 'rev_id' => $this->thisRev
],
560 $model = $row->rev_content_model
;
561 $format = $row->rev_content_format
;
565 if ( $model === null ||
$model === '' ) {
569 while ( $failures < $this->maxFailures
) {
571 // As soon as we found a good text for the $id, we will return immediately.
572 // Hence, if we make it past the try catch block, we know that we did not
576 // Step 1: Get some text (or reuse from previous iteratuon if checking
577 // for plausibility failed)
579 // Trying to get prefetch, if it has not been tried before
580 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
581 $prefetchNotTried = false;
582 $tryIsPrefetch = true;
583 $text = $this->prefetch
->prefetch( intval( $this->thisPage
),
584 intval( $this->thisRev
) );
586 if ( $text === null ) {
590 if ( is_string( $text ) && $model !== false ) {
591 // Apply export transformation to text coming from an old dump.
592 // The purpose of this transformation is to convert up from legacy
593 // formats, which may still be used in the older dump that is used
594 // for pre-fetching. Applying the transformation again should not
595 // interfere with content that is already in the correct form.
596 $text = $this->exportTransform( $text, $model, $format );
600 if ( $text === false ) {
601 // Fallback to asking the database
602 $tryIsPrefetch = false;
603 if ( $this->spawn
) {
604 $text = $this->getTextSpawned( $id );
606 $text = $this->getTextDb( $id );
609 if ( $text !== false && $model !== false ) {
610 // Apply export transformation to text coming from the database.
611 // Prefetched text should already have transformations applied.
612 $text = $this->exportTransform( $text, $model, $format );
615 // No more checks for texts from DB for now.
616 // If we received something that is not false,
617 // We treat it as good text, regardless of whether it actually is or is not
618 if ( $text !== false ) {
623 if ( $text === false ) {
624 throw new MWException( "Generic error while obtaining text for id " . $id );
627 // We received a good candidate for the text of $id via some method
629 // Step 2: Checking for plausibility and return the text if it is
631 $revID = intval( $this->thisRev
);
632 if ( !isset( $this->db
) ) {
633 throw new MWException( "No database available" );
636 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
637 $revLength = strlen( $text );
639 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
642 if ( strlen( $text ) == $revLength ) {
643 if ( $tryIsPrefetch ) {
644 $this->prefetchCount++
;
651 throw new MWException( "Received text is unplausible for id " . $id );
652 } catch ( Exception
$e ) {
653 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
654 if ( $failures +
1 < $this->maxFailures
) {
655 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
657 $this->progress( $msg );
660 // Something went wrong; we did not a text that was plausible :(
663 // A failure in a prefetch hit does not warrant resetting db connection etc.
664 if ( !$tryIsPrefetch ) {
665 // After backing off for some time, we try to reboot the whole process as
666 // much as possible to not carry over failures from one part to the other
668 sleep( $this->failureTimeout
);
671 if ( $this->spawn
) {
675 } catch ( Exception
$e ) {
676 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
677 " Trying to continue anyways" );
682 // Retirieving a good text for $id failed (at least) maxFailures times.
683 // We abort for this $id.
685 // Restoring the consecutive failures, and maybe aborting, if the dump
687 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
688 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
689 throw new MWException( "Graceful storage failure" );
696 * May throw a database error if, say, the server dies during query.
698 * @return bool|string
699 * @throws MWException
701 private function getTextDb( $id ) {
703 if ( !isset( $this->db
) ) {
704 throw new MWException( __METHOD__
. "No database available" );
706 $row = $this->db
->selectRow( 'text',
707 [ 'old_text', 'old_flags' ],
710 $text = Revision
::getRevisionText( $row );
711 if ( $text === false ) {
714 $stripped = str_replace( "\r", "", $text );
715 $normalized = $wgContLang->normalize( $stripped );
720 private function getTextSpawned( $id ) {
721 MediaWiki\
suppressWarnings();
722 if ( !$this->spawnProc
) {
726 $text = $this->getTextSpawnedOnce( $id );
727 MediaWiki\restoreWarnings
();
732 function openSpawn() {
735 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
737 array_map( 'wfEscapeShellArg',
740 "$IP/../multiversion/MWScript.php",
742 '--wiki', wfWikiID() ] ) );
745 array_map( 'wfEscapeShellArg',
748 "$IP/maintenance/fetchText.php",
749 '--wiki', wfWikiID() ] ) );
752 0 => [ "pipe", "r" ],
753 1 => [ "pipe", "w" ],
754 2 => [ "file", "/dev/null", "a" ] ];
757 $this->progress( "Spawning database subprocess: $cmd" );
758 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
759 if ( !$this->spawnProc
) {
760 $this->progress( "Subprocess spawn failed." );
765 $this->spawnWrite
, // -> stdin
766 $this->spawnRead
, // <- stdout
772 private function closeSpawn() {
773 MediaWiki\
suppressWarnings();
774 if ( $this->spawnRead
) {
775 fclose( $this->spawnRead
);
777 $this->spawnRead
= false;
778 if ( $this->spawnWrite
) {
779 fclose( $this->spawnWrite
);
781 $this->spawnWrite
= false;
782 if ( $this->spawnErr
) {
783 fclose( $this->spawnErr
);
785 $this->spawnErr
= false;
786 if ( $this->spawnProc
) {
787 pclose( $this->spawnProc
);
789 $this->spawnProc
= false;
790 MediaWiki\restoreWarnings
();
793 private function getTextSpawnedOnce( $id ) {
796 $ok = fwrite( $this->spawnWrite
, "$id\n" );
797 // $this->progress( ">> $id" );
802 $ok = fflush( $this->spawnWrite
);
803 // $this->progress( ">> [flush]" );
808 // check that the text id they are sending is the one we asked for
809 // this avoids out of sync revision text errors we have encountered in the past
810 $newId = fgets( $this->spawnRead
);
811 if ( $newId === false ) {
814 if ( $id != intval( $newId ) ) {
818 $len = fgets( $this->spawnRead
);
819 // $this->progress( "<< " . trim( $len ) );
820 if ( $len === false ) {
824 $nbytes = intval( $len );
825 // actual error, not zero-length text
832 // Subprocess may not send everything at once, we have to loop.
833 while ( $nbytes > strlen( $text ) ) {
834 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
835 if ( $buffer === false ) {
841 $gotbytes = strlen( $text );
842 if ( $gotbytes != $nbytes ) {
843 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
848 // Do normalization in the dump thread...
849 $stripped = str_replace( "\r", "", $text );
850 $normalized = $wgContLang->normalize( $stripped );
855 function startElement( $parser, $name, $attribs ) {
856 $this->checkpointJustWritten
= false;
858 $this->clearOpenElement( null );
859 $this->lastName
= $name;
861 if ( $name == 'revision' ) {
862 $this->state
= $name;
863 $this->egress
->writeOpenPage( null, $this->buffer
);
865 } elseif ( $name == 'page' ) {
866 $this->state
= $name;
867 if ( $this->atStart
) {
868 $this->egress
->writeOpenStream( $this->buffer
);
870 $this->atStart
= false;
874 if ( $name == "text" && isset( $attribs['id'] ) ) {
875 $id = $attribs['id'];
876 $model = trim( $this->thisRevModel
);
877 $format = trim( $this->thisRevFormat
);
879 $model = $model === '' ?
null : $model;
880 $format = $format === '' ?
null : $format;
882 $text = $this->getText( $id, $model, $format );
883 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
884 if ( strlen( $text ) > 0 ) {
885 $this->characterData( $parser, $text );
888 $this->openElement
= [ $name, $attribs ];
892 function endElement( $parser, $name ) {
893 $this->checkpointJustWritten
= false;
895 if ( $this->openElement
) {
896 $this->clearOpenElement( "" );
898 $this->buffer
.= "</$name>";
901 if ( $name == 'revision' ) {
902 $this->egress
->writeRevision( null, $this->buffer
);
905 $this->thisRevModel
= null;
906 $this->thisRevFormat
= null;
907 } elseif ( $name == 'page' ) {
908 if ( !$this->firstPageWritten
) {
909 $this->firstPageWritten
= trim( $this->thisPage
);
911 $this->lastPageWritten
= trim( $this->thisPage
);
912 if ( $this->timeExceeded
) {
913 $this->egress
->writeClosePage( $this->buffer
);
914 // nasty hack, we can't just write the chardata after the
915 // page tag, it will include leading blanks from the next line
916 $this->egress
->sink
->write( "\n" );
918 $this->buffer
= $this->xmlwriterobj
->closeStream();
919 $this->egress
->writeCloseStream( $this->buffer
);
922 $this->thisPage
= "";
923 // this could be more than one file if we had more than one output arg
925 $filenameList = (array)$this->egress
->getFilenames();
927 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
928 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
929 $filenamesCount = count( $filenameList );
930 for ( $i = 0; $i < $filenamesCount; $i++
) {
931 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
932 $fileinfo = pathinfo( $filenameList[$i] );
933 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
935 $this->egress
->closeRenameAndReopen( $newFilenames );
936 $this->buffer
= $this->xmlwriterobj
->openStream();
937 $this->timeExceeded
= false;
938 $this->timeOfCheckpoint
= $this->lastTime
;
939 $this->firstPageWritten
= false;
940 $this->checkpointJustWritten
= true;
942 $this->egress
->writeClosePage( $this->buffer
);
944 $this->thisPage
= "";
946 } elseif ( $name == 'mediawiki' ) {
947 $this->egress
->writeCloseStream( $this->buffer
);
952 function characterData( $parser, $data ) {
953 $this->clearOpenElement( null );
954 if ( $this->lastName
== "id" ) {
955 if ( $this->state
== "revision" ) {
956 $this->thisRev
.= $data;
957 } elseif ( $this->state
== "page" ) {
958 $this->thisPage
.= $data;
960 } elseif ( $this->lastName
== "model" ) {
961 $this->thisRevModel
.= $data;
962 } elseif ( $this->lastName
== "format" ) {
963 $this->thisRevFormat
.= $data;
966 // have to skip the newline left over from closepagetag line of
967 // end of checkpoint files. nasty hack!!
968 if ( $this->checkpointJustWritten
) {
969 if ( $data[0] == "\n" ) {
970 $data = substr( $data, 1 );
972 $this->checkpointJustWritten
= false;
974 $this->buffer
.= htmlspecialchars( $data );
977 function clearOpenElement( $style ) {
978 if ( $this->openElement
) {
979 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
980 $this->openElement
= false;
985 $maintClass = 'TextPassDumper';
986 require_once RUN_MAINTENANCE_IF_MAIN
;