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