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 MediaWiki\MediaWikiServices
;
32 use Wikimedia\Rdbms\IMaintainableDatabase
;
35 * @ingroup Maintenance
37 class TextPassDumper
extends BackupDumper
{
39 public $prefetch = null;
40 /** @var string|bool */
42 /** @var string|bool */
45 // when we spend more than maxTimeAllowed seconds on this run, we continue
46 // processing until we write out the next complete page, then save output file(s),
47 // rename it/them and open new one(s)
48 public $maxTimeAllowed = 0; // 0 = no limit
50 protected $input = "php://stdin";
51 protected $history = WikiExporter
::FULL
;
52 protected $fetchCount = 0;
53 protected $prefetchCount = 0;
54 protected $prefetchCountLast = 0;
55 protected $fetchCountLast = 0;
57 protected $maxFailures = 5;
58 protected $maxConsecutiveFailedTextRetrievals = 200;
59 protected $failureTimeout = 5; // Seconds to sleep after db failure
61 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
63 protected $php = "php";
64 protected $spawn = false;
69 protected $spawnProc = false;
74 protected $spawnWrite = false;
79 protected $spawnRead = false;
84 protected $spawnErr = false;
87 * @var bool|XmlDumpWriter
89 protected $xmlwriterobj = false;
91 protected $timeExceeded = false;
92 protected $firstPageWritten = false;
93 protected $lastPageWritten = false;
94 protected $checkpointJustWritten = false;
95 protected $checkpointFiles = [];
98 * @var IMaintainableDatabase
103 * @param array|null $args For backward compatibility
105 function __construct( $args = null ) {
106 parent
::__construct();
108 $this->addDescription( <<<TEXT
109 This script postprocesses XML dumps from dumpBackup.php to add
110 page text which was stubbed out (using --stub).
112 XML input is accepted on stdin.
113 XML output is sent to stdout; progress reports are sent to stderr.
116 $this->stderr
= fopen( "php://stderr", "wt" );
118 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
119 'Specify as --stub=<type>:<file>.', false, true );
120 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
121 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
123 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
124 'out complete page, closing xml file properly, and opening new one' .
125 'with header). This option requires the checkpointfile option.', false, true );
126 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
127 'first pageid written for the first %s (required) and the last pageid written for the ' .
128 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
129 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
130 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
131 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
132 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
133 '(Default: 512KB, Minimum: 4KB)', false, true );
136 $this->loadWithArgv( $args );
137 $this->processOptions();
142 $this->processOptions();
146 function processOptions() {
147 parent
::processOptions();
149 if ( $this->hasOption( 'buffersize' ) ) {
150 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
153 if ( $this->hasOption( 'prefetch' ) ) {
154 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
155 $this->prefetch
= new BaseDump( $url );
158 if ( $this->hasOption( 'stub' ) ) {
159 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
162 if ( $this->hasOption( 'maxtime' ) ) {
163 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
166 if ( $this->hasOption( 'checkpointfile' ) ) {
167 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
170 if ( $this->hasOption( 'current' ) ) {
171 $this->history
= WikiExporter
::CURRENT
;
174 if ( $this->hasOption( 'full' ) ) {
175 $this->history
= WikiExporter
::FULL
;
178 if ( $this->hasOption( 'spawn' ) ) {
180 $val = $this->getOption( 'spawn' );
188 * Drop the database connection $this->db and try to get a new one.
190 * This function tries to get a /different/ connection if this is
191 * possible. Hence, (if this is possible) it switches to a different
192 * failover upon each call.
194 * This function resets $this->lb and closes all connections on it.
196 * @throws MWException
198 function rotateDb() {
199 // Cleaning up old connections
200 if ( isset( $this->lb
) ) {
201 $this->lb
->closeAll();
205 if ( $this->forcedDb
!== null ) {
206 $this->db
= $this->forcedDb
;
211 if ( isset( $this->db
) && $this->db
->isOpen() ) {
212 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
217 // Trying to set up new connection.
218 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
219 // individually retrying at different layers of code.
222 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
223 $this->lb
= $lbFactory->newMainLB();
224 } catch ( Exception
$e ) {
225 throw new MWException( __METHOD__
226 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
230 $this->db
= $this->lb
->getConnection( DB_REPLICA
, 'dump' );
231 } catch ( Exception
$e ) {
232 throw new MWException( __METHOD__
233 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
237 function initProgress( $history = WikiExporter
::FULL
) {
238 parent
::initProgress();
239 $this->timeOfCheckpoint
= $this->startTime
;
242 function dump( $history, $text = WikiExporter
::TEXT
) {
243 // Notice messages will foul up your XML output even if they're
244 // relatively harmless.
245 if ( ini_get( 'display_errors' ) ) {
246 ini_set( 'display_errors', 'stderr' );
249 $this->initProgress( $this->history
);
251 // We are trying to get an initial database connection to avoid that the
252 // first try of this request's first call to getText fails. However, if
253 // obtaining a good DB connection fails it's not a serious issue, as
254 // getText does retry upon failure and can start without having a working
258 } catch ( Exception
$e ) {
259 // We do not even count this as failure. Just let eventual
261 $this->progress( "Getting initial DB connection failed (" .
262 $e->getMessage() . ")" );
265 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
267 // it would be nice to do it in the constructor, oh well. need egress set
268 $this->finalOptionCheck();
270 // we only want this so we know how to close a stream :-P
271 $this->xmlwriterobj
= new XmlDumpWriter();
273 $input = fopen( $this->input
, "rt" );
274 $this->readDump( $input );
276 if ( $this->spawnProc
) {
280 $this->report( true );
283 function processFileOpt( $opt ) {
284 $split = explode( ':', $opt, 2 );
287 if ( count( $split ) === 2 ) {
290 $fileURIs = explode( ';', $param );
291 foreach ( $fileURIs as $URI ) {
297 $newURI = "compress.zlib://$URI";
300 $newURI = "compress.bzip2://$URI";
303 $newURI = "mediawiki.compress.7z://$URI";
308 $newFileURIs[] = $newURI;
310 $val = implode( ';', $newFileURIs );
316 * Overridden to include prefetch ratio if enabled.
318 function showReport() {
319 if ( !$this->prefetch
) {
320 parent
::showReport();
325 if ( $this->reporting
) {
326 $now = wfTimestamp( TS_DB
);
327 $nowts = microtime( true );
328 $deltaAll = $nowts - $this->startTime
;
329 $deltaPart = $nowts - $this->lastTime
;
330 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
331 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
334 $portion = $this->revCount
/ $this->maxCount
;
335 $eta = $this->startTime +
$deltaAll / $portion;
336 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
337 if ( $this->fetchCount
) {
338 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
342 $pageRate = $this->pageCount
/ $deltaAll;
343 $revRate = $this->revCount
/ $deltaAll;
351 if ( $this->fetchCountLast
) {
352 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
354 $fetchRatePart = '-';
356 $pageRatePart = $this->pageCountPart
/ $deltaPart;
357 $revRatePart = $this->revCountPart
/ $deltaPart;
359 $fetchRatePart = '-';
363 $this->progress( sprintf(
364 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
365 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
366 . "prefetched (all|curr), ETA %s [max %d]",
367 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
368 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
369 $fetchRate, $fetchRatePart, $etats, $this->maxCount
371 $this->lastTime
= $nowts;
372 $this->revCountLast
= $this->revCount
;
373 $this->prefetchCountLast
= $this->prefetchCount
;
374 $this->fetchCountLast
= $this->fetchCount
;
378 function setTimeExceeded() {
379 $this->timeExceeded
= true;
382 function checkIfTimeExceeded() {
383 if ( $this->maxTimeAllowed
384 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
392 function finalOptionCheck() {
393 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
394 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
396 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
398 foreach ( $this->checkpointFiles
as $checkpointFile ) {
399 $count = substr_count( $checkpointFile, "%s" );
401 throw new MWException( "Option checkpointfile must contain two '%s' "
402 . "for substitution of first and last pageids, count is $count instead, "
403 . "file is $checkpointFile.\n" );
407 if ( $this->checkpointFiles
) {
408 $filenameList = (array)$this->egress
->getFilenames();
409 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
410 throw new MWException( "One checkpointfile must be specified "
411 . "for each output option, if maxtime is used.\n" );
417 * @throws MWException Failure to parse XML input
418 * @param string $input
421 function readDump( $input ) {
423 $this->openElement
= false;
424 $this->atStart
= true;
426 $this->lastName
= "";
429 $this->thisRevModel
= null;
430 $this->thisRevFormat
= null;
432 $parser = xml_parser_create( "UTF-8" );
433 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
435 xml_set_element_handler(
437 [ $this, 'startElement' ],
438 [ $this, 'endElement' ]
440 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
442 $offset = 0; // for context extraction on error reporting
444 if ( $this->checkIfTimeExceeded() ) {
445 $this->setTimeExceeded();
447 $chunk = fread( $input, $this->bufferSize
);
448 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
449 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
451 $byte = xml_get_current_byte_index( $parser );
452 $msg = wfMessage( 'xml-error-string',
453 'XML import parse failure',
454 xml_get_current_line_number( $parser ),
455 xml_get_current_column_number( $parser ),
456 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
457 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
459 xml_parser_free( $parser );
461 throw new MWException( $msg );
463 $offset +
= strlen( $chunk );
464 } while ( $chunk !== false && !feof( $input ) );
465 if ( $this->maxTimeAllowed
) {
466 $filenameList = (array)$this->egress
->getFilenames();
467 // we wrote some stuff after last checkpoint that needs renamed
468 if ( file_exists( $filenameList[0] ) ) {
470 # we might have just written the header and footer and had no
471 # pages or revisions written... perhaps they were all deleted
472 # there's no pageID 0 so we use that. the caller is responsible
473 # for deciding what to do with a file containing only the
474 # siteinfo information and the mw tags.
475 if ( !$this->firstPageWritten
) {
476 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
477 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
479 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
480 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
483 $filenameCount = count( $filenameList );
484 for ( $i = 0; $i < $filenameCount; $i++
) {
485 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
486 $fileinfo = pathinfo( $filenameList[$i] );
487 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
489 $this->egress
->closeAndRename( $newFilenames );
492 xml_parser_free( $parser );
498 * Applies applicable export transformations to $text.
500 * @param string $text
501 * @param string $model
502 * @param string|null $format
506 private function exportTransform( $text, $model, $format = null ) {
508 $handler = ContentHandler
::getForModelID( $model );
509 $text = $handler->exportTransform( $text, $format );
511 catch ( MWException
$ex ) {
513 "Unable to apply export transformation for content model '$model': " .
522 * Tries to get the revision text for a revision id.
523 * Export transformations are applied if the content model can is given or can be
524 * determined from the database.
526 * Upon errors, retries (Up to $this->maxFailures tries each call).
527 * If still no good revision get could be found even after this retrying, "" is returned.
528 * If no good revision text could be returned for
529 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
532 * @param string $id The revision id to get the text for
533 * @param string|bool|null $model The content model used to determine
534 * applicable export transformations.
535 * If $model is null, it will be determined from the database.
536 * @param string|null $format The content format used when applying export transformations.
538 * @throws MWException
539 * @return string The revision text for $id, or ""
541 function getText( $id, $model = null, $format = null ) {
542 global $wgContentHandlerUseDB;
544 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
545 $text = false; // The candidate for a good text. false if no proper value.
546 $failures = 0; // The number of times, this invocation of getText already failed.
548 // The number of times getText failed without yielding a good text in between.
549 static $consecutiveFailedTextRetrievals = 0;
553 // To allow to simply return on success and do not have to worry about book keeping,
554 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
555 // the old value, so we can restore it, if problems occur (See after the while loop).
556 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
557 $consecutiveFailedTextRetrievals = 0;
559 if ( $model === null && $wgContentHandlerUseDB ) {
560 $row = $this->db
->selectRow(
562 [ 'rev_content_model', 'rev_content_format' ],
563 [ 'rev_id' => $this->thisRev
],
568 $model = $row->rev_content_model
;
569 $format = $row->rev_content_format
;
573 if ( $model === null ||
$model === '' ) {
577 while ( $failures < $this->maxFailures
) {
578 // As soon as we found a good text for the $id, we will return immediately.
579 // Hence, if we make it past the try catch block, we know that we did not
583 // Step 1: Get some text (or reuse from previous iteratuon if checking
584 // for plausibility failed)
586 // Trying to get prefetch, if it has not been tried before
587 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
588 $prefetchNotTried = false;
589 $tryIsPrefetch = true;
590 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
592 if ( $text === null ) {
596 if ( is_string( $text ) && $model !== false ) {
597 // Apply export transformation to text coming from an old dump.
598 // The purpose of this transformation is to convert up from legacy
599 // formats, which may still be used in the older dump that is used
600 // for pre-fetching. Applying the transformation again should not
601 // interfere with content that is already in the correct form.
602 $text = $this->exportTransform( $text, $model, $format );
606 if ( $text === false ) {
607 // Fallback to asking the database
608 $tryIsPrefetch = false;
609 if ( $this->spawn
) {
610 $text = $this->getTextSpawned( $id );
612 $text = $this->getTextDb( $id );
615 if ( $text !== false && $model !== false ) {
616 // Apply export transformation to text coming from the database.
617 // Prefetched text should already have transformations applied.
618 $text = $this->exportTransform( $text, $model, $format );
621 // No more checks for texts from DB for now.
622 // If we received something that is not false,
623 // We treat it as good text, regardless of whether it actually is or is not
624 if ( $text !== false ) {
629 if ( $text === false ) {
630 throw new MWException( "Generic error while obtaining text for id " . $id );
633 // We received a good candidate for the text of $id via some method
635 // Step 2: Checking for plausibility and return the text if it is
637 $revID = intval( $this->thisRev
);
638 if ( !isset( $this->db
) ) {
639 throw new MWException( "No database available" );
642 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
643 $revLength = strlen( $text );
645 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
648 if ( strlen( $text ) == $revLength ) {
649 if ( $tryIsPrefetch ) {
650 $this->prefetchCount++
;
657 throw new MWException( "Received text is unplausible for id " . $id );
658 } catch ( Exception
$e ) {
659 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
660 if ( $failures +
1 < $this->maxFailures
) {
661 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
663 $this->progress( $msg );
666 // Something went wrong; we did not a text that was plausible :(
669 // A failure in a prefetch hit does not warrant resetting db connection etc.
670 if ( !$tryIsPrefetch ) {
671 // After backing off for some time, we try to reboot the whole process as
672 // much as possible to not carry over failures from one part to the other
674 sleep( $this->failureTimeout
);
677 if ( $this->spawn
) {
681 } catch ( Exception
$e ) {
682 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
683 " Trying to continue anyways" );
688 // Retirieving a good text for $id failed (at least) maxFailures times.
689 // We abort for this $id.
691 // Restoring the consecutive failures, and maybe aborting, if the dump
693 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
694 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
695 throw new MWException( "Graceful storage failure" );
702 * May throw a database error if, say, the server dies during query.
704 * @return bool|string
705 * @throws MWException
707 private function getTextDb( $id ) {
708 if ( !isset( $this->db
) ) {
709 throw new MWException( __METHOD__
. "No database available" );
711 $row = $this->db
->selectRow( 'text',
712 [ 'old_text', 'old_flags' ],
715 $text = Revision
::getRevisionText( $row );
716 if ( $text === false ) {
719 $stripped = str_replace( "\r", "", $text );
720 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()->
721 normalize( $stripped );
726 private function getTextSpawned( $id ) {
727 Wikimedia\
suppressWarnings();
728 if ( !$this->spawnProc
) {
732 $text = $this->getTextSpawnedOnce( $id );
733 Wikimedia\restoreWarnings
();
738 function openSpawn() {
741 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
743 array_map( 'wfEscapeShellArg',
746 "$IP/../multiversion/MWScript.php",
748 '--wiki', wfWikiID() ] ) );
751 array_map( 'wfEscapeShellArg',
754 "$IP/maintenance/fetchText.php",
755 '--wiki', wfWikiID() ] ) );
758 0 => [ "pipe", "r" ],
759 1 => [ "pipe", "w" ],
760 2 => [ "file", "/dev/null", "a" ] ];
763 $this->progress( "Spawning database subprocess: $cmd" );
764 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
765 if ( !$this->spawnProc
) {
766 $this->progress( "Subprocess spawn failed." );
771 $this->spawnWrite
, // -> stdin
772 $this->spawnRead
, // <- stdout
778 private function closeSpawn() {
779 Wikimedia\
suppressWarnings();
780 if ( $this->spawnRead
) {
781 fclose( $this->spawnRead
);
783 $this->spawnRead
= false;
784 if ( $this->spawnWrite
) {
785 fclose( $this->spawnWrite
);
787 $this->spawnWrite
= false;
788 if ( $this->spawnErr
) {
789 fclose( $this->spawnErr
);
791 $this->spawnErr
= false;
792 if ( $this->spawnProc
) {
793 pclose( $this->spawnProc
);
795 $this->spawnProc
= false;
796 Wikimedia\restoreWarnings
();
799 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 = MediaWikiServices
::getInstance()->getContentLanguage()->
855 normalize( $stripped );
860 function startElement( $parser, $name, $attribs ) {
861 $this->checkpointJustWritten
= false;
863 $this->clearOpenElement( null );
864 $this->lastName
= $name;
866 if ( $name == 'revision' ) {
867 $this->state
= $name;
868 $this->egress
->writeOpenPage( null, $this->buffer
);
870 } elseif ( $name == 'page' ) {
871 $this->state
= $name;
872 if ( $this->atStart
) {
873 $this->egress
->writeOpenStream( $this->buffer
);
875 $this->atStart
= false;
879 if ( $name == "text" && isset( $attribs['id'] ) ) {
880 $id = $attribs['id'];
881 $model = trim( $this->thisRevModel
);
882 $format = trim( $this->thisRevFormat
);
884 $model = $model === '' ?
null : $model;
885 $format = $format === '' ?
null : $format;
887 $text = $this->getText( $id, $model, $format );
888 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
889 if ( strlen( $text ) > 0 ) {
890 $this->characterData( $parser, $text );
893 $this->openElement
= [ $name, $attribs ];
897 function endElement( $parser, $name ) {
898 $this->checkpointJustWritten
= false;
900 if ( $this->openElement
) {
901 $this->clearOpenElement( "" );
903 $this->buffer
.= "</$name>";
906 if ( $name == 'revision' ) {
907 $this->egress
->writeRevision( null, $this->buffer
);
910 $this->thisRevModel
= null;
911 $this->thisRevFormat
= null;
912 } elseif ( $name == 'page' ) {
913 if ( !$this->firstPageWritten
) {
914 $this->firstPageWritten
= trim( $this->thisPage
);
916 $this->lastPageWritten
= trim( $this->thisPage
);
917 if ( $this->timeExceeded
) {
918 $this->egress
->writeClosePage( $this->buffer
);
919 // nasty hack, we can't just write the chardata after the
920 // page tag, it will include leading blanks from the next line
921 $this->egress
->sink
->write( "\n" );
923 $this->buffer
= $this->xmlwriterobj
->closeStream();
924 $this->egress
->writeCloseStream( $this->buffer
);
927 $this->thisPage
= "";
928 // this could be more than one file if we had more than one output arg
930 $filenameList = (array)$this->egress
->getFilenames();
932 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
933 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
934 $filenamesCount = count( $filenameList );
935 for ( $i = 0; $i < $filenamesCount; $i++
) {
936 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
937 $fileinfo = pathinfo( $filenameList[$i] );
938 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
940 $this->egress
->closeRenameAndReopen( $newFilenames );
941 $this->buffer
= $this->xmlwriterobj
->openStream();
942 $this->timeExceeded
= false;
943 $this->timeOfCheckpoint
= $this->lastTime
;
944 $this->firstPageWritten
= false;
945 $this->checkpointJustWritten
= true;
947 $this->egress
->writeClosePage( $this->buffer
);
949 $this->thisPage
= "";
951 } elseif ( $name == 'mediawiki' ) {
952 $this->egress
->writeCloseStream( $this->buffer
);
957 function characterData( $parser, $data ) {
958 $this->clearOpenElement( null );
959 if ( $this->lastName
== "id" ) {
960 if ( $this->state
== "revision" ) {
961 $this->thisRev
.= $data;
962 } elseif ( $this->state
== "page" ) {
963 $this->thisPage
.= $data;
965 } elseif ( $this->lastName
== "model" ) {
966 $this->thisRevModel
.= $data;
967 } elseif ( $this->lastName
== "format" ) {
968 $this->thisRevFormat
.= $data;
971 // have to skip the newline left over from closepagetag line of
972 // end of checkpoint files. nasty hack!!
973 if ( $this->checkpointJustWritten
) {
974 if ( $data[0] == "\n" ) {
975 $data = substr( $data, 1 );
977 $this->checkpointJustWritten
= false;
979 $this->buffer
.= htmlspecialchars( $data );
982 function clearOpenElement( $style ) {
983 if ( $this->openElement
) {
984 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
985 $this->openElement
= false;
990 $maintClass = TextPassDumper
::class;
991 require_once RUN_MAINTENANCE_IF_MAIN
;