Don't use deprecated User::checkPassword() in TestUser
[mediawiki.git] / maintenance / dumpTextPass.php
blob6d5a0e9d27d953959a1284b8b40e463a538b0496
1 <?php
2 /**
3 * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
5 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
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.
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.
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
23 * @file
24 * @ingroup Maintenance
27 require_once __DIR__ . '/backup.inc';
28 require_once __DIR__ . '/../includes/export/WikiExporter.php';
30 /**
31 * @ingroup Maintenance
33 class TextPassDumper extends BackupDumper {
34 public $prefetch = null;
36 // when we spend more than maxTimeAllowed seconds on this run, we continue
37 // processing until we write out the next complete page, then save output file(s),
38 // rename it/them and open new one(s)
39 public $maxTimeAllowed = 0; // 0 = no limit
41 protected $input = "php://stdin";
42 protected $history = WikiExporter::FULL;
43 protected $fetchCount = 0;
44 protected $prefetchCount = 0;
45 protected $prefetchCountLast = 0;
46 protected $fetchCountLast = 0;
48 protected $maxFailures = 5;
49 protected $maxConsecutiveFailedTextRetrievals = 200;
50 protected $failureTimeout = 5; // Seconds to sleep after db failure
52 protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
54 protected $php = "php";
55 protected $spawn = false;
57 /**
58 * @var bool|resource
60 protected $spawnProc = false;
62 /**
63 * @var bool|resource
65 protected $spawnWrite = false;
67 /**
68 * @var bool|resource
70 protected $spawnRead = false;
72 /**
73 * @var bool|resource
75 protected $spawnErr = false;
77 protected $xmlwriterobj = false;
79 protected $timeExceeded = false;
80 protected $firstPageWritten = false;
81 protected $lastPageWritten = false;
82 protected $checkpointJustWritten = false;
83 protected $checkpointFiles = [];
85 /**
86 * @var DatabaseBase
88 protected $db;
90 /**
91 * @param array $args For backward compatibility
93 function __construct( $args = null ) {
94 parent::__construct();
96 $this->addDescription( <<<TEXT
97 This script postprocesses XML dumps from dumpBackup.php to add
98 page text which was stubbed out (using --stub).
100 XML input is accepted on stdin.
101 XML output is sent to stdout; progress reports are sent to stderr.
102 TEXT
104 $this->stderr = fopen( "php://stderr", "wt" );
106 $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
107 'Specify as --stub=<type>:<file>.', false, true );
108 $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
109 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
110 false, true );
111 $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
112 'out complete page, closing xml file properly, and opening new one' .
113 'with header). This option requires the checkpointfile option.', false, true );
114 $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
115 'first pageid written for the first %s (required) and the last pageid written for the ' .
116 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
117 $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
118 $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
119 $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
120 $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
121 '(Default: 512KB, Minimum: 4KB)', false, true );
123 if ( $args ) {
124 $this->loadWithArgv( $args );
125 $this->processOptions();
129 function execute() {
130 $this->processOptions();
131 $this->dump( true );
134 function processOptions() {
135 global $IP;
137 parent::processOptions();
139 if ( $this->hasOption( 'buffersize' ) ) {
140 $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
143 if ( $this->hasOption( 'prefetch' ) ) {
144 require_once "$IP/maintenance/backupPrefetch.inc";
145 $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
146 $this->prefetch = new BaseDump( $url );
149 if ( $this->hasOption( 'stub' ) ) {
150 $this->input = $this->processFileOpt( $this->getOption( 'stub' ) );
153 if ( $this->hasOption( 'maxtime' ) ) {
154 $this->maxTimeAllowed = intval( $this->getOption( 'maxtime' ) ) * 60;
157 if ( $this->hasOption( 'checkpointfile' ) ) {
158 $this->checkpointFiles = $this->getOption( 'checkpointfile' );
161 if ( $this->hasOption( 'current' ) ) {
162 $this->history = WikiExporter::CURRENT;
165 if ( $this->hasOption( 'full' ) ) {
166 $this->history = WikiExporter::FULL;
169 if ( $this->hasOption( 'spawn' ) ) {
170 $this->spawn = true;
171 $val = $this->getOption( 'spawn' );
172 if ( $val !== 1 ) {
173 $this->php = $val;
179 * Drop the database connection $this->db and try to get a new one.
181 * This function tries to get a /different/ connection if this is
182 * possible. Hence, (if this is possible) it switches to a different
183 * failover upon each call.
185 * This function resets $this->lb and closes all connections on it.
187 * @throws MWException
189 function rotateDb() {
190 // Cleaning up old connections
191 if ( isset( $this->lb ) ) {
192 $this->lb->closeAll();
193 unset( $this->lb );
196 if ( $this->forcedDb !== null ) {
197 $this->db = $this->forcedDb;
199 return;
202 if ( isset( $this->db ) && $this->db->isOpen() ) {
203 throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
206 unset( $this->db );
208 // Trying to set up new connection.
209 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
210 // individually retrying at different layers of code.
212 // 1. The LoadBalancer.
213 try {
214 $this->lb = wfGetLBFactory()->newMainLB();
215 } catch ( Exception $e ) {
216 throw new MWException( __METHOD__
217 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
220 // 2. The Connection, through the load balancer.
221 try {
222 $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
223 } catch ( Exception $e ) {
224 throw new MWException( __METHOD__
225 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
229 function initProgress( $history = WikiExporter::FULL ) {
230 parent::initProgress();
231 $this->timeOfCheckpoint = $this->startTime;
234 function dump( $history, $text = WikiExporter::TEXT ) {
235 // Notice messages will foul up your XML output even if they're
236 // relatively harmless.
237 if ( ini_get( 'display_errors' ) ) {
238 ini_set( 'display_errors', 'stderr' );
241 $this->initProgress( $this->history );
243 // We are trying to get an initial database connection to avoid that the
244 // first try of this request's first call to getText fails. However, if
245 // obtaining a good DB connection fails it's not a serious issue, as
246 // getText does retry upon failure and can start without having a working
247 // DB connection.
248 try {
249 $this->rotateDb();
250 } catch ( Exception $e ) {
251 // We do not even count this as failure. Just let eventual
252 // watchdogs know.
253 $this->progress( "Getting initial DB connection failed (" .
254 $e->getMessage() . ")" );
257 $this->egress = new ExportProgressFilter( $this->sink, $this );
259 // it would be nice to do it in the constructor, oh well. need egress set
260 $this->finalOptionCheck();
262 // we only want this so we know how to close a stream :-P
263 $this->xmlwriterobj = new XmlDumpWriter();
265 $input = fopen( $this->input, "rt" );
266 $this->readDump( $input );
268 if ( $this->spawnProc ) {
269 $this->closeSpawn();
272 $this->report( true );
275 function processFileOpt( $opt ) {
276 $split = explode( ':', $opt, 2 );
277 $val = $split[0];
278 $param = '';
279 if ( count( $split ) === 2 ) {
280 $param = $split[1];
282 $fileURIs = explode( ';', $param );
283 foreach ( $fileURIs as $URI ) {
284 switch ( $val ) {
285 case "file":
286 $newURI = $URI;
287 break;
288 case "gzip":
289 $newURI = "compress.zlib://$URI";
290 break;
291 case "bzip2":
292 $newURI = "compress.bzip2://$URI";
293 break;
294 case "7zip":
295 $newURI = "mediawiki.compress.7z://$URI";
296 break;
297 default:
298 $newURI = $URI;
300 $newFileURIs[] = $newURI;
302 $val = implode( ';', $newFileURIs );
304 return $val;
308 * Overridden to include prefetch ratio if enabled.
310 function showReport() {
311 if ( !$this->prefetch ) {
312 parent::showReport();
314 return;
317 if ( $this->reporting ) {
318 $now = wfTimestamp( TS_DB );
319 $nowts = microtime( true );
320 $deltaAll = $nowts - $this->startTime;
321 $deltaPart = $nowts - $this->lastTime;
322 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
323 $this->revCountPart = $this->revCount - $this->revCountLast;
325 if ( $deltaAll ) {
326 $portion = $this->revCount / $this->maxCount;
327 $eta = $this->startTime + $deltaAll / $portion;
328 $etats = wfTimestamp( TS_DB, intval( $eta ) );
329 if ( $this->fetchCount ) {
330 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
331 } else {
332 $fetchRate = '-';
334 $pageRate = $this->pageCount / $deltaAll;
335 $revRate = $this->revCount / $deltaAll;
336 } else {
337 $pageRate = '-';
338 $revRate = '-';
339 $etats = '-';
340 $fetchRate = '-';
342 if ( $deltaPart ) {
343 if ( $this->fetchCountLast ) {
344 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
345 } else {
346 $fetchRatePart = '-';
348 $pageRatePart = $this->pageCountPart / $deltaPart;
349 $revRatePart = $this->revCountPart / $deltaPart;
350 } else {
351 $fetchRatePart = '-';
352 $pageRatePart = '-';
353 $revRatePart = '-';
355 $this->progress( sprintf(
356 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
357 . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
358 . "prefetched (all|curr), ETA %s [max %d]",
359 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
360 $pageRatePart, $this->revCount, $revRate, $revRatePart,
361 $fetchRate, $fetchRatePart, $etats, $this->maxCount
362 ) );
363 $this->lastTime = $nowts;
364 $this->revCountLast = $this->revCount;
365 $this->prefetchCountLast = $this->prefetchCount;
366 $this->fetchCountLast = $this->fetchCount;
370 function setTimeExceeded() {
371 $this->timeExceeded = true;
374 function checkIfTimeExceeded() {
375 if ( $this->maxTimeAllowed
376 && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
378 return true;
381 return false;
384 function finalOptionCheck() {
385 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
386 || ( $this->maxTimeAllowed && !$this->checkpointFiles )
388 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
390 foreach ( $this->checkpointFiles as $checkpointFile ) {
391 $count = substr_count( $checkpointFile, "%s" );
392 if ( $count != 2 ) {
393 throw new MWException( "Option checkpointfile must contain two '%s' "
394 . "for substitution of first and last pageids, count is $count instead, "
395 . "file is $checkpointFile.\n" );
399 if ( $this->checkpointFiles ) {
400 $filenameList = (array)$this->egress->getFilenames();
401 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
402 throw new MWException( "One checkpointfile must be specified "
403 . "for each output option, if maxtime is used.\n" );
409 * @throws MWException Failure to parse XML input
410 * @param string $input
411 * @return bool
413 function readDump( $input ) {
414 $this->buffer = "";
415 $this->openElement = false;
416 $this->atStart = true;
417 $this->state = "";
418 $this->lastName = "";
419 $this->thisPage = 0;
420 $this->thisRev = 0;
421 $this->thisRevModel = null;
422 $this->thisRevFormat = null;
424 $parser = xml_parser_create( "UTF-8" );
425 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
427 xml_set_element_handler(
428 $parser,
429 [ $this, 'startElement' ],
430 [ $this, 'endElement' ]
432 xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
434 $offset = 0; // for context extraction on error reporting
435 do {
436 if ( $this->checkIfTimeExceeded() ) {
437 $this->setTimeExceeded();
439 $chunk = fread( $input, $this->bufferSize );
440 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
441 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
443 $byte = xml_get_current_byte_index( $parser );
444 $msg = wfMessage( 'xml-error-string',
445 'XML import parse failure',
446 xml_get_current_line_number( $parser ),
447 xml_get_current_column_number( $parser ),
448 $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
449 xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
451 xml_parser_free( $parser );
453 throw new MWException( $msg );
455 $offset += strlen( $chunk );
456 } while ( $chunk !== false && !feof( $input ) );
457 if ( $this->maxTimeAllowed ) {
458 $filenameList = (array)$this->egress->getFilenames();
459 // we wrote some stuff after last checkpoint that needs renamed
460 if ( file_exists( $filenameList[0] ) ) {
461 $newFilenames = [];
462 # we might have just written the header and footer and had no
463 # pages or revisions written... perhaps they were all deleted
464 # there's no pageID 0 so we use that. the caller is responsible
465 # for deciding what to do with a file containing only the
466 # siteinfo information and the mw tags.
467 if ( !$this->firstPageWritten ) {
468 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
469 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
470 } else {
471 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
472 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
475 $filenameCount = count( $filenameList );
476 for ( $i = 0; $i < $filenameCount; $i++ ) {
477 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
478 $fileinfo = pathinfo( $filenameList[$i] );
479 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
481 $this->egress->closeAndRename( $newFilenames );
484 xml_parser_free( $parser );
486 return true;
490 * Applies applicable export transformations to $text.
492 * @param string $text
493 * @param string $model
494 * @param string|null $format
496 * @return string
498 private function exportTransform( $text, $model, $format = null ) {
499 try {
500 $handler = ContentHandler::getForModelID( $model );
501 $text = $handler->exportTransform( $text, $format );
503 catch ( MWException $ex ) {
504 $this->progress(
505 "Unable to apply export transformation for content model '$model': " .
506 $ex->getMessage()
510 return $text;
514 * Tries to get the revision text for a revision id.
515 * Export transformations are applied if the content model can is given or can be
516 * determined from the database.
518 * Upon errors, retries (Up to $this->maxFailures tries each call).
519 * If still no good revision get could be found even after this retrying, "" is returned.
520 * If no good revision text could be returned for
521 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
522 * is thrown.
524 * @param string $id The revision id to get the text for
525 * @param string|bool|null $model The content model used to determine
526 * applicable export transformations.
527 * If $model is null, it will be determined from the database.
528 * @param string|null $format The content format used when applying export transformations.
530 * @throws MWException
531 * @return string The revision text for $id, or ""
533 function getText( $id, $model = null, $format = null ) {
534 global $wgContentHandlerUseDB;
536 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
537 $text = false; // The candidate for a good text. false if no proper value.
538 $failures = 0; // The number of times, this invocation of getText already failed.
540 // The number of times getText failed without yielding a good text in between.
541 static $consecutiveFailedTextRetrievals = 0;
543 $this->fetchCount++;
545 // To allow to simply return on success and do not have to worry about book keeping,
546 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
547 // the old value, so we can restore it, if problems occur (See after the while loop).
548 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
549 $consecutiveFailedTextRetrievals = 0;
551 if ( $model === null && $wgContentHandlerUseDB ) {
552 $row = $this->db->selectRow(
553 'revision',
554 [ 'rev_content_model', 'rev_content_format' ],
555 [ 'rev_id' => $this->thisRev ],
556 __METHOD__
559 if ( $row ) {
560 $model = $row->rev_content_model;
561 $format = $row->rev_content_format;
565 if ( $model === null || $model === '' ) {
566 $model = false;
569 while ( $failures < $this->maxFailures ) {
571 // As soon as we found a good text for the $id, we will return immediately.
572 // Hence, if we make it past the try catch block, we know that we did not
573 // find a good text.
575 try {
576 // Step 1: Get some text (or reuse from previous iteratuon if checking
577 // for plausibility failed)
579 // Trying to get prefetch, if it has not been tried before
580 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
581 $prefetchNotTried = false;
582 $tryIsPrefetch = true;
583 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
584 intval( $this->thisRev ) );
586 if ( $text === null ) {
587 $text = false;
590 if ( is_string( $text ) && $model !== false ) {
591 // Apply export transformation to text coming from an old dump.
592 // The purpose of this transformation is to convert up from legacy
593 // formats, which may still be used in the older dump that is used
594 // for pre-fetching. Applying the transformation again should not
595 // interfere with content that is already in the correct form.
596 $text = $this->exportTransform( $text, $model, $format );
600 if ( $text === false ) {
601 // Fallback to asking the database
602 $tryIsPrefetch = false;
603 if ( $this->spawn ) {
604 $text = $this->getTextSpawned( $id );
605 } else {
606 $text = $this->getTextDb( $id );
609 if ( $text !== false && $model !== false ) {
610 // Apply export transformation to text coming from the database.
611 // Prefetched text should already have transformations applied.
612 $text = $this->exportTransform( $text, $model, $format );
615 // No more checks for texts from DB for now.
616 // If we received something that is not false,
617 // We treat it as good text, regardless of whether it actually is or is not
618 if ( $text !== false ) {
619 return $text;
623 if ( $text === false ) {
624 throw new MWException( "Generic error while obtaining text for id " . $id );
627 // We received a good candidate for the text of $id via some method
629 // Step 2: Checking for plausibility and return the text if it is
630 // plausible
631 $revID = intval( $this->thisRev );
632 if ( !isset( $this->db ) ) {
633 throw new MWException( "No database available" );
636 if ( $model !== CONTENT_MODEL_WIKITEXT ) {
637 $revLength = strlen( $text );
638 } else {
639 $revLength = $this->db->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
642 if ( strlen( $text ) == $revLength ) {
643 if ( $tryIsPrefetch ) {
644 $this->prefetchCount++;
647 return $text;
650 $text = false;
651 throw new MWException( "Received text is unplausible for id " . $id );
652 } catch ( Exception $e ) {
653 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
654 if ( $failures + 1 < $this->maxFailures ) {
655 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
657 $this->progress( $msg );
660 // Something went wrong; we did not a text that was plausible :(
661 $failures++;
663 // A failure in a prefetch hit does not warrant resetting db connection etc.
664 if ( !$tryIsPrefetch ) {
665 // After backing off for some time, we try to reboot the whole process as
666 // much as possible to not carry over failures from one part to the other
667 // parts
668 sleep( $this->failureTimeout );
669 try {
670 $this->rotateDb();
671 if ( $this->spawn ) {
672 $this->closeSpawn();
673 $this->openSpawn();
675 } catch ( Exception $e ) {
676 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
677 " Trying to continue anyways" );
682 // Retirieving a good text for $id failed (at least) maxFailures times.
683 // We abort for this $id.
685 // Restoring the consecutive failures, and maybe aborting, if the dump
686 // is too broken.
687 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
688 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
689 throw new MWException( "Graceful storage failure" );
692 return "";
696 * May throw a database error if, say, the server dies during query.
697 * @param int $id
698 * @return bool|string
699 * @throws MWException
701 private function getTextDb( $id ) {
702 global $wgContLang;
703 if ( !isset( $this->db ) ) {
704 throw new MWException( __METHOD__ . "No database available" );
706 $row = $this->db->selectRow( 'text',
707 [ 'old_text', 'old_flags' ],
708 [ 'old_id' => $id ],
709 __METHOD__ );
710 $text = Revision::getRevisionText( $row );
711 if ( $text === false ) {
712 return false;
714 $stripped = str_replace( "\r", "", $text );
715 $normalized = $wgContLang->normalize( $stripped );
717 return $normalized;
720 private function getTextSpawned( $id ) {
721 MediaWiki\suppressWarnings();
722 if ( !$this->spawnProc ) {
723 // First time?
724 $this->openSpawn();
726 $text = $this->getTextSpawnedOnce( $id );
727 MediaWiki\restoreWarnings();
729 return $text;
732 function openSpawn() {
733 global $IP;
735 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
736 $cmd = implode( " ",
737 array_map( 'wfEscapeShellArg',
739 $this->php,
740 "$IP/../multiversion/MWScript.php",
741 "fetchText.php",
742 '--wiki', wfWikiID() ] ) );
743 } else {
744 $cmd = implode( " ",
745 array_map( 'wfEscapeShellArg',
747 $this->php,
748 "$IP/maintenance/fetchText.php",
749 '--wiki', wfWikiID() ] ) );
751 $spec = [
752 0 => [ "pipe", "r" ],
753 1 => [ "pipe", "w" ],
754 2 => [ "file", "/dev/null", "a" ] ];
755 $pipes = [];
757 $this->progress( "Spawning database subprocess: $cmd" );
758 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
759 if ( !$this->spawnProc ) {
760 $this->progress( "Subprocess spawn failed." );
762 return false;
764 list(
765 $this->spawnWrite, // -> stdin
766 $this->spawnRead, // <- stdout
767 ) = $pipes;
769 return true;
772 private function closeSpawn() {
773 MediaWiki\suppressWarnings();
774 if ( $this->spawnRead ) {
775 fclose( $this->spawnRead );
777 $this->spawnRead = false;
778 if ( $this->spawnWrite ) {
779 fclose( $this->spawnWrite );
781 $this->spawnWrite = false;
782 if ( $this->spawnErr ) {
783 fclose( $this->spawnErr );
785 $this->spawnErr = false;
786 if ( $this->spawnProc ) {
787 pclose( $this->spawnProc );
789 $this->spawnProc = false;
790 MediaWiki\restoreWarnings();
793 private function getTextSpawnedOnce( $id ) {
794 global $wgContLang;
796 $ok = fwrite( $this->spawnWrite, "$id\n" );
797 // $this->progress( ">> $id" );
798 if ( !$ok ) {
799 return false;
802 $ok = fflush( $this->spawnWrite );
803 // $this->progress( ">> [flush]" );
804 if ( !$ok ) {
805 return false;
808 // check that the text id they are sending is the one we asked for
809 // this avoids out of sync revision text errors we have encountered in the past
810 $newId = fgets( $this->spawnRead );
811 if ( $newId === false ) {
812 return false;
814 if ( $id != intval( $newId ) ) {
815 return false;
818 $len = fgets( $this->spawnRead );
819 // $this->progress( "<< " . trim( $len ) );
820 if ( $len === false ) {
821 return false;
824 $nbytes = intval( $len );
825 // actual error, not zero-length text
826 if ( $nbytes < 0 ) {
827 return false;
830 $text = "";
832 // Subprocess may not send everything at once, we have to loop.
833 while ( $nbytes > strlen( $text ) ) {
834 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
835 if ( $buffer === false ) {
836 break;
838 $text .= $buffer;
841 $gotbytes = strlen( $text );
842 if ( $gotbytes != $nbytes ) {
843 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
845 return false;
848 // Do normalization in the dump thread...
849 $stripped = str_replace( "\r", "", $text );
850 $normalized = $wgContLang->normalize( $stripped );
852 return $normalized;
855 function startElement( $parser, $name, $attribs ) {
856 $this->checkpointJustWritten = false;
858 $this->clearOpenElement( null );
859 $this->lastName = $name;
861 if ( $name == 'revision' ) {
862 $this->state = $name;
863 $this->egress->writeOpenPage( null, $this->buffer );
864 $this->buffer = "";
865 } elseif ( $name == 'page' ) {
866 $this->state = $name;
867 if ( $this->atStart ) {
868 $this->egress->writeOpenStream( $this->buffer );
869 $this->buffer = "";
870 $this->atStart = false;
874 if ( $name == "text" && isset( $attribs['id'] ) ) {
875 $id = $attribs['id'];
876 $model = trim( $this->thisRevModel );
877 $format = trim( $this->thisRevFormat );
879 $model = $model === '' ? null : $model;
880 $format = $format === '' ? null : $format;
882 $text = $this->getText( $id, $model, $format );
883 $this->openElement = [ $name, [ 'xml:space' => 'preserve' ] ];
884 if ( strlen( $text ) > 0 ) {
885 $this->characterData( $parser, $text );
887 } else {
888 $this->openElement = [ $name, $attribs ];
892 function endElement( $parser, $name ) {
893 $this->checkpointJustWritten = false;
895 if ( $this->openElement ) {
896 $this->clearOpenElement( "" );
897 } else {
898 $this->buffer .= "</$name>";
901 if ( $name == 'revision' ) {
902 $this->egress->writeRevision( null, $this->buffer );
903 $this->buffer = "";
904 $this->thisRev = "";
905 $this->thisRevModel = null;
906 $this->thisRevFormat = null;
907 } elseif ( $name == 'page' ) {
908 if ( !$this->firstPageWritten ) {
909 $this->firstPageWritten = trim( $this->thisPage );
911 $this->lastPageWritten = trim( $this->thisPage );
912 if ( $this->timeExceeded ) {
913 $this->egress->writeClosePage( $this->buffer );
914 // nasty hack, we can't just write the chardata after the
915 // page tag, it will include leading blanks from the next line
916 $this->egress->sink->write( "\n" );
918 $this->buffer = $this->xmlwriterobj->closeStream();
919 $this->egress->writeCloseStream( $this->buffer );
921 $this->buffer = "";
922 $this->thisPage = "";
923 // this could be more than one file if we had more than one output arg
925 $filenameList = (array)$this->egress->getFilenames();
926 $newFilenames = [];
927 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
928 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
929 $filenamesCount = count( $filenameList );
930 for ( $i = 0; $i < $filenamesCount; $i++ ) {
931 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
932 $fileinfo = pathinfo( $filenameList[$i] );
933 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
935 $this->egress->closeRenameAndReopen( $newFilenames );
936 $this->buffer = $this->xmlwriterobj->openStream();
937 $this->timeExceeded = false;
938 $this->timeOfCheckpoint = $this->lastTime;
939 $this->firstPageWritten = false;
940 $this->checkpointJustWritten = true;
941 } else {
942 $this->egress->writeClosePage( $this->buffer );
943 $this->buffer = "";
944 $this->thisPage = "";
946 } elseif ( $name == 'mediawiki' ) {
947 $this->egress->writeCloseStream( $this->buffer );
948 $this->buffer = "";
952 function characterData( $parser, $data ) {
953 $this->clearOpenElement( null );
954 if ( $this->lastName == "id" ) {
955 if ( $this->state == "revision" ) {
956 $this->thisRev .= $data;
957 } elseif ( $this->state == "page" ) {
958 $this->thisPage .= $data;
960 } elseif ( $this->lastName == "model" ) {
961 $this->thisRevModel .= $data;
962 } elseif ( $this->lastName == "format" ) {
963 $this->thisRevFormat .= $data;
966 // have to skip the newline left over from closepagetag line of
967 // end of checkpoint files. nasty hack!!
968 if ( $this->checkpointJustWritten ) {
969 if ( $data[0] == "\n" ) {
970 $data = substr( $data, 1 );
972 $this->checkpointJustWritten = false;
974 $this->buffer .= htmlspecialchars( $data );
977 function clearOpenElement( $style ) {
978 if ( $this->openElement ) {
979 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
980 $this->openElement = false;
985 $maintClass = 'TextPassDumper';
986 require_once RUN_MAINTENANCE_IF_MAIN;