MediaWiki master
TextPassDumper.php
Go to the documentation of this file.
1<?php
14namespace MediaWiki\Maintenance;
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/BackupDumper.php';
18require_once __DIR__ . '/../../includes/Export/WikiExporter.php';
19// @codeCoverageIgnoreEnd
20
21use Exception;
37use RuntimeException;
38use Wikimedia\Timestamp\ConvertibleTimestamp;
39use Wikimedia\Timestamp\TimestampFormat as TS;
40use XMLParser;
41
47 public $prefetch = null;
49 private $thisPage;
51 private $thisRev;
53 private $thisRole = null;
54
60 public $maxTimeAllowed = 0;
61
63 protected $input = "php://stdin";
65 protected $history = WikiExporter::FULL;
67 protected $fetchCount = 0;
69 protected $prefetchCount = 0;
71 protected $prefetchCountLast = 0;
73 protected $fetchCountLast = 0;
74
76 protected $maxFailures = 5;
80 protected $failureTimeout = 5;
81
83 protected $bufferSize = 524_288;
84
86 protected $php = [ PHP_BINARY ];
88 protected $spawn = false;
89
93 protected $spawnProc = false;
94
98 protected $spawnWrite;
99
103 protected $spawnRead;
104
108 protected $spawnErr = false;
109
113 protected $xmlwriterobj = false;
114
116 protected $timeExceeded = false;
118 protected $firstPageWritten = false;
120 protected $lastPageWritten = false;
122 protected $checkpointJustWritten = false;
124 protected $checkpointFiles = [];
125
129 public function __construct( $args = null ) {
130 parent::__construct();
131
132 $this->addDescription( <<<TEXT
133This script postprocesses XML dumps from dumpBackup.php to add
134page text which was stubbed out (using --stub).
135
136XML input is accepted on stdin.
137XML output is sent to stdout; progress reports are sent to stderr.
138TEXT
139 );
140 $this->stderr = fopen( "php://stderr", "wt" );
141
142 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
143 'Specify as --stub=<type>:<file>.', false, true );
144 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
145 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
146 false, true );
147 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
148 'out complete page, closing xml file properly, and opening new one' .
149 'with header). This option requires the checkpointfile option.', false, true );
150 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
151 'first pageid written for the first %s (required) and the last pageid written for the ' .
152 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
153 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
154 $this->addOption( 'full', 'Dump all revisions of every page' );
155 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
156 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records, optionally specify ' .
157 'php[,mwscript] paths' );
158 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
159 '(Default: 512 KiB, Minimum: 4 KiB)', false, true );
160
161 if ( $args ) {
162 $this->loadWithArgv( $args );
163 $this->processOptions();
164 }
165 }
166
167 public function finalSetup( SettingsBuilder $settingsBuilder ) {
168 parent::finalSetup( $settingsBuilder );
169
171 }
172
176 private function getBlobStore() {
177 return $this->getServiceContainer()->getBlobStore();
178 }
179
183 private function getRevisionStore() {
184 return $this->getServiceContainer()->getRevisionStore();
185 }
186
187 public function execute() {
188 $this->processOptions();
189 $this->dump( $this->history );
190 }
191
192 protected function processOptions() {
193 parent::processOptions();
194
195 if ( $this->hasOption( 'buffersize' ) ) {
196 $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
197 }
198
199 if ( $this->hasOption( 'prefetch' ) ) {
200 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
201 $this->prefetch = new BaseDump( $url );
202 }
203
204 if ( $this->hasOption( 'stub' ) ) {
205 $this->input = $this->processFileOpt( $this->getOption( 'stub' ) );
206 }
207
208 if ( $this->hasOption( 'maxtime' ) ) {
209 $this->maxTimeAllowed = intval( $this->getOption( 'maxtime' ) ) * 60;
210 }
211
212 if ( $this->hasOption( 'checkpointfile' ) ) {
213 $this->checkpointFiles = $this->getOption( 'checkpointfile' );
214 }
215
216 if ( $this->hasOption( 'current' ) ) {
217 $this->history = WikiExporter::CURRENT;
218 }
219
220 if ( $this->hasOption( 'full' ) ) {
221 $this->history = WikiExporter::FULL;
222 }
223
224 if ( $this->hasOption( 'spawn' ) ) {
225 $this->spawn = true;
226 $val = $this->getOption( 'spawn' );
227 if ( $val !== 1 ) {
228 $this->php = explode( ',', $val, 2 );
229 }
230 }
231 }
232
234 public function initProgress( $history = WikiExporter::FULL ) {
235 parent::initProgress( $history );
236 $this->timeOfCheckpoint = $this->startTime;
237 }
238
240 public function dump( $history, $text = WikiExporter::TEXT ) {
241 // Notice messages will foul up your XML output even if they're
242 // relatively harmless.
243 if ( ini_get( 'display_errors' ) ) {
244 ini_set( 'display_errors', 'stderr' );
245 }
246
247 $this->initProgress( $history );
248
249 $this->egress = new ExportProgressFilter( $this->sink, $this );
250
251 // it would be nice to do it in the constructor, oh well. need egress set
252 $this->finalOptionCheck();
253
254 // we only want this so we know how to close a stream :-P
255 $this->xmlwriterobj = new XmlDumpWriter( XmlDumpWriter::WRITE_CONTENT, $this->schemaVersion );
256
257 $input = fopen( $this->input, "rt" );
258 $this->readDump( $input );
259
260 if ( $this->spawnProc ) {
261 $this->closeSpawn();
262 }
263
264 $this->report( true );
265 }
266
267 protected function processFileOpt( string $opt ): string {
268 $split = explode( ':', $opt, 2 );
269 $val = $split[0];
270 $param = $split[1] ?? '';
271 $newFileURIs = [];
272 foreach ( explode( ';', $param ) as $uri ) {
273 $newFileURIs[] = match ( $val ) {
274 'gzip' => "compress.zlib://$uri",
275 'bzip2' => "compress.bzip2://$uri",
276 '7zip' => "mediawiki.compress.7z://$uri",
277 default => $uri,
278 };
279 }
280 return implode( ';', $newFileURIs );
281 }
282
286 public function showReport() {
287 if ( !$this->prefetch ) {
288 parent::showReport();
289
290 return;
291 }
292
293 if ( $this->reporting ) {
294 $now = ConvertibleTimestamp::now( TS::DB );
295 $nowts = microtime( true );
296 $deltaAll = $nowts - $this->startTime;
297 $deltaPart = $nowts - $this->lastTime;
298 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
299 $this->revCountPart = $this->revCount - $this->revCountLast;
300
301 if ( $deltaAll ) {
302 $portion = $this->revCount / $this->maxCount;
303 $eta = $this->startTime + $deltaAll / $portion;
304 $etats = wfTimestamp( TS::DB, intval( $eta ) );
305 if ( $this->fetchCount ) {
306 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
307 } else {
308 $fetchRate = '-';
309 }
310 $pageRate = $this->pageCount / $deltaAll;
311 $revRate = $this->revCount / $deltaAll;
312 } else {
313 $pageRate = '-';
314 $revRate = '-';
315 $etats = '-';
316 $fetchRate = '-';
317 }
318 if ( $deltaPart ) {
319 if ( $this->fetchCountLast ) {
320 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
321 } else {
322 $fetchRatePart = '-';
323 }
324 $pageRatePart = $this->pageCountPart / $deltaPart;
325 $revRatePart = $this->revCountPart / $deltaPart;
326 } else {
327 $fetchRatePart = '-';
328 $pageRatePart = '-';
329 $revRatePart = '-';
330 }
331
332 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
333 $this->progress( sprintf(
334 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
335 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
336 . "prefetched (all|curr), ETA %s [max %d]",
337 $now, $dbDomain, $this->ID, $this->pageCount, $pageRate,
338 $pageRatePart, $this->revCount, $revRate, $revRatePart,
339 $fetchRate, $fetchRatePart, $etats, $this->maxCount
340 ) );
341 $this->lastTime = $nowts;
342 $this->revCountLast = $this->revCount;
343 $this->prefetchCountLast = $this->prefetchCount;
344 $this->fetchCountLast = $this->fetchCount;
345 }
346 }
347
348 private function setTimeExceeded() {
349 $this->timeExceeded = true;
350 }
351
352 private function checkIfTimeExceeded(): bool {
353 if ( $this->maxTimeAllowed
354 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
355 ) {
356 return true;
357 }
358
359 return false;
360 }
361
362 private function finalOptionCheck() {
363 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
364 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
365 ) {
366 throw new RuntimeException( "Options checkpointfile and maxtime must be specified together.\n" );
367 }
368 foreach ( $this->checkpointFiles as $checkpointFile ) {
369 $count = substr_count( $checkpointFile, "%s" );
370 if ( $count !== 2 ) {
371 throw new RuntimeException( "Option checkpointfile must contain two '%s' "
372 . "for substitution of first and last pageids, count is $count instead, "
373 . "file is $checkpointFile.\n" );
374 }
375 }
376
377 if ( $this->checkpointFiles ) {
378 $filenameList = (array)$this->egress->getFilenames();
379 if ( count( $filenameList ) !== count( $this->checkpointFiles ) ) {
380 throw new RuntimeException( "One checkpointfile must be specified "
381 . "for each output option, if maxtime is used.\n" );
382 }
383 }
384 }
385
391 protected function readDump( $input ) {
392 $this->buffer = "";
393 $this->openElement = false;
394 $this->atStart = true;
395 $this->state = "";
396 $this->lastName = "";
397 $this->thisPage = "";
398 $this->thisRev = "";
399 $this->thisRole = null;
400 $this->thisRevModel = null;
401 $this->thisRevFormat = null;
402
403 $parser = xml_parser_create( "UTF-8" );
404 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
405
406 xml_set_element_handler(
407 $parser,
408 $this->startElement( ... ),
409 $this->endElement( ... )
410 );
411 xml_set_character_data_handler( $parser, $this->characterData( ... ) );
412
413 $offset = 0; // for context extraction on error reporting
414 do {
415 if ( $this->checkIfTimeExceeded() ) {
416 $this->setTimeExceeded();
417 }
418 $chunk = fread( $input, $this->bufferSize );
419 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
420 wfDebug( "TextDumpPass::readDump encountered XML parsing error" );
421
422 $byte = xml_get_current_byte_index( $parser );
423 $msg = wfMessage( 'xml-error-string',
424 'XML import parse failure',
425 xml_get_current_line_number( $parser ),
426 xml_get_current_column_number( $parser ),
427 $byte . ( $chunk === false ? '' : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
428 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
429
430 throw new MWException( $msg );
431 }
432 $offset += strlen( $chunk );
433 } while ( $chunk !== false && !feof( $input ) );
434 if ( $this->maxTimeAllowed ) {
435 $filenameList = (array)$this->egress->getFilenames();
436 // we wrote some stuff after last checkpoint that needs renamed
437 if ( file_exists( $filenameList[0] ) ) {
438 $newFilenames = [];
439 # we might have just written the header and footer and had no
440 # pages or revisions written... perhaps they were all deleted
441 # there's no pageID 0 so we use that. the caller is responsible
442 # for deciding what to do with a file containing only the
443 # siteinfo information and the mw tags.
444 if ( !$this->firstPageWritten ) {
445 $firstPageID = str_pad( '0', 9, "0", STR_PAD_LEFT );
446 $lastPageID = str_pad( '0', 9, "0", STR_PAD_LEFT );
447 } else {
448 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
449 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
450 }
451
452 $filenameCount = count( $filenameList );
453 for ( $i = 0; $i < $filenameCount; $i++ ) {
454 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
455 $fileinfo = pathinfo( $filenameList[$i] );
456 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
457 }
458 $this->egress->closeAndRename( $newFilenames );
459 }
460 }
461
462 return true;
463 }
464
474 private function exportTransform( $text, $model, $format = null ) {
475 try {
476 $contentHandler = $this->getServiceContainer()
477 ->getContentHandlerFactory()
478 ->getContentHandler( $model );
479 } catch ( UnknownContentModelException $ex ) {
480 wfWarn( "Unable to apply export transformation for content model '$model': " .
481 $ex->getMessage() );
482
483 $this->progress(
484 "Unable to apply export transformation for content model '$model': " .
485 $ex->getMessage()
486 );
487 return $text;
488 }
489
490 return $contentHandler->exportTransform( $text, $format );
491 }
492
513 protected function getText( $id, $model = null, $format = null, $expSize = null ) {
514 if ( !$this->isValidTextId( $id ) ) {
515 $msg = "Skipping bad text id " . $id . " of revision " . $this->thisRev;
516 $this->progress( $msg );
517 return '';
518 }
519
520 $model = $model ?: null;
521 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
522 $text = false; // The candidate for a good text. false if no proper value.
523 $failures = 0; // The number of times, this invocation of getText already failed.
524 $contentAddress = $id; // Where the content should be found
525
526 // The number of times getText failed without yielding a good text in between.
527 static $consecutiveFailedTextRetrievals = 0;
528
529 $this->fetchCount++;
530
531 // To allow to simply return on success and do not have to worry about book keeping,
532 // we assume, this fetch works (possible after some retries). Nevertheless, we keep
533 // the old value, so we can restore it, if problems occur (See after the while loop).
534 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
535 $consecutiveFailedTextRetrievals = 0;
536
537 while ( $failures < $this->maxFailures ) {
538 // As soon as we found a good text for the $id, we will return immediately.
539 // Hence, if we make it past the try catch block, we know that we did not
540 // find a good text.
541
542 try {
543 // Step 1: Get some text (or reuse from previous iteratuon if checking
544 // for plausibility failed)
545
546 // Trying to get prefetch, if it has not been tried before
547 // @phan-suppress-next-line PhanRedundantValueComparisonInLoop
548 if ( $text === false && $this->prefetch && $prefetchNotTried ) {
549 $prefetchNotTried = false;
550 $tryIsPrefetch = true;
551 $text = $this->prefetch->prefetch(
552 (int)$this->thisPage,
553 (int)$this->thisRev,
554 trim( $this->thisRole )
555 ) ?? false;
556
557 if ( is_string( $text ) && $model !== null ) {
558 // Apply export transformation to text coming from an old dump.
559 // The purpose of this transformation is to convert up from legacy
560 // formats, which may still be used in the older dump that is used
561 // for pre-fetching. Applying the transformation again should not
562 // interfere with content that is already in the correct form.
563 $text = $this->exportTransform( $text, $model, $format );
564 }
565 }
566
567 if ( $text === false ) {
568 // Fallback to asking the database
569 $tryIsPrefetch = false;
570 if ( $this->spawn ) {
571 $text = $this->getTextSpawned( $contentAddress );
572 } else {
573 $text = $this->getTextDb( $contentAddress );
574 }
575
576 if ( $text !== false && $model !== null ) {
577 // Apply export transformation to text coming from the database.
578 // Prefetched text should already have transformations applied.
579 $text = $this->exportTransform( $text, $model, $format );
580 }
581
582 // No more checks for texts from DB for now.
583 // If we received something that is not false,
584 // We treat it as good text, regardless of whether it actually is or is not
585 if ( $text !== false ) {
586 return $text;
587 }
588 }
589
590 if ( $text === false ) {
591 throw new RuntimeException( "Generic error while obtaining text for id " . $contentAddress );
592 }
593
594 // We received a good candidate for the text of $id via some method
595
596 // Step 2: Checking for plausibility and return the text if it is
597 // plausible
598
599 if ( $expSize === null || strlen( $text ) == $expSize ) {
600 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Set when text is not false
601 if ( $tryIsPrefetch ) {
602 $this->prefetchCount++;
603 }
604
605 return $text;
606 }
607
608 $text = false;
609 throw new RuntimeException( "Received text is unplausible for id " . $contentAddress );
610 } catch ( Exception $e ) {
611 $msg = "getting/checking text " . $contentAddress . " failed (" . $e->getMessage()
612 . ") for revision " . $this->thisRev;
613 if ( $failures + 1 < $this->maxFailures ) {
614 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
615 }
616 $this->progress( $msg );
617 }
618
619 // Something went wrong; we did not get a text that was plausible :(
620 $failures++;
621
622 if ( $contentAddress === $id && $this->thisRev && trim( $this->thisRole ) ) {
623 try {
624 // MediaWiki doesn't guarantee that content addresses are valid
625 // for any significant length of time. Try refreshing as the
626 // previously retrieved address may no longer be valid.
627 $revRecord = $this->getRevisionStore()->getRevisionById( (int)$this->thisRev );
628 if ( $revRecord !== null ) {
629 $refreshed = $revRecord->getSlot( trim( $this->thisRole ) )->getAddress();
630 if ( $contentAddress !== $refreshed ) {
631 $this->progress(
632 "Updated content address for rev {$this->thisRev} from "
633 . "{$contentAddress} to {$refreshed}"
634 );
635 $contentAddress = $refreshed;
636 // Skip sleeping if we updated the address
637 continue;
638 }
639 }
640 } catch ( Exception $e ) {
641 $this->progress(
642 "refreshing content address for revision {$this->thisRev} failed ({$e->getMessage()})"
643 );
644 }
645 }
646
647 // A failure in a prefetch hit does not warrant resetting db connection etc.
648 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Set in the prefetch block above
649 if ( !$tryIsPrefetch ) {
650 // After backing off for some time, we try to reboot the whole process as
651 // much as possible to not carry over failures from one part to the other
652 // parts
653 sleep( $this->failureTimeout );
654 try {
655 if ( $this->spawn ) {
656 $this->closeSpawn();
657 $this->openSpawn();
658 }
659 } catch ( Exception $e ) {
660 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
661 " Trying to continue anyways" );
662 }
663 }
664 }
665
666 // Retrieving a good text for $id failed (at least) maxFailures times.
667 // We abort for this $id.
668
669 // Restoring the consecutive failures, and maybe aborting, if the dump
670 // is too broken.
671 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
672 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
673 throw new MWException( "Graceful storage failure" );
674 }
675
676 return "";
677 }
678
685 private function getTextDb( $id ) {
686 $store = $this->getBlobStore();
687 $address = ( is_int( $id ) || !str_contains( $id, ':' ) )
688 ? SqlBlobStore::makeAddressFromTextId( (int)$id )
689 : $id;
690
691 try {
692 $text = $store->getBlob( $address );
693
694 $stripped = str_replace( "\r", "", $text );
695 $normalized = $this->getServiceContainer()->getContentLanguage()
696 ->normalize( $stripped );
697
698 return $normalized;
699 } catch ( BlobAccessException ) {
700 // XXX: log a warning?
701 return false;
702 }
703 }
704
709 private function getTextSpawned( $address ) {
710 if ( !$this->spawnProc ) {
711 // First time?
712 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
713 @$this->openSpawn();
714 }
715 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
716 return @$this->getTextSpawnedOnce( $address );
717 }
718
719 protected function openSpawn(): bool {
720 $wiki = WikiMap::getCurrentWikiId();
721 if ( count( $this->php ) == 2 ) {
722 $mwscriptpath = $this->php[1];
723 } else {
724 // FIXME: Avoid this hardcoded wmf-config reference.
725 // Perhaps refactor the below by using wfShellWikiCmd or use the
726 // 'wrapper' option which is already injected for this purpose.
727 $mwscriptpath = MW_INSTALL_PATH . '/../multiversion/MWScript.php';
728 }
729 if ( file_exists( $mwscriptpath ) ) {
730 $cmd = implode( " ",
731 array_map( Shell::escape( ... ),
732 [
733 $this->php[0],
734 $mwscriptpath,
735 "fetchText.php",
736 '--wiki', $wiki ] ) );
737 } else {
738 $cmd = implode( " ",
739 array_map( Shell::escape( ... ),
740 [
741 $this->php[0],
742 MW_INSTALL_PATH . '/maintenance/fetchText.php',
743 '--wiki', $wiki ] ) );
744 }
745 $spec = [
746 0 => [ "pipe", "r" ],
747 1 => [ "pipe", "w" ],
748 2 => [ "file", "/dev/null", "a" ] ];
749 $pipes = [];
750
751 $this->progress( "Spawning database subprocess: $cmd" );
752 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
753 if ( !$this->spawnProc ) {
754 $this->progress( "Subprocess spawn failed." );
755
756 return false;
757 }
758 [
759 $this->spawnWrite, // -> stdin
760 $this->spawnRead, // <- stdout
761 ] = $pipes;
762
763 return true;
764 }
765
766 private function closeSpawn() {
767 if ( $this->spawnRead ) {
768 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
769 @fclose( $this->spawnRead );
770 }
771 $this->spawnRead = null;
772 if ( $this->spawnWrite ) {
773 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
774 @fclose( $this->spawnWrite );
775 }
776 $this->spawnWrite = null;
777 if ( $this->spawnErr ) {
778 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
779 @fclose( $this->spawnErr );
780 }
781 $this->spawnErr = false;
782 if ( $this->spawnProc ) {
783 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
784 @proc_close( $this->spawnProc );
785 }
786 $this->spawnProc = false;
787 }
788
793 private function getTextSpawnedOnce( $address ) {
794 if ( is_int( $address ) || intval( $address ) ) {
795 $address = SqlBlobStore::makeAddressFromTextId( (int)$address );
796 }
797
798 $ok = fwrite( $this->spawnWrite, "$address\n" );
799 // $this->progress( ">> $id" );
800 if ( !$ok ) {
801 return false;
802 }
803
804 $ok = fflush( $this->spawnWrite );
805 // $this->progress( ">> [flush]" );
806 if ( !$ok ) {
807 return false;
808 }
809
810 // check that the text address they are sending is the one we asked for
811 // this avoids out of sync revision text errors we have encountered in the past
812 $newAddress = fgets( $this->spawnRead );
813 if ( $newAddress === false ) {
814 return false;
815 }
816 $newAddress = trim( $newAddress );
817 if ( !str_contains( $newAddress, ':' ) ) {
818 $newAddress = SqlBlobStore::makeAddressFromTextId( intval( $newAddress ) );
819 }
820
821 if ( $newAddress !== $address ) {
822 return false;
823 }
824
825 $len = fgets( $this->spawnRead );
826 // $this->progress( "<< " . trim( $len ) );
827 if ( $len === false ) {
828 return false;
829 }
830
831 $nbytes = intval( $len );
832 // actual error, not zero-length text
833 if ( $nbytes < 0 ) {
834 return false;
835 }
836
837 $text = "";
838
839 // Subprocess may not send everything at once, we have to loop.
840 while ( $nbytes > strlen( $text ) ) {
841 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
842 if ( $buffer === false ) {
843 break;
844 }
845 $text .= $buffer;
846 }
847
848 $gotbytes = strlen( $text );
849 if ( $gotbytes != $nbytes ) {
850 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
851
852 return false;
853 }
854
855 // Do normalization in the dump thread...
856 $stripped = str_replace( "\r", "", $text );
857 $normalized = $this->getServiceContainer()->getContentLanguage()->
858 normalize( $stripped );
859
860 return $normalized;
861 }
862
868 protected function startElement( $parser, string $name, array $attribs ) {
869 $this->checkpointJustWritten = false;
870
871 $this->clearOpenElement( null );
872 $this->lastName = $name;
873
874 if ( $name == 'revision' ) {
875 $this->state = $name;
876 $this->egress->writeOpenPage( null, $this->buffer );
877 $this->buffer = "";
878 } elseif ( $name == 'page' ) {
879 $this->state = $name;
880 if ( $this->atStart ) {
881 $this->egress->writeOpenStream( $this->buffer );
882 $this->buffer = "";
883 $this->atStart = false;
884 }
885 } elseif ( $name === 'mediawiki' ) {
886 if ( isset( $attribs['version'] ) ) {
887 if ( $attribs['version'] !== $this->schemaVersion ) {
888 throw new RuntimeException( 'Mismatching schema version. '
889 . 'Use the --schema-version option to set the output schema version to '
890 . 'the version declared by the stub file, namely ' . $attribs['version'] );
891 }
892 }
893 }
894
895 if ( $name == "text" && ( isset( $attribs['id'] ) || isset( $attribs['location'] ) ) ) {
896 $id = $attribs['location'] ?? $attribs['id'];
897 $model = trim( $this->thisRevModel );
898 $format = trim( $this->thisRevFormat );
899
900 $model = $model === '' ? null : $model;
901 $format = $format === '' ? null : $format;
902 $expSize = !empty( $attribs['bytes'] ) && $model === CONTENT_MODEL_WIKITEXT
903 ? (int)$attribs['bytes'] : null;
904
905 $text = $this->getText( $id, $model, $format, $expSize );
906
907 unset( $attribs['id'] );
908 unset( $attribs['location'] );
909 if ( $text !== '' ) {
910 $attribs['xml:space'] = 'preserve';
911 }
912
913 $this->openElement = [ $name, $attribs ];
914 if ( $text !== '' ) {
915 $this->characterData( $parser, $text );
916 }
917 } else {
918 $this->openElement = [ $name, $attribs ];
919 }
920 }
921
926 protected function endElement( $parser, string $name ) {
927 $this->checkpointJustWritten = false;
928
929 if ( $this->openElement ) {
930 $this->clearOpenElement( "" );
931 } else {
932 $this->buffer .= "</$name>";
933 }
934
935 if ( $name == 'revision' ) {
936 $this->egress->writeRevision( null, $this->buffer );
937 $this->buffer = "";
938 $this->thisRev = "";
939 $this->thisRole = null;
940 $this->thisRevModel = null;
941 $this->thisRevFormat = null;
942 } elseif ( $name == 'page' ) {
943 if ( !$this->firstPageWritten ) {
944 $this->firstPageWritten = trim( $this->thisPage );
945 }
946 $this->lastPageWritten = trim( $this->thisPage );
947 if ( $this->timeExceeded ) {
948 $this->egress->writeClosePage( $this->buffer );
949 // nasty hack, we can't just write the chardata after the
950 // page tag, it will include leading blanks from the next line
951 $this->egress->sink->write( "\n" );
952
953 $this->buffer = $this->xmlwriterobj->closeStream();
954 $this->egress->writeCloseStream( $this->buffer );
955
956 $this->buffer = "";
957 $this->thisPage = "";
958 // this could be more than one file if we had more than one output arg
959
960 $filenameList = (array)$this->egress->getFilenames();
961 $newFilenames = [];
962 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
963 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
964 $filenamesCount = count( $filenameList );
965 for ( $i = 0; $i < $filenamesCount; $i++ ) {
966 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
967 $fileinfo = pathinfo( $filenameList[$i] );
968 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
969 }
970 $this->egress->closeRenameAndReopen( $newFilenames );
971 $this->buffer = $this->xmlwriterobj->openStream();
972 $this->timeExceeded = false;
973 $this->timeOfCheckpoint = $this->lastTime;
974 $this->firstPageWritten = false;
975 $this->checkpointJustWritten = true;
976 } else {
977 $this->egress->writeClosePage( $this->buffer );
978 $this->buffer = "";
979 $this->thisPage = "";
980 }
981 } elseif ( $name == 'mediawiki' ) {
982 $this->egress->writeCloseStream( $this->buffer );
983 $this->buffer = "";
984 }
985 }
986
991 protected function characterData( $parser, string $data ) {
992 $this->clearOpenElement( null );
993 if ( $this->lastName == "id" ) {
994 if ( $this->state == "revision" ) {
995 $this->thisRev .= $data;
996 $this->thisRole = SlotRecord::MAIN;
997 } elseif ( $this->state == "page" ) {
998 $this->thisPage .= $data;
999 }
1000 } elseif ( $this->lastName == "model" ) {
1001 $this->thisRevModel .= $data;
1002 } elseif ( $this->lastName == "format" ) {
1003 $this->thisRevFormat .= $data;
1004 } elseif ( $this->lastName == "content" ) {
1005 $this->thisRole = "";
1006 $this->thisRevModel = "";
1007 $this->thisRevFormat = "";
1008 } elseif ( $this->lastName == "role" ) {
1009 $this->thisRole .= $data;
1010 }
1011
1012 // have to skip the newline left over from closepagetag line of
1013 // end of checkpoint files. nasty hack!!
1014 if ( $this->checkpointJustWritten ) {
1015 if ( $data[0] == "\n" ) {
1016 $data = substr( $data, 1 );
1017 }
1018 $this->checkpointJustWritten = false;
1019 }
1020 $this->buffer .= htmlspecialchars( $data, ENT_COMPAT );
1021 }
1022
1023 protected function clearOpenElement( ?string $style ) {
1024 if ( $this->openElement ) {
1025 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
1026 $this->openElement = false;
1027 }
1028 }
1029
1030 private function isValidTextId( string $id ): bool {
1031 if ( preg_match( '/:/', $id ) ) {
1032 return $id !== 'tt:0';
1033 } elseif ( preg_match( '/^\d+$/', $id ) ) {
1034 return intval( $id ) > 0;
1035 }
1036
1037 return false;
1038 }
1039
1040}
1041
1043class_alias( TextPassDumper::class, 'TextPassDumper' );
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:235
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('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
Exception thrown when an unregistered content model is requested.
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
Definition BaseDump.php:33
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.
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.We'll make ETA calculations based on progress,...
startElement( $parser, string $name, array $attribs)
characterData( $parser, string $data)
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.
Service for looking up page revisions.
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:32
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:19
Module of static functions for generating XML.
Definition Xml.php:19
Service for loading and storing data blobs.
Definition BlobStore.php:19
Update the CREDITS list by merging in the list of git commit authors.
if(!isset( $specs[$class])) $spec