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
25 * @ingroup Maintenance
28 require_once __DIR__
. '/BackupDumper.php';
29 require_once __DIR__
. '/SevenZipStream.php';
30 require_once __DIR__
. '/../../includes/export/WikiExporter.php';
32 use MediaWiki\MediaWikiServices
;
33 use MediaWiki\Shell\Shell
;
34 use MediaWiki\Storage\BlobAccessException
;
35 use MediaWiki\Storage\SqlBlobStore
;
36 use Wikimedia\Rdbms\IMaintainableDatabase
;
39 * @ingroup Maintenance
41 class TextPassDumper
extends BackupDumper
{
43 public $prefetch = null;
44 /** @var string|bool */
46 /** @var string|bool */
49 // when we spend more than maxTimeAllowed seconds on this run, we continue
50 // processing until we write out the next complete page, then save output file(s),
51 // rename it/them and open new one(s)
52 public $maxTimeAllowed = 0; // 0 = no limit
54 protected $input = "php://stdin";
55 protected $history = WikiExporter
::FULL
;
56 protected $fetchCount = 0;
57 protected $prefetchCount = 0;
58 protected $prefetchCountLast = 0;
59 protected $fetchCountLast = 0;
61 protected $maxFailures = 5;
62 protected $maxConsecutiveFailedTextRetrievals = 200;
63 protected $failureTimeout = 5; // Seconds to sleep after db failure
65 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
69 protected $spawn = false;
74 protected $spawnProc = false;
79 protected $spawnWrite;
89 protected $spawnErr = false;
92 * @var bool|XmlDumpWriter
94 protected $xmlwriterobj = false;
96 protected $timeExceeded = false;
97 protected $firstPageWritten = false;
98 protected $lastPageWritten = false;
99 protected $checkpointJustWritten = false;
100 protected $checkpointFiles = [];
103 * @var IMaintainableDatabase
108 * @param array|null $args For backward compatibility
110 function __construct( $args = null ) {
111 parent
::__construct();
113 $this->addDescription( <<<TEXT
114 This script postprocesses XML dumps from dumpBackup.php to add
115 page text which was stubbed out (using --stub).
117 XML input is accepted on stdin.
118 XML output is sent to stdout; progress reports are sent to stderr.
121 $this->stderr
= fopen( "php://stderr", "wt" );
123 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
124 'Specify as --stub=<type>:<file>.', false, true );
125 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
126 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
128 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
129 'out complete page, closing xml file properly, and opening new one' .
130 'with header). This option requires the checkpointfile option.', false, true );
131 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
132 'first pageid written for the first %s (required) and the last pageid written for the ' .
133 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
134 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
135 $this->addOption( 'full', 'Dump all revisions of every page' );
136 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
137 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records, optionally specify ' .
138 'php[,mwscript] paths' );
139 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
140 '(Default: 512KB, Minimum: 4KB)', false, true );
143 $this->loadWithArgv( $args );
144 $this->processOptions();
149 * @return SqlBlobStore
151 private function getBlobStore() {
152 return MediaWikiServices
::getInstance()->getBlobStore();
156 $this->processOptions();
160 function processOptions() {
161 parent
::processOptions();
163 if ( $this->hasOption( 'buffersize' ) ) {
164 $this->bufferSize
= max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
167 if ( $this->hasOption( 'prefetch' ) ) {
168 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
169 $this->prefetch
= new BaseDump( $url );
172 if ( $this->hasOption( 'stub' ) ) {
173 $this->input
= $this->processFileOpt( $this->getOption( 'stub' ) );
176 if ( $this->hasOption( 'maxtime' ) ) {
177 $this->maxTimeAllowed
= intval( $this->getOption( 'maxtime' ) ) * 60;
180 if ( $this->hasOption( 'checkpointfile' ) ) {
181 $this->checkpointFiles
= $this->getOption( 'checkpointfile' );
184 if ( $this->hasOption( 'current' ) ) {
185 $this->history
= WikiExporter
::CURRENT
;
188 if ( $this->hasOption( 'full' ) ) {
189 $this->history
= WikiExporter
::FULL
;
192 if ( $this->hasOption( 'spawn' ) ) {
194 $val = $this->getOption( 'spawn' );
196 $this->php
= explode( ',', $val, 2 );
202 * Drop the database connection $this->db and try to get a new one.
204 * This function tries to get a /different/ connection if this is
205 * possible. Hence, (if this is possible) it switches to a different
206 * failover upon each call.
208 * This function resets $this->lb and closes all connections on it.
210 * @throws MWException
211 * @suppress PhanTypeObjectUnsetDeclaredProperty
213 function rotateDb() {
214 // Cleaning up old connections
215 if ( isset( $this->lb
) ) {
216 $this->lb
->closeAll();
220 if ( $this->forcedDb
!== null ) {
221 $this->db
= $this->forcedDb
;
226 if ( isset( $this->db
) && $this->db
->isOpen() ) {
227 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
232 // Trying to set up new connection.
233 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
234 // individually retrying at different layers of code.
237 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
238 $this->lb
= $lbFactory->newMainLB();
239 } catch ( Exception
$e ) {
240 throw new MWException( __METHOD__
241 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
245 $this->db
= $this->lb
->getMaintenanceConnectionRef( DB_REPLICA
, 'dump' );
246 } catch ( Exception
$e ) {
247 throw new MWException( __METHOD__
248 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
252 function initProgress( $history = WikiExporter
::FULL
) {
253 parent
::initProgress();
254 $this->timeOfCheckpoint
= $this->startTime
;
257 function dump( $history, $text = WikiExporter
::TEXT
) {
258 // Notice messages will foul up your XML output even if they're
259 // relatively harmless.
260 if ( ini_get( 'display_errors' ) ) {
261 ini_set( 'display_errors', 'stderr' );
264 $this->initProgress( $this->history
);
266 // We are trying to get an initial database connection to avoid that the
267 // first try of this request's first call to getText fails. However, if
268 // obtaining a good DB connection fails it's not a serious issue, as
269 // getText does retry upon failure and can start without having a working
273 } catch ( Exception
$e ) {
274 // We do not even count this as failure. Just let eventual
276 $this->progress( "Getting initial DB connection failed (" .
277 $e->getMessage() . ")" );
280 $this->egress
= new ExportProgressFilter( $this->sink
, $this );
282 // it would be nice to do it in the constructor, oh well. need egress set
283 $this->finalOptionCheck();
285 // we only want this so we know how to close a stream :-P
286 $this->xmlwriterobj
= new XmlDumpWriter( XmlDumpWriter
::WRITE_CONTENT
, $this->schemaVersion
);
288 $input = fopen( $this->input
, "rt" );
289 $this->readDump( $input );
291 if ( $this->spawnProc
) {
295 $this->report( true );
298 function processFileOpt( $opt ) {
299 $split = explode( ':', $opt, 2 );
302 if ( count( $split ) === 2 ) {
305 $fileURIs = explode( ';', $param );
307 foreach ( $fileURIs as $URI ) {
313 $newURI = "compress.zlib://$URI";
316 $newURI = "compress.bzip2://$URI";
319 $newURI = "mediawiki.compress.7z://$URI";
324 $newFileURIs[] = $newURI;
326 $val = implode( ';', $newFileURIs );
332 * Overridden to include prefetch ratio if enabled.
334 function showReport() {
335 if ( !$this->prefetch
) {
336 parent
::showReport();
341 if ( $this->reporting
) {
342 $now = wfTimestamp( TS_DB
);
343 $nowts = microtime( true );
344 $deltaAll = $nowts - $this->startTime
;
345 $deltaPart = $nowts - $this->lastTime
;
346 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
347 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
350 $portion = $this->revCount
/ $this->maxCount
;
351 $eta = $this->startTime +
$deltaAll / $portion;
352 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
353 if ( $this->fetchCount
) {
354 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
358 $pageRate = $this->pageCount
/ $deltaAll;
359 $revRate = $this->revCount
/ $deltaAll;
367 if ( $this->fetchCountLast
) {
368 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
370 $fetchRatePart = '-';
372 $pageRatePart = $this->pageCountPart
/ $deltaPart;
373 $revRatePart = $this->revCountPart
/ $deltaPart;
375 $fetchRatePart = '-';
380 $dbDomain = WikiMap
::getCurrentWikiDbDomain()->getId();
381 $this->progress( sprintf(
382 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
383 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
384 . "prefetched (all|curr), ETA %s [max %d]",
385 $now, $dbDomain, $this->ID
, $this->pageCount
, $pageRate,
386 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
387 $fetchRate, $fetchRatePart, $etats, $this->maxCount
389 $this->lastTime
= $nowts;
390 $this->revCountLast
= $this->revCount
;
391 $this->prefetchCountLast
= $this->prefetchCount
;
392 $this->fetchCountLast
= $this->fetchCount
;
396 function setTimeExceeded() {
397 $this->timeExceeded
= true;
400 function checkIfTimeExceeded() {
401 if ( $this->maxTimeAllowed
402 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
410 function finalOptionCheck() {
411 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
412 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
414 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
416 foreach ( $this->checkpointFiles
as $checkpointFile ) {
417 $count = substr_count( $checkpointFile, "%s" );
419 throw new MWException( "Option checkpointfile must contain two '%s' "
420 . "for substitution of first and last pageids, count is $count instead, "
421 . "file is $checkpointFile.\n" );
425 if ( $this->checkpointFiles
) {
426 $filenameList = (array)$this->egress
->getFilenames();
427 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
428 throw new MWException( "One checkpointfile must be specified "
429 . "for each output option, if maxtime is used.\n" );
435 * @throws MWException Failure to parse XML input
436 * @param resource $input
439 function readDump( $input ) {
441 $this->openElement
= false;
442 $this->atStart
= true;
444 $this->lastName
= "";
447 $this->thisRevModel
= null;
448 $this->thisRevFormat
= null;
450 $parser = xml_parser_create( "UTF-8" );
451 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
453 xml_set_element_handler(
455 [ $this, 'startElement' ],
456 [ $this, 'endElement' ]
458 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
460 $offset = 0; // for context extraction on error reporting
462 if ( $this->checkIfTimeExceeded() ) {
463 $this->setTimeExceeded();
465 $chunk = fread( $input, $this->bufferSize
);
466 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
467 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
469 $byte = xml_get_current_byte_index( $parser );
470 $msg = wfMessage( 'xml-error-string',
471 'XML import parse failure',
472 xml_get_current_line_number( $parser ),
473 xml_get_current_column_number( $parser ),
474 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
475 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
477 xml_parser_free( $parser );
479 throw new MWException( $msg );
481 $offset +
= strlen( $chunk );
482 } while ( $chunk !== false && !feof( $input ) );
483 if ( $this->maxTimeAllowed
) {
484 $filenameList = (array)$this->egress
->getFilenames();
485 // we wrote some stuff after last checkpoint that needs renamed
486 if ( file_exists( $filenameList[0] ) ) {
488 # we might have just written the header and footer and had no
489 # pages or revisions written... perhaps they were all deleted
490 # there's no pageID 0 so we use that. the caller is responsible
491 # for deciding what to do with a file containing only the
492 # siteinfo information and the mw tags.
493 if ( !$this->firstPageWritten
) {
494 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
495 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
497 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
498 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
501 $filenameCount = count( $filenameList );
502 for ( $i = 0; $i < $filenameCount; $i++
) {
503 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
504 $fileinfo = pathinfo( $filenameList[$i] );
505 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
507 $this->egress
->closeAndRename( $newFilenames );
510 xml_parser_free( $parser );
516 * Applies applicable export transformations to $text.
518 * @param string $text
519 * @param string $model
520 * @param string|null $format
524 private function exportTransform( $text, $model, $format = null ) {
526 $handler = ContentHandler
::getForModelID( $model );
527 $text = $handler->exportTransform( $text, $format );
529 catch ( MWException
$ex ) {
531 "Unable to apply export transformation for content model '$model': " .
540 * Tries to load revision text.
541 * Export transformations are applied if the content model is given or can be
542 * determined from the database.
544 * Upon errors, retries (Up to $this->maxFailures tries each call).
545 * If still no good revision could be found even after this retrying, "" is returned.
546 * If no good revision text could be returned for
547 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
550 * @param int|string $id Content address, or text row ID.
551 * @param string|bool|null $model The content model used to determine
552 * applicable export transformations.
553 * If $model is null, it will be determined from the database.
554 * @param string|null $format The content format used when applying export transformations.
556 * @throws MWException
557 * @return string The revision text for $id, or ""
559 function getText( $id, $model = null, $format = null ) {
560 global $wgContentHandlerUseDB;
562 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
563 $text = false; // The candidate for a good text. false if no proper value.
564 $failures = 0; // The number of times, this invocation of getText already failed.
566 // The number of times getText failed without yielding a good text in between.
567 static $consecutiveFailedTextRetrievals = 0;
571 // To allow to simply return on success and do not have to worry about book keeping,
572 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
573 // the old value, so we can restore it, if problems occur (See after the while loop).
574 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
575 $consecutiveFailedTextRetrievals = 0;
577 if ( $model === null && $wgContentHandlerUseDB ) {
578 // TODO: MCR: use content table
579 $row = $this->db
->selectRow(
581 [ 'rev_content_model', 'rev_content_format' ],
582 [ 'rev_id' => $this->thisRev
],
587 $model = $row->rev_content_model
;
588 $format = $row->rev_content_format
;
592 if ( $model === null ||
$model === '' ) {
596 while ( $failures < $this->maxFailures
) {
597 // As soon as we found a good text for the $id, we will return immediately.
598 // Hence, if we make it past the try catch block, we know that we did not
602 // Step 1: Get some text (or reuse from previous iteratuon if checking
603 // for plausibility failed)
605 // Trying to get prefetch, if it has not been tried before
606 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
607 $prefetchNotTried = false;
608 $tryIsPrefetch = true;
609 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
611 if ( $text === null ) {
615 if ( is_string( $text ) && $model !== false ) {
616 // Apply export transformation to text coming from an old dump.
617 // The purpose of this transformation is to convert up from legacy
618 // formats, which may still be used in the older dump that is used
619 // for pre-fetching. Applying the transformation again should not
620 // interfere with content that is already in the correct form.
621 $text = $this->exportTransform( $text, $model, $format );
625 if ( $text === false ) {
626 // Fallback to asking the database
627 $tryIsPrefetch = false;
628 if ( $this->spawn
) {
629 $text = $this->getTextSpawned( $id );
631 $text = $this->getTextDb( $id );
634 if ( $text !== false && $model !== false ) {
635 // Apply export transformation to text coming from the database.
636 // Prefetched text should already have transformations applied.
637 $text = $this->exportTransform( $text, $model, $format );
640 // No more checks for texts from DB for now.
641 // If we received something that is not false,
642 // We treat it as good text, regardless of whether it actually is or is not
643 if ( $text !== false ) {
648 if ( $text === false ) {
649 throw new MWException( "Generic error while obtaining text for id " . $id );
652 // We received a good candidate for the text of $id via some method
654 // Step 2: Checking for plausibility and return the text if it is
656 $revID = intval( $this->thisRev
);
657 if ( !isset( $this->db
) ) {
658 throw new MWException( "No database available" );
661 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
662 $revLength = strlen( $text );
664 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
667 if ( strlen( $text ) == $revLength ) {
668 if ( $tryIsPrefetch ) {
669 $this->prefetchCount++
;
676 throw new MWException( "Received text is unplausible for id " . $id );
677 } catch ( Exception
$e ) {
678 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
679 if ( $failures +
1 < $this->maxFailures
) {
680 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
682 $this->progress( $msg );
685 // Something went wrong; we did not a text that was plausible :(
688 // A failure in a prefetch hit does not warrant resetting db connection etc.
689 if ( !$tryIsPrefetch ) {
690 // After backing off for some time, we try to reboot the whole process as
691 // much as possible to not carry over failures from one part to the other
693 sleep( $this->failureTimeout
);
696 if ( $this->spawn
) {
700 } catch ( Exception
$e ) {
701 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
702 " Trying to continue anyways" );
707 // Retirieving a good text for $id failed (at least) maxFailures times.
708 // We abort for this $id.
710 // Restoring the consecutive failures, and maybe aborting, if the dump
712 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
713 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
714 throw new MWException( "Graceful storage failure" );
721 * Loads the serialized content from storage.
723 * @param int|string $id Content address, or text row ID.
724 * @return bool|string
726 private function getTextDb( $id ) {
727 $store = $this->getBlobStore();
728 $address = ( is_int( $id ) ||
strpos( $id, ':' ) === false )
729 ? SqlBlobStore
::makeAddressFromTextId( (int)$id )
733 $text = $store->getBlob( $address );
735 $stripped = str_replace( "\r", "", $text );
736 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()
737 ->normalize( $stripped );
740 } catch ( BlobAccessException
$ex ) {
741 // XXX: log a warning?
747 * @param int|string $address Content address, or text row ID.
748 * @return bool|string
750 private function getTextSpawned( $address ) {
751 Wikimedia\
suppressWarnings();
752 if ( !$this->spawnProc
) {
756 $text = $this->getTextSpawnedOnce( $address );
757 Wikimedia\restoreWarnings
();
762 function openSpawn() {
765 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
766 if ( count( $this->php
) == 2 ) {
767 $mwscriptpath = $this->php
[1];
769 $mwscriptpath = "$IP/../multiversion/MWScript.php";
771 if ( file_exists( $mwscriptpath ) ) {
773 array_map( [ Shell
::class, 'escape' ],
778 '--wiki', $wiki ] ) );
781 array_map( [ Shell
::class, 'escape' ],
784 "$IP/maintenance/fetchText.php",
785 '--wiki', $wiki ] ) );
788 0 => [ "pipe", "r" ],
789 1 => [ "pipe", "w" ],
790 2 => [ "file", "/dev/null", "a" ] ];
793 $this->progress( "Spawning database subprocess: $cmd" );
794 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
795 if ( !$this->spawnProc
) {
796 $this->progress( "Subprocess spawn failed." );
801 $this->spawnWrite
, // -> stdin
802 $this->spawnRead
, // <- stdout
808 private function closeSpawn() {
809 Wikimedia\
suppressWarnings();
810 if ( $this->spawnRead
) {
811 fclose( $this->spawnRead
);
813 $this->spawnRead
= null;
814 if ( $this->spawnWrite
) {
815 fclose( $this->spawnWrite
);
817 $this->spawnWrite
= null;
818 if ( $this->spawnErr
) {
819 fclose( $this->spawnErr
);
821 $this->spawnErr
= false;
822 if ( $this->spawnProc
) {
823 pclose( $this->spawnProc
);
825 $this->spawnProc
= false;
826 Wikimedia\restoreWarnings
();
830 * @param int|string $address Content address, or text row ID.
831 * @return bool|string
833 private function getTextSpawnedOnce( $address ) {
834 if ( is_int( $address ) ||
intval( $address ) ) {
835 $address = SqlBlobStore
::makeAddressFromTextId( (int)$address );
838 $ok = fwrite( $this->spawnWrite
, "$address\n" );
839 // $this->progress( ">> $id" );
844 $ok = fflush( $this->spawnWrite
);
845 // $this->progress( ">> [flush]" );
850 // check that the text address they are sending is the one we asked for
851 // this avoids out of sync revision text errors we have encountered in the past
852 $newAddress = fgets( $this->spawnRead
);
853 if ( $newAddress === false ) {
856 $newAddress = trim( $newAddress );
857 if ( strpos( $newAddress, ':' ) === false ) {
858 $newAddress = SqlBlobStore
::makeAddressFromTextId( intval( $newAddress ) );
861 if ( $newAddress !== $address ) {
865 $len = fgets( $this->spawnRead
);
866 // $this->progress( "<< " . trim( $len ) );
867 if ( $len === false ) {
871 $nbytes = intval( $len );
872 // actual error, not zero-length text
879 // Subprocess may not send everything at once, we have to loop.
880 while ( $nbytes > strlen( $text ) ) {
881 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
882 if ( $buffer === false ) {
888 $gotbytes = strlen( $text );
889 if ( $gotbytes != $nbytes ) {
890 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
895 // Do normalization in the dump thread...
896 $stripped = str_replace( "\r", "", $text );
897 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()->
898 normalize( $stripped );
903 function startElement( $parser, $name, $attribs ) {
904 $this->checkpointJustWritten
= false;
906 $this->clearOpenElement( null );
907 $this->lastName
= $name;
909 if ( $name == 'revision' ) {
910 $this->state
= $name;
911 $this->egress
->writeOpenPage( null, $this->buffer
);
913 } elseif ( $name == 'page' ) {
914 $this->state
= $name;
915 if ( $this->atStart
) {
916 $this->egress
->writeOpenStream( $this->buffer
);
918 $this->atStart
= false;
922 if ( $name == "text" && isset( $attribs['id'] ) ) {
923 $id = $attribs['id'];
924 $model = trim( $this->thisRevModel
);
925 $format = trim( $this->thisRevFormat
);
927 $model = $model === '' ?
null : $model;
928 $format = $format === '' ?
null : $format;
930 $text = $this->getText( $id, $model, $format );
931 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
932 if ( strlen( $text ) > 0 ) {
933 $this->characterData( $parser, $text );
936 $this->openElement
= [ $name, $attribs ];
940 function endElement( $parser, $name ) {
941 $this->checkpointJustWritten
= false;
943 if ( $this->openElement
) {
944 $this->clearOpenElement( "" );
946 $this->buffer
.= "</$name>";
949 if ( $name == 'revision' ) {
950 $this->egress
->writeRevision( null, $this->buffer
);
953 $this->thisRevModel
= null;
954 $this->thisRevFormat
= null;
955 } elseif ( $name == 'page' ) {
956 if ( !$this->firstPageWritten
) {
957 $this->firstPageWritten
= trim( $this->thisPage
);
959 $this->lastPageWritten
= trim( $this->thisPage
);
960 if ( $this->timeExceeded
) {
961 $this->egress
->writeClosePage( $this->buffer
);
962 // nasty hack, we can't just write the chardata after the
963 // page tag, it will include leading blanks from the next line
964 $this->egress
->sink
->write( "\n" );
966 $this->buffer
= $this->xmlwriterobj
->closeStream();
967 $this->egress
->writeCloseStream( $this->buffer
);
970 $this->thisPage
= "";
971 // this could be more than one file if we had more than one output arg
973 $filenameList = (array)$this->egress
->getFilenames();
975 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
976 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
977 $filenamesCount = count( $filenameList );
978 for ( $i = 0; $i < $filenamesCount; $i++
) {
979 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
980 $fileinfo = pathinfo( $filenameList[$i] );
981 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
983 $this->egress
->closeRenameAndReopen( $newFilenames );
984 $this->buffer
= $this->xmlwriterobj
->openStream();
985 $this->timeExceeded
= false;
986 $this->timeOfCheckpoint
= $this->lastTime
;
987 $this->firstPageWritten
= false;
988 $this->checkpointJustWritten
= true;
990 $this->egress
->writeClosePage( $this->buffer
);
992 $this->thisPage
= "";
994 } elseif ( $name == 'mediawiki' ) {
995 $this->egress
->writeCloseStream( $this->buffer
);
1000 function characterData( $parser, $data ) {
1001 $this->clearOpenElement( null );
1002 if ( $this->lastName
== "id" ) {
1003 if ( $this->state
== "revision" ) {
1004 $this->thisRev
.= $data;
1005 } elseif ( $this->state
== "page" ) {
1006 $this->thisPage
.= $data;
1008 } elseif ( $this->lastName
== "model" ) {
1009 $this->thisRevModel
.= $data;
1010 } elseif ( $this->lastName
== "format" ) {
1011 $this->thisRevFormat
.= $data;
1014 // have to skip the newline left over from closepagetag line of
1015 // end of checkpoint files. nasty hack!!
1016 if ( $this->checkpointJustWritten
) {
1017 if ( $data[0] == "\n" ) {
1018 $data = substr( $data, 1 );
1020 $this->checkpointJustWritten
= false;
1022 $this->buffer
.= htmlspecialchars( $data );
1025 function clearOpenElement( $style ) {
1026 if ( $this->openElement
) {
1027 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
1028 $this->openElement
= false;