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\SqlBlobStore
;
34 use Wikimedia\Rdbms\IMaintainableDatabase
;
37 * @ingroup Maintenance
39 class TextPassDumper
extends BackupDumper
{
41 public $prefetch = null;
42 /** @var string|bool */
44 /** @var string|bool */
47 // when we spend more than maxTimeAllowed seconds on this run, we continue
48 // processing until we write out the next complete page, then save output file(s),
49 // rename it/them and open new one(s)
50 public $maxTimeAllowed = 0; // 0 = no limit
52 protected $input = "php://stdin";
53 protected $history = WikiExporter
::FULL
;
54 protected $fetchCount = 0;
55 protected $prefetchCount = 0;
56 protected $prefetchCountLast = 0;
57 protected $fetchCountLast = 0;
59 protected $maxFailures = 5;
60 protected $maxConsecutiveFailedTextRetrievals = 200;
61 protected $failureTimeout = 5; // Seconds to sleep after db failure
63 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
65 protected $php = "php";
66 protected $spawn = false;
71 protected $spawnProc = false;
76 protected $spawnWrite = false;
81 protected $spawnRead = false;
86 protected $spawnErr = false;
89 * @var bool|XmlDumpWriter
91 protected $xmlwriterobj = false;
93 protected $timeExceeded = false;
94 protected $firstPageWritten = false;
95 protected $lastPageWritten = false;
96 protected $checkpointJustWritten = false;
97 protected $checkpointFiles = [];
100 * @var IMaintainableDatabase
105 * @param array|null $args For backward compatibility
107 function __construct( $args = null ) {
108 parent
::__construct();
110 $this->addDescription( <<<TEXT
111 This script postprocesses XML dumps from dumpBackup.php to add
112 page text which was stubbed out (using --stub).
114 XML input is accepted on stdin.
115 XML output is sent to stdout; progress reports are sent to stderr.
118 $this->stderr
= fopen( "php://stderr", "wt" );
120 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
121 'Specify as --stub=<type>:<file>.', false, true );
122 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
123 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
125 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
126 'out complete page, closing xml file properly, and opening new one' .
127 'with header). This option requires the checkpointfile option.', false, true );
128 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
129 'first pageid written for the first %s (required) and the last pageid written for the ' .
130 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
131 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
132 $this->addOption( 'full', 'Dump all revisions of every page' );
133 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
134 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
135 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
136 '(Default: 512KB, Minimum: 4KB)', false, true );
139 $this->loadWithArgv( $args );
140 $this->processOptions();
145 * @return SqlBlobStore
147 private function getBlobStore() {
148 return MediaWikiServices
::getInstance()->getBlobStore();
152 $this->processOptions();
156 function processOptions() {
157 parent
::processOptions();
159 if ( $this->hasOption( 'buffersize' ) ) {
160 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
163 if ( $this->hasOption( 'prefetch' ) ) {
164 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
165 $this->prefetch
= new BaseDump( $url );
168 if ( $this->hasOption( 'stub' ) ) {
169 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
172 if ( $this->hasOption( 'maxtime' ) ) {
173 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
176 if ( $this->hasOption( 'checkpointfile' ) ) {
177 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
180 if ( $this->hasOption( 'current' ) ) {
181 $this->history
= WikiExporter
::CURRENT
;
184 if ( $this->hasOption( 'full' ) ) {
185 $this->history
= WikiExporter
::FULL
;
188 if ( $this->hasOption( 'spawn' ) ) {
190 $val = $this->getOption( 'spawn' );
198 * Drop the database connection $this->db and try to get a new one.
200 * This function tries to get a /different/ connection if this is
201 * possible. Hence, (if this is possible) it switches to a different
202 * failover upon each call.
204 * This function resets $this->lb and closes all connections on it.
206 * @throws MWException
208 function rotateDb() {
209 // Cleaning up old connections
210 if ( isset( $this->lb
) ) {
211 $this->lb
->closeAll();
215 if ( $this->forcedDb
!== null ) {
216 $this->db
= $this->forcedDb
;
221 if ( isset( $this->db
) && $this->db
->isOpen() ) {
222 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
227 // Trying to set up new connection.
228 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
229 // individually retrying at different layers of code.
232 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
233 $this->lb
= $lbFactory->newMainLB();
234 } catch ( Exception
$e ) {
235 throw new MWException( __METHOD__
236 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
240 $this->db
= $this->lb
->getConnection( DB_REPLICA
, 'dump' );
241 } catch ( Exception
$e ) {
242 throw new MWException( __METHOD__
243 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
247 function initProgress( $history = WikiExporter
::FULL
) {
248 parent
::initProgress();
249 $this->timeOfCheckpoint
= $this->startTime
;
252 function dump( $history, $text = WikiExporter
::TEXT
) {
253 // Notice messages will foul up your XML output even if they're
254 // relatively harmless.
255 if ( ini_get( 'display_errors' ) ) {
256 ini_set( 'display_errors', 'stderr' );
259 $this->initProgress( $this->history
);
261 // We are trying to get an initial database connection to avoid that the
262 // first try of this request's first call to getText fails. However, if
263 // obtaining a good DB connection fails it's not a serious issue, as
264 // getText does retry upon failure and can start without having a working
268 } catch ( Exception
$e ) {
269 // We do not even count this as failure. Just let eventual
271 $this->progress( "Getting initial DB connection failed (" .
272 $e->getMessage() . ")" );
275 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
277 // it would be nice to do it in the constructor, oh well. need egress set
278 $this->finalOptionCheck();
280 // we only want this so we know how to close a stream :-P
281 $this->xmlwriterobj
= new XmlDumpWriter();
283 $input = fopen( $this->input
, "rt" );
284 $this->readDump( $input );
286 if ( $this->spawnProc
) {
290 $this->report( true );
293 function processFileOpt( $opt ) {
294 $split = explode( ':', $opt, 2 );
297 if ( count( $split ) === 2 ) {
300 $fileURIs = explode( ';', $param );
301 foreach ( $fileURIs as $URI ) {
307 $newURI = "compress.zlib://$URI";
310 $newURI = "compress.bzip2://$URI";
313 $newURI = "mediawiki.compress.7z://$URI";
318 $newFileURIs[] = $newURI;
320 $val = implode( ';', $newFileURIs );
326 * Overridden to include prefetch ratio if enabled.
328 function showReport() {
329 if ( !$this->prefetch
) {
330 parent
::showReport();
335 if ( $this->reporting
) {
336 $now = wfTimestamp( TS_DB
);
337 $nowts = microtime( true );
338 $deltaAll = $nowts - $this->startTime
;
339 $deltaPart = $nowts - $this->lastTime
;
340 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
341 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
344 $portion = $this->revCount
/ $this->maxCount
;
345 $eta = $this->startTime +
$deltaAll / $portion;
346 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
347 if ( $this->fetchCount
) {
348 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
352 $pageRate = $this->pageCount
/ $deltaAll;
353 $revRate = $this->revCount
/ $deltaAll;
361 if ( $this->fetchCountLast
) {
362 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
364 $fetchRatePart = '-';
366 $pageRatePart = $this->pageCountPart
/ $deltaPart;
367 $revRatePart = $this->revCountPart
/ $deltaPart;
369 $fetchRatePart = '-';
373 $this->progress( sprintf(
374 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
375 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
376 . "prefetched (all|curr), ETA %s [max %d]",
377 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
378 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
379 $fetchRate, $fetchRatePart, $etats, $this->maxCount
381 $this->lastTime
= $nowts;
382 $this->revCountLast
= $this->revCount
;
383 $this->prefetchCountLast
= $this->prefetchCount
;
384 $this->fetchCountLast
= $this->fetchCount
;
388 function setTimeExceeded() {
389 $this->timeExceeded
= true;
392 function checkIfTimeExceeded() {
393 if ( $this->maxTimeAllowed
394 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
402 function finalOptionCheck() {
403 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
404 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
406 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
408 foreach ( $this->checkpointFiles
as $checkpointFile ) {
409 $count = substr_count( $checkpointFile, "%s" );
411 throw new MWException( "Option checkpointfile must contain two '%s' "
412 . "for substitution of first and last pageids, count is $count instead, "
413 . "file is $checkpointFile.\n" );
417 if ( $this->checkpointFiles
) {
418 $filenameList = (array)$this->egress
->getFilenames();
419 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
420 throw new MWException( "One checkpointfile must be specified "
421 . "for each output option, if maxtime is used.\n" );
427 * @throws MWException Failure to parse XML input
428 * @param string $input
431 function readDump( $input ) {
433 $this->openElement
= false;
434 $this->atStart
= true;
436 $this->lastName
= "";
439 $this->thisRevModel
= null;
440 $this->thisRevFormat
= null;
442 $parser = xml_parser_create( "UTF-8" );
443 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
445 xml_set_element_handler(
447 [ $this, 'startElement' ],
448 [ $this, 'endElement' ]
450 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
452 $offset = 0; // for context extraction on error reporting
454 if ( $this->checkIfTimeExceeded() ) {
455 $this->setTimeExceeded();
457 $chunk = fread( $input, $this->bufferSize
);
458 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
459 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
461 $byte = xml_get_current_byte_index( $parser );
462 $msg = wfMessage( 'xml-error-string',
463 'XML import parse failure',
464 xml_get_current_line_number( $parser ),
465 xml_get_current_column_number( $parser ),
466 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
467 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
469 xml_parser_free( $parser );
471 throw new MWException( $msg );
473 $offset +
= strlen( $chunk );
474 } while ( $chunk !== false && !feof( $input ) );
475 if ( $this->maxTimeAllowed
) {
476 $filenameList = (array)$this->egress
->getFilenames();
477 // we wrote some stuff after last checkpoint that needs renamed
478 if ( file_exists( $filenameList[0] ) ) {
480 # we might have just written the header and footer and had no
481 # pages or revisions written... perhaps they were all deleted
482 # there's no pageID 0 so we use that. the caller is responsible
483 # for deciding what to do with a file containing only the
484 # siteinfo information and the mw tags.
485 if ( !$this->firstPageWritten
) {
486 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
487 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
489 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
490 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
493 $filenameCount = count( $filenameList );
494 for ( $i = 0; $i < $filenameCount; $i++
) {
495 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
496 $fileinfo = pathinfo( $filenameList[$i] );
497 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
499 $this->egress
->closeAndRename( $newFilenames );
502 xml_parser_free( $parser );
508 * Applies applicable export transformations to $text.
510 * @param string $text
511 * @param string $model
512 * @param string|null $format
516 private function exportTransform( $text, $model, $format = null ) {
518 $handler = ContentHandler
::getForModelID( $model );
519 $text = $handler->exportTransform( $text, $format );
521 catch ( MWException
$ex ) {
523 "Unable to apply export transformation for content model '$model': " .
532 * Tries to load revision text.
533 * Export transformations are applied if the content model is given or can be
534 * determined from the database.
536 * Upon errors, retries (Up to $this->maxFailures tries each call).
537 * If still no good revision could be found even after this retrying, "" is returned.
538 * If no good revision text could be returned for
539 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
542 * @param int|string $id Content address, or text row ID.
543 * @param string|bool|null $model The content model used to determine
544 * applicable export transformations.
545 * If $model is null, it will be determined from the database.
546 * @param string|null $format The content format used when applying export transformations.
548 * @throws MWException
549 * @return string The revision text for $id, or ""
551 function getText( $id, $model = null, $format = null ) {
552 global $wgContentHandlerUseDB;
554 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
555 $text = false; // The candidate for a good text. false if no proper value.
556 $failures = 0; // The number of times, this invocation of getText already failed.
558 // The number of times getText failed without yielding a good text in between.
559 static $consecutiveFailedTextRetrievals = 0;
563 // To allow to simply return on success and do not have to worry about book keeping,
564 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
565 // the old value, so we can restore it, if problems occur (See after the while loop).
566 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
567 $consecutiveFailedTextRetrievals = 0;
569 if ( $model === null && $wgContentHandlerUseDB ) {
570 // TODO: MCR: use content table
571 $row = $this->db
->selectRow(
573 [ 'rev_content_model', 'rev_content_format' ],
574 [ 'rev_id' => $this->thisRev
],
579 $model = $row->rev_content_model
;
580 $format = $row->rev_content_format
;
584 if ( $model === null ||
$model === '' ) {
588 while ( $failures < $this->maxFailures
) {
589 // As soon as we found a good text for the $id, we will return immediately.
590 // Hence, if we make it past the try catch block, we know that we did not
594 // Step 1: Get some text (or reuse from previous iteratuon if checking
595 // for plausibility failed)
597 // Trying to get prefetch, if it has not been tried before
598 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
599 $prefetchNotTried = false;
600 $tryIsPrefetch = true;
601 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
603 if ( $text === null ) {
607 if ( is_string( $text ) && $model !== false ) {
608 // Apply export transformation to text coming from an old dump.
609 // The purpose of this transformation is to convert up from legacy
610 // formats, which may still be used in the older dump that is used
611 // for pre-fetching. Applying the transformation again should not
612 // interfere with content that is already in the correct form.
613 $text = $this->exportTransform( $text, $model, $format );
617 if ( $text === false ) {
618 // Fallback to asking the database
619 $tryIsPrefetch = false;
620 if ( $this->spawn
) {
621 $text = $this->getTextSpawned( $id );
623 $text = $this->getTextDb( $id );
626 if ( $text !== false && $model !== false ) {
627 // Apply export transformation to text coming from the database.
628 // Prefetched text should already have transformations applied.
629 $text = $this->exportTransform( $text, $model, $format );
632 // No more checks for texts from DB for now.
633 // If we received something that is not false,
634 // We treat it as good text, regardless of whether it actually is or is not
635 if ( $text !== false ) {
640 if ( $text === false ) {
641 throw new MWException( "Generic error while obtaining text for id " . $id );
644 // We received a good candidate for the text of $id via some method
646 // Step 2: Checking for plausibility and return the text if it is
648 $revID = intval( $this->thisRev
);
649 if ( !isset( $this->db
) ) {
650 throw new MWException( "No database available" );
653 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
654 $revLength = strlen( $text );
656 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
659 if ( strlen( $text ) == $revLength ) {
660 if ( $tryIsPrefetch ) {
661 $this->prefetchCount++
;
668 throw new MWException( "Received text is unplausible for id " . $id );
669 } catch ( Exception
$e ) {
670 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
671 if ( $failures +
1 < $this->maxFailures
) {
672 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
674 $this->progress( $msg );
677 // Something went wrong; we did not a text that was plausible :(
680 // A failure in a prefetch hit does not warrant resetting db connection etc.
681 if ( !$tryIsPrefetch ) {
682 // After backing off for some time, we try to reboot the whole process as
683 // much as possible to not carry over failures from one part to the other
685 sleep( $this->failureTimeout
);
688 if ( $this->spawn
) {
692 } catch ( Exception
$e ) {
693 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
694 " Trying to continue anyways" );
699 // Retirieving a good text for $id failed (at least) maxFailures times.
700 // We abort for this $id.
702 // Restoring the consecutive failures, and maybe aborting, if the dump
704 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
705 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
706 throw new MWException( "Graceful storage failure" );
713 * Loads the serialized content from storage.
715 * @param int|string $id Content address, or text row ID.
716 * @return bool|string
718 private function getTextDb( $id ) {
719 $store = $this->getBlobStore();
720 $address = ( is_int( $id ) ||
strpos( $id, ':' ) === false )
721 ? SqlBlobStore
::makeAddressFromTextId( (int)$id )
725 $text = $store->getBlob( $address );
727 $stripped = str_replace( "\r", "", $text );
728 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()
729 ->normalize( $stripped );
732 } catch ( BlobAccessException
$ex ) {
733 // XXX: log a warning?
739 * @param int|string $address Content address, or text row ID.
740 * @return bool|string
742 private function getTextSpawned( $address ) {
743 Wikimedia\
suppressWarnings();
744 if ( !$this->spawnProc
) {
748 $text = $this->getTextSpawnedOnce( $address );
749 Wikimedia\restoreWarnings
();
754 function openSpawn() {
757 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
759 array_map( 'wfEscapeShellArg',
762 "$IP/../multiversion/MWScript.php",
764 '--wiki', wfWikiID() ] ) );
767 array_map( 'wfEscapeShellArg',
770 "$IP/maintenance/fetchText.php",
771 '--wiki', wfWikiID() ] ) );
774 0 => [ "pipe", "r" ],
775 1 => [ "pipe", "w" ],
776 2 => [ "file", "/dev/null", "a" ] ];
779 $this->progress( "Spawning database subprocess: $cmd" );
780 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
781 if ( !$this->spawnProc
) {
782 $this->progress( "Subprocess spawn failed." );
787 $this->spawnWrite
, // -> stdin
788 $this->spawnRead
, // <- stdout
794 private function closeSpawn() {
795 Wikimedia\
suppressWarnings();
796 if ( $this->spawnRead
) {
797 fclose( $this->spawnRead
);
799 $this->spawnRead
= false;
800 if ( $this->spawnWrite
) {
801 fclose( $this->spawnWrite
);
803 $this->spawnWrite
= false;
804 if ( $this->spawnErr
) {
805 fclose( $this->spawnErr
);
807 $this->spawnErr
= false;
808 if ( $this->spawnProc
) {
809 pclose( $this->spawnProc
);
811 $this->spawnProc
= false;
812 Wikimedia\restoreWarnings
();
816 * @param int|string $address Content address, or text row ID.
817 * @return bool|string
819 private function getTextSpawnedOnce( $address ) {
820 if ( is_int( $address ) ||
intval( $address ) ) {
821 $address = SqlBlobStore
::makeAddressFromTextId( (int)$address );
824 $ok = fwrite( $this->spawnWrite
, "$address\n" );
825 // $this->progress( ">> $id" );
830 $ok = fflush( $this->spawnWrite
);
831 // $this->progress( ">> [flush]" );
836 // check that the text address they are sending is the one we asked for
837 // this avoids out of sync revision text errors we have encountered in the past
838 $newAddress = fgets( $this->spawnRead
);
839 if ( $newAddress === false ) {
842 $newAddress = trim( $newAddress );
843 if ( strpos( $newAddress, ':' ) === false ) {
844 $newAddress = SqlBlobStore
::makeAddressFromTextId( intval( $newAddress ) );
847 if ( $newAddress !== $address ) {
851 $len = fgets( $this->spawnRead
);
852 // $this->progress( "<< " . trim( $len ) );
853 if ( $len === false ) {
857 $nbytes = intval( $len );
858 // actual error, not zero-length text
865 // Subprocess may not send everything at once, we have to loop.
866 while ( $nbytes > strlen( $text ) ) {
867 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
868 if ( $buffer === false ) {
874 $gotbytes = strlen( $text );
875 if ( $gotbytes != $nbytes ) {
876 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
881 // Do normalization in the dump thread...
882 $stripped = str_replace( "\r", "", $text );
883 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()->
884 normalize( $stripped );
889 function startElement( $parser, $name, $attribs ) {
890 $this->checkpointJustWritten
= false;
892 $this->clearOpenElement( null );
893 $this->lastName
= $name;
895 if ( $name == 'revision' ) {
896 $this->state
= $name;
897 $this->egress
->writeOpenPage( null, $this->buffer
);
899 } elseif ( $name == 'page' ) {
900 $this->state
= $name;
901 if ( $this->atStart
) {
902 $this->egress
->writeOpenStream( $this->buffer
);
904 $this->atStart
= false;
908 if ( $name == "text" && isset( $attribs['id'] ) ) {
909 $id = $attribs['id'];
910 $model = trim( $this->thisRevModel
);
911 $format = trim( $this->thisRevFormat
);
913 $model = $model === '' ?
null : $model;
914 $format = $format === '' ?
null : $format;
916 $text = $this->getText( $id, $model, $format );
917 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
918 if ( strlen( $text ) > 0 ) {
919 $this->characterData( $parser, $text );
922 $this->openElement
= [ $name, $attribs ];
926 function endElement( $parser, $name ) {
927 $this->checkpointJustWritten
= false;
929 if ( $this->openElement
) {
930 $this->clearOpenElement( "" );
932 $this->buffer
.= "</$name>";
935 if ( $name == 'revision' ) {
936 $this->egress
->writeRevision( null, $this->buffer
);
939 $this->thisRevModel
= null;
940 $this->thisRevFormat
= null;
941 } elseif ( $name == 'page' ) {
942 if ( !$this->firstPageWritten
) {
943 $this->firstPageWritten
= trim( $this->thisPage
);
945 $this->lastPageWritten
= trim( $this->thisPage
);
946 if ( $this->timeExceeded
) {
947 $this->egress
->writeClosePage( $this->buffer
);
948 // nasty hack, we can't just write the chardata after the
949 // page tag, it will include leading blanks from the next line
950 $this->egress
->sink
->write( "\n" );
952 $this->buffer
= $this->xmlwriterobj
->closeStream();
953 $this->egress
->writeCloseStream( $this->buffer
);
956 $this->thisPage
= "";
957 // this could be more than one file if we had more than one output arg
959 $filenameList = (array)$this->egress
->getFilenames();
961 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
962 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
963 $filenamesCount = count( $filenameList );
964 for ( $i = 0; $i < $filenamesCount; $i++
) {
965 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
966 $fileinfo = pathinfo( $filenameList[$i] );
967 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
969 $this->egress
->closeRenameAndReopen( $newFilenames );
970 $this->buffer
= $this->xmlwriterobj
->openStream();
971 $this->timeExceeded
= false;
972 $this->timeOfCheckpoint
= $this->lastTime
;
973 $this->firstPageWritten
= false;
974 $this->checkpointJustWritten
= true;
976 $this->egress
->writeClosePage( $this->buffer
);
978 $this->thisPage
= "";
980 } elseif ( $name == 'mediawiki' ) {
981 $this->egress
->writeCloseStream( $this->buffer
);
986 function characterData( $parser, $data ) {
987 $this->clearOpenElement( null );
988 if ( $this->lastName
== "id" ) {
989 if ( $this->state
== "revision" ) {
990 $this->thisRev
.= $data;
991 } elseif ( $this->state
== "page" ) {
992 $this->thisPage
.= $data;
994 } elseif ( $this->lastName
== "model" ) {
995 $this->thisRevModel
.= $data;
996 } elseif ( $this->lastName
== "format" ) {
997 $this->thisRevFormat
.= $data;
1000 // have to skip the newline left over from closepagetag line of
1001 // end of checkpoint files. nasty hack!!
1002 if ( $this->checkpointJustWritten
) {
1003 if ( $data[0] == "\n" ) {
1004 $data = substr( $data, 1 );
1006 $this->checkpointJustWritten
= false;
1008 $this->buffer
.= htmlspecialchars( $data );
1011 function clearOpenElement( $style ) {
1012 if ( $this->openElement
) {
1013 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
1014 $this->openElement
= false;
1019 $maintClass = TextPassDumper
::class;
1020 require_once RUN_MAINTENANCE_IF_MAIN
;