Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 492
0.00% covered (danger)
0.00%
0 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
TextPassDumper
0.00% covered (danger)
0.00%
0 / 491
0.00% covered (danger)
0.00%
0 / 26
22650
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
6
 finalSetup
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getBlobStore
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRevisionStore
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 processOptions
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
110
 initProgress
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 dump
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 processFileOpt
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 showReport
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
56
 setTimeExceeded
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 checkIfTimeExceeded
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 finalOptionCheck
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
90
 readDump
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
90
 exportTransform
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 getText
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
930
 getTextDb
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 getTextSpawned
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 openSpawn
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
20
 closeSpawn
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 getTextSpawnedOnce
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
182
 startElement
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
272
 endElement
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
72
 characterData
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
110
 clearOpenElement
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isValidTextId
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
4 *
5 * Copyright (C) 2005 Brooke Vibber <bvibber@wikimedia.org>
6 * https://www.mediawiki.org/
7 *
8 * @license GPL-2.0-or-later
9 * @file
10 * @ingroup Dump
11 * @ingroup Maintenance
12 */
13
14namespace MediaWiki\Maintenance;
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/BackupDumper.php';
18require_once __DIR__ . '/../../includes/Export/WikiExporter.php';
19// @codeCoverageIgnoreEnd
20
21use BaseDump;
22use Exception;
23use ExportProgressFilter;
24use MediaWiki\Exception\MWException;
25use MediaWiki\Exception\MWUnknownContentModelException;
26use MediaWiki\Revision\RevisionStore;
27use MediaWiki\Revision\SlotRecord;
28use MediaWiki\Settings\SettingsBuilder;
29use MediaWiki\Shell\Shell;
30use MediaWiki\Storage\BlobAccessException;
31use MediaWiki\Storage\BlobStore;
32use MediaWiki\Storage\SqlBlobStore;
33use MediaWiki\WikiMap\WikiMap;
34use MediaWiki\Xml\Xml;
35use RuntimeException;
36use WikiExporter;
37use Wikimedia\AtEase\AtEase;
38use Wikimedia\Timestamp\ConvertibleTimestamp;
39use Wikimedia\Timestamp\TimestampFormat as TS;
40use XmlDumpWriter;
41use XMLParser;
42
43/**
44 * @ingroup Maintenance
45 */
46class TextPassDumper extends BackupDumper {
47    /** @var BaseDump|null */
48    public $prefetch = null;
49    /** @var string */
50    private $thisPage;
51    /** @var string */
52    private $thisRev;
53    /** @var string|null */
54    private $thisRole = null;
55
56    /**
57     * @var int when we spend more than maxTimeAllowed seconds on this run, we continue
58     * processing until we write out the next complete page, then save output file(s),
59     * rename it/them and open new one(s); 0 = no limit
60     */
61    public $maxTimeAllowed = 0;
62
63    /** @var string */
64    protected $input = "php://stdin";
65    /** @var int */
66    protected $history = WikiExporter::FULL;
67    /** @var int */
68    protected $fetchCount = 0;
69    /** @var int */
70    protected $prefetchCount = 0;
71    /** @var int */
72    protected $prefetchCountLast = 0;
73    /** @var int */
74    protected $fetchCountLast = 0;
75
76    /** @var int */
77    protected $maxFailures = 5;
78    /** @var int */
79    protected $maxConsecutiveFailedTextRetrievals = 200;
80    /** @var int Seconds to sleep after db failure */
81    protected $failureTimeout = 5;
82
83    /** @var int In bytes. Maximum size to read from the stub in on go. */
84    protected $bufferSize = 524_288;
85
86    /** @var array */
87    protected $php = [ PHP_BINARY ];
88    /** @var bool */
89    protected $spawn = false;
90
91    /**
92     * @var resource|false
93     */
94    protected $spawnProc = false;
95
96    /**
97     * @var resource|null
98     */
99    protected $spawnWrite;
100
101    /**
102     * @var resource|null
103     */
104    protected $spawnRead;
105
106    /**
107     * @var resource|false
108     */
109    protected $spawnErr = false;
110
111    /**
112     * @var XmlDumpWriter|false
113     */
114    protected $xmlwriterobj = false;
115
116    /** @var bool */
117    protected $timeExceeded = false;
118    /** @var string|false */
119    protected $firstPageWritten = false;
120    /** @var string|false */
121    protected $lastPageWritten = false;
122    /** @var bool */
123    protected $checkpointJustWritten = false;
124    /** @var string[] */
125    protected $checkpointFiles = [];
126
127    /**
128     * @param array|null $args For backward compatibility
129     */
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
171        SevenZipStream::register();
172    }
173
174    /**
175     * @return BlobStore
176     */
177    private function getBlobStore() {
178        return $this->getServiceContainer()->getBlobStore();
179    }
180
181    /**
182     * @return RevisionStore
183     */
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
234    /** @inheritDoc */
235    public function initProgress( $history = WikiExporter::FULL ) {
236        parent::initProgress( $history );
237        $this->timeOfCheckpoint = $this->startTime;
238    }
239
240    /** @inheritDoc */
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
284    /**
285     * Overridden to include prefetch ratio if enabled.
286     */
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
387    /**
388     * @throws MWException Failure to parse XML input
389     * @param resource $input
390     * @return bool
391     */
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
466    /**
467     * Applies applicable export transformations to $text.
468     *
469     * @param string $text
470     * @param string $model
471     * @param string|null $format
472     *
473     * @return string
474     */
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
494    /**
495     * Tries to load revision text.
496     * Export transformations are applied if the content model is given or can be
497     * determined from the database.
498     *
499     * Upon errors, retries (Up to $this->maxFailures tries each call).
500     * If still no good revision could be found even after this retrying, "" is returned.
501     * If no good revision text could be returned for
502     * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
503     * is thrown.
504     *
505     * @param int|string $id Content address, or text row ID.
506     * @param string|false|null $model The content model used to determine
507     *  applicable export transformations. If $model is null, no transformation is applied.
508     * @param string|null $format The content format used when applying export transformations.
509     * @param int|null $expSize Expected length of the text, for checks
510     *
511     * @return string The revision text for $id, or ""
512     * @throws MWException
513     */
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
679    /**
680     * Loads the serialized content from storage.
681     *
682     * @param int|string $id Content address, or text row ID.
683     * @return string|false
684     */
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
705    /**
706     * @param int|string $address Content address, or text row ID.
707     * @return string|false
708     */
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
788    /**
789     * @param int|string $address Content address, or text row ID.
790     * @return string|false
791     */
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
862    /**
863     * @param XMLParser $parser
864     * @param string $name
865     * @param array $attribs
866     */
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
921    /**
922     * @param XMLParser $parser
923     * @param string $name
924     */
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
986    /**
987     * @param XMLParser $parser
988     * @param string $data
989     */
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
1041/** @deprecated class alias since 1.43 */
1042class_alias( TextPassDumper::class, 'TextPassDumper' );