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() {
146 parent
::processOptions();
148 if ( $this->hasOption( 'buffersize' ) ) {
149 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
152 if ( $this->hasOption( 'prefetch' ) ) {
153 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
154 $this->prefetch
= new BaseDump( $url );
157 if ( $this->hasOption( 'stub' ) ) {
158 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
161 if ( $this->hasOption( 'maxtime' ) ) {
162 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
165 if ( $this->hasOption( 'checkpointfile' ) ) {
166 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
169 if ( $this->hasOption( 'current' ) ) {
170 $this->history
= WikiExporter
::CURRENT
;
173 if ( $this->hasOption( 'full' ) ) {
174 $this->history
= WikiExporter
::FULL
;
177 if ( $this->hasOption( 'spawn' ) ) {
179 $val = $this->getOption( 'spawn' );
187 * Drop the database connection $this->db and try to get a new one.
189 * This function tries to get a /different/ connection if this is
190 * possible. Hence, (if this is possible) it switches to a different
191 * failover upon each call.
193 * This function resets $this->lb and closes all connections on it.
195 * @throws MWException
197 function rotateDb() {
198 // Cleaning up old connections
199 if ( isset( $this->lb
) ) {
200 $this->lb
->closeAll();
204 if ( $this->forcedDb
!== null ) {
205 $this->db
= $this->forcedDb
;
210 if ( isset( $this->db
) && $this->db
->isOpen() ) {
211 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
216 // Trying to set up new connection.
217 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
218 // individually retrying at different layers of code.
221 $this->lb
= wfGetLBFactory()->newMainLB();
222 } catch ( Exception
$e ) {
223 throw new MWException( __METHOD__
224 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
228 $this->db
= $this->lb
->getConnection( DB_REPLICA
, 'dump' );
229 } catch ( Exception
$e ) {
230 throw new MWException( __METHOD__
231 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
235 function initProgress( $history = WikiExporter
::FULL
) {
236 parent
::initProgress();
237 $this->timeOfCheckpoint
= $this->startTime
;
240 function dump( $history, $text = WikiExporter
::TEXT
) {
241 // Notice messages will foul up your XML output even if they're
242 // relatively harmless.
243 if ( ini_get( 'display_errors' ) ) {
244 ini_set( 'display_errors', 'stderr' );
247 $this->initProgress( $this->history
);
249 // We are trying to get an initial database connection to avoid that the
250 // first try of this request's first call to getText fails. However, if
251 // obtaining a good DB connection fails it's not a serious issue, as
252 // getText does retry upon failure and can start without having a working
256 } catch ( Exception
$e ) {
257 // We do not even count this as failure. Just let eventual
259 $this->progress( "Getting initial DB connection failed (" .
260 $e->getMessage() . ")" );
263 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
265 // it would be nice to do it in the constructor, oh well. need egress set
266 $this->finalOptionCheck();
268 // we only want this so we know how to close a stream :-P
269 $this->xmlwriterobj
= new XmlDumpWriter();
271 $input = fopen( $this->input
, "rt" );
272 $this->readDump( $input );
274 if ( $this->spawnProc
) {
278 $this->report( true );
281 function processFileOpt( $opt ) {
282 $split = explode( ':', $opt, 2 );
285 if ( count( $split ) === 2 ) {
288 $fileURIs = explode( ';', $param );
289 foreach ( $fileURIs as $URI ) {
295 $newURI = "compress.zlib://$URI";
298 $newURI = "compress.bzip2://$URI";
301 $newURI = "mediawiki.compress.7z://$URI";
306 $newFileURIs[] = $newURI;
308 $val = implode( ';', $newFileURIs );
314 * Overridden to include prefetch ratio if enabled.
316 function showReport() {
317 if ( !$this->prefetch
) {
318 parent
::showReport();
323 if ( $this->reporting
) {
324 $now = wfTimestamp( TS_DB
);
325 $nowts = microtime( true );
326 $deltaAll = $nowts - $this->startTime
;
327 $deltaPart = $nowts - $this->lastTime
;
328 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
329 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
332 $portion = $this->revCount
/ $this->maxCount
;
333 $eta = $this->startTime +
$deltaAll / $portion;
334 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
335 if ( $this->fetchCount
) {
336 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
340 $pageRate = $this->pageCount
/ $deltaAll;
341 $revRate = $this->revCount
/ $deltaAll;
349 if ( $this->fetchCountLast
) {
350 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
352 $fetchRatePart = '-';
354 $pageRatePart = $this->pageCountPart
/ $deltaPart;
355 $revRatePart = $this->revCountPart
/ $deltaPart;
357 $fetchRatePart = '-';
361 $this->progress( sprintf(
362 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
363 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
364 . "prefetched (all|curr), ETA %s [max %d]",
365 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
366 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
367 $fetchRate, $fetchRatePart, $etats, $this->maxCount
369 $this->lastTime
= $nowts;
370 $this->revCountLast
= $this->revCount
;
371 $this->prefetchCountLast
= $this->prefetchCount
;
372 $this->fetchCountLast
= $this->fetchCount
;
376 function setTimeExceeded() {
377 $this->timeExceeded
= true;
380 function checkIfTimeExceeded() {
381 if ( $this->maxTimeAllowed
382 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
390 function finalOptionCheck() {
391 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
392 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
394 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
396 foreach ( $this->checkpointFiles
as $checkpointFile ) {
397 $count = substr_count( $checkpointFile, "%s" );
399 throw new MWException( "Option checkpointfile must contain two '%s' "
400 . "for substitution of first and last pageids, count is $count instead, "
401 . "file is $checkpointFile.\n" );
405 if ( $this->checkpointFiles
) {
406 $filenameList = (array)$this->egress
->getFilenames();
407 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
408 throw new MWException( "One checkpointfile must be specified "
409 . "for each output option, if maxtime is used.\n" );
415 * @throws MWException Failure to parse XML input
416 * @param string $input
419 function readDump( $input ) {
421 $this->openElement
= false;
422 $this->atStart
= true;
424 $this->lastName
= "";
427 $this->thisRevModel
= null;
428 $this->thisRevFormat
= null;
430 $parser = xml_parser_create( "UTF-8" );
431 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
433 xml_set_element_handler(
435 [ $this, 'startElement' ],
436 [ $this, 'endElement' ]
438 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
440 $offset = 0; // for context extraction on error reporting
442 if ( $this->checkIfTimeExceeded() ) {
443 $this->setTimeExceeded();
445 $chunk = fread( $input, $this->bufferSize
);
446 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
447 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
449 $byte = xml_get_current_byte_index( $parser );
450 $msg = wfMessage( 'xml-error-string',
451 'XML import parse failure',
452 xml_get_current_line_number( $parser ),
453 xml_get_current_column_number( $parser ),
454 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
455 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
457 xml_parser_free( $parser );
459 throw new MWException( $msg );
461 $offset +
= strlen( $chunk );
462 } while ( $chunk !== false && !feof( $input ) );
463 if ( $this->maxTimeAllowed
) {
464 $filenameList = (array)$this->egress
->getFilenames();
465 // we wrote some stuff after last checkpoint that needs renamed
466 if ( file_exists( $filenameList[0] ) ) {
468 # we might have just written the header and footer and had no
469 # pages or revisions written... perhaps they were all deleted
470 # there's no pageID 0 so we use that. the caller is responsible
471 # for deciding what to do with a file containing only the
472 # siteinfo information and the mw tags.
473 if ( !$this->firstPageWritten
) {
474 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
475 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
477 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
478 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
481 $filenameCount = count( $filenameList );
482 for ( $i = 0; $i < $filenameCount; $i++
) {
483 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
484 $fileinfo = pathinfo( $filenameList[$i] );
485 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
487 $this->egress
->closeAndRename( $newFilenames );
490 xml_parser_free( $parser );
496 * Applies applicable export transformations to $text.
498 * @param string $text
499 * @param string $model
500 * @param string|null $format
504 private function exportTransform( $text, $model, $format = null ) {
506 $handler = ContentHandler
::getForModelID( $model );
507 $text = $handler->exportTransform( $text, $format );
509 catch ( MWException
$ex ) {
511 "Unable to apply export transformation for content model '$model': " .
520 * Tries to get the revision text for a revision id.
521 * Export transformations are applied if the content model can is given or can be
522 * determined from the database.
524 * Upon errors, retries (Up to $this->maxFailures tries each call).
525 * If still no good revision get could be found even after this retrying, "" is returned.
526 * If no good revision text could be returned for
527 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
530 * @param string $id The revision id to get the text for
531 * @param string|bool|null $model The content model used to determine
532 * applicable export transformations.
533 * If $model is null, it will be determined from the database.
534 * @param string|null $format The content format used when applying export transformations.
536 * @throws MWException
537 * @return string The revision text for $id, or ""
539 function getText( $id, $model = null, $format = null ) {
540 global $wgContentHandlerUseDB;
542 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
543 $text = false; // The candidate for a good text. false if no proper value.
544 $failures = 0; // The number of times, this invocation of getText already failed.
546 // The number of times getText failed without yielding a good text in between.
547 static $consecutiveFailedTextRetrievals = 0;
551 // To allow to simply return on success and do not have to worry about book keeping,
552 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
553 // the old value, so we can restore it, if problems occur (See after the while loop).
554 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
555 $consecutiveFailedTextRetrievals = 0;
557 if ( $model === null && $wgContentHandlerUseDB ) {
558 $row = $this->db
->selectRow(
560 [ 'rev_content_model', 'rev_content_format' ],
561 [ 'rev_id' => $this->thisRev
],
566 $model = $row->rev_content_model
;
567 $format = $row->rev_content_format
;
571 if ( $model === null ||
$model === '' ) {
575 while ( $failures < $this->maxFailures
) {
576 // As soon as we found a good text for the $id, we will return immediately.
577 // Hence, if we make it past the try catch block, we know that we did not
581 // Step 1: Get some text (or reuse from previous iteratuon if checking
582 // for plausibility failed)
584 // Trying to get prefetch, if it has not been tried before
585 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
586 $prefetchNotTried = false;
587 $tryIsPrefetch = true;
588 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
590 if ( $text === null ) {
594 if ( is_string( $text ) && $model !== false ) {
595 // Apply export transformation to text coming from an old dump.
596 // The purpose of this transformation is to convert up from legacy
597 // formats, which may still be used in the older dump that is used
598 // for pre-fetching. Applying the transformation again should not
599 // interfere with content that is already in the correct form.
600 $text = $this->exportTransform( $text, $model, $format );
604 if ( $text === false ) {
605 // Fallback to asking the database
606 $tryIsPrefetch = false;
607 if ( $this->spawn
) {
608 $text = $this->getTextSpawned( $id );
610 $text = $this->getTextDb( $id );
613 if ( $text !== false && $model !== false ) {
614 // Apply export transformation to text coming from the database.
615 // Prefetched text should already have transformations applied.
616 $text = $this->exportTransform( $text, $model, $format );
619 // No more checks for texts from DB for now.
620 // If we received something that is not false,
621 // We treat it as good text, regardless of whether it actually is or is not
622 if ( $text !== false ) {
627 if ( $text === false ) {
628 throw new MWException( "Generic error while obtaining text for id " . $id );
631 // We received a good candidate for the text of $id via some method
633 // Step 2: Checking for plausibility and return the text if it is
635 $revID = intval( $this->thisRev
);
636 if ( !isset( $this->db
) ) {
637 throw new MWException( "No database available" );
640 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
641 $revLength = strlen( $text );
643 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
646 if ( strlen( $text ) == $revLength ) {
647 if ( $tryIsPrefetch ) {
648 $this->prefetchCount++
;
655 throw new MWException( "Received text is unplausible for id " . $id );
656 } catch ( Exception
$e ) {
657 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
658 if ( $failures +
1 < $this->maxFailures
) {
659 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
661 $this->progress( $msg );
664 // Something went wrong; we did not a text that was plausible :(
667 // A failure in a prefetch hit does not warrant resetting db connection etc.
668 if ( !$tryIsPrefetch ) {
669 // After backing off for some time, we try to reboot the whole process as
670 // much as possible to not carry over failures from one part to the other
672 sleep( $this->failureTimeout
);
675 if ( $this->spawn
) {
679 } catch ( Exception
$e ) {
680 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
681 " Trying to continue anyways" );
686 // Retirieving a good text for $id failed (at least) maxFailures times.
687 // We abort for this $id.
689 // Restoring the consecutive failures, and maybe aborting, if the dump
691 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
692 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
693 throw new MWException( "Graceful storage failure" );
700 * May throw a database error if, say, the server dies during query.
702 * @return bool|string
703 * @throws MWException
705 private function getTextDb( $id ) {
707 if ( !isset( $this->db
) ) {
708 throw new MWException( __METHOD__
. "No database available" );
710 $row = $this->db
->selectRow( 'text',
711 [ 'old_text', 'old_flags' ],
714 $text = Revision
::getRevisionText( $row );
715 if ( $text === false ) {
718 $stripped = str_replace( "\r", "", $text );
719 $normalized = $wgContLang->normalize( $stripped );
724 private function getTextSpawned( $id ) {
725 MediaWiki\
suppressWarnings();
726 if ( !$this->spawnProc
) {
730 $text = $this->getTextSpawnedOnce( $id );
731 MediaWiki\restoreWarnings
();
736 function openSpawn() {
739 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
741 array_map( 'wfEscapeShellArg',
744 "$IP/../multiversion/MWScript.php",
746 '--wiki', wfWikiID() ] ) );
749 array_map( 'wfEscapeShellArg',
752 "$IP/maintenance/fetchText.php",
753 '--wiki', wfWikiID() ] ) );
756 0 => [ "pipe", "r" ],
757 1 => [ "pipe", "w" ],
758 2 => [ "file", "/dev/null", "a" ] ];
761 $this->progress( "Spawning database subprocess: $cmd" );
762 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
763 if ( !$this->spawnProc
) {
764 $this->progress( "Subprocess spawn failed." );
769 $this->spawnWrite
, // -> stdin
770 $this->spawnRead
, // <- stdout
776 private function closeSpawn() {
777 MediaWiki\
suppressWarnings();
778 if ( $this->spawnRead
) {
779 fclose( $this->spawnRead
);
781 $this->spawnRead
= false;
782 if ( $this->spawnWrite
) {
783 fclose( $this->spawnWrite
);
785 $this->spawnWrite
= false;
786 if ( $this->spawnErr
) {
787 fclose( $this->spawnErr
);
789 $this->spawnErr
= false;
790 if ( $this->spawnProc
) {
791 pclose( $this->spawnProc
);
793 $this->spawnProc
= false;
794 MediaWiki\restoreWarnings
();
797 private function getTextSpawnedOnce( $id ) {
800 $ok = fwrite( $this->spawnWrite
, "$id\n" );
801 // $this->progress( ">> $id" );
806 $ok = fflush( $this->spawnWrite
);
807 // $this->progress( ">> [flush]" );
812 // check that the text id they are sending is the one we asked for
813 // this avoids out of sync revision text errors we have encountered in the past
814 $newId = fgets( $this->spawnRead
);
815 if ( $newId === false ) {
818 if ( $id != intval( $newId ) ) {
822 $len = fgets( $this->spawnRead
);
823 // $this->progress( "<< " . trim( $len ) );
824 if ( $len === false ) {
828 $nbytes = intval( $len );
829 // actual error, not zero-length text
836 // Subprocess may not send everything at once, we have to loop.
837 while ( $nbytes > strlen( $text ) ) {
838 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
839 if ( $buffer === false ) {
845 $gotbytes = strlen( $text );
846 if ( $gotbytes != $nbytes ) {
847 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
852 // Do normalization in the dump thread...
853 $stripped = str_replace( "\r", "", $text );
854 $normalized = $wgContLang->normalize( $stripped );
859 function startElement( $parser, $name, $attribs ) {
860 $this->checkpointJustWritten
= false;
862 $this->clearOpenElement( null );
863 $this->lastName
= $name;
865 if ( $name == 'revision' ) {
866 $this->state
= $name;
867 $this->egress
->writeOpenPage( null, $this->buffer
);
869 } elseif ( $name == 'page' ) {
870 $this->state
= $name;
871 if ( $this->atStart
) {
872 $this->egress
->writeOpenStream( $this->buffer
);
874 $this->atStart
= false;
878 if ( $name == "text" && isset( $attribs['id'] ) ) {
879 $id = $attribs['id'];
880 $model = trim( $this->thisRevModel
);
881 $format = trim( $this->thisRevFormat
);
883 $model = $model === '' ?
null : $model;
884 $format = $format === '' ?
null : $format;
886 $text = $this->getText( $id, $model, $format );
887 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
888 if ( strlen( $text ) > 0 ) {
889 $this->characterData( $parser, $text );
892 $this->openElement
= [ $name, $attribs ];
896 function endElement( $parser, $name ) {
897 $this->checkpointJustWritten
= false;
899 if ( $this->openElement
) {
900 $this->clearOpenElement( "" );
902 $this->buffer
.= "</$name>";
905 if ( $name == 'revision' ) {
906 $this->egress
->writeRevision( null, $this->buffer
);
909 $this->thisRevModel
= null;
910 $this->thisRevFormat
= null;
911 } elseif ( $name == 'page' ) {
912 if ( !$this->firstPageWritten
) {
913 $this->firstPageWritten
= trim( $this->thisPage
);
915 $this->lastPageWritten
= trim( $this->thisPage
);
916 if ( $this->timeExceeded
) {
917 $this->egress
->writeClosePage( $this->buffer
);
918 // nasty hack, we can't just write the chardata after the
919 // page tag, it will include leading blanks from the next line
920 $this->egress
->sink
->write( "\n" );
922 $this->buffer
= $this->xmlwriterobj
->closeStream();
923 $this->egress
->writeCloseStream( $this->buffer
);
926 $this->thisPage
= "";
927 // this could be more than one file if we had more than one output arg
929 $filenameList = (array)$this->egress
->getFilenames();
931 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
932 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
933 $filenamesCount = count( $filenameList );
934 for ( $i = 0; $i < $filenamesCount; $i++
) {
935 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
936 $fileinfo = pathinfo( $filenameList[$i] );
937 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
939 $this->egress
->closeRenameAndReopen( $newFilenames );
940 $this->buffer
= $this->xmlwriterobj
->openStream();
941 $this->timeExceeded
= false;
942 $this->timeOfCheckpoint
= $this->lastTime
;
943 $this->firstPageWritten
= false;
944 $this->checkpointJustWritten
= true;
946 $this->egress
->writeClosePage( $this->buffer
);
948 $this->thisPage
= "";
950 } elseif ( $name == 'mediawiki' ) {
951 $this->egress
->writeCloseStream( $this->buffer
);
956 function characterData( $parser, $data ) {
957 $this->clearOpenElement( null );
958 if ( $this->lastName
== "id" ) {
959 if ( $this->state
== "revision" ) {
960 $this->thisRev
.= $data;
961 } elseif ( $this->state
== "page" ) {
962 $this->thisPage
.= $data;
964 } elseif ( $this->lastName
== "model" ) {
965 $this->thisRevModel
.= $data;
966 } elseif ( $this->lastName
== "format" ) {
967 $this->thisRevFormat
.= $data;
970 // have to skip the newline left over from closepagetag line of
971 // end of checkpoint files. nasty hack!!
972 if ( $this->checkpointJustWritten
) {
973 if ( $data[0] == "\n" ) {
974 $data = substr( $data, 1 );
976 $this->checkpointJustWritten
= false;
978 $this->buffer
.= htmlspecialchars( $data );
981 function clearOpenElement( $style ) {
982 if ( $this->openElement
) {
983 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
984 $this->openElement
= false;
989 $maintClass = TextPassDumper
::class;
990 require_once RUN_MAINTENANCE_IF_MAIN
;