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 = false;
84 protected $spawnRead = false;
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 );
306 foreach ( $fileURIs as $URI ) {
312 $newURI = "compress.zlib://$URI";
315 $newURI = "compress.bzip2://$URI";
318 $newURI = "mediawiki.compress.7z://$URI";
323 $newFileURIs[] = $newURI;
325 $val = implode( ';', $newFileURIs );
331 * Overridden to include prefetch ratio if enabled.
333 function showReport() {
334 if ( !$this->prefetch
) {
335 parent
::showReport();
340 if ( $this->reporting
) {
341 $now = wfTimestamp( TS_DB
);
342 $nowts = microtime( true );
343 $deltaAll = $nowts - $this->startTime
;
344 $deltaPart = $nowts - $this->lastTime
;
345 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
346 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
349 $portion = $this->revCount
/ $this->maxCount
;
350 $eta = $this->startTime +
$deltaAll / $portion;
351 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
352 if ( $this->fetchCount
) {
353 $fetchRate = 100.0 * $this->prefetchCount
/ $this->fetchCount
;
357 $pageRate = $this->pageCount
/ $deltaAll;
358 $revRate = $this->revCount
/ $deltaAll;
366 if ( $this->fetchCountLast
) {
367 $fetchRatePart = 100.0 * $this->prefetchCountLast
/ $this->fetchCountLast
;
369 $fetchRatePart = '-';
371 $pageRatePart = $this->pageCountPart
/ $deltaPart;
372 $revRatePart = $this->revCountPart
/ $deltaPart;
374 $fetchRatePart = '-';
379 $dbDomain = WikiMap
::getCurrentWikiDbDomain()->getId();
380 $this->progress( sprintf(
381 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
382 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
383 . "prefetched (all|curr), ETA %s [max %d]",
384 $now, $dbDomain, $this->ID
, $this->pageCount
, $pageRate,
385 $pageRatePart, $this->revCount
, $revRate, $revRatePart,
386 $fetchRate, $fetchRatePart, $etats, $this->maxCount
388 $this->lastTime
= $nowts;
389 $this->revCountLast
= $this->revCount
;
390 $this->prefetchCountLast
= $this->prefetchCount
;
391 $this->fetchCountLast
= $this->fetchCount
;
395 function setTimeExceeded() {
396 $this->timeExceeded
= true;
399 function checkIfTimeExceeded() {
400 if ( $this->maxTimeAllowed
401 && ( $this->lastTime
- $this->timeOfCheckpoint
> $this->maxTimeAllowed
)
409 function finalOptionCheck() {
410 if ( ( $this->checkpointFiles
&& !$this->maxTimeAllowed
)
411 ||
( $this->maxTimeAllowed
&& !$this->checkpointFiles
)
413 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
415 foreach ( $this->checkpointFiles
as $checkpointFile ) {
416 $count = substr_count( $checkpointFile, "%s" );
418 throw new MWException( "Option checkpointfile must contain two '%s' "
419 . "for substitution of first and last pageids, count is $count instead, "
420 . "file is $checkpointFile.\n" );
424 if ( $this->checkpointFiles
) {
425 $filenameList = (array)$this->egress
->getFilenames();
426 if ( count( $filenameList ) != count( $this->checkpointFiles
) ) {
427 throw new MWException( "One checkpointfile must be specified "
428 . "for each output option, if maxtime is used.\n" );
434 * @throws MWException Failure to parse XML input
435 * @param resource $input
438 function readDump( $input ) {
440 $this->openElement
= false;
441 $this->atStart
= true;
443 $this->lastName
= "";
446 $this->thisRevModel
= null;
447 $this->thisRevFormat
= null;
449 $parser = xml_parser_create( "UTF-8" );
450 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
452 xml_set_element_handler(
454 [ $this, 'startElement' ],
455 [ $this, 'endElement' ]
457 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
459 $offset = 0; // for context extraction on error reporting
461 if ( $this->checkIfTimeExceeded() ) {
462 $this->setTimeExceeded();
464 $chunk = fread( $input, $this->bufferSize
);
465 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
466 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
468 $byte = xml_get_current_byte_index( $parser );
469 $msg = wfMessage( 'xml-error-string',
470 'XML import parse failure',
471 xml_get_current_line_number( $parser ),
472 xml_get_current_column_number( $parser ),
473 $byte . ( is_null( $chunk ) ?
null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
474 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
476 xml_parser_free( $parser );
478 throw new MWException( $msg );
480 $offset +
= strlen( $chunk );
481 } while ( $chunk !== false && !feof( $input ) );
482 if ( $this->maxTimeAllowed
) {
483 $filenameList = (array)$this->egress
->getFilenames();
484 // we wrote some stuff after last checkpoint that needs renamed
485 if ( file_exists( $filenameList[0] ) ) {
487 # we might have just written the header and footer and had no
488 # pages or revisions written... perhaps they were all deleted
489 # there's no pageID 0 so we use that. the caller is responsible
490 # for deciding what to do with a file containing only the
491 # siteinfo information and the mw tags.
492 if ( !$this->firstPageWritten
) {
493 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
494 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT
);
496 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
497 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
500 $filenameCount = count( $filenameList );
501 for ( $i = 0; $i < $filenameCount; $i++
) {
502 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
503 $fileinfo = pathinfo( $filenameList[$i] );
504 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
506 $this->egress
->closeAndRename( $newFilenames );
509 xml_parser_free( $parser );
515 * Applies applicable export transformations to $text.
517 * @param string $text
518 * @param string $model
519 * @param string|null $format
523 private function exportTransform( $text, $model, $format = null ) {
525 $handler = ContentHandler
::getForModelID( $model );
526 $text = $handler->exportTransform( $text, $format );
528 catch ( MWException
$ex ) {
530 "Unable to apply export transformation for content model '$model': " .
539 * Tries to load revision text.
540 * Export transformations are applied if the content model is given or can be
541 * determined from the database.
543 * Upon errors, retries (Up to $this->maxFailures tries each call).
544 * If still no good revision could be found even after this retrying, "" is returned.
545 * If no good revision text could be returned for
546 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
549 * @param int|string $id Content address, or text row ID.
550 * @param string|bool|null $model The content model used to determine
551 * applicable export transformations.
552 * If $model is null, it will be determined from the database.
553 * @param string|null $format The content format used when applying export transformations.
555 * @throws MWException
556 * @return string The revision text for $id, or ""
558 function getText( $id, $model = null, $format = null ) {
559 global $wgContentHandlerUseDB;
561 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
562 $text = false; // The candidate for a good text. false if no proper value.
563 $failures = 0; // The number of times, this invocation of getText already failed.
565 // The number of times getText failed without yielding a good text in between.
566 static $consecutiveFailedTextRetrievals = 0;
570 // To allow to simply return on success and do not have to worry about book keeping,
571 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
572 // the old value, so we can restore it, if problems occur (See after the while loop).
573 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
574 $consecutiveFailedTextRetrievals = 0;
576 if ( $model === null && $wgContentHandlerUseDB ) {
577 // TODO: MCR: use content table
578 $row = $this->db
->selectRow(
580 [ 'rev_content_model', 'rev_content_format' ],
581 [ 'rev_id' => $this->thisRev
],
586 $model = $row->rev_content_model
;
587 $format = $row->rev_content_format
;
591 if ( $model === null ||
$model === '' ) {
595 while ( $failures < $this->maxFailures
) {
596 // As soon as we found a good text for the $id, we will return immediately.
597 // Hence, if we make it past the try catch block, we know that we did not
601 // Step 1: Get some text (or reuse from previous iteratuon if checking
602 // for plausibility failed)
604 // Trying to get prefetch, if it has not been tried before
605 if ( $text === false && isset( $this->prefetch
) && $prefetchNotTried ) {
606 $prefetchNotTried = false;
607 $tryIsPrefetch = true;
608 $text = $this->prefetch
->prefetch( (int)$this->thisPage
, (int)$this->thisRev
);
610 if ( $text === null ) {
614 if ( is_string( $text ) && $model !== false ) {
615 // Apply export transformation to text coming from an old dump.
616 // The purpose of this transformation is to convert up from legacy
617 // formats, which may still be used in the older dump that is used
618 // for pre-fetching. Applying the transformation again should not
619 // interfere with content that is already in the correct form.
620 $text = $this->exportTransform( $text, $model, $format );
624 if ( $text === false ) {
625 // Fallback to asking the database
626 $tryIsPrefetch = false;
627 if ( $this->spawn
) {
628 $text = $this->getTextSpawned( $id );
630 $text = $this->getTextDb( $id );
633 if ( $text !== false && $model !== false ) {
634 // Apply export transformation to text coming from the database.
635 // Prefetched text should already have transformations applied.
636 $text = $this->exportTransform( $text, $model, $format );
639 // No more checks for texts from DB for now.
640 // If we received something that is not false,
641 // We treat it as good text, regardless of whether it actually is or is not
642 if ( $text !== false ) {
647 if ( $text === false ) {
648 throw new MWException( "Generic error while obtaining text for id " . $id );
651 // We received a good candidate for the text of $id via some method
653 // Step 2: Checking for plausibility and return the text if it is
655 $revID = intval( $this->thisRev
);
656 if ( !isset( $this->db
) ) {
657 throw new MWException( "No database available" );
660 if ( $model !== CONTENT_MODEL_WIKITEXT
) {
661 $revLength = strlen( $text );
663 $revLength = $this->db
->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
666 if ( strlen( $text ) == $revLength ) {
667 if ( $tryIsPrefetch ) {
668 $this->prefetchCount++
;
675 throw new MWException( "Received text is unplausible for id " . $id );
676 } catch ( Exception
$e ) {
677 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
678 if ( $failures +
1 < $this->maxFailures
) {
679 $msg .= " (Will retry " . ( $this->maxFailures
- $failures - 1 ) . " more times)";
681 $this->progress( $msg );
684 // Something went wrong; we did not a text that was plausible :(
687 // A failure in a prefetch hit does not warrant resetting db connection etc.
688 if ( !$tryIsPrefetch ) {
689 // After backing off for some time, we try to reboot the whole process as
690 // much as possible to not carry over failures from one part to the other
692 sleep( $this->failureTimeout
);
695 if ( $this->spawn
) {
699 } catch ( Exception
$e ) {
700 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
701 " Trying to continue anyways" );
706 // Retirieving a good text for $id failed (at least) maxFailures times.
707 // We abort for this $id.
709 // Restoring the consecutive failures, and maybe aborting, if the dump
711 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals +
1;
712 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals
) {
713 throw new MWException( "Graceful storage failure" );
720 * Loads the serialized content from storage.
722 * @param int|string $id Content address, or text row ID.
723 * @return bool|string
725 private function getTextDb( $id ) {
726 $store = $this->getBlobStore();
727 $address = ( is_int( $id ) ||
strpos( $id, ':' ) === false )
728 ? SqlBlobStore
::makeAddressFromTextId( (int)$id )
732 $text = $store->getBlob( $address );
734 $stripped = str_replace( "\r", "", $text );
735 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()
736 ->normalize( $stripped );
739 } catch ( BlobAccessException
$ex ) {
740 // XXX: log a warning?
746 * @param int|string $address Content address, or text row ID.
747 * @return bool|string
749 private function getTextSpawned( $address ) {
750 Wikimedia\
suppressWarnings();
751 if ( !$this->spawnProc
) {
755 $text = $this->getTextSpawnedOnce( $address );
756 Wikimedia\restoreWarnings
();
761 function openSpawn() {
764 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
765 if ( count( $this->php
) == 2 ) {
766 $mwscriptpath = $this->php
[1];
768 $mwscriptpath = "$IP/../multiversion/MWScript.php";
770 if ( file_exists( $mwscriptpath ) ) {
772 array_map( [ Shell
::class, 'escape' ],
777 '--wiki', $wiki ] ) );
780 array_map( [ Shell
::class, 'escape' ],
783 "$IP/maintenance/fetchText.php",
784 '--wiki', $wiki ] ) );
787 0 => [ "pipe", "r" ],
788 1 => [ "pipe", "w" ],
789 2 => [ "file", "/dev/null", "a" ] ];
792 $this->progress( "Spawning database subprocess: $cmd" );
793 $this->spawnProc
= proc_open( $cmd, $spec, $pipes );
794 if ( !$this->spawnProc
) {
795 $this->progress( "Subprocess spawn failed." );
800 $this->spawnWrite
, // -> stdin
801 $this->spawnRead
, // <- stdout
807 private function closeSpawn() {
808 Wikimedia\
suppressWarnings();
809 if ( $this->spawnRead
) {
810 fclose( $this->spawnRead
);
812 $this->spawnRead
= false;
813 if ( $this->spawnWrite
) {
814 fclose( $this->spawnWrite
);
816 $this->spawnWrite
= false;
817 if ( $this->spawnErr
) {
818 fclose( $this->spawnErr
);
820 $this->spawnErr
= false;
821 if ( $this->spawnProc
) {
822 pclose( $this->spawnProc
);
824 $this->spawnProc
= false;
825 Wikimedia\restoreWarnings
();
829 * @param int|string $address Content address, or text row ID.
830 * @return bool|string
832 private function getTextSpawnedOnce( $address ) {
833 if ( is_int( $address ) ||
intval( $address ) ) {
834 $address = SqlBlobStore
::makeAddressFromTextId( (int)$address );
837 $ok = fwrite( $this->spawnWrite
, "$address\n" );
838 // $this->progress( ">> $id" );
843 $ok = fflush( $this->spawnWrite
);
844 // $this->progress( ">> [flush]" );
849 // check that the text address they are sending is the one we asked for
850 // this avoids out of sync revision text errors we have encountered in the past
851 $newAddress = fgets( $this->spawnRead
);
852 if ( $newAddress === false ) {
855 $newAddress = trim( $newAddress );
856 if ( strpos( $newAddress, ':' ) === false ) {
857 $newAddress = SqlBlobStore
::makeAddressFromTextId( intval( $newAddress ) );
860 if ( $newAddress !== $address ) {
864 $len = fgets( $this->spawnRead
);
865 // $this->progress( "<< " . trim( $len ) );
866 if ( $len === false ) {
870 $nbytes = intval( $len );
871 // actual error, not zero-length text
878 // Subprocess may not send everything at once, we have to loop.
879 while ( $nbytes > strlen( $text ) ) {
880 $buffer = fread( $this->spawnRead
, $nbytes - strlen( $text ) );
881 if ( $buffer === false ) {
887 $gotbytes = strlen( $text );
888 if ( $gotbytes != $nbytes ) {
889 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
894 // Do normalization in the dump thread...
895 $stripped = str_replace( "\r", "", $text );
896 $normalized = MediaWikiServices
::getInstance()->getContentLanguage()->
897 normalize( $stripped );
902 function startElement( $parser, $name, $attribs ) {
903 $this->checkpointJustWritten
= false;
905 $this->clearOpenElement( null );
906 $this->lastName
= $name;
908 if ( $name == 'revision' ) {
909 $this->state
= $name;
910 $this->egress
->writeOpenPage( null, $this->buffer
);
912 } elseif ( $name == 'page' ) {
913 $this->state
= $name;
914 if ( $this->atStart
) {
915 $this->egress
->writeOpenStream( $this->buffer
);
917 $this->atStart
= false;
921 if ( $name == "text" && isset( $attribs['id'] ) ) {
922 $id = $attribs['id'];
923 $model = trim( $this->thisRevModel
);
924 $format = trim( $this->thisRevFormat
);
926 $model = $model === '' ?
null : $model;
927 $format = $format === '' ?
null : $format;
929 $text = $this->getText( $id, $model, $format );
930 $this->openElement
= [ $name, [ 'xml:space' => 'preserve' ] ];
931 if ( strlen( $text ) > 0 ) {
932 $this->characterData( $parser, $text );
935 $this->openElement
= [ $name, $attribs ];
939 function endElement( $parser, $name ) {
940 $this->checkpointJustWritten
= false;
942 if ( $this->openElement
) {
943 $this->clearOpenElement( "" );
945 $this->buffer
.= "</$name>";
948 if ( $name == 'revision' ) {
949 $this->egress
->writeRevision( null, $this->buffer
);
952 $this->thisRevModel
= null;
953 $this->thisRevFormat
= null;
954 } elseif ( $name == 'page' ) {
955 if ( !$this->firstPageWritten
) {
956 $this->firstPageWritten
= trim( $this->thisPage
);
958 $this->lastPageWritten
= trim( $this->thisPage
);
959 if ( $this->timeExceeded
) {
960 $this->egress
->writeClosePage( $this->buffer
);
961 // nasty hack, we can't just write the chardata after the
962 // page tag, it will include leading blanks from the next line
963 $this->egress
->sink
->write( "\n" );
965 $this->buffer
= $this->xmlwriterobj
->closeStream();
966 $this->egress
->writeCloseStream( $this->buffer
);
969 $this->thisPage
= "";
970 // this could be more than one file if we had more than one output arg
972 $filenameList = (array)$this->egress
->getFilenames();
974 $firstPageID = str_pad( $this->firstPageWritten
, 9, "0", STR_PAD_LEFT
);
975 $lastPageID = str_pad( $this->lastPageWritten
, 9, "0", STR_PAD_LEFT
);
976 $filenamesCount = count( $filenameList );
977 for ( $i = 0; $i < $filenamesCount; $i++
) {
978 $checkpointNameFilledIn = sprintf( $this->checkpointFiles
[$i], $firstPageID, $lastPageID );
979 $fileinfo = pathinfo( $filenameList[$i] );
980 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
982 $this->egress
->closeRenameAndReopen( $newFilenames );
983 $this->buffer
= $this->xmlwriterobj
->openStream();
984 $this->timeExceeded
= false;
985 $this->timeOfCheckpoint
= $this->lastTime
;
986 $this->firstPageWritten
= false;
987 $this->checkpointJustWritten
= true;
989 $this->egress
->writeClosePage( $this->buffer
);
991 $this->thisPage
= "";
993 } elseif ( $name == 'mediawiki' ) {
994 $this->egress
->writeCloseStream( $this->buffer
);
999 function characterData( $parser, $data ) {
1000 $this->clearOpenElement( null );
1001 if ( $this->lastName
== "id" ) {
1002 if ( $this->state
== "revision" ) {
1003 $this->thisRev
.= $data;
1004 } elseif ( $this->state
== "page" ) {
1005 $this->thisPage
.= $data;
1007 } elseif ( $this->lastName
== "model" ) {
1008 $this->thisRevModel
.= $data;
1009 } elseif ( $this->lastName
== "format" ) {
1010 $this->thisRevFormat
.= $data;
1013 // have to skip the newline left over from closepagetag line of
1014 // end of checkpoint files. nasty hack!!
1015 if ( $this->checkpointJustWritten
) {
1016 if ( $data[0] == "\n" ) {
1017 $data = substr( $data, 1 );
1019 $this->checkpointJustWritten
= false;
1021 $this->buffer
.= htmlspecialchars( $data );
1024 function clearOpenElement( $style ) {
1025 if ( $this->openElement
) {
1026 $this->buffer
.= Xml
::element( $this->openElement
[0], $this->openElement
[1], $style );
1027 $this->openElement
= false;