27require_once __DIR__ .
'/includes/BackupDumper.php';
28require_once __DIR__ .
'/7zip.inc';
29require_once __DIR__ .
'/../includes/export/WikiExporter.php';
106 parent::__construct();
109This script postprocesses XML dumps from dumpBackup.php to add
110page text which was stubbed out (
using --stub).
112XML input is accepted on stdin.
116 $this->stderr = fopen(
"php://stderr",
"wt" );
118 $this->
addOption(
'stub',
'To load a compressed stub dump instead of stdin. ' .
119 'Specify as --stub=<type>:<file>.',
false,
true );
120 $this->
addOption(
'prefetch',
'Use a prior dump file as a text source, to savepressure on the ' .
121 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
123 $this->
addOption(
'maxtime',
'Write out checkpoint file after this many minutes (writing' .
124 'out complete page, closing xml file properly, and opening new one' .
125 'with header). This option requires the checkpointfile option.',
false,
true );
126 $this->
addOption(
'checkpointfile',
'Use this string for checkpoint filenames,substituting ' .
127 'first pageid written for the first %s (required) and the last pageid written for the ' .
128 'second %s if it exists.',
false,
true,
false,
true );
129 $this->
addOption(
'quiet',
'Don\'t dump status reports to stderr.' );
130 $this->
addOption(
'full',
'Dump all revisions of every page' );
131 $this->
addOption(
'current',
'Base ETA on number of pages in database instead of all revisions' );
132 $this->
addOption(
'spawn',
'Spawn a subprocess for loading text records' );
133 $this->
addOption(
'buffersize',
'Buffer size in bytes to use for reading the stub. ' .
134 '(Default: 512KB, Minimum: 4KB)',
false,
true );
148 parent::processOptions();
150 if ( $this->
hasOption(
'buffersize' ) ) {
151 $this->bufferSize = max( intval( $this->
getOption(
'buffersize' ) ), 4 * 1024 );
156 $this->prefetch =
new BaseDump( $url );
164 $this->maxTimeAllowed = intval( $this->
getOption(
'maxtime' ) ) * 60;
167 if ( $this->
hasOption(
'checkpointfile' ) ) {
168 $this->checkpointFiles = $this->
getOption(
'checkpointfile' );
172 $this->
history = WikiExporter::CURRENT;
176 $this->
history = WikiExporter::FULL;
201 if ( isset( $this->lb ) ) {
202 $this->lb->closeAll();
206 if ( $this->forcedDb !==
null ) {
207 $this->db = $this->forcedDb;
212 if ( isset( $this->db ) && $this->db->isOpen() ) {
213 throw new MWException(
'DB is set and has not been closed by the Load Balancer' );
223 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
224 $this->lb = $lbFactory->newMainLB();
225 }
catch ( Exception
$e ) {
227 .
" rotating DB failed to obtain new load balancer (" .
$e->getMessage() .
")" );
231 $this->db = $this->lb->getConnection(
DB_REPLICA,
'dump' );
232 }
catch ( Exception
$e ) {
234 .
" rotating DB failed to obtain new database (" .
$e->getMessage() .
")" );
239 parent::initProgress();
240 $this->timeOfCheckpoint = $this->startTime;
243 function dump( $history, $text = WikiExporter::TEXT ) {
246 if ( ini_get(
'display_errors' ) ) {
247 ini_set(
'display_errors',
'stderr' );
259 }
catch ( Exception
$e ) {
262 $this->
progress(
"Getting initial DB connection failed (" .
263 $e->getMessage() .
")" );
274 $input = fopen( $this->input,
"rt" );
277 if ( $this->spawnProc ) {
285 $split = explode(
':',
$opt, 2 );
288 if ( count( $split ) === 2 ) {
291 $fileURIs = explode(
';', $param );
292 foreach ( $fileURIs as $URI ) {
298 $newURI =
"compress.zlib://$URI";
301 $newURI =
"compress.bzip2://$URI";
304 $newURI =
"mediawiki.compress.7z://$URI";
309 $newFileURIs[] = $newURI;
311 $val = implode(
';', $newFileURIs );
320 if ( !$this->prefetch ) {
321 parent::showReport();
326 if ( $this->reporting ) {
328 $nowts = microtime(
true );
329 $deltaAll = $nowts - $this->startTime;
330 $deltaPart = $nowts - $this->lastTime;
331 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
332 $this->revCountPart = $this->
revCount - $this->revCountLast;
335 $portion = $this->
revCount / $this->maxCount;
336 $eta = $this->startTime + $deltaAll / $portion;
338 if ( $this->fetchCount ) {
339 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
343 $pageRate = $this->pageCount / $deltaAll;
344 $revRate = $this->
revCount / $deltaAll;
352 if ( $this->fetchCountLast ) {
353 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
355 $fetchRatePart =
'-';
357 $pageRatePart = $this->pageCountPart / $deltaPart;
358 $revRatePart = $this->revCountPart / $deltaPart;
360 $fetchRatePart =
'-';
365 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
366 .
"%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
367 .
"prefetched (all|curr), ETA %s [max %d]",
368 $now,
wfWikiID(), $this->ID, $this->pageCount, $pageRate,
369 $pageRatePart, $this->
revCount, $revRate, $revRatePart,
370 $fetchRate, $fetchRatePart, $etats, $this->maxCount
372 $this->lastTime = $nowts;
373 $this->revCountLast = $this->revCount;
374 $this->prefetchCountLast = $this->prefetchCount;
375 $this->fetchCountLast = $this->fetchCount;
380 $this->timeExceeded =
true;
384 if ( $this->maxTimeAllowed
385 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
394 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
395 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
397 throw new MWException(
"Options checkpointfile and maxtime must be specified together.\n" );
399 foreach ( $this->checkpointFiles as $checkpointFile ) {
400 $count = substr_count( $checkpointFile,
"%s" );
402 throw new MWException(
"Option checkpointfile must contain two '%s' "
403 .
"for substitution of first and last pageids, count is $count instead, "
404 .
"file is $checkpointFile.\n" );
408 if ( $this->checkpointFiles ) {
409 $filenameList = (
array)$this->egress->getFilenames();
410 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
411 throw new MWException(
"One checkpointfile must be specified "
412 .
"for each output option, if maxtime is used.\n" );
424 $this->openElement =
false;
425 $this->atStart =
true;
427 $this->lastName =
"";
430 $this->thisRevModel =
null;
431 $this->thisRevFormat =
null;
433 $parser = xml_parser_create(
"UTF-8" );
434 xml_parser_set_option(
$parser, XML_OPTION_CASE_FOLDING,
false );
436 xml_set_element_handler(
438 [ $this,
'startElement' ],
439 [ $this,
'endElement' ]
441 xml_set_character_data_handler(
$parser, [ $this,
'characterData' ] );
448 $chunk = fread(
$input, $this->bufferSize );
450 wfDebug(
"TextDumpPass::readDump encountered XML parsing error\n" );
452 $byte = xml_get_current_byte_index(
$parser );
454 'XML import parse failure',
455 xml_get_current_line_number(
$parser ),
456 xml_get_current_column_number(
$parser ),
457 $byte . ( is_null( $chunk ) ?
null : (
'; "' . substr( $chunk, $byte - $offset, 16 ) .
'"' ) ),
458 xml_error_string( xml_get_error_code(
$parser ) ) )->escaped();
464 $offset += strlen( $chunk );
465 }
while ( $chunk !==
false && !feof(
$input ) );
466 if ( $this->maxTimeAllowed ) {
467 $filenameList = (
array)$this->egress->getFilenames();
469 if ( file_exists( $filenameList[0] ) ) {
471 # we might have just written the header and footer and had no
472 # pages or revisions written... perhaps they were all deleted
473 # there's no pageID 0 so we use that. the caller is responsible
474 # for deciding what to do with a file containing only the
475 # siteinfo information and the mw tags.
476 if ( !$this->firstPageWritten ) {
477 $firstPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
478 $lastPageID = str_pad( 0, 9,
"0", STR_PAD_LEFT );
480 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
481 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
484 $filenameCount = count( $filenameList );
485 for ( $i = 0; $i < $filenameCount; $i++ ) {
486 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
487 $fileinfo = pathinfo( $filenameList[$i] );
488 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
490 $this->egress->closeAndRename( $newFilenames );
509 $handler = ContentHandler::getForModelID( $model );
510 $text =
$handler->exportTransform( $text, $format );
514 "Unable to apply export transformation for content model '$model': " .
542 function getText( $id, $model =
null, $format =
null ) {
545 $prefetchNotTried =
true;
550 static $consecutiveFailedTextRetrievals = 0;
557 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
558 $consecutiveFailedTextRetrievals = 0;
561 $row = $this->db->selectRow(
563 [
'rev_content_model',
'rev_content_format' ],
564 [
'rev_id' => $this->thisRev ],
569 $model = $row->rev_content_model;
570 $format = $row->rev_content_format;
574 if ( $model ===
null || $model ===
'' ) {
578 while ( $failures < $this->maxFailures ) {
588 if ( $text ===
false && isset( $this->prefetch ) && $prefetchNotTried ) {
589 $prefetchNotTried =
false;
590 $tryIsPrefetch =
true;
591 $text = $this->prefetch->prefetch( (
int)$this->thisPage, (
int)$this->thisRev );
593 if ( $text ===
null ) {
597 if ( is_string( $text ) && $model !==
false ) {
607 if ( $text ===
false ) {
609 $tryIsPrefetch =
false;
610 if ( $this->spawn ) {
616 if ( $text !==
false && $model !==
false ) {
625 if ( $text !==
false ) {
630 if ( $text ===
false ) {
631 throw new MWException(
"Generic error while obtaining text for id " . $id );
638 $revID = intval( $this->thisRev );
639 if ( !isset( $this->db ) ) {
644 $revLength = strlen( $text );
646 $revLength = $this->db->selectField(
'revision',
'rev_len', [
'rev_id' => $revID ] );
649 if ( strlen( $text ) == $revLength ) {
650 if ( $tryIsPrefetch ) {
651 $this->prefetchCount++;
658 throw new MWException(
"Received text is unplausible for id " . $id );
659 }
catch ( Exception
$e ) {
660 $msg =
"getting/checking text " . $id .
" failed (" .
$e->getMessage() .
")";
661 if ( $failures + 1 < $this->maxFailures ) {
662 $msg .=
" (Will retry " . ( $this->maxFailures - $failures - 1 ) .
" more times)";
671 if ( !$tryIsPrefetch ) {
675 sleep( $this->failureTimeout );
678 if ( $this->spawn ) {
682 }
catch ( Exception
$e ) {
683 $this->
progress(
"Rebooting getText infrastructure failed (" .
$e->getMessage() .
")" .
684 " Trying to continue anyways" );
694 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
695 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
696 throw new MWException(
"Graceful storage failure" );
709 if ( !isset( $this->db ) ) {
710 throw new MWException( __METHOD__ .
"No database available" );
712 $row = $this->db->selectRow(
'text',
713 [
'old_text',
'old_flags' ],
717 if ( $text ===
false ) {
720 $stripped = str_replace(
"\r",
"", $text );
721 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
722 normalize( $stripped );
728 Wikimedia\suppressWarnings();
729 if ( !$this->spawnProc ) {
734 Wikimedia\restoreWarnings();
742 if ( file_exists(
"$IP/../multiversion/MWScript.php" ) ) {
744 array_map(
'wfEscapeShellArg',
747 "$IP/../multiversion/MWScript.php",
752 array_map(
'wfEscapeShellArg',
755 "$IP/maintenance/fetchText.php",
759 0 => [
"pipe",
"r" ],
760 1 => [
"pipe",
"w" ],
761 2 => [
"file",
"/dev/null",
"a" ] ];
764 $this->
progress(
"Spawning database subprocess: $cmd" );
765 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
766 if ( !$this->spawnProc ) {
767 $this->
progress(
"Subprocess spawn failed." );
780 Wikimedia\suppressWarnings();
781 if ( $this->spawnRead ) {
782 fclose( $this->spawnRead );
784 $this->spawnRead =
false;
785 if ( $this->spawnWrite ) {
786 fclose( $this->spawnWrite );
788 $this->spawnWrite =
false;
789 if ( $this->spawnErr ) {
790 fclose( $this->spawnErr );
792 $this->spawnErr =
false;
793 if ( $this->spawnProc ) {
794 pclose( $this->spawnProc );
796 $this->spawnProc =
false;
797 Wikimedia\restoreWarnings();
801 $ok = fwrite( $this->spawnWrite,
"$id\n" );
807 $ok = fflush( $this->spawnWrite );
815 $newId = fgets( $this->spawnRead );
816 if ( $newId ===
false ) {
819 if ( $id != intval( $newId ) ) {
823 $len = fgets( $this->spawnRead );
825 if ( $len ===
false ) {
829 $nbytes = intval( $len );
838 while ( $nbytes > strlen( $text ) ) {
839 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
846 $gotbytes = strlen( $text );
847 if ( $gotbytes != $nbytes ) {
848 $this->
progress(
"Expected $nbytes bytes from database subprocess, got $gotbytes " );
854 $stripped = str_replace(
"\r",
"", $text );
855 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
856 normalize( $stripped );
862 $this->checkpointJustWritten =
false;
865 $this->lastName =
$name;
867 if ( $name ==
'revision' ) {
868 $this->state =
$name;
869 $this->egress->writeOpenPage(
null, $this->buffer );
871 } elseif ( $name ==
'page' ) {
872 $this->state =
$name;
873 if ( $this->atStart ) {
874 $this->egress->writeOpenStream( $this->buffer );
876 $this->atStart =
false;
880 if ( $name ==
"text" && isset(
$attribs[
'id'] ) ) {
882 $model = trim( $this->thisRevModel );
883 $format = trim( $this->thisRevFormat );
885 $model = $model ===
'' ? null : $model;
886 $format = $format ===
'' ? null : $format;
888 $text = $this->
getText( $id, $model, $format );
889 $this->openElement = [
$name, [
'xml:space' =>
'preserve' ] ];
890 if ( strlen( $text ) > 0 ) {
899 $this->checkpointJustWritten =
false;
901 if ( $this->openElement ) {
904 $this->buffer .=
"</$name>";
907 if ( $name ==
'revision' ) {
908 $this->egress->writeRevision(
null, $this->buffer );
911 $this->thisRevModel =
null;
912 $this->thisRevFormat =
null;
913 } elseif ( $name ==
'page' ) {
914 if ( !$this->firstPageWritten ) {
915 $this->firstPageWritten = trim( $this->thisPage );
917 $this->lastPageWritten = trim( $this->thisPage );
918 if ( $this->timeExceeded ) {
919 $this->egress->writeClosePage( $this->buffer );
922 $this->egress->sink->write(
"\n" );
924 $this->buffer = $this->xmlwriterobj->closeStream();
925 $this->egress->writeCloseStream( $this->buffer );
928 $this->thisPage =
"";
931 $filenameList = (
array)$this->egress->getFilenames();
933 $firstPageID = str_pad( $this->firstPageWritten, 9,
"0", STR_PAD_LEFT );
934 $lastPageID = str_pad( $this->lastPageWritten, 9,
"0", STR_PAD_LEFT );
935 $filenamesCount = count( $filenameList );
936 for ( $i = 0; $i < $filenamesCount; $i++ ) {
937 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
938 $fileinfo = pathinfo( $filenameList[$i] );
939 $newFilenames[] =
$fileinfo[
'dirname'] .
'/' . $checkpointNameFilledIn;
941 $this->egress->closeRenameAndReopen( $newFilenames );
942 $this->buffer = $this->xmlwriterobj->openStream();
943 $this->timeExceeded =
false;
944 $this->timeOfCheckpoint = $this->lastTime;
945 $this->firstPageWritten =
false;
946 $this->checkpointJustWritten =
true;
948 $this->egress->writeClosePage( $this->buffer );
950 $this->thisPage =
"";
952 } elseif ( $name ==
'mediawiki' ) {
953 $this->egress->writeCloseStream( $this->buffer );
960 if ( $this->lastName ==
"id" ) {
961 if ( $this->state ==
"revision" ) {
962 $this->thisRev .= $data;
963 } elseif ( $this->state ==
"page" ) {
964 $this->thisPage .= $data;
966 } elseif ( $this->lastName ==
"model" ) {
967 $this->thisRevModel .= $data;
968 } elseif ( $this->lastName ==
"format" ) {
969 $this->thisRevFormat .= $data;
974 if ( $this->checkpointJustWritten ) {
975 if ( $data[0] ==
"\n" ) {
976 $data = substr( $data, 1 );
978 $this->checkpointJustWritten =
false;
980 $this->buffer .= htmlspecialchars( $data );
984 if ( $this->openElement ) {
985 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
986 $this->openElement =
false;
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
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 exists.
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.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
$maxConsecutiveFailedTextRetrievals
showReport()
Overridden to include prefetch ratio if enabled.
getTextDb( $id)
May throw a database error if, say, the server dies during query.
endElement( $parser, $name)
clearOpenElement( $style)
getText( $id, $model=null, $format=null)
Tries to get the revision text for a revision id.
exportTransform( $text, $model, $format=null)
Applies applicable export transformations to $text.
startElement( $parser, $name, $attribs)
processOptions()
Processes arguments and sets $this->$sink accordingly.
characterData( $parser, $data)
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
execute()
Do the actual work.
dump( $history, $text=WikiExporter::TEXT)
bool XmlDumpWriter $xmlwriterobj
IMaintainableDatabase $db
bool resource $spawnWrite
rotateDb()
Drop the database connection $this->db and try to get a new one.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc next in line in page history
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
Allows to change the fields on the form that will be generated $name
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
returning false will NOT prevent logging $e
const CONTENT_MODEL_WIKITEXT
Advanced database interface for IDatabase handles that include maintenance methods.
require_once RUN_MAINTENANCE_IF_MAIN
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(is_array($mode)) switch( $mode) $input