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