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__
. '/includes/BackupDumper.php';
28 require_once __DIR__
. '/7zip.inc';
29 require_once __DIR__
. '/../includes/export/WikiExporter.php';
31 use MediaWiki\MediaWikiServices
;
32 use MediaWiki\Storage\BlobAccessException
;
33 use MediaWiki\Storage\BlobStore
;
34 use MediaWiki\Storage\SqlBlobStore
;
35 use Wikimedia\Rdbms\IMaintainableDatabase
;
38 * @ingroup Maintenance
40 class TextPassDumper
extends BackupDumper
{
42 public $prefetch = null;
43 /** @var string|bool */
45 /** @var string|bool */
48 // when we spend more than maxTimeAllowed seconds on this run, we continue
49 // processing until we write out the next complete page, then save output file(s),
50 // rename it/them and open new one(s)
51 public $maxTimeAllowed = 0; // 0 = no limit
53 protected $input = "php://stdin";
54 protected $history = WikiExporter
::FULL
;
55 protected $fetchCount = 0;
56 protected $prefetchCount = 0;
57 protected $prefetchCountLast = 0;
58 protected $fetchCountLast = 0;
60 protected $maxFailures = 5;
61 protected $maxConsecutiveFailedTextRetrievals = 200;
62 protected $failureTimeout = 5; // Seconds to sleep after db failure
64 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
66 protected $php = "php";
67 protected $spawn = false;
72 protected $spawnProc = false;
77 protected $spawnWrite = false;
82 protected $spawnRead = false;
87 protected $spawnErr = false;
90 * @var bool|XmlDumpWriter
92 protected $xmlwriterobj = false;
94 protected $timeExceeded = false;
95 protected $firstPageWritten = false;
96 protected $lastPageWritten = false;
97 protected $checkpointJustWritten = false;
98 protected $checkpointFiles = [];
101 * @var IMaintainableDatabase
106 * @param array|null $args For backward compatibility
108 function __construct( $args = null ) {
109 parent
::__construct();
111 $this->addDescription( <<<TEXT
112 This script postprocesses XML dumps from dumpBackup.php to add
113 page text which was stubbed out (using --stub).
115 XML input is accepted on stdin.
116 XML output is sent to stdout; progress reports are sent to stderr.
119 $this->stderr
= fopen( "php://stderr", "wt" );
121 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
122 'Specify as --stub=<type>:<file>.', false, true );
123 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
124 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
126 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
127 'out complete page, closing xml file properly, and opening new one' .
128 'with header). This option requires the checkpointfile option.', false, true );
129 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
130 'first pageid written for the first %s (required) and the last pageid written for the ' .
131 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
132 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
133 $this->addOption( 'full', 'Dump all revisions of every page' );
134 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
135 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
136 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
137 '(Default: 512KB, Minimum: 4KB)', false, true );
140 $this->loadWithArgv( $args );
141 $this->processOptions();
148 private function getBlobStore() {
149 return MediaWikiServices
::getInstance()->getBlobStore();
153 $this->processOptions();
157 function processOptions() {
158 parent
::processOptions();
160 if ( $this->hasOption( 'buffersize' ) ) {
161 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
164 if ( $this->hasOption( 'prefetch' ) ) {
165 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
166 $this->prefetch
= new BaseDump( $url );
169 if ( $this->hasOption( 'stub' ) ) {
170 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
173 if ( $this->hasOption( 'maxtime' ) ) {
174 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
177 if ( $this->hasOption( 'checkpointfile' ) ) {
178 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
181 if ( $this->hasOption( 'current' ) ) {
182 $this->history
= WikiExporter
::CURRENT
;
185 if ( $this->hasOption( 'full' ) ) {
186 $this->history
= WikiExporter
::FULL
;
189 if ( $this->hasOption( 'spawn' ) ) {
191 $val = $this->getOption( 'spawn' );
199 * Drop the database connection $this->db and try to get a new one.
201 * This function tries to get a /different/ connection if this is
202 * possible. Hence, (if this is possible) it switches to a different
203 * failover upon each call.
205 * This function resets $this->lb and closes all connections on it.
207 * @throws MWException
209 function rotateDb() {
210 // Cleaning up old connections
211 if ( isset( $this->lb
) ) {
212 $this->lb
->closeAll();
216 if ( $this->forcedDb
!== null ) {
217 $this->db
= $this->forcedDb
;
222 if ( isset( $this->db
) && $this->db
->isOpen() ) {
223 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
228 // Trying to set up new connection.
229 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
230 // individually retrying at different layers of code.
233 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
234 $this->lb
= $lbFactory->newMainLB();
235 } catch ( Exception
$e ) {
236 throw new MWException( __METHOD__
237 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
241 $this->db
= $this->lb
->getConnection( DB_REPLICA
, 'dump' );
242 } catch ( Exception
$e ) {
243 throw new MWException( __METHOD__
244 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
248 function initProgress( $history = WikiExporter
::FULL
) {
249 parent
::initProgress();
250 $this->timeOfCheckpoint
= $this->startTime
;
253 function dump( $history, $text = WikiExporter
::TEXT
) {
254 // Notice messages will foul up your XML output even if they're
255 // relatively harmless.
256 if ( ini_get( 'display_errors' ) ) {
257 ini_set( 'display_errors', 'stderr' );
260 $this->initProgress( $this->history
);
262 // We are trying to get an initial database connection to avoid that the
263 // first try of this request's first call to getText fails. However, if
264 // obtaining a good DB connection fails it's not a serious issue, as
265 // getText does retry upon failure and can start without having a working
269 } catch ( Exception
$e ) {
270 // We do not even count this as failure. Just let eventual
272 $this->progress( "Getting initial DB connection failed (" .
273 $e->getMessage() . ")" );
276 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
278 // it would be nice to do it in the constructor, oh well. need egress set
279 $this->finalOptionCheck();
281 // we only want this so we know how to close a stream :-P
282 $this->xmlwriterobj
= new XmlDumpWriter();
284 $input = fopen( $this->input
, "rt" );
285 $this->readDump( $input );
287 if ( $this->spawnProc
) {
291 $this->report( true );
294 function processFileOpt( $opt ) {
295 $split = explode( ':', $opt, 2 );
298 if ( count( $split ) === 2 ) {
301 $fileURIs = explode( ';', $param );
302 foreach ( $fileURIs as $URI ) {
308 $newURI = "compress.zlib://$URI";
311 $newURI = "compress.bzip2://$URI";
314 $newURI = "mediawiki.compress.7z://$URI";
319 $newFileURIs[] = $newURI;
321 $val = implode( ';', $newFileURIs );
327 * Overridden to include prefetch ratio if enabled.
329 function showReport() {
330 if ( !$this->prefetch
) {
331 parent
::showReport();
336 if ( $this->reporting
) {
337 $now = wfTimestamp( TS_DB
);
338 $nowts = microtime( true );
339 $deltaAll = $nowts - $this->startTime
;
340 $deltaPart = $nowts - $this->lastTime
;
341 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
342 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
345 $portion = $this->revCount
/ $this->maxCount
;
346 $eta = $this->startTime +
$deltaAll / $portion;
347 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
348 if ( $this->fetchCount
) {
349 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
353 $pageRate = $this->pageCount
/ $deltaAll;
354 $revRate = $this->revCount
/ $deltaAll;
362 if ( $this->fetchCountLast
) {
363 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
365 $fetchRatePart = '-';
367 $pageRatePart = $this->pageCountPart
/ $deltaPart;
368 $revRatePart = $this->revCountPart
/ $deltaPart;
370 $fetchRatePart = '-';
374 $this->progress( sprintf(
375 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
376 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
377 . "prefetched (all|curr), ETA %s [max %d]",
378 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
379 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
380 $fetchRate, $fetchRatePart, $etats, $this->maxCount
382 $this->lastTime
= $nowts;
383 $this->revCountLast
= $this->revCount
;
384 $this->prefetchCountLast
= $this->prefetchCount
;
385 $this->fetchCountLast
= $this->fetchCount
;
389 function setTimeExceeded() {
390 $this->timeExceeded
= true;
393 function checkIfTimeExceeded() {
394 if ( $this->maxTimeAllowed
395 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
403 function finalOptionCheck() {
404 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
405 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
407 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
409 foreach ( $this->checkpointFiles
as $checkpointFile ) {
410 $count = substr_count( $checkpointFile, "%s" );
412 throw new MWException( "Option checkpointfile must contain two '%s' "
413 . "for substitution of first and last pageids, count is $count instead, "
414 . "file is $checkpointFile.\n" );
418 if ( $this->checkpointFiles
) {
419 $filenameList = (array)$this->egress
->getFilenames();
420 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
421 throw new MWException( "One checkpointfile must be specified "
422 . "for each output option, if maxtime is used.\n" );
428 * @throws MWException Failure to parse XML input
429 * @param string $input
432 function readDump( $input ) {
434 $this->openElement
= false;
435 $this->atStart
= true;
437 $this->lastName
= "";
440 $this->thisRevModel
= null;
441 $this->thisRevFormat
= null;
443 $parser = xml_parser_create( "UTF-8" );
444 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
446 xml_set_element_handler(
448 [ $this, 'startElement' ],
449 [ $this, 'endElement' ]
451 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
453 $offset = 0; // for context extraction on error reporting
455 if ( $this->checkIfTimeExceeded() ) {
456 $this->setTimeExceeded();
458 $chunk = fread( $input, $this->bufferSize
);
459 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
460 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
462 $byte = xml_get_current_byte_index( $parser );
463 $msg = wfMessage( 'xml-error-string',
464 'XML import parse failure',
465 xml_get_current_line_number( $parser ),
466 xml_get_current_column_number( $parser ),
467 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
468 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
470 xml_parser_free( $parser );
472 throw new MWException( $msg );
474 $offset +
= strlen( $chunk );
475 } while ( $chunk !== false && !feof( $input ) );
476 if ( $this->maxTimeAllowed
) {
477 $filenameList = (array)$this->egress
->getFilenames();
478 // we wrote some stuff after last checkpoint that needs renamed
479 if ( file_exists( $filenameList[0] ) ) {
481 # we might have just written the header and footer and had no
482 # pages or revisions written... perhaps they were all deleted
483 # there's no pageID 0 so we use that. the caller is responsible
484 # for deciding what to do with a file containing only the
485 # siteinfo information and the mw tags.
486 if ( !$this->firstPageWritten
) {
487 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
488 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
490 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
491 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
494 $filenameCount = count( $filenameList );
495 for ( $i = 0; $i < $filenameCount; $i++
) {
496 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
497 $fileinfo = pathinfo( $filenameList[$i] );
498 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
500 $this->egress
->closeAndRename( $newFilenames );
503 xml_parser_free( $parser );
509 * Applies applicable export transformations to $text.
511 * @param string $text
512 * @param string $model
513 * @param string|null $format
517 private function exportTransform( $text, $model, $format = null ) {
519 $handler = ContentHandler
::getForModelID( $model );
520 $text = $handler->exportTransform( $text, $format );
522 catch ( MWException
$ex ) {
524 "Unable to apply export transformation for content model '$model': " .
533 * Tries to load revision text.
534 * Export transformations are applied if the content model is given or can be
535 * determined from the database.
537 * Upon errors, retries (Up to $this->maxFailures tries each call).
538 * If still no good revision could be found even after this retrying, "" is returned.
539 * If no good revision text could be returned for
540 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
543 * @param int|string $id Content address, or text row ID.
544 * @param string|bool|null $model The content model used to determine
545 * applicable export transformations.
546 * If $model is null, it will be determined from the database.
547 * @param string|null $format The content format used when applying export transformations.
549 * @throws MWException
550 * @return string The revision text for $id, or ""
552 function getText( $id, $model = null, $format = null ) {
553 global $wgContentHandlerUseDB;
555 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
556 $text = false; // The candidate for a good text. false if no proper value.
557 $failures = 0; // The number of times, this invocation of getText already failed.
559 // The number of times getText failed without yielding a good text in between.
560 static $consecutiveFailedTextRetrievals = 0;
564 // To allow to simply return on success and do not have to worry about book keeping,
565 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
566 // the old value, so we can restore it, if problems occur (See after the while loop).
567 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
568 $consecutiveFailedTextRetrievals = 0;
570 if ( $model === null && $wgContentHandlerUseDB ) {
571 // TODO: MCR: use content table
572 $row = $this->db
->selectRow(
574 [ 'rev_content_model', 'rev_content_format' ],
575 [ 'rev_id' => $this->thisRev
],
580 $model = $row->rev_content_model
;
581 $format = $row->rev_content_format
;
585 if ( $model === null ||
$model === '' ) {
589 while ( $failures < $this->maxFailures
) {
590 // As soon as we found a good text for the $id, we will return immediately.
591 // Hence, if we make it past the try catch block, we know that we did not
595 // Step 1: Get some text (or reuse from previous iteratuon if checking
596 // for plausibility failed)
598 // Trying to get prefetch, if it has not been tried before
599 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
600 $prefetchNotTried = false;
601 $tryIsPrefetch = true;
602 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
604 if ( $text === null ) {
608 if ( is_string( $text ) && $model !== false ) {
609 // Apply export transformation to text coming from an old dump.
610 // The purpose of this transformation is to convert up from legacy
611 // formats, which may still be used in the older dump that is used
612 // for pre-fetching. Applying the transformation again should not
613 // interfere with content that is already in the correct form.
614 $text = $this->exportTransform( $text, $model, $format );
618 if ( $text === false ) {
619 // Fallback to asking the database
620 $tryIsPrefetch = false;
621 if ( $this->spawn
) {
622 $text = $this->getTextSpawned( $id );
624 $text = $this->getTextDb( $id );
627 if ( $text !== false && $model !== false ) {
628 // Apply export transformation to text coming from the database.
629 // Prefetched text should already have transformations applied.
630 $text = $this->exportTransform( $text, $model, $format );
633 // No more checks for texts from DB for now.
634 // If we received something that is not false,
635 // We treat it as good text, regardless of whether it actually is or is not
636 if ( $text !== false ) {
641 if ( $text === false ) {
642 throw new MWException( "Generic error while obtaining text for id " . $id );
645 // We received a good candidate for the text of $id via some method
647 // Step 2: Checking for plausibility and return the text if it is
649 $revID = intval( $this->thisRev
);
650 if ( !isset( $this->db
) ) {
651 throw new MWException( "No database available" );
654 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
655 $revLength = strlen( $text );
657 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
660 if ( strlen( $text ) == $revLength ) {
661 if ( $tryIsPrefetch ) {
662 $this->prefetchCount++
;
669 throw new MWException( "Received text is unplausible for id " . $id );
670 } catch ( Exception
$e ) {
671 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
672 if ( $failures +
1 < $this->maxFailures
) {
673 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
675 $this->progress( $msg );
678 // Something went wrong; we did not a text that was plausible :(
681 // A failure in a prefetch hit does not warrant resetting db connection etc.
682 if ( !$tryIsPrefetch ) {
683 // After backing off for some time, we try to reboot the whole process as
684 // much as possible to not carry over failures from one part to the other
686 sleep( $this->failureTimeout
);
689 if ( $this->spawn
) {
693 } catch ( Exception
$e ) {
694 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
695 " Trying to continue anyways" );
700 // Retirieving a good text for $id failed (at least) maxFailures times.
701 // We abort for this $id.
703 // Restoring the consecutive failures, and maybe aborting, if the dump
705 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
706 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
707 throw new MWException( "Graceful storage failure" );
714 * Loads the serialized content from storage.
716 * @param int|string $id Content address, or text row ID.
717 * @return bool|string
719 private function getTextDb( $id ) {
720 $store = $this->getBlobStore();
721 $address = ( is_int( $id ) ||
strpos( $id, ':' ) === false )
722 ? SqlBlobStore
::makeAddressFromTextId( (int)$id )
726 $text = $store->getBlob( $address );
728 $stripped = str_replace( "\r", "", $text );
729 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()
730 ->normalize( $stripped );
733 } catch ( BlobAccessException
$ex ) {
734 // XXX: log a warning?
740 * @param int|string $id Content address, or text row ID.
741 * @return bool|string
743 private function getTextSpawned( $id ) {
744 Wikimedia\
suppressWarnings();
745 if ( !$this->spawnProc
) {
749 $text = $this->getTextSpawnedOnce( $id );
750 Wikimedia\restoreWarnings
();
755 function openSpawn() {
758 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
760 array_map( 'wfEscapeShellArg',
763 "$IP/../multiversion/MWScript.php",
765 '--wiki', wfWikiID() ] ) );
768 array_map( 'wfEscapeShellArg',
771 "$IP/maintenance/fetchText.php",
772 '--wiki', wfWikiID() ] ) );
775 0 => [ "pipe", "r" ],
776 1 => [ "pipe", "w" ],
777 2 => [ "file", "/dev/null", "a" ] ];
780 $this->progress( "Spawning database subprocess: $cmd" );
781 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
782 if ( !$this->spawnProc
) {
783 $this->progress( "Subprocess spawn failed." );
788 $this->spawnWrite
, // -> stdin
789 $this->spawnRead
, // <- stdout
795 private function closeSpawn() {
796 Wikimedia\
suppressWarnings();
797 if ( $this->spawnRead
) {
798 fclose( $this->spawnRead
);
800 $this->spawnRead
= false;
801 if ( $this->spawnWrite
) {
802 fclose( $this->spawnWrite
);
804 $this->spawnWrite
= false;
805 if ( $this->spawnErr
) {
806 fclose( $this->spawnErr
);
808 $this->spawnErr
= false;
809 if ( $this->spawnProc
) {
810 pclose( $this->spawnProc
);
812 $this->spawnProc
= false;
813 Wikimedia\restoreWarnings
();
817 * @param int|string $id Content address, or text row ID.
818 * @return bool|string
820 private function getTextSpawnedOnce( $id ) {
821 $ok = fwrite( $this->spawnWrite
, "$id\n" );
822 // $this->progress( ">> $id" );
827 $ok = fflush( $this->spawnWrite
);
828 // $this->progress( ">> [flush]" );
833 // check that the text id they are sending is the one we asked for
834 // this avoids out of sync revision text errors we have encountered in the past
835 $newAddress = fgets( $this->spawnRead
);
836 if ( $newAddress === false ) {
839 if ( strpos( $newAddress, ':' ) === false ) {
840 $newId = intval( $newAddress );
841 if ( $newId === false ) {
846 $newAddressFields = SqlBlobStore
::splitBlobAddress( $newAddress );
847 $newId = $newAddressFields[ 1 ];
848 } catch ( InvalidArgumentException
$ex ) {
852 if ( $id != intval( $newId ) ) {
856 $len = fgets( $this->spawnRead
);
857 // $this->progress( "<< " . trim( $len ) );
858 if ( $len === false ) {
862 $nbytes = intval( $len );
863 // actual error, not zero-length text
870 // Subprocess may not send everything at once, we have to loop.
871 while ( $nbytes > strlen( $text ) ) {
872 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
873 if ( $buffer === false ) {
879 $gotbytes = strlen( $text );
880 if ( $gotbytes != $nbytes ) {
881 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
886 // Do normalization in the dump thread...
887 $stripped = str_replace( "\r", "", $text );
888 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()->
889 normalize( $stripped );
894 function startElement( $parser, $name, $attribs ) {
895 $this->checkpointJustWritten
= false;
897 $this->clearOpenElement( null );
898 $this->lastName
= $name;
900 if ( $name == 'revision' ) {
901 $this->state
= $name;
902 $this->egress
->writeOpenPage( null, $this->buffer
);
904 } elseif ( $name == 'page' ) {
905 $this->state
= $name;
906 if ( $this->atStart
) {
907 $this->egress
->writeOpenStream( $this->buffer
);
909 $this->atStart
= false;
913 if ( $name == "text" && isset( $attribs['id'] ) ) {
914 $id = $attribs['id'];
915 $model = trim( $this->thisRevModel
);
916 $format = trim( $this->thisRevFormat
);
918 $model = $model === '' ?
null : $model;
919 $format = $format === '' ?
null : $format;
921 $text = $this->getText( $id, $model, $format );
922 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
923 if ( strlen( $text ) > 0 ) {
924 $this->characterData( $parser, $text );
927 $this->openElement
= [ $name, $attribs ];
931 function endElement( $parser, $name ) {
932 $this->checkpointJustWritten
= false;
934 if ( $this->openElement
) {
935 $this->clearOpenElement( "" );
937 $this->buffer
.= "</$name>";
940 if ( $name == 'revision' ) {
941 $this->egress
->writeRevision( null, $this->buffer
);
944 $this->thisRevModel
= null;
945 $this->thisRevFormat
= null;
946 } elseif ( $name == 'page' ) {
947 if ( !$this->firstPageWritten
) {
948 $this->firstPageWritten
= trim( $this->thisPage
);
950 $this->lastPageWritten
= trim( $this->thisPage
);
951 if ( $this->timeExceeded
) {
952 $this->egress
->writeClosePage( $this->buffer
);
953 // nasty hack, we can't just write the chardata after the
954 // page tag, it will include leading blanks from the next line
955 $this->egress
->sink
->write( "\n" );
957 $this->buffer
= $this->xmlwriterobj
->closeStream();
958 $this->egress
->writeCloseStream( $this->buffer
);
961 $this->thisPage
= "";
962 // this could be more than one file if we had more than one output arg
964 $filenameList = (array)$this->egress
->getFilenames();
966 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
967 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
968 $filenamesCount = count( $filenameList );
969 for ( $i = 0; $i < $filenamesCount; $i++
) {
970 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
971 $fileinfo = pathinfo( $filenameList[$i] );
972 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
974 $this->egress
->closeRenameAndReopen( $newFilenames );
975 $this->buffer
= $this->xmlwriterobj
->openStream();
976 $this->timeExceeded
= false;
977 $this->timeOfCheckpoint
= $this->lastTime
;
978 $this->firstPageWritten
= false;
979 $this->checkpointJustWritten
= true;
981 $this->egress
->writeClosePage( $this->buffer
);
983 $this->thisPage
= "";
985 } elseif ( $name == 'mediawiki' ) {
986 $this->egress
->writeCloseStream( $this->buffer
);
991 function characterData( $parser, $data ) {
992 $this->clearOpenElement( null );
993 if ( $this->lastName
== "id" ) {
994 if ( $this->state
== "revision" ) {
995 $this->thisRev
.= $data;
996 } elseif ( $this->state
== "page" ) {
997 $this->thisPage
.= $data;
999 } elseif ( $this->lastName
== "model" ) {
1000 $this->thisRevModel
.= $data;
1001 } elseif ( $this->lastName
== "format" ) {
1002 $this->thisRevFormat
.= $data;
1005 // have to skip the newline left over from closepagetag line of
1006 // end of checkpoint files. nasty hack!!
1007 if ( $this->checkpointJustWritten
) {
1008 if ( $data[0] == "\n" ) {
1009 $data = substr( $data, 1 );
1011 $this->checkpointJustWritten
= false;
1013 $this->buffer
.= htmlspecialchars( $data );
1016 function clearOpenElement( $style ) {
1017 if ( $this->openElement
) {
1018 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
1019 $this->openElement
= false;
1024 $maintClass = TextPassDumper
::class;
1025 require_once RUN_MAINTENANCE_IF_MAIN
;