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