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