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