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