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__
. '/7zip.inc';
29 require_once __DIR__
. '/../includes/export/WikiExporter.php';
31 use Wikimedia\Rdbms\IMaintainableDatabase
;
34 * @ingroup Maintenance
36 class TextPassDumper
extends BackupDumper
{
38 public $prefetch = null;
39 /** @var string|bool */
41 /** @var string|bool */
44 // when we spend more than maxTimeAllowed seconds on this run, we continue
45 // processing until we write out the next complete page, then save output file(s),
46 // rename it/them and open new one(s)
47 public $maxTimeAllowed = 0; // 0 = no limit
49 protected $input = "php://stdin";
50 protected $history = WikiExporter
::FULL
;
51 protected $fetchCount = 0;
52 protected $prefetchCount = 0;
53 protected $prefetchCountLast = 0;
54 protected $fetchCountLast = 0;
56 protected $maxFailures = 5;
57 protected $maxConsecutiveFailedTextRetrievals = 200;
58 protected $failureTimeout = 5; // Seconds to sleep after db failure
60 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
62 protected $php = "php";
63 protected $spawn = false;
68 protected $spawnProc = false;
73 protected $spawnWrite = false;
78 protected $spawnRead = false;
83 protected $spawnErr = false;
86 * @var bool|XmlDumpWriter
88 protected $xmlwriterobj = false;
90 protected $timeExceeded = false;
91 protected $firstPageWritten = false;
92 protected $lastPageWritten = false;
93 protected $checkpointJustWritten = false;
94 protected $checkpointFiles = [];
97 * @var IMaintainableDatabase
102 * @param array $args For backward compatibility
104 function __construct( $args = null ) {
105 parent
::__construct();
107 $this->addDescription( <<<TEXT
108 This script postprocesses XML dumps from dumpBackup.php to add
109 page text which was stubbed out (using --stub).
111 XML input is accepted on stdin.
112 XML output is sent to stdout; progress reports are sent to stderr.
115 $this->stderr
= fopen( "php://stderr", "wt" );
117 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
118 'Specify as --stub=<type>:<file>.', false, true );
119 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
120 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
122 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
123 'out complete page, closing xml file properly, and opening new one' .
124 'with header). This option requires the checkpointfile option.', false, true );
125 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
126 'first pageid written for the first %s (required) and the last pageid written for the ' .
127 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
128 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
129 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
130 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
131 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
132 '(Default: 512KB, Minimum: 4KB)', false, true );
135 $this->loadWithArgv( $args );
136 $this->processOptions();
141 $this->processOptions();
145 function processOptions() {
148 parent
::processOptions();
150 if ( $this->hasOption( 'buffersize' ) ) {
151 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
154 if ( $this->hasOption( 'prefetch' ) ) {
155 require_once "$IP/maintenance/backupPrefetch.inc";
156 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
157 $this->prefetch
= new BaseDump( $url );
160 if ( $this->hasOption( 'stub' ) ) {
161 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
164 if ( $this->hasOption( 'maxtime' ) ) {
165 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
168 if ( $this->hasOption( 'checkpointfile' ) ) {
169 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
172 if ( $this->hasOption( 'current' ) ) {
173 $this->history
= WikiExporter
::CURRENT
;
176 if ( $this->hasOption( 'full' ) ) {
177 $this->history
= WikiExporter
::FULL
;
180 if ( $this->hasOption( 'spawn' ) ) {
182 $val = $this->getOption( 'spawn' );
190 * Drop the database connection $this->db and try to get a new one.
192 * This function tries to get a /different/ connection if this is
193 * possible. Hence, (if this is possible) it switches to a different
194 * failover upon each call.
196 * This function resets $this->lb and closes all connections on it.
198 * @throws MWException
200 function rotateDb() {
201 // Cleaning up old connections
202 if ( isset( $this->lb
) ) {
203 $this->lb
->closeAll();
207 if ( $this->forcedDb
!== null ) {
208 $this->db
= $this->forcedDb
;
213 if ( isset( $this->db
) && $this->db
->isOpen() ) {
214 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
219 // Trying to set up new connection.
220 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
221 // individually retrying at different layers of code.
224 $this->lb
= wfGetLBFactory()->newMainLB();
225 } catch ( Exception
$e ) {
226 throw new MWException( __METHOD__
227 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
231 $this->db
= $this->lb
->getConnection( DB_REPLICA
, 'dump' );
232 } catch ( Exception
$e ) {
233 throw new MWException( __METHOD__
234 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
238 function initProgress( $history = WikiExporter
::FULL
) {
239 parent
::initProgress();
240 $this->timeOfCheckpoint
= $this->startTime
;
243 function dump( $history, $text = WikiExporter
::TEXT
) {
244 // Notice messages will foul up your XML output even if they're
245 // relatively harmless.
246 if ( ini_get( 'display_errors' ) ) {
247 ini_set( 'display_errors', 'stderr' );
250 $this->initProgress( $this->history
);
252 // We are trying to get an initial database connection to avoid that the
253 // first try of this request's first call to getText fails. However, if
254 // obtaining a good DB connection fails it's not a serious issue, as
255 // getText does retry upon failure and can start without having a working
259 } catch ( Exception
$e ) {
260 // We do not even count this as failure. Just let eventual
262 $this->progress( "Getting initial DB connection failed (" .
263 $e->getMessage() . ")" );
266 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
268 // it would be nice to do it in the constructor, oh well. need egress set
269 $this->finalOptionCheck();
271 // we only want this so we know how to close a stream :-P
272 $this->xmlwriterobj
= new XmlDumpWriter();
274 $input = fopen( $this->input
, "rt" );
275 $this->readDump( $input );
277 if ( $this->spawnProc
) {
281 $this->report( true );
284 function processFileOpt( $opt ) {
285 $split = explode( ':', $opt, 2 );
288 if ( count( $split ) === 2 ) {
291 $fileURIs = explode( ';', $param );
292 foreach ( $fileURIs as $URI ) {
298 $newURI = "compress.zlib://$URI";
301 $newURI = "compress.bzip2://$URI";
304 $newURI = "mediawiki.compress.7z://$URI";
309 $newFileURIs[] = $newURI;
311 $val = implode( ';', $newFileURIs );
317 * Overridden to include prefetch ratio if enabled.
319 function showReport() {
320 if ( !$this->prefetch
) {
321 parent
::showReport();
326 if ( $this->reporting
) {
327 $now = wfTimestamp( TS_DB
);
328 $nowts = microtime( true );
329 $deltaAll = $nowts - $this->startTime
;
330 $deltaPart = $nowts - $this->lastTime
;
331 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
332 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
335 $portion = $this->revCount
/ $this->maxCount
;
336 $eta = $this->startTime +
$deltaAll / $portion;
337 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
338 if ( $this->fetchCount
) {
339 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
343 $pageRate = $this->pageCount
/ $deltaAll;
344 $revRate = $this->revCount
/ $deltaAll;
352 if ( $this->fetchCountLast
) {
353 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
355 $fetchRatePart = '-';
357 $pageRatePart = $this->pageCountPart
/ $deltaPart;
358 $revRatePart = $this->revCountPart
/ $deltaPart;
360 $fetchRatePart = '-';
364 $this->progress( sprintf(
365 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
366 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
367 . "prefetched (all|curr), ETA %s [max %d]",
368 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
369 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
370 $fetchRate, $fetchRatePart, $etats, $this->maxCount
372 $this->lastTime
= $nowts;
373 $this->revCountLast
= $this->revCount
;
374 $this->prefetchCountLast
= $this->prefetchCount
;
375 $this->fetchCountLast
= $this->fetchCount
;
379 function setTimeExceeded() {
380 $this->timeExceeded
= true;
383 function checkIfTimeExceeded() {
384 if ( $this->maxTimeAllowed
385 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
393 function finalOptionCheck() {
394 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
395 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
397 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
399 foreach ( $this->checkpointFiles
as $checkpointFile ) {
400 $count = substr_count( $checkpointFile, "%s" );
402 throw new MWException( "Option checkpointfile must contain two '%s' "
403 . "for substitution of first and last pageids, count is $count instead, "
404 . "file is $checkpointFile.\n" );
408 if ( $this->checkpointFiles
) {
409 $filenameList = (array)$this->egress
->getFilenames();
410 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
411 throw new MWException( "One checkpointfile must be specified "
412 . "for each output option, if maxtime is used.\n" );
418 * @throws MWException Failure to parse XML input
419 * @param string $input
422 function readDump( $input ) {
424 $this->openElement
= false;
425 $this->atStart
= true;
427 $this->lastName
= "";
430 $this->thisRevModel
= null;
431 $this->thisRevFormat
= null;
433 $parser = xml_parser_create( "UTF-8" );
434 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
436 xml_set_element_handler(
438 [ $this, 'startElement' ],
439 [ $this, 'endElement' ]
441 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
443 $offset = 0; // for context extraction on error reporting
445 if ( $this->checkIfTimeExceeded() ) {
446 $this->setTimeExceeded();
448 $chunk = fread( $input, $this->bufferSize
);
449 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
450 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
452 $byte = xml_get_current_byte_index( $parser );
453 $msg = wfMessage( 'xml-error-string',
454 'XML import parse failure',
455 xml_get_current_line_number( $parser ),
456 xml_get_current_column_number( $parser ),
457 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
458 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
460 xml_parser_free( $parser );
462 throw new MWException( $msg );
464 $offset +
= strlen( $chunk );
465 } while ( $chunk !== false && !feof( $input ) );
466 if ( $this->maxTimeAllowed
) {
467 $filenameList = (array)$this->egress
->getFilenames();
468 // we wrote some stuff after last checkpoint that needs renamed
469 if ( file_exists( $filenameList[0] ) ) {
471 # we might have just written the header and footer and had no
472 # pages or revisions written... perhaps they were all deleted
473 # there's no pageID 0 so we use that. the caller is responsible
474 # for deciding what to do with a file containing only the
475 # siteinfo information and the mw tags.
476 if ( !$this->firstPageWritten
) {
477 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
478 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
480 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
481 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
484 $filenameCount = count( $filenameList );
485 for ( $i = 0; $i < $filenameCount; $i++
) {
486 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
487 $fileinfo = pathinfo( $filenameList[$i] );
488 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
490 $this->egress
->closeAndRename( $newFilenames );
493 xml_parser_free( $parser );
499 * Applies applicable export transformations to $text.
501 * @param string $text
502 * @param string $model
503 * @param string|null $format
507 private function exportTransform( $text, $model, $format = null ) {
509 $handler = ContentHandler
::getForModelID( $model );
510 $text = $handler->exportTransform( $text, $format );
512 catch ( MWException
$ex ) {
514 "Unable to apply export transformation for content model '$model': " .
523 * Tries to get the revision text for a revision id.
524 * Export transformations are applied if the content model can is given or can be
525 * determined from the database.
527 * Upon errors, retries (Up to $this->maxFailures tries each call).
528 * If still no good revision get could be found even after this retrying, "" is returned.
529 * If no good revision text could be returned for
530 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
533 * @param string $id The revision id to get the text for
534 * @param string|bool|null $model The content model used to determine
535 * applicable export transformations.
536 * If $model is null, it will be determined from the database.
537 * @param string|null $format The content format used when applying export transformations.
539 * @throws MWException
540 * @return string The revision text for $id, or ""
542 function getText( $id, $model = null, $format = null ) {
543 global $wgContentHandlerUseDB;
545 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
546 $text = false; // The candidate for a good text. false if no proper value.
547 $failures = 0; // The number of times, this invocation of getText already failed.
549 // The number of times getText failed without yielding a good text in between.
550 static $consecutiveFailedTextRetrievals = 0;
554 // To allow to simply return on success and do not have to worry about book keeping,
555 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
556 // the old value, so we can restore it, if problems occur (See after the while loop).
557 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
558 $consecutiveFailedTextRetrievals = 0;
560 if ( $model === null && $wgContentHandlerUseDB ) {
561 $row = $this->db
->selectRow(
563 [ 'rev_content_model', 'rev_content_format' ],
564 [ 'rev_id' => $this->thisRev
],
569 $model = $row->rev_content_model
;
570 $format = $row->rev_content_format
;
574 if ( $model === null ||
$model === '' ) {
578 while ( $failures < $this->maxFailures
) {
579 // As soon as we found a good text for the $id, we will return immediately.
580 // Hence, if we make it past the try catch block, we know that we did not
584 // Step 1: Get some text (or reuse from previous iteratuon if checking
585 // for plausibility failed)
587 // Trying to get prefetch, if it has not been tried before
588 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
589 $prefetchNotTried = false;
590 $tryIsPrefetch = true;
591 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
593 if ( $text === null ) {
597 if ( is_string( $text ) && $model !== false ) {
598 // Apply export transformation to text coming from an old dump.
599 // The purpose of this transformation is to convert up from legacy
600 // formats, which may still be used in the older dump that is used
601 // for pre-fetching. Applying the transformation again should not
602 // interfere with content that is already in the correct form.
603 $text = $this->exportTransform( $text, $model, $format );
607 if ( $text === false ) {
608 // Fallback to asking the database
609 $tryIsPrefetch = false;
610 if ( $this->spawn
) {
611 $text = $this->getTextSpawned( $id );
613 $text = $this->getTextDb( $id );
616 if ( $text !== false && $model !== false ) {
617 // Apply export transformation to text coming from the database.
618 // Prefetched text should already have transformations applied.
619 $text = $this->exportTransform( $text, $model, $format );
622 // No more checks for texts from DB for now.
623 // If we received something that is not false,
624 // We treat it as good text, regardless of whether it actually is or is not
625 if ( $text !== false ) {
630 if ( $text === false ) {
631 throw new MWException( "Generic error while obtaining text for id " . $id );
634 // We received a good candidate for the text of $id via some method
636 // Step 2: Checking for plausibility and return the text if it is
638 $revID = intval( $this->thisRev
);
639 if ( !isset( $this->db
) ) {
640 throw new MWException( "No database available" );
643 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
644 $revLength = strlen( $text );
646 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
649 if ( strlen( $text ) == $revLength ) {
650 if ( $tryIsPrefetch ) {
651 $this->prefetchCount++
;
658 throw new MWException( "Received text is unplausible for id " . $id );
659 } catch ( Exception
$e ) {
660 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
661 if ( $failures +
1 < $this->maxFailures
) {
662 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
664 $this->progress( $msg );
667 // Something went wrong; we did not a text that was plausible :(
670 // A failure in a prefetch hit does not warrant resetting db connection etc.
671 if ( !$tryIsPrefetch ) {
672 // After backing off for some time, we try to reboot the whole process as
673 // much as possible to not carry over failures from one part to the other
675 sleep( $this->failureTimeout
);
678 if ( $this->spawn
) {
682 } catch ( Exception
$e ) {
683 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
684 " Trying to continue anyways" );
689 // Retirieving a good text for $id failed (at least) maxFailures times.
690 // We abort for this $id.
692 // Restoring the consecutive failures, and maybe aborting, if the dump
694 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
695 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
696 throw new MWException( "Graceful storage failure" );
703 * May throw a database error if, say, the server dies during query.
705 * @return bool|string
706 * @throws MWException
708 private function getTextDb( $id ) {
710 if ( !isset( $this->db
) ) {
711 throw new MWException( __METHOD__
. "No database available" );
713 $row = $this->db
->selectRow( 'text',
714 [ 'old_text', 'old_flags' ],
717 $text = Revision
::getRevisionText( $row );
718 if ( $text === false ) {
721 $stripped = str_replace( "\r", "", $text );
722 $normalized = $wgContLang->normalize( $stripped );
727 private function getTextSpawned( $id ) {
728 MediaWiki\
suppressWarnings();
729 if ( !$this->spawnProc
) {
733 $text = $this->getTextSpawnedOnce( $id );
734 MediaWiki\restoreWarnings
();
739 function openSpawn() {
742 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
744 array_map( 'wfEscapeShellArg',
747 "$IP/../multiversion/MWScript.php",
749 '--wiki', wfWikiID() ] ) );
752 array_map( 'wfEscapeShellArg',
755 "$IP/maintenance/fetchText.php",
756 '--wiki', wfWikiID() ] ) );
759 0 => [ "pipe", "r" ],
760 1 => [ "pipe", "w" ],
761 2 => [ "file", "/dev/null", "a" ] ];
764 $this->progress( "Spawning database subprocess: $cmd" );
765 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
766 if ( !$this->spawnProc
) {
767 $this->progress( "Subprocess spawn failed." );
772 $this->spawnWrite
, // -> stdin
773 $this->spawnRead
, // <- stdout
779 private function closeSpawn() {
780 MediaWiki\
suppressWarnings();
781 if ( $this->spawnRead
) {
782 fclose( $this->spawnRead
);
784 $this->spawnRead
= false;
785 if ( $this->spawnWrite
) {
786 fclose( $this->spawnWrite
);
788 $this->spawnWrite
= false;
789 if ( $this->spawnErr
) {
790 fclose( $this->spawnErr
);
792 $this->spawnErr
= false;
793 if ( $this->spawnProc
) {
794 pclose( $this->spawnProc
);
796 $this->spawnProc
= false;
797 MediaWiki\restoreWarnings
();
800 private function getTextSpawnedOnce( $id ) {
803 $ok = fwrite( $this->spawnWrite
, "$id\n" );
804 // $this->progress( ">> $id" );
809 $ok = fflush( $this->spawnWrite
);
810 // $this->progress( ">> [flush]" );
815 // check that the text id they are sending is the one we asked for
816 // this avoids out of sync revision text errors we have encountered in the past
817 $newId = fgets( $this->spawnRead
);
818 if ( $newId === false ) {
821 if ( $id != intval( $newId ) ) {
825 $len = fgets( $this->spawnRead
);
826 // $this->progress( "<< " . trim( $len ) );
827 if ( $len === false ) {
831 $nbytes = intval( $len );
832 // actual error, not zero-length text
839 // Subprocess may not send everything at once, we have to loop.
840 while ( $nbytes > strlen( $text ) ) {
841 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
842 if ( $buffer === false ) {
848 $gotbytes = strlen( $text );
849 if ( $gotbytes != $nbytes ) {
850 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
855 // Do normalization in the dump thread...
856 $stripped = str_replace( "\r", "", $text );
857 $normalized = $wgContLang->normalize( $stripped );
862 function startElement( $parser, $name, $attribs ) {
863 $this->checkpointJustWritten
= false;
865 $this->clearOpenElement( null );
866 $this->lastName
= $name;
868 if ( $name == 'revision' ) {
869 $this->state
= $name;
870 $this->egress
->writeOpenPage( null, $this->buffer
);
872 } elseif ( $name == 'page' ) {
873 $this->state
= $name;
874 if ( $this->atStart
) {
875 $this->egress
->writeOpenStream( $this->buffer
);
877 $this->atStart
= false;
881 if ( $name == "text" && isset( $attribs['id'] ) ) {
882 $id = $attribs['id'];
883 $model = trim( $this->thisRevModel
);
884 $format = trim( $this->thisRevFormat
);
886 $model = $model === '' ?
null : $model;
887 $format = $format === '' ?
null : $format;
889 $text = $this->getText( $id, $model, $format );
890 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
891 if ( strlen( $text ) > 0 ) {
892 $this->characterData( $parser, $text );
895 $this->openElement
= [ $name, $attribs ];
899 function endElement( $parser, $name ) {
900 $this->checkpointJustWritten
= false;
902 if ( $this->openElement
) {
903 $this->clearOpenElement( "" );
905 $this->buffer
.= "</$name>";
908 if ( $name == 'revision' ) {
909 $this->egress
->writeRevision( null, $this->buffer
);
912 $this->thisRevModel
= null;
913 $this->thisRevFormat
= null;
914 } elseif ( $name == 'page' ) {
915 if ( !$this->firstPageWritten
) {
916 $this->firstPageWritten
= trim( $this->thisPage
);
918 $this->lastPageWritten
= trim( $this->thisPage
);
919 if ( $this->timeExceeded
) {
920 $this->egress
->writeClosePage( $this->buffer
);
921 // nasty hack, we can't just write the chardata after the
922 // page tag, it will include leading blanks from the next line
923 $this->egress
->sink
->write( "\n" );
925 $this->buffer
= $this->xmlwriterobj
->closeStream();
926 $this->egress
->writeCloseStream( $this->buffer
);
929 $this->thisPage
= "";
930 // this could be more than one file if we had more than one output arg
932 $filenameList = (array)$this->egress
->getFilenames();
934 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
935 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
936 $filenamesCount = count( $filenameList );
937 for ( $i = 0; $i < $filenamesCount; $i++
) {
938 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
939 $fileinfo = pathinfo( $filenameList[$i] );
940 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
942 $this->egress
->closeRenameAndReopen( $newFilenames );
943 $this->buffer
= $this->xmlwriterobj
->openStream();
944 $this->timeExceeded
= false;
945 $this->timeOfCheckpoint
= $this->lastTime
;
946 $this->firstPageWritten
= false;
947 $this->checkpointJustWritten
= true;
949 $this->egress
->writeClosePage( $this->buffer
);
951 $this->thisPage
= "";
953 } elseif ( $name == 'mediawiki' ) {
954 $this->egress
->writeCloseStream( $this->buffer
);
959 function characterData( $parser, $data ) {
960 $this->clearOpenElement( null );
961 if ( $this->lastName
== "id" ) {
962 if ( $this->state
== "revision" ) {
963 $this->thisRev
.= $data;
964 } elseif ( $this->state
== "page" ) {
965 $this->thisPage
.= $data;
967 } elseif ( $this->lastName
== "model" ) {
968 $this->thisRevModel
.= $data;
969 } elseif ( $this->lastName
== "format" ) {
970 $this->thisRevFormat
.= $data;
973 // have to skip the newline left over from closepagetag line of
974 // end of checkpoint files. nasty hack!!
975 if ( $this->checkpointJustWritten
) {
976 if ( $data[0] == "\n" ) {
977 $data = substr( $data, 1 );
979 $this->checkpointJustWritten
= false;
981 $this->buffer
.= htmlspecialchars( $data );
984 function clearOpenElement( $style ) {
985 if ( $this->openElement
) {
986 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
987 $this->openElement
= false;
992 $maintClass = 'TextPassDumper';
993 require_once RUN_MAINTENANCE_IF_MAIN
;