MediaWiki  1.32.0
dumpTextPass.php
Go to the documentation of this file.
1 <?php
27 require_once __DIR__ . '/includes/BackupDumper.php';
28 require_once __DIR__ . '/7zip.inc';
29 require_once __DIR__ . '/../includes/export/WikiExporter.php';
30 
33 
39  public $prefetch = null;
41  private $thisPage;
43  private $thisRev;
44 
45  // when we spend more than maxTimeAllowed seconds on this run, we continue
46  // processing until we write out the next complete page, then save output file(s),
47  // rename it/them and open new one(s)
48  public $maxTimeAllowed = 0; // 0 = no limit
49 
50  protected $input = "php://stdin";
52  protected $fetchCount = 0;
53  protected $prefetchCount = 0;
54  protected $prefetchCountLast = 0;
55  protected $fetchCountLast = 0;
56 
57  protected $maxFailures = 5;
59  protected $failureTimeout = 5; // Seconds to sleep after db failure
60 
61  protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
62 
63  protected $php = "php";
64  protected $spawn = false;
65 
69  protected $spawnProc = false;
70 
74  protected $spawnWrite = false;
75 
79  protected $spawnRead = false;
80 
84  protected $spawnErr = false;
85 
89  protected $xmlwriterobj = false;
90 
91  protected $timeExceeded = false;
92  protected $firstPageWritten = false;
93  protected $lastPageWritten = false;
94  protected $checkpointJustWritten = false;
95  protected $checkpointFiles = [];
96 
100  protected $db;
101 
105  function __construct( $args = null ) {
106  parent::__construct();
107 
108  $this->addDescription( <<<TEXT
109 This script postprocesses XML dumps from dumpBackup.php to add
110 page text which was stubbed out (using --stub).
111 
112 XML input is accepted on stdin.
113 XML output is sent to stdout; progress reports are sent to stderr.
114 TEXT
115  );
116  $this->stderr = fopen( "php://stderr", "wt" );
117 
118  $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
119  'Specify as --stub=<type>:<file>.', false, true );
120  $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
121  'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
122  false, true );
123  $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
124  'out complete page, closing xml file properly, and opening new one' .
125  'with header). This option requires the checkpointfile option.', false, true );
126  $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
127  'first pageid written for the first %s (required) and the last pageid written for the ' .
128  'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
129  $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
130  $this->addOption( 'full', 'Dump all revisions of every page' );
131  $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
132  $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
133  $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
134  '(Default: 512KB, Minimum: 4KB)', false, true );
135 
136  if ( $args ) {
137  $this->loadWithArgv( $args );
138  $this->processOptions();
139  }
140  }
141 
142  function execute() {
143  $this->processOptions();
144  $this->dump( true );
145  }
146 
147  function processOptions() {
148  parent::processOptions();
149 
150  if ( $this->hasOption( 'buffersize' ) ) {
151  $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
152  }
153 
154  if ( $this->hasOption( 'prefetch' ) ) {
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' ) ) {
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 
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  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
224  $this->lb = $lbFactory->newMainLB();
225  } catch ( Exception $e ) {
226  throw new MWException( __METHOD__
227  . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
228  }
229 
230  try {
231  $this->db = $this->lb->getConnection( DB_REPLICA, 'dump' );
232  } catch ( Exception $e ) {
233  throw new MWException( __METHOD__
234  . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
235  }
236  }
237 
239  parent::initProgress();
240  $this->timeOfCheckpoint = $this->startTime;
241  }
242 
243  function dump( $history, $text = WikiExporter::TEXT ) {
244  // Notice messages will foul up your XML output even if they're
245  // relatively harmless.
246  if ( ini_get( 'display_errors' ) ) {
247  ini_set( 'display_errors', 'stderr' );
248  }
249 
250  $this->initProgress( $this->history );
251 
252  // We are trying to get an initial database connection to avoid that the
253  // first try of this request's first call to getText fails. However, if
254  // obtaining a good DB connection fails it's not a serious issue, as
255  // getText does retry upon failure and can start without having a working
256  // DB connection.
257  try {
258  $this->rotateDb();
259  } catch ( Exception $e ) {
260  // We do not even count this as failure. Just let eventual
261  // watchdogs know.
262  $this->progress( "Getting initial DB connection failed (" .
263  $e->getMessage() . ")" );
264  }
265 
266  $this->egress = new ExportProgressFilter( $this->sink, $this );
267 
268  // it would be nice to do it in the constructor, oh well. need egress set
269  $this->finalOptionCheck();
270 
271  // we only want this so we know how to close a stream :-P
272  $this->xmlwriterobj = new XmlDumpWriter();
273 
274  $input = fopen( $this->input, "rt" );
275  $this->readDump( $input );
276 
277  if ( $this->spawnProc ) {
278  $this->closeSpawn();
279  }
280 
281  $this->report( true );
282  }
283 
284  function processFileOpt( $opt ) {
285  $split = explode( ':', $opt, 2 );
286  $val = $split[0];
287  $param = '';
288  if ( count( $split ) === 2 ) {
289  $param = $split[1];
290  }
291  $fileURIs = explode( ';', $param );
292  foreach ( $fileURIs as $URI ) {
293  switch ( $val ) {
294  case "file":
295  $newURI = $URI;
296  break;
297  case "gzip":
298  $newURI = "compress.zlib://$URI";
299  break;
300  case "bzip2":
301  $newURI = "compress.bzip2://$URI";
302  break;
303  case "7zip":
304  $newURI = "mediawiki.compress.7z://$URI";
305  break;
306  default:
307  $newURI = $URI;
308  }
309  $newFileURIs[] = $newURI;
310  }
311  $val = implode( ';', $newFileURIs );
312 
313  return $val;
314  }
315 
319  function showReport() {
320  if ( !$this->prefetch ) {
321  parent::showReport();
322 
323  return;
324  }
325 
326  if ( $this->reporting ) {
327  $now = wfTimestamp( TS_DB );
328  $nowts = microtime( true );
329  $deltaAll = $nowts - $this->startTime;
330  $deltaPart = $nowts - $this->lastTime;
331  $this->pageCountPart = $this->pageCount - $this->pageCountLast;
332  $this->revCountPart = $this->revCount - $this->revCountLast;
333 
334  if ( $deltaAll ) {
335  $portion = $this->revCount / $this->maxCount;
336  $eta = $this->startTime + $deltaAll / $portion;
337  $etats = wfTimestamp( TS_DB, intval( $eta ) );
338  if ( $this->fetchCount ) {
339  $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
340  } else {
341  $fetchRate = '-';
342  }
343  $pageRate = $this->pageCount / $deltaAll;
344  $revRate = $this->revCount / $deltaAll;
345  } else {
346  $pageRate = '-';
347  $revRate = '-';
348  $etats = '-';
349  $fetchRate = '-';
350  }
351  if ( $deltaPart ) {
352  if ( $this->fetchCountLast ) {
353  $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
354  } else {
355  $fetchRatePart = '-';
356  }
357  $pageRatePart = $this->pageCountPart / $deltaPart;
358  $revRatePart = $this->revCountPart / $deltaPart;
359  } else {
360  $fetchRatePart = '-';
361  $pageRatePart = '-';
362  $revRatePart = '-';
363  }
364  $this->progress( sprintf(
365  "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
366  . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
367  . "prefetched (all|curr), ETA %s [max %d]",
368  $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
369  $pageRatePart, $this->revCount, $revRate, $revRatePart,
370  $fetchRate, $fetchRatePart, $etats, $this->maxCount
371  ) );
372  $this->lastTime = $nowts;
373  $this->revCountLast = $this->revCount;
374  $this->prefetchCountLast = $this->prefetchCount;
375  $this->fetchCountLast = $this->fetchCount;
376  }
377  }
378 
379  function setTimeExceeded() {
380  $this->timeExceeded = true;
381  }
382 
383  function checkIfTimeExceeded() {
384  if ( $this->maxTimeAllowed
385  && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
386  ) {
387  return true;
388  }
389 
390  return false;
391  }
392 
393  function finalOptionCheck() {
394  if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
395  || ( $this->maxTimeAllowed && !$this->checkpointFiles )
396  ) {
397  throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
398  }
399  foreach ( $this->checkpointFiles as $checkpointFile ) {
400  $count = substr_count( $checkpointFile, "%s" );
401  if ( $count != 2 ) {
402  throw new MWException( "Option checkpointfile must contain two '%s' "
403  . "for substitution of first and last pageids, count is $count instead, "
404  . "file is $checkpointFile.\n" );
405  }
406  }
407 
408  if ( $this->checkpointFiles ) {
409  $filenameList = (array)$this->egress->getFilenames();
410  if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
411  throw new MWException( "One checkpointfile must be specified "
412  . "for each output option, if maxtime is used.\n" );
413  }
414  }
415  }
416 
422  function readDump( $input ) {
423  $this->buffer = "";
424  $this->openElement = false;
425  $this->atStart = true;
426  $this->state = "";
427  $this->lastName = "";
428  $this->thisPage = 0;
429  $this->thisRev = 0;
430  $this->thisRevModel = null;
431  $this->thisRevFormat = null;
432 
433  $parser = xml_parser_create( "UTF-8" );
434  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
435 
436  xml_set_element_handler(
437  $parser,
438  [ $this, 'startElement' ],
439  [ $this, 'endElement' ]
440  );
441  xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
442 
443  $offset = 0; // for context extraction on error reporting
444  do {
445  if ( $this->checkIfTimeExceeded() ) {
446  $this->setTimeExceeded();
447  }
448  $chunk = fread( $input, $this->bufferSize );
449  if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
450  wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
451 
452  $byte = xml_get_current_byte_index( $parser );
453  $msg = wfMessage( 'xml-error-string',
454  'XML import parse failure',
455  xml_get_current_line_number( $parser ),
456  xml_get_current_column_number( $parser ),
457  $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
458  xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
459 
460  xml_parser_free( $parser );
461 
462  throw new MWException( $msg );
463  }
464  $offset += strlen( $chunk );
465  } while ( $chunk !== false && !feof( $input ) );
466  if ( $this->maxTimeAllowed ) {
467  $filenameList = (array)$this->egress->getFilenames();
468  // we wrote some stuff after last checkpoint that needs renamed
469  if ( file_exists( $filenameList[0] ) ) {
470  $newFilenames = [];
471  # we might have just written the header and footer and had no
472  # pages or revisions written... perhaps they were all deleted
473  # there's no pageID 0 so we use that. the caller is responsible
474  # for deciding what to do with a file containing only the
475  # siteinfo information and the mw tags.
476  if ( !$this->firstPageWritten ) {
477  $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
478  $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
479  } else {
480  $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
481  $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
482  }
483 
484  $filenameCount = count( $filenameList );
485  for ( $i = 0; $i < $filenameCount; $i++ ) {
486  $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
487  $fileinfo = pathinfo( $filenameList[$i] );
488  $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
489  }
490  $this->egress->closeAndRename( $newFilenames );
491  }
492  }
493  xml_parser_free( $parser );
494 
495  return true;
496  }
497 
507  private function exportTransform( $text, $model, $format = null ) {
508  try {
510  $text = $handler->exportTransform( $text, $format );
511  }
512  catch ( MWException $ex ) {
513  $this->progress(
514  "Unable to apply export transformation for content model '$model': " .
515  $ex->getMessage()
516  );
517  }
518 
519  return $text;
520  }
521 
542  function getText( $id, $model = null, $format = null ) {
543  global $wgContentHandlerUseDB;
544 
545  $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
546  $text = false; // The candidate for a good text. false if no proper value.
547  $failures = 0; // The number of times, this invocation of getText already failed.
548 
549  // The number of times getText failed without yielding a good text in between.
550  static $consecutiveFailedTextRetrievals = 0;
551 
552  $this->fetchCount++;
553 
554  // To allow to simply return on success and do not have to worry about book keeping,
555  // we assume, this fetch works (possible after some retries). Nevertheless, we koop
556  // the old value, so we can restore it, if problems occur (See after the while loop).
557  $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
558  $consecutiveFailedTextRetrievals = 0;
559 
560  if ( $model === null && $wgContentHandlerUseDB ) {
561  $row = $this->db->selectRow(
562  'revision',
563  [ 'rev_content_model', 'rev_content_format' ],
564  [ 'rev_id' => $this->thisRev ],
565  __METHOD__
566  );
567 
568  if ( $row ) {
569  $model = $row->rev_content_model;
570  $format = $row->rev_content_format;
571  }
572  }
573 
574  if ( $model === null || $model === '' ) {
575  $model = false;
576  }
577 
578  while ( $failures < $this->maxFailures ) {
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 
708  private function getTextDb( $id ) {
709  if ( !isset( $this->db ) ) {
710  throw new MWException( __METHOD__ . "No database available" );
711  }
712  $row = $this->db->selectRow( 'text',
713  [ 'old_text', 'old_flags' ],
714  [ 'old_id' => $id ],
715  __METHOD__ );
716  $text = Revision::getRevisionText( $row );
717  if ( $text === false ) {
718  return false;
719  }
720  $stripped = str_replace( "\r", "", $text );
721  $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
722  normalize( $stripped );
723 
724  return $normalized;
725  }
726 
727  private function getTextSpawned( $id ) {
728  Wikimedia\suppressWarnings();
729  if ( !$this->spawnProc ) {
730  // First time?
731  $this->openSpawn();
732  }
733  $text = $this->getTextSpawnedOnce( $id );
734  Wikimedia\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  Wikimedia\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  Wikimedia\restoreWarnings();
798  }
799 
800  private function getTextSpawnedOnce( $id ) {
801  $ok = fwrite( $this->spawnWrite, "$id\n" );
802  // $this->progress( ">> $id" );
803  if ( !$ok ) {
804  return false;
805  }
806 
807  $ok = fflush( $this->spawnWrite );
808  // $this->progress( ">> [flush]" );
809  if ( !$ok ) {
810  return false;
811  }
812 
813  // check that the text id they are sending is the one we asked for
814  // this avoids out of sync revision text errors we have encountered in the past
815  $newId = fgets( $this->spawnRead );
816  if ( $newId === false ) {
817  return false;
818  }
819  if ( $id != intval( $newId ) ) {
820  return false;
821  }
822 
823  $len = fgets( $this->spawnRead );
824  // $this->progress( "<< " . trim( $len ) );
825  if ( $len === false ) {
826  return false;
827  }
828 
829  $nbytes = intval( $len );
830  // actual error, not zero-length text
831  if ( $nbytes < 0 ) {
832  return false;
833  }
834 
835  $text = "";
836 
837  // Subprocess may not send everything at once, we have to loop.
838  while ( $nbytes > strlen( $text ) ) {
839  $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
840  if ( $buffer === false ) {
841  break;
842  }
843  $text .= $buffer;
844  }
845 
846  $gotbytes = strlen( $text );
847  if ( $gotbytes != $nbytes ) {
848  $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
849 
850  return false;
851  }
852 
853  // Do normalization in the dump thread...
854  $stripped = str_replace( "\r", "", $text );
855  $normalized = MediaWikiServices::getInstance()->getContentLanguage()->
856  normalize( $stripped );
857 
858  return $normalized;
859  }
860 
862  $this->checkpointJustWritten = false;
863 
864  $this->clearOpenElement( null );
865  $this->lastName = $name;
866 
867  if ( $name == 'revision' ) {
868  $this->state = $name;
869  $this->egress->writeOpenPage( null, $this->buffer );
870  $this->buffer = "";
871  } elseif ( $name == 'page' ) {
872  $this->state = $name;
873  if ( $this->atStart ) {
874  $this->egress->writeOpenStream( $this->buffer );
875  $this->buffer = "";
876  $this->atStart = false;
877  }
878  }
879 
880  if ( $name == "text" && isset( $attribs['id'] ) ) {
881  $id = $attribs['id'];
882  $model = trim( $this->thisRevModel );
883  $format = trim( $this->thisRevFormat );
884 
885  $model = $model === '' ? null : $model;
886  $format = $format === '' ? null : $format;
887 
888  $text = $this->getText( $id, $model, $format );
889  $this->openElement = [ $name, [ 'xml:space' => 'preserve' ] ];
890  if ( strlen( $text ) > 0 ) {
891  $this->characterData( $parser, $text );
892  }
893  } else {
894  $this->openElement = [ $name, $attribs ];
895  }
896  }
897 
898  function endElement( $parser, $name ) {
899  $this->checkpointJustWritten = false;
900 
901  if ( $this->openElement ) {
902  $this->clearOpenElement( "" );
903  } else {
904  $this->buffer .= "</$name>";
905  }
906 
907  if ( $name == 'revision' ) {
908  $this->egress->writeRevision( null, $this->buffer );
909  $this->buffer = "";
910  $this->thisRev = "";
911  $this->thisRevModel = null;
912  $this->thisRevFormat = null;
913  } elseif ( $name == 'page' ) {
914  if ( !$this->firstPageWritten ) {
915  $this->firstPageWritten = trim( $this->thisPage );
916  }
917  $this->lastPageWritten = trim( $this->thisPage );
918  if ( $this->timeExceeded ) {
919  $this->egress->writeClosePage( $this->buffer );
920  // nasty hack, we can't just write the chardata after the
921  // page tag, it will include leading blanks from the next line
922  $this->egress->sink->write( "\n" );
923 
924  $this->buffer = $this->xmlwriterobj->closeStream();
925  $this->egress->writeCloseStream( $this->buffer );
926 
927  $this->buffer = "";
928  $this->thisPage = "";
929  // this could be more than one file if we had more than one output arg
930 
931  $filenameList = (array)$this->egress->getFilenames();
932  $newFilenames = [];
933  $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
934  $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
935  $filenamesCount = count( $filenameList );
936  for ( $i = 0; $i < $filenamesCount; $i++ ) {
937  $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
938  $fileinfo = pathinfo( $filenameList[$i] );
939  $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
940  }
941  $this->egress->closeRenameAndReopen( $newFilenames );
942  $this->buffer = $this->xmlwriterobj->openStream();
943  $this->timeExceeded = false;
944  $this->timeOfCheckpoint = $this->lastTime;
945  $this->firstPageWritten = false;
946  $this->checkpointJustWritten = true;
947  } else {
948  $this->egress->writeClosePage( $this->buffer );
949  $this->buffer = "";
950  $this->thisPage = "";
951  }
952  } elseif ( $name == 'mediawiki' ) {
953  $this->egress->writeCloseStream( $this->buffer );
954  $this->buffer = "";
955  }
956  }
957 
958  function characterData( $parser, $data ) {
959  $this->clearOpenElement( null );
960  if ( $this->lastName == "id" ) {
961  if ( $this->state == "revision" ) {
962  $this->thisRev .= $data;
963  } elseif ( $this->state == "page" ) {
964  $this->thisPage .= $data;
965  }
966  } elseif ( $this->lastName == "model" ) {
967  $this->thisRevModel .= $data;
968  } elseif ( $this->lastName == "format" ) {
969  $this->thisRevFormat .= $data;
970  }
971 
972  // have to skip the newline left over from closepagetag line of
973  // end of checkpoint files. nasty hack!!
974  if ( $this->checkpointJustWritten ) {
975  if ( $data[0] == "\n" ) {
976  $data = substr( $data, 1 );
977  }
978  $this->checkpointJustWritten = false;
979  }
980  $this->buffer .= htmlspecialchars( $data );
981  }
982 
983  function clearOpenElement( $style ) {
984  if ( $this->openElement ) {
985  $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
986  $this->openElement = false;
987  }
988  }
989 }
990 
992 require_once RUN_MAINTENANCE_IF_MAIN;
TextPassDumper\clearOpenElement
clearOpenElement( $style)
Definition: dumpTextPass.php:983
TextPassDumper\$bufferSize
$bufferSize
Definition: dumpTextPass.php:61
ContentHandler\getForModelID
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
Definition: ContentHandler.php:297
BaseDump
Readahead helper for making large MediaWiki data dumps; reads in a previous XML dump to sequentially ...
Definition: BaseDump.php:42
TextPassDumper\execute
execute()
Do the actual work.
Definition: dumpTextPass.php:142
BackupDumper\revCount
revCount()
Definition: BackupDumper.php:370
TextPassDumper\readDump
readDump( $input)
Definition: dumpTextPass.php:422
TextPassDumper\startElement
startElement( $parser, $name, $attribs)
Definition: dumpTextPass.php:861
TextPassDumper\__construct
__construct( $args=null)
Definition: dumpTextPass.php:105
$opt
$opt
Definition: postprocess-phan.php:115
TextPassDumper\$history
$history
Definition: dumpTextPass.php:51
WikiExporter\CURRENT
const CURRENT
Definition: WikiExporter.php:50
captcha-old.count
count
Definition: captcha-old.py:249
TextPassDumper\processFileOpt
processFileOpt( $opt)
Definition: dumpTextPass.php:284
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:317
TextPassDumper\showReport
showReport()
Overridden to include prefetch ratio if enabled.
Definition: dumpTextPass.php:319
TextPassDumper\$db
IMaintainableDatabase $db
Definition: dumpTextPass.php:100
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1954
TextPassDumper\$spawnProc
bool resource $spawnProc
Definition: dumpTextPass.php:69
BackupDumper\$revCountLast
$revCountLast
Definition: BackupDumper.php:58
TextPassDumper\$maxTimeAllowed
$maxTimeAllowed
Definition: dumpTextPass.php:48
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
Revision\getRevisionText
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Definition: Revision.php:1050
TextPassDumper\$spawnErr
bool resource $spawnErr
Definition: dumpTextPass.php:84
add
An extension or a will often add custom code to the function with or without a global variable For someone wanting email notification when an article is shown may add
Definition: hooks.txt:51
BackupDumper\$pageCountLast
$pageCountLast
Definition: BackupDumper.php:57
TextPassDumper\setTimeExceeded
setTimeExceeded()
Definition: dumpTextPass.php:379
TextPassDumper\rotateDb
rotateDb()
Drop the database connection $this->db and try to get a new one.
Definition: dumpTextPass.php:199
BackupDumper\$revCount
$revCount
Definition: BackupDumper.php:53
TextPassDumper\$xmlwriterobj
bool XmlDumpWriter $xmlwriterobj
Definition: dumpTextPass.php:89
page
target page
Definition: All_system_messages.txt:1267
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:235
$wgContentHandlerUseDB
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility.
Definition: DefaultSettings.php:8624
TextPassDumper\$thisRev
string bool $thisRev
Definition: dumpTextPass.php:43
is
This document provides an overview of the usage of PageUpdater and that is
Definition: pageupdater.txt:3
TextPassDumper\exportTransform
exportTransform( $text, $model, $format=null)
Applies applicable export transformations to $text.
Definition: dumpTextPass.php:507
TextPassDumper\$spawnWrite
bool resource $spawnWrite
Definition: dumpTextPass.php:74
TextPassDumper\finalOptionCheck
finalOptionCheck()
Definition: dumpTextPass.php:393
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
BackupDumper\$forcedDb
IDatabase null $forcedDb
The dependency-injected database to use.
Definition: BackupDumper.php:72
Maintenance\loadWithArgv
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
Definition: Maintenance.php:837
script
script(document.cookie)%253c/script%253e</pre ></div > !! end !! test XSS is escaped(inline) !!input< source lang
TextPassDumper\processOptions
processOptions()
Processes arguments and sets $this->$sink accordingly.
Definition: dumpTextPass.php:147
TextPassDumper\$maxConsecutiveFailedTextRetrievals
$maxConsecutiveFailedTextRetrievals
Definition: dumpTextPass.php:58
MWException
MediaWiki exception.
Definition: MWException.php:26
TextPassDumper\$firstPageWritten
$firstPageWritten
Definition: dumpTextPass.php:92
WikiExporter\TEXT
const TEXT
Definition: WikiExporter.php:55
TextPassDumper\dump
dump( $history, $text=WikiExporter::TEXT)
Definition: dumpTextPass.php:243
TextPassDumper\$prefetchCount
$prefetchCount
Definition: dumpTextPass.php:53
TextPassDumper\$timeExceeded
$timeExceeded
Definition: dumpTextPass.php:91
TextPassDumper\$maxFailures
$maxFailures
Definition: dumpTextPass.php:57
$attribs
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:2036
TextPassDumper\$fetchCountLast
$fetchCountLast
Definition: dumpTextPass.php:55
TextPassDumper\$fetchCount
$fetchCount
Definition: dumpTextPass.php:52
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:236
TextPassDumper\$failureTimeout
$failureTimeout
Definition: dumpTextPass.php:59
TextPassDumper\$spawnRead
bool resource $spawnRead
Definition: dumpTextPass.php:79
$IP
$IP
Definition: update.php:3
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$parser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1841
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
TextPassDumper\checkIfTimeExceeded
checkIfTimeExceeded()
Definition: dumpTextPass.php:383
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:988
TextPassDumper\getTextSpawnedOnce
getTextSpawnedOnce( $id)
Definition: dumpTextPass.php:800
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
TextPassDumper\getText
getText( $id, $model=null, $format=null)
Tries to get the revision text for a revision id.
Definition: dumpTextPass.php:542
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
TextPassDumper\$php
$php
Definition: dumpTextPass.php:63
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2644
TextPassDumper\initProgress
initProgress( $history=WikiExporter::FULL)
Initialise starting time and maximum revision count.
Definition: dumpTextPass.php:238
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2213
BackupDumper\report
report( $final=false)
Definition: BackupDumper.php:375
TextPassDumper\$prefetch
BaseDump $prefetch
Definition: dumpTextPass.php:39
TextPassDumper\$checkpointFiles
$checkpointFiles
Definition: dumpTextPass.php:95
on
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:77
WikiExporter\FULL
const FULL
Definition: WikiExporter.php:49
TextPassDumper\$input
$input
Definition: dumpTextPass.php:50
BackupDumper\progress
progress( $string)
Definition: BackupDumper.php:420
$handler
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:813
TextPassDumper\$prefetchCountLast
$prefetchCountLast
Definition: dumpTextPass.php:54
TextPassDumper\characterData
characterData( $parser, $data)
Definition: dumpTextPass.php:958
text
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
Definition: All_system_messages.txt:1267
$args
if( $line===false) $args
Definition: cdb.php:64
TextPassDumper\getTextDb
getTextDb( $id)
May throw a database error if, say, the server dies during query.
Definition: dumpTextPass.php:708
BackupDumper
Definition: BackupDumper.php:38
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:271
TextPassDumper\getTextSpawned
getTextSpawned( $id)
Definition: dumpTextPass.php:727
TextPassDumper\$lastPageWritten
$lastPageWritten
Definition: dumpTextPass.php:93
TextPassDumper\openSpawn
openSpawn()
Definition: dumpTextPass.php:739
are
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of and so on Built in content types are
Definition: contenthandler.txt:5
history
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc next in line in page history
Definition: hooks.txt:1808
XmlDumpWriter
Definition: XmlDumpWriter.php:31
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
from
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable from
Definition: APACHE-LICENSE-2.0.txt:43
BackupDumper\$lastTime
$lastTime
Definition: BackupDumper.php:56
TextPassDumper\$spawn
$spawn
Definition: dumpTextPass.php:64
TextPassDumper\$thisPage
string bool $thisPage
Definition: dumpTextPass.php:41
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:414
TextPassDumper\endElement
endElement( $parser, $name)
Definition: dumpTextPass.php:898
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
ExportProgressFilter
Definition: ExportProgressFilter.php:27
TextPassDumper
Definition: dumpTextPass.php:37
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:257
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
TextPassDumper\$checkpointJustWritten
$checkpointJustWritten
Definition: dumpTextPass.php:94
$fileinfo
$fileinfo
Definition: generateLocalAutoload.php:18
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
$buffer
$buffer
Definition: mwdoc-filter.php:49
TextPassDumper\closeSpawn
closeSpawn()
Definition: dumpTextPass.php:779
$maintClass
$maintClass
Definition: dumpTextPass.php:985