MediaWiki REL1_39
TextPassDumper.php
Go to the documentation of this file.
1<?php
28require_once __DIR__ . '/BackupDumper.php';
29require_once __DIR__ . '/../../includes/export/WikiExporter.php';
30
38use Wikimedia\AtEase\AtEase;
40
46 public $prefetch = null;
48 private $thisPage;
50 private $thisRev;
52 private $thisRole = null;
53
59 public $maxTimeAllowed = 0;
60
62 protected $input = "php://stdin";
64 protected $history = WikiExporter::FULL;
66 protected $fetchCount = 0;
68 protected $prefetchCount = 0;
70 protected $prefetchCountLast = 0;
72 protected $fetchCountLast = 0;
73
75 protected $maxFailures = 5;
79 protected $failureTimeout = 5;
80
82 protected $bufferSize = 524288;
83
85 protected $php = [ PHP_BINARY ];
87 protected $spawn = false;
88
92 protected $spawnProc = false;
93
97 protected $spawnWrite;
98
102 protected $spawnRead;
103
107 protected $spawnErr = false;
108
112 protected $xmlwriterobj = false;
113
115 protected $timeExceeded = false;
117 protected $firstPageWritten = false;
119 protected $lastPageWritten = false;
121 protected $checkpointJustWritten = false;
123 protected $checkpointFiles = [];
124
128 protected $db;
129
133 public function __construct( $args = null ) {
134 parent::__construct();
135
136 $this->addDescription( <<<TEXT
137This script postprocesses XML dumps from dumpBackup.php to add
138page text which was stubbed out (using --stub).
139
140XML input is accepted on stdin.
141XML output is sent to stdout; progress reports are sent to stderr.
142TEXT
143 );
144 $this->stderr = fopen( "php://stderr", "wt" );
145
146 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
147 'Specify as --stub=<type>:<file>.', false, true );
148 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
149 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
150 false, true );
151 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
152 'out complete page, closing xml file properly, and opening new one' .
153 'with header). This option requires the checkpointfile option.', false, true );
154 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
155 'first pageid written for the first %s (required) and the last pageid written for the ' .
156 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
157 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
158 $this->addOption( 'full', 'Dump all revisions of every page' );
159 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
160 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records, optionally specify ' .
161 'php[,mwscript] paths' );
162 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
163 '(Default: 512 KiB, Minimum: 4 KiB)', false, true );
164
165 if ( $args ) {
166 $this->loadWithArgv( $args );
167 $this->processOptions();
168 }
169 }
170
171 public function finalSetup( SettingsBuilder $settingsBuilder = null ) {
172 parent::finalSetup( $settingsBuilder );
173
175 }
176
180 private function getBlobStore() {
181 return MediaWikiServices::getInstance()->getBlobStore();
182 }
183
184 public function execute() {
185 $this->processOptions();
186 $this->dump( true );
187 }
188
189 protected function processOptions() {
190 parent::processOptions();
191
192 if ( $this->hasOption( 'buffersize' ) ) {
193 $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
194 }
195
196 if ( $this->hasOption( 'prefetch' ) ) {
197 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
198 $this->prefetch = new BaseDump( $url );
199 }
200
201 if ( $this->hasOption( 'stub' ) ) {
202 $this->input = $this->processFileOpt( $this->getOption( 'stub' ) );
203 }
204
205 if ( $this->hasOption( 'maxtime' ) ) {
206 $this->maxTimeAllowed = intval( $this->getOption( 'maxtime' ) ) * 60;
207 }
208
209 if ( $this->hasOption( 'checkpointfile' ) ) {
210 $this->checkpointFiles = $this->getOption( 'checkpointfile' );
211 }
212
213 if ( $this->hasOption( 'current' ) ) {
214 $this->history = WikiExporter::CURRENT;
215 }
216
217 if ( $this->hasOption( 'full' ) ) {
218 $this->history = WikiExporter::FULL;
219 }
220
221 if ( $this->hasOption( 'spawn' ) ) {
222 $this->spawn = true;
223 $val = $this->getOption( 'spawn' );
224 if ( $val !== 1 ) {
225 $this->php = explode( ',', $val, 2 );
226 }
227 }
228 }
229
242 protected function rotateDb() {
243 // Cleaning up old connections
244 if ( isset( $this->lb ) ) {
245 $this->lb->closeAll( __METHOD__ );
246 unset( $this->lb );
247 }
248
249 if ( $this->forcedDb !== null ) {
250 $this->db = $this->forcedDb;
251
252 return;
253 }
254
255 if ( isset( $this->db ) && $this->db->isOpen() ) {
256 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
257 }
258
259 unset( $this->db );
260
261 // Trying to set up new connection.
262 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
263 // individually retrying at different layers of code.
264
265 try {
266 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
267 $this->lb = $lbFactory->newMainLB();
268 } catch ( Exception $e ) {
269 throw new MWException( __METHOD__
270 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
271 }
272
273 try {
274 $this->db = $this->lb->getMaintenanceConnectionRef( DB_REPLICA, 'dump' );
275 } catch ( Exception $e ) {
276 throw new MWException( __METHOD__
277 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
278 }
279 }
280
281 public function initProgress( $history = WikiExporter::FULL ) {
282 parent::initProgress();
283 $this->timeOfCheckpoint = $this->startTime;
284 }
285
286 public function dump( $history, $text = WikiExporter::TEXT ) {
287 // Notice messages will foul up your XML output even if they're
288 // relatively harmless.
289 if ( ini_get( 'display_errors' ) ) {
290 ini_set( 'display_errors', 'stderr' );
291 }
292
293 $this->initProgress( $this->history );
294
295 // We are trying to get an initial database connection to avoid that the
296 // first try of this request's first call to getText fails. However, if
297 // obtaining a good DB connection fails it's not a serious issue, as
298 // getText does retry upon failure and can start without having a working
299 // DB connection.
300 try {
301 $this->rotateDb();
302 } catch ( Exception $e ) {
303 // We do not even count this as failure. Just let eventual
304 // watchdogs know.
305 $this->progress( "Getting initial DB connection failed (" .
306 $e->getMessage() . ")" );
307 }
308
309 $this->egress = new ExportProgressFilter( $this->sink, $this );
310
311 // it would be nice to do it in the constructor, oh well. need egress set
312 $this->finalOptionCheck();
313
314 // we only want this so we know how to close a stream :-P
315 $this->xmlwriterobj = new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
316
317 $input = fopen( $this->input, "rt" );
318 $this->readDump( $input );
319
320 if ( $this->spawnProc ) {
321 $this->closeSpawn();
322 }
323
324 $this->report( true );
325 }
326
327 protected function processFileOpt( $opt ) {
328 $split = explode( ':', $opt, 2 );
329 $val = $split[0];
330 $param = '';
331 if ( count( $split ) === 2 ) {
332 $param = $split[1];
333 }
334 $fileURIs = explode( ';', $param );
335 $newFileURIs = [];
336 foreach ( $fileURIs as $URI ) {
337 switch ( $val ) {
338 case "file":
339 $newURI = $URI;
340 break;
341 case "gzip":
342 $newURI = "compress.zlib://$URI";
343 break;
344 case "bzip2":
345 $newURI = "compress.bzip2://$URI";
346 break;
347 case "7zip":
348 $newURI = "mediawiki.compress.7z://$URI";
349 break;
350 default:
351 $newURI = $URI;
352 }
353 $newFileURIs[] = $newURI;
354 }
355 $val = implode( ';', $newFileURIs );
356
357 return $val;
358 }
359
363 public function showReport() {
364 if ( !$this->prefetch ) {
365 parent::showReport();
366
367 return;
368 }
369
370 if ( $this->reporting ) {
371 $now = wfTimestamp( TS_DB );
372 $nowts = microtime( true );
373 $deltaAll = $nowts - $this->startTime;
374 $deltaPart = $nowts - $this->lastTime;
375 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
376 $this->revCountPart = $this->revCount - $this->revCountLast;
377
378 if ( $deltaAll ) {
379 $portion = $this->revCount / $this->maxCount;
380 $eta = $this->startTime + $deltaAll / $portion;
381 $etats = wfTimestamp( TS_DB, intval( $eta ) );
382 if ( $this->fetchCount ) {
383 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
384 } else {
385 $fetchRate = '-';
386 }
387 $pageRate = $this->pageCount / $deltaAll;
388 $revRate = $this->revCount / $deltaAll;
389 } else {
390 $pageRate = '-';
391 $revRate = '-';
392 $etats = '-';
393 $fetchRate = '-';
394 }
395 if ( $deltaPart ) {
396 if ( $this->fetchCountLast ) {
397 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
398 } else {
399 $fetchRatePart = '-';
400 }
401 $pageRatePart = $this->pageCountPart / $deltaPart;
402 $revRatePart = $this->revCountPart / $deltaPart;
403 } else {
404 $fetchRatePart = '-';
405 $pageRatePart = '-';
406 $revRatePart = '-';
407 }
408
409 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
410 $this->progress( sprintf(
411 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
412 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
413 . "prefetched (all|curr), ETA %s [max %d]",
414 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
415 $pageRatePart, $this->revCount, $revRate, $revRatePart,
416 $fetchRate, $fetchRatePart, $etats, $this->maxCount
417 ) );
418 $this->lastTime = $nowts;
419 $this->revCountLast = $this->revCount;
420 $this->prefetchCountLast = $this->prefetchCount;
421 $this->fetchCountLast = $this->fetchCount;
422 }
423 }
424
425 private function setTimeExceeded() {
426 $this->timeExceeded = true;
427 }
428
429 private function checkIfTimeExceeded() {
430 if ( $this->maxTimeAllowed
431 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
432 ) {
433 return true;
434 }
435
436 return false;
437 }
438
439 private function finalOptionCheck() {
440 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
441 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
442 ) {
443 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
444 }
445 foreach ( $this->checkpointFiles as $checkpointFile ) {
446 $count = substr_count( $checkpointFile, "%s" );
447 if ( $count != 2 ) {
448 throw new MWException( "Option checkpointfile must contain two '%s' "
449 . "for substitution of first and last pageids, count is $count instead, "
450 . "file is $checkpointFile.\n" );
451 }
452 }
453
454 if ( $this->checkpointFiles ) {
455 $filenameList = (array)$this->egress->getFilenames();
456 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
457 throw new MWException( "One checkpointfile must be specified "
458 . "for each output option, if maxtime is used.\n" );
459 }
460 }
461 }
462
468 protected function readDump( $input ) {
469 $this->buffer = "";
470 $this->openElement = false;
471 $this->atStart = true;
472 $this->state = "";
473 $this->lastName = "";
474 $this->thisPage = "";
475 $this->thisRev = "";
476 $this->thisRole = null;
477 $this->thisRevModel = null;
478 $this->thisRevFormat = null;
479
480 $parser = xml_parser_create( "UTF-8" );
481 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
482
483 xml_set_element_handler(
484 $parser,
485 [ $this, 'startElement' ],
486 [ $this, 'endElement' ]
487 );
488 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
489
490 $offset = 0; // for context extraction on error reporting
491 do {
492 if ( $this->checkIfTimeExceeded() ) {
493 $this->setTimeExceeded();
494 }
495 $chunk = fread( $input, $this->bufferSize );
496 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
497 wfDebug( "TextDumpPass::readDump encountered XML parsing error" );
498
499 $byte = xml_get_current_byte_index( $parser );
500 $msg = wfMessage( 'xml-error-string',
501 'XML import parse failure',
502 xml_get_current_line_number( $parser ),
503 xml_get_current_column_number( $parser ),
504 $byte . ( $chunk === false ? '' : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
505 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
506
507 xml_parser_free( $parser );
508
509 throw new MWException( $msg );
510 }
511 $offset += strlen( $chunk );
512 } while ( $chunk !== false && !feof( $input ) );
513 if ( $this->maxTimeAllowed ) {
514 $filenameList = (array)$this->egress->getFilenames();
515 // we wrote some stuff after last checkpoint that needs renamed
516 if ( file_exists( $filenameList[0] ) ) {
517 $newFilenames = [];
518 # we might have just written the header and footer and had no
519 # pages or revisions written... perhaps they were all deleted
520 # there's no pageID 0 so we use that. the caller is responsible
521 # for deciding what to do with a file containing only the
522 # siteinfo information and the mw tags.
523 if ( !$this->firstPageWritten ) {
524 $firstPageID = str_pad( '0', 9, "0", STR_PAD_LEFT );
525 $lastPageID = str_pad( '0', 9, "0", STR_PAD_LEFT );
526 } else {
527 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
528 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
529 }
530
531 $filenameCount = count( $filenameList );
532 for ( $i = 0; $i < $filenameCount; $i++ ) {
533 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
534 $fileinfo = pathinfo( $filenameList[$i] );
535 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
536 }
537 $this->egress->closeAndRename( $newFilenames );
538 }
539 }
540 xml_parser_free( $parser );
541
542 return true;
543 }
544
554 private function exportTransform( $text, $model, $format = null ) {
555 try {
556 $text = MediaWikiServices::getInstance()
557 ->getContentHandlerFactory()
558 ->getContentHandler( $model )
559 ->exportTransform( $text, $format );
560 } catch ( MWException $ex ) {
561 wfWarn( "Unable to apply export transformation for content model '$model': " .
562 $ex->getMessage() );
563
564 $this->progress(
565 "Unable to apply export transformation for content model '$model': " .
566 $ex->getMessage()
567 );
568 }
569
570 return $text;
571 }
572
593 protected function getText( $id, $model = null, $format = null, $expSize = null ) {
594 if ( !$this->isValidTextId( $id ) ) {
595 $msg = "Skipping bad text id " . $id . " of revision " . $this->thisRev;
596 $this->progress( $msg );
597 return '';
598 }
599
600 $model = $model ?: null;
601 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
602 $text = false; // The candidate for a good text. false if no proper value.
603 $failures = 0; // The number of times, this invocation of getText already failed.
604
605 // The number of times getText failed without yielding a good text in between.
606 static $consecutiveFailedTextRetrievals = 0;
607
608 $this->fetchCount++;
609
610 // To allow to simply return on success and do not have to worry about book keeping,
611 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
612 // the old value, so we can restore it, if problems occur (See after the while loop).
613 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
614 $consecutiveFailedTextRetrievals = 0;
615
616 while ( $failures < $this->maxFailures ) {
617 // As soon as we found a good text for the $id, we will return immediately.
618 // Hence, if we make it past the try catch block, we know that we did not
619 // find a good text.
620
621 try {
622 // Step 1: Get some text (or reuse from previous iteratuon if checking
623 // for plausibility failed)
624
625 // Trying to get prefetch, if it has not been tried before
626 // @phan-suppress-next-line PhanSuspiciousValueComparisonInLoop
627 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
628 $prefetchNotTried = false;
629 $tryIsPrefetch = true;
630 $text = $this->prefetch->prefetch(
631 (int)$this->thisPage,
632 (int)$this->thisRev,
633 trim( $this->thisRole )
634 );
635
636 if ( $text === null ) {
637 $text = false;
638 }
639
640 if ( is_string( $text ) && $model !== null ) {
641 // Apply export transformation to text coming from an old dump.
642 // The purpose of this transformation is to convert up from legacy
643 // formats, which may still be used in the older dump that is used
644 // for pre-fetching. Applying the transformation again should not
645 // interfere with content that is already in the correct form.
646 $text = $this->exportTransform( $text, $model, $format );
647 }
648 }
649
650 if ( $text === false ) {
651 // Fallback to asking the database
652 $tryIsPrefetch = false;
653 if ( $this->spawn ) {
654 $text = $this->getTextSpawned( $id );
655 } else {
656 $text = $this->getTextDb( $id );
657 }
658
659 if ( $text !== false && $model !== null ) {
660 // Apply export transformation to text coming from the database.
661 // Prefetched text should already have transformations applied.
662 $text = $this->exportTransform( $text, $model, $format );
663 }
664
665 // No more checks for texts from DB for now.
666 // If we received something that is not false,
667 // We treat it as good text, regardless of whether it actually is or is not
668 if ( $text !== false ) {
669 return $text;
670 }
671 }
672
673 if ( $text === false ) {
674 throw new MWException( "Generic error while obtaining text for id " . $id );
675 }
676
677 // We received a good candidate for the text of $id via some method
678
679 // Step 2: Checking for plausibility and return the text if it is
680 // plausible
681
682 if ( $expSize === null || strlen( $text ) == $expSize ) {
683 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Set when text is not false
684 if ( $tryIsPrefetch ) {
685 $this->prefetchCount++;
686 }
687
688 return $text;
689 }
690
691 $text = false;
692 throw new MWException( "Received text is unplausible for id " . $id );
693 } catch ( Exception $e ) {
694 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage()
695 . ") for revision " . $this->thisRev;
696 if ( $failures + 1 < $this->maxFailures ) {
697 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
698 }
699 $this->progress( $msg );
700 }
701
702 // Something went wrong; we did not a text that was plausible :(
703 $failures++;
704
705 // A failure in a prefetch hit does not warrant resetting db connection etc.
706 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Control flow is hard to understand here.
707 if ( !$tryIsPrefetch ) {
708 // After backing off for some time, we try to reboot the whole process as
709 // much as possible to not carry over failures from one part to the other
710 // parts
711 sleep( $this->failureTimeout );
712 try {
713 $this->rotateDb();
714 if ( $this->spawn ) {
715 $this->closeSpawn();
716 $this->openSpawn();
717 }
718 } catch ( Exception $e ) {
719 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
720 " Trying to continue anyways" );
721 }
722 }
723 }
724
725 // Retrieving a good text for $id failed (at least) maxFailures times.
726 // We abort for this $id.
727
728 // Restoring the consecutive failures, and maybe aborting, if the dump
729 // is too broken.
730 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
731 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
732 throw new MWException( "Graceful storage failure" );
733 }
734
735 return "";
736 }
737
744 private function getTextDb( $id ) {
745 $store = $this->getBlobStore();
746 $address = ( is_int( $id ) || strpos( $id, ':' ) === false )
747 ? SqlBlobStore::makeAddressFromTextId( (int)$id )
748 : $id;
749
750 try {
751 $text = $store->getBlob( $address );
752
753 $stripped = str_replace( "\r", "", $text );
754 $normalized = MediaWikiServices::getInstance()->getContentLanguage()
755 ->normalize( $stripped );
756
757 return $normalized;
758 } catch ( BlobAccessException $ex ) {
759 // XXX: log a warning?
760 return false;
761 }
762 }
763
768 private function getTextSpawned( $address ) {
769 AtEase::suppressWarnings();
770 if ( !$this->spawnProc ) {
771 // First time?
772 $this->openSpawn();
773 }
774 $text = $this->getTextSpawnedOnce( $address );
775 AtEase::restoreWarnings();
776
777 return $text;
778 }
779
780 protected function openSpawn() {
781 global $IP;
782
783 $wiki = WikiMap::getCurrentWikiId();
784 if ( count( $this->php ) == 2 ) {
785 $mwscriptpath = $this->php[1];
786 } else {
787 $mwscriptpath = "$IP/../multiversion/MWScript.php";
788 }
789 if ( file_exists( $mwscriptpath ) ) {
790 $cmd = implode( " ",
791 array_map( [ Shell::class, 'escape' ],
792 [
793 $this->php[0],
794 $mwscriptpath,
795 "fetchText.php",
796 '--wiki', $wiki ] ) );
797 } else {
798 $cmd = implode( " ",
799 array_map( [ Shell::class, 'escape' ],
800 [
801 $this->php[0],
802 "$IP/maintenance/fetchText.php",
803 '--wiki', $wiki ] ) );
804 }
805 $spec = [
806 0 => [ "pipe", "r" ],
807 1 => [ "pipe", "w" ],
808 2 => [ "file", "/dev/null", "a" ] ];
809 $pipes = [];
810
811 $this->progress( "Spawning database subprocess: $cmd" );
812 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
813 if ( !$this->spawnProc ) {
814 $this->progress( "Subprocess spawn failed." );
815
816 return false;
817 }
818 [
819 $this->spawnWrite, // -> stdin
820 $this->spawnRead, // <- stdout
821 ] = $pipes;
822
823 return true;
824 }
825
826 private function closeSpawn() {
827 AtEase::suppressWarnings();
828 if ( $this->spawnRead ) {
829 fclose( $this->spawnRead );
830 }
831 $this->spawnRead = null;
832 if ( $this->spawnWrite ) {
833 fclose( $this->spawnWrite );
834 }
835 $this->spawnWrite = null;
836 if ( $this->spawnErr ) {
837 fclose( $this->spawnErr );
838 }
839 $this->spawnErr = false;
840 if ( $this->spawnProc ) {
841 pclose( $this->spawnProc );
842 }
843 $this->spawnProc = false;
844 AtEase::restoreWarnings();
845 }
846
851 private function getTextSpawnedOnce( $address ) {
852 if ( is_int( $address ) || intval( $address ) ) {
853 $address = SqlBlobStore::makeAddressFromTextId( (int)$address );
854 }
855
856 $ok = fwrite( $this->spawnWrite, "$address\n" );
857 // $this->progress( ">> $id" );
858 if ( !$ok ) {
859 return false;
860 }
861
862 $ok = fflush( $this->spawnWrite );
863 // $this->progress( ">> [flush]" );
864 if ( !$ok ) {
865 return false;
866 }
867
868 // check that the text address they are sending is the one we asked for
869 // this avoids out of sync revision text errors we have encountered in the past
870 $newAddress = fgets( $this->spawnRead );
871 if ( $newAddress === false ) {
872 return false;
873 }
874 $newAddress = trim( $newAddress );
875 if ( strpos( $newAddress, ':' ) === false ) {
876 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
877 }
878
879 if ( $newAddress !== $address ) {
880 return false;
881 }
882
883 $len = fgets( $this->spawnRead );
884 // $this->progress( "<< " . trim( $len ) );
885 if ( $len === false ) {
886 return false;
887 }
888
889 $nbytes = intval( $len );
890 // actual error, not zero-length text
891 if ( $nbytes < 0 ) {
892 return false;
893 }
894
895 $text = "";
896
897 // Subprocess may not send everything at once, we have to loop.
898 while ( $nbytes > strlen( $text ) ) {
899 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
900 if ( $buffer === false ) {
901 break;
902 }
903 $text .= $buffer;
904 }
905
906 $gotbytes = strlen( $text );
907 if ( $gotbytes != $nbytes ) {
908 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
909
910 return false;
911 }
912
913 // Do normalization in the dump thread...
914 $stripped = str_replace( "\r", "", $text );
915 $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
916 normalize( $stripped );
917
918 return $normalized;
919 }
920
921 protected function startElement( $parser, $name, $attribs ) {
922 $this->checkpointJustWritten = false;
923
924 $this->clearOpenElement( null );
925 $this->lastName = $name;
926
927 if ( $name == 'revision' ) {
928 $this->state = $name;
929 $this->egress->writeOpenPage( null, $this->buffer );
930 $this->buffer = "";
931 } elseif ( $name == 'page' ) {
932 $this->state = $name;
933 if ( $this->atStart ) {
934 $this->egress->writeOpenStream( $this->buffer );
935 $this->buffer = "";
936 $this->atStart = false;
937 }
938 } elseif ( $name === 'mediawiki' ) {
939 if ( isset( $attribs['version'] ) ) {
940 if ( $attribs['version'] !== $this->schemaVersion ) {
941 throw new MWException( 'Mismatching schema version. '
942 . 'Use the --schema-version option to set the output schema version to '
943 . 'the version declared by the stub file, namely ' . $attribs['version'] );
944 }
945 }
946 }
947
948 if ( $name == "text" && ( isset( $attribs['id'] ) || isset( $attribs['location'] ) ) ) {
949 $id = $attribs['location'] ?? $attribs['id'];
950 $model = trim( $this->thisRevModel );
951 $format = trim( $this->thisRevFormat );
952
953 $model = $model === '' ? null : $model;
954 $format = $format === '' ? null : $format;
955 $expSize = !empty( $attribs['bytes'] ) && $model === CONTENT_MODEL_WIKITEXT
956 ? (int)$attribs['bytes'] : null;
957
958 $text = $this->getText( $id, $model, $format, $expSize );
959
960 unset( $attribs['id'] );
961 unset( $attribs['location'] );
962 if ( strlen( $text ) > 0 ) {
963 $attribs['xml:space'] = 'preserve';
964 }
965
966 $this->openElement = [ $name, $attribs ];
967 if ( strlen( $text ) > 0 ) {
968 $this->characterData( $parser, $text );
969 }
970 } else {
971 $this->openElement = [ $name, $attribs ];
972 }
973 }
974
975 protected function endElement( $parser, $name ) {
976 $this->checkpointJustWritten = false;
977
978 if ( $this->openElement ) {
979 $this->clearOpenElement( "" );
980 } else {
981 $this->buffer .= "</$name>";
982 }
983
984 if ( $name == 'revision' ) {
985 $this->egress->writeRevision( null, $this->buffer );
986 $this->buffer = "";
987 $this->thisRev = "";
988 $this->thisRole = null;
989 $this->thisRevModel = null;
990 $this->thisRevFormat = null;
991 } elseif ( $name == 'page' ) {
992 if ( !$this->firstPageWritten ) {
993 $this->firstPageWritten = trim( $this->thisPage );
994 }
995 $this->lastPageWritten = trim( $this->thisPage );
996 if ( $this->timeExceeded ) {
997 $this->egress->writeClosePage( $this->buffer );
998 // nasty hack, we can't just write the chardata after the
999 // page tag, it will include leading blanks from the next line
1000 $this->egress->sink->write( "\n" );
1001
1002 $this->buffer = $this->xmlwriterobj->closeStream();
1003 $this->egress->writeCloseStream( $this->buffer );
1004
1005 $this->buffer = "";
1006 $this->thisPage = "";
1007 // this could be more than one file if we had more than one output arg
1008
1009 $filenameList = (array)$this->egress->getFilenames();
1010 $newFilenames = [];
1011 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
1012 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
1013 $filenamesCount = count( $filenameList );
1014 for ( $i = 0; $i < $filenamesCount; $i++ ) {
1015 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
1016 $fileinfo = pathinfo( $filenameList[$i] );
1017 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
1018 }
1019 $this->egress->closeRenameAndReopen( $newFilenames );
1020 $this->buffer = $this->xmlwriterobj->openStream();
1021 $this->timeExceeded = false;
1022 $this->timeOfCheckpoint = $this->lastTime;
1023 $this->firstPageWritten = false;
1024 $this->checkpointJustWritten = true;
1025 } else {
1026 $this->egress->writeClosePage( $this->buffer );
1027 $this->buffer = "";
1028 $this->thisPage = "";
1029 }
1030 } elseif ( $name == 'mediawiki' ) {
1031 $this->egress->writeCloseStream( $this->buffer );
1032 $this->buffer = "";
1033 }
1034 }
1035
1036 protected function characterData( $parser, $data ) {
1037 $this->clearOpenElement( null );
1038 if ( $this->lastName == "id" ) {
1039 if ( $this->state == "revision" ) {
1040 $this->thisRev .= $data;
1041 $this->thisRole = SlotRecord::MAIN;
1042 } elseif ( $this->state == "page" ) {
1043 $this->thisPage .= $data;
1044 }
1045 } elseif ( $this->lastName == "model" ) {
1046 $this->thisRevModel .= $data;
1047 } elseif ( $this->lastName == "format" ) {
1048 $this->thisRevFormat .= $data;
1049 } elseif ( $this->lastName == "content" ) {
1050 $this->thisRole = "";
1051 $this->thisRevModel = "";
1052 $this->thisRevFormat = "";
1053 } elseif ( $this->lastName == "role" ) {
1054 $this->thisRole .= $data;
1055 }
1056
1057 // have to skip the newline left over from closepagetag line of
1058 // end of checkpoint files. nasty hack!!
1059 if ( $this->checkpointJustWritten ) {
1060 if ( $data[0] == "\n" ) {
1061 $data = substr( $data, 1 );
1062 }
1063 $this->checkpointJustWritten = false;
1064 }
1065 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1066 }
1067
1068 protected function clearOpenElement( $style ) {
1069 if ( $this->openElement ) {
1070 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1071 $this->openElement = false;
1072 }
1073 }
1074
1075 private function isValidTextId( $id ) {
1076 if ( preg_match( '/:/', $id ) ) {
1077 return $id !== 'tt:0';
1078 } elseif ( preg_match( '/^\d+$/', $id ) ) {
1079 return intval( $id ) > 0;
1080 }
1081
1082 return false;
1083 }
1084
1085}
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:211
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.
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:91
progress( $string)
IMaintainableDatabase null $forcedDb
The dependency-injected database to use.
report( $final=false)
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
Definition BaseDump.php:44
MediaWiki exception.
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.
Service locator for MediaWiki core services.
Value object representing a content slot associated with a page revision.
Utility for loading settings files.
Executes shell commands.
Definition Shell.php:46
Exception representing a failure to access a data blob.
Service for storing and loading Content objects.
showReport()
Overridden to include prefetch ratio if enabled.
int $bufferSize
In bytes.
string false $lastPageWritten
endElement( $parser, $name)
clearOpenElement( $style)
string false $firstPageWritten
startElement( $parser, $name, $attribs)
finalSetup(SettingsBuilder $settingsBuilder=null)
Handle some last-minute setup here.
BaseDump null $prefetch
int $maxConsecutiveFailedTextRetrievals
int $failureTimeout
Seconds to sleep after db failure.
processOptions()
Processes arguments and sets $this->$sink accordingly.
getText( $id, $model=null, $format=null, $expSize=null)
Tries to load revision text.
characterData( $parser, $data)
resource false $spawnProc
resource null $spawnRead
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
execute()
Do the actual work.
__construct( $args=null)
resource false $spawnErr
dump( $history, $text=WikiExporter::TEXT)
string[] $checkpointFiles
XmlDumpWriter false $xmlwriterobj
int $maxTimeAllowed
when we spend more than maxTimeAllowed seconds on this run, we continue processing until we write out...
IMaintainableDatabase $db
resource null $spawnWrite
rotateDb()
Drop the database connection $this->db and try to get a new one.
Service for loading and storing data blobs.
Definition BlobStore.php:35
Advanced database interface for IDatabase handles that include maintenance methods.
if( $line===false) $args
Definition mcc.php:124
const DB_REPLICA
Definition defines.php:26