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