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