28require_once __DIR__ .
'/BackupDumper.php';
29require_once __DIR__ .
'/SevenZipStream.php';
30require_once __DIR__ .
'/../../includes/export/WikiExporter.php';
71 protected $php = [ PHP_BINARY ];
115 parent::__construct();
118This script postprocesses XML dumps from dumpBackup.php to add
119page text which was stubbed out (
using --stub).
121XML input is accepted on stdin.
125 $this->stderr = fopen(
"php://stderr",
"wt" );
127 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
128 'Specify as --stub=<type>:<file>.',
false,
true );
129 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
130 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
132 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
133 'out complete page, closing xml file properly, and opening new one' .
134 'with header). This option requires the checkpointfile option.',
false,
true );
135 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
136 'first pageid written for the first %s (required) and the last pageid written for the ' .
137 'second %s if it exists.',
false,
true,
false,
true );
138 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
139 $this->
addOption(
'full',
'Dump all revisions of every page' );
140 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
141 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records, optionally specify ' .
142 'php[,mwscript] paths' );
143 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
144 '(Default: 512KB, Minimum: 4KB)',
false,
true );
156 return MediaWikiServices::getInstance()->getBlobStore();
165 parent::processOptions();
167 if ( $this->
hasOption(
'buffersize' ) ) {
168 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
173 $this->prefetch =
new BaseDump( $url );
181 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
184 if ( $this->
hasOption(
'checkpointfile' ) ) {
185 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
200 $this->php = explode(
',', $val, 2 );
219 if ( isset( $this->lb ) ) {
220 $this->lb->closeAll( __METHOD__ );
224 if ( $this->forcedDb !==
null ) {
230 if ( isset( $this->db ) && $this->db->isOpen() ) {
231 throw new MWException(
'DB is set and has not been closed by the Load Balancer' );
241 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
242 $this->lb = $lbFactory->newMainLB();
243 }
catch ( Exception $e ) {
245 .
" rotating DB failed to obtain new load balancer (" . $e->getMessage() .
")" );
249 $this->db = $this->lb->getMaintenanceConnectionRef(
DB_REPLICA,
'dump' );
250 }
catch ( Exception $e ) {
252 .
" rotating DB failed to obtain new database (" . $e->getMessage() .
")" );
257 parent::initProgress();
264 if ( ini_get(
'display_errors' ) ) {
265 ini_set(
'display_errors',
'stderr' );
277 }
catch ( Exception $e ) {
280 $this->
progress(
"Getting initial DB connection failed (" .
281 $e->getMessage() .
")" );
290 $this->xmlwriterobj =
new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
292 $input = fopen( $this->input,
"rt" );
295 if ( $this->spawnProc ) {
303 $split = explode(
':', $opt, 2 );
306 if ( count( $split ) === 2 ) {
309 $fileURIs = explode(
';', $param );
311 foreach ( $fileURIs as $URI ) {
317 $newURI =
"compress.zlib://$URI";
320 $newURI =
"compress.bzip2://$URI";
323 $newURI =
"mediawiki.compress.7z://$URI";
328 $newFileURIs[] = $newURI;
330 $val = implode(
';', $newFileURIs );
339 if ( !$this->prefetch ) {
340 parent::showReport();
345 if ( $this->reporting ) {
347 $nowts = microtime(
true );
355 $eta = $this->startTime + $deltaAll / $portion;
357 if ( $this->fetchCount ) {
362 $pageRate = $this->pageCount / $deltaAll;
363 $revRate = $this->
revCount / $deltaAll;
371 if ( $this->fetchCountLast ) {
374 $fetchRatePart =
'-';
376 $pageRatePart = $this->pageCountPart / $deltaPart;
377 $revRatePart = $this->revCountPart / $deltaPart;
379 $fetchRatePart =
'-';
384 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
386 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
387 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
388 .
"prefetched (all|curr), ETA %s [max %d]",
389 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
390 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
391 $fetchRate, $fetchRatePart, $etats, $this->maxCount
393 $this->lastTime = $nowts;
401 $this->timeExceeded =
true;
405 if ( $this->maxTimeAllowed
406 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
415 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
416 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
418 throw new MWException(
"Options checkpointfile and maxtime must be specified together.\n" );
420 foreach ( $this->checkpointFiles as $checkpointFile ) {
421 $count = substr_count( $checkpointFile,
"%s" );
423 throw new MWException(
"Option checkpointfile must contain two '%s' "
424 .
"for substitution of first and last pageids, count is $count instead, "
425 .
"file is $checkpointFile.\n" );
429 if ( $this->checkpointFiles ) {
430 $filenameList = (array)$this->egress->getFilenames();
431 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
432 throw new MWException(
"One checkpointfile must be specified "
433 .
"for each output option, if maxtime is used.\n" );
445 $this->openElement =
false;
446 $this->atStart =
true;
448 $this->lastName =
"";
451 $this->thisRole =
null;
452 $this->thisRevModel =
null;
453 $this->thisRevFormat =
null;
455 $parser = xml_parser_create(
"UTF-8" );
456 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING,
false );
458 xml_set_element_handler(
460 [ $this,
'startElement' ],
461 [ $this,
'endElement' ]
463 xml_set_character_data_handler( $parser, [ $this,
'characterData' ] );
470 $chunk = fread(
$input, $this->bufferSize );
471 if ( !xml_parse( $parser, $chunk, feof(
$input ) ) ) {
472 wfDebug(
"TextDumpPass::readDump encountered XML parsing error" );
474 $byte = xml_get_current_byte_index( $parser );
476 'XML import parse failure',
477 xml_get_current_line_number( $parser ),
478 xml_get_current_column_number( $parser ),
479 $byte . ( $chunk ===
null ?
null : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
480 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
482 xml_parser_free( $parser );
486 $offset += strlen( $chunk );
487 }
while ( $chunk !==
false && !feof(
$input ) );
488 if ( $this->maxTimeAllowed ) {
489 $filenameList = (array)$this->egress->getFilenames();
491 if ( file_exists( $filenameList[0] ) ) {
493 # we might have just written the header and footer and had no
494 # pages or revisions written... perhaps they were all deleted
495 # there's no pageID 0 so we use that. the caller is responsible
496 # for deciding what to do with a file containing only the
497 # siteinfo information and the mw tags.
498 if ( !$this->firstPageWritten ) {
499 $firstPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
500 $lastPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
502 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
503 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
506 $filenameCount = count( $filenameList );
507 for ( $i = 0; $i < $filenameCount; $i++ ) {
508 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
509 $fileinfo = pathinfo( $filenameList[$i] );
510 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
512 $this->egress->closeAndRename( $newFilenames );
515 xml_parser_free( $parser );
531 $text = MediaWikiServices::getInstance()
532 ->getContentHandlerFactory()
533 ->getContentHandler( $model )
534 ->exportTransform( $text, $format );
537 wfWarn(
"Unable to apply export transformation for content model '$model': " .
541 "Unable to apply export transformation for content model '$model': " .
569 protected function getText( $id, $model =
null, $format =
null, $expSize =
null ) {
571 $msg =
"Skipping bad text id " . $id .
" of revision " .
$this->thisRev;
576 $model = $model ?:
null;
577 $prefetchNotTried =
true;
582 static $consecutiveFailedTextRetrievals = 0;
589 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
590 $consecutiveFailedTextRetrievals = 0;
592 while ( $failures < $this->maxFailures ) {
603 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
604 $prefetchNotTried =
false;
605 $tryIsPrefetch =
true;
606 $text = $this->prefetch->prefetch(
607 (
int)$this->thisPage,
609 trim( $this->thisRole )
612 if ( $text ===
null ) {
616 if ( is_string( $text ) && $model !==
null ) {
626 if ( $text ===
false ) {
628 $tryIsPrefetch =
false;
629 if ( $this->spawn ) {
635 if ( $text !==
false && $model !==
null ) {
644 if ( $text !==
false ) {
649 if ( $text ===
false ) {
650 throw new MWException(
"Generic error while obtaining text for id " . $id );
658 if ( $expSize ===
null || strlen( $text ) == $expSize ) {
659 if ( $tryIsPrefetch ) {
660 $this->prefetchCount++;
667 throw new MWException(
"Received text is unplausible for id " . $id );
668 }
catch ( Exception $e ) {
669 $msg =
"getting/checking text " . $id .
" failed (" . $e->getMessage()
671 if ( $failures + 1 < $this->maxFailures ) {
672 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
681 if ( !$tryIsPrefetch ) {
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" );
704 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
705 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
706 throw new MWException(
"Graceful storage failure" );
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 );
743 Wikimedia\suppressWarnings();
744 if ( !$this->spawnProc ) {
749 Wikimedia\restoreWarnings();
757 $wiki = WikiMap::getCurrentWikiId();
758 if ( count( $this->php ) == 2 ) {
759 $mwscriptpath = $this->php[1];
761 $mwscriptpath =
"$IP/../multiversion/MWScript.php";
763 if ( file_exists( $mwscriptpath ) ) {
765 array_map( [ Shell::class,
'escape' ],
770 '--wiki', $wiki ] ) );
773 array_map( [ Shell::class,
'escape' ],
776 "$IP/maintenance/fetchText.php",
777 '--wiki', $wiki ] ) );
780 0 => [
"pipe",
"r" ],
781 1 => [
"pipe",
"w" ],
782 2 => [
"file",
"/dev/null",
"a" ] ];
785 $this->
progress(
"Spawning database subprocess: $cmd" );
786 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
787 if ( !$this->spawnProc ) {
788 $this->
progress(
"Subprocess spawn failed." );
801 Wikimedia\suppressWarnings();
802 if ( $this->spawnRead ) {
803 fclose( $this->spawnRead );
805 $this->spawnRead =
null;
806 if ( $this->spawnWrite ) {
807 fclose( $this->spawnWrite );
809 $this->spawnWrite =
null;
810 if ( $this->spawnErr ) {
811 fclose( $this->spawnErr );
813 $this->spawnErr =
false;
814 if ( $this->spawnProc ) {
815 pclose( $this->spawnProc );
817 $this->spawnProc =
false;
818 Wikimedia\restoreWarnings();
826 if ( is_int( $address ) || intval( $address ) ) {
827 $address = SqlBlobStore::makeAddressFromTextId( (
int)$address );
830 $ok = fwrite( $this->spawnWrite,
"$address\n" );
836 $ok = fflush( $this->spawnWrite );
844 $newAddress = fgets( $this->spawnRead );
845 if ( $newAddress ===
false ) {
848 $newAddress = trim( $newAddress );
849 if ( strpos( $newAddress,
':' ) ===
false ) {
850 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
853 if ( $newAddress !== $address ) {
857 $len = fgets( $this->spawnRead );
859 if ( $len ===
false ) {
863 $nbytes = intval( $len );
872 while ( $nbytes > strlen( $text ) ) {
873 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
880 $gotbytes = strlen( $text );
881 if ( $gotbytes != $nbytes ) {
882 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
888 $stripped = str_replace(
"\r",
"", $text );
889 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
890 normalize( $stripped );
896 $this->checkpointJustWritten =
false;
899 $this->lastName = $name;
901 if ( $name ==
'revision' ) {
902 $this->state = $name;
903 $this->egress->writeOpenPage(
null, $this->buffer );
905 } elseif ( $name ==
'page' ) {
906 $this->state = $name;
907 if ( $this->atStart ) {
908 $this->egress->writeOpenStream( $this->buffer );
910 $this->atStart =
false;
912 } elseif ( $name ===
'mediawiki' ) {
913 if ( isset( $attribs[
'version'] ) ) {
914 if ( $attribs[
'version'] !== $this->schemaVersion ) {
915 throw new MWException(
'Mismatching schema version. '
916 .
'Use the --schema-version option to set the output schema version to '
917 .
'the version declared by the stub file, namely ' . $attribs[
'version'] );
922 if ( $name ==
"text" && ( isset( $attribs[
'id'] ) || isset( $attribs[
'location'] ) ) ) {
923 $id = $attribs[
'location'] ?? $attribs[
'id'];
924 $model = trim( $this->thisRevModel );
925 $format = trim( $this->thisRevFormat );
927 $model = $model ===
'' ? null : $model;
928 $format = $format ===
'' ? null : $format;
930 ? (int)$attribs[
'bytes'] :
null;
932 $text = $this->
getText( $id, $model, $format, $expSize );
934 unset( $attribs[
'id'] );
935 unset( $attribs[
'location'] );
936 if ( strlen( $text ) > 0 ) {
937 $attribs[
'xml:space'] =
'preserve';
940 $this->openElement = [ $name, $attribs ];
941 if ( strlen( $text ) > 0 ) {
945 $this->openElement = [ $name, $attribs ];
950 $this->checkpointJustWritten =
false;
952 if ( $this->openElement ) {
955 $this->buffer .=
"</$name>";
958 if ( $name ==
'revision' ) {
959 $this->egress->writeRevision(
null, $this->buffer );
962 $this->thisRole =
null;
963 $this->thisRevModel =
null;
964 $this->thisRevFormat =
null;
965 } elseif ( $name ==
'page' ) {
966 if ( !$this->firstPageWritten ) {
967 $this->firstPageWritten = trim( $this->thisPage );
969 $this->lastPageWritten = trim( $this->thisPage );
970 if ( $this->timeExceeded ) {
971 $this->egress->writeClosePage( $this->buffer );
974 $this->egress->sink->write(
"\n" );
976 $this->buffer = $this->xmlwriterobj->closeStream();
977 $this->egress->writeCloseStream( $this->buffer );
980 $this->thisPage =
"";
983 $filenameList = (array)$this->egress->getFilenames();
985 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
986 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
987 $filenamesCount = count( $filenameList );
988 for ( $i = 0; $i < $filenamesCount; $i++ ) {
989 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
990 $fileinfo = pathinfo( $filenameList[$i] );
991 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
993 $this->egress->closeRenameAndReopen( $newFilenames );
994 $this->buffer = $this->xmlwriterobj->openStream();
995 $this->timeExceeded =
false;
997 $this->firstPageWritten =
false;
998 $this->checkpointJustWritten =
true;
1000 $this->egress->writeClosePage( $this->buffer );
1002 $this->thisPage =
"";
1004 } elseif ( $name ==
'mediawiki' ) {
1005 $this->egress->writeCloseStream( $this->buffer );
1012 if ( $this->lastName ==
"id" ) {
1013 if ( $this->state ==
"revision" ) {
1014 $this->thisRev .= $data;
1015 $this->thisRole = SlotRecord::MAIN;
1016 } elseif ( $this->state ==
"page" ) {
1017 $this->thisPage .= $data;
1019 } elseif ( $this->lastName ==
"model" ) {
1020 $this->thisRevModel .= $data;
1021 } elseif ( $this->lastName ==
"format" ) {
1022 $this->thisRevFormat .= $data;
1023 } elseif ( $this->lastName ==
"content" ) {
1024 $this->thisRole =
"";
1025 $this->thisRevModel =
"";
1026 $this->thisRevFormat =
"";
1027 } elseif ( $this->lastName ==
"role" ) {
1028 $this->thisRole .= $data;
1033 if ( $this->checkpointJustWritten ) {
1034 if ( $data[0] ==
"\n" ) {
1035 $data = substr( $data, 1 );
1037 $this->checkpointJustWritten =
false;
1039 $this->buffer .= htmlspecialchars( $data );
1043 if ( $this->openElement ) {
1044 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1045 $this->openElement =
false;
1050 if ( preg_match(
'/:/', $id ) ) {
1051 return $id !==
'tt:0';
1052 } elseif ( preg_match(
'/^\d+$/', $id ) ) {
1053 return intval( $id ) > 0;
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
addDescription( $text)
Set the description text.
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
$maxConsecutiveFailedTextRetrievals
showReport()
Overridden to include prefetch ratio if enabled.
getTextDb( $id)
Loads the serialized content from storage.
endElement( $parser, $name)
clearOpenElement( $style)
getTextSpawned( $address)
exportTransform( $text, $model, $format=null)
Applies applicable export transformations to $text.
startElement( $parser, $name, $attribs)
getTextSpawnedOnce( $address)
processOptions()
Processes arguments and sets $this->$sink accordingly.
getText( $id, $model=null, $format=null, $expSize=null)
Tries to load revision text.
characterData( $parser, $data)
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
execute()
Do the actual work.
dump( $history, $text=WikiExporter::TEXT)
string[] $checkpointFiles
bool XmlDumpWriter $xmlwriterobj
IMaintainableDatabase $db
rotateDb()
Drop the database connection $this->db and try to get a new one.
const CONTENT_MODEL_WIKITEXT
Advanced database interface for IDatabase handles that include maintenance methods.