MediaWiki  master
WikiExporter.php
Go to the documentation of this file.
1 <?php
32 
36 class WikiExporter {
38  public $list_authors = false;
39 
41  public $dumpUploads = false;
42 
44  public $dumpUploadFileContents = false;
45 
47  public $author_list = "";
48 
49  const FULL = 1;
50  const CURRENT = 2;
51  const STABLE = 4; // extension defined
52  const LOGS = 8;
53  const RANGE = 16;
54 
55  const TEXT = 0;
56  const STUB = 1;
57 
58  const BATCH_SIZE = 50000;
59 
61  public $text;
62 
64  public $sink;
65 
67  private $writer;
68 
73  public static function schemaVersion() {
76  }
77 
89  function __construct( $db, $history = self::CURRENT, $text = self::TEXT,
90  $limitNamespaces = null
91  ) {
92  $this->db = $db;
93  $this->history = $history;
94  $this->writer = new XmlDumpWriter( $text, self::schemaVersion() );
95  $this->sink = new DumpOutput();
96  $this->text = $text;
97  $this->limitNamespaces = $limitNamespaces;
98  }
99 
105  public function setSchemaVersion( $schemaVersion ) {
106  $this->writer = new XmlDumpWriter( $this->text, $schemaVersion );
107  }
108 
116  public function setOutputSink( &$sink ) {
117  $this->sink =& $sink;
118  }
119 
120  public function openStream() {
121  $output = $this->writer->openStream();
122  $this->sink->writeOpenStream( $output );
123  }
124 
125  public function closeStream() {
126  $output = $this->writer->closeStream();
127  $this->sink->writeCloseStream( $output );
128  }
129 
135  public function allPages() {
136  $this->dumpFrom( '' );
137  }
138 
147  public function pagesByRange( $start, $end, $orderRevs ) {
148  if ( $orderRevs ) {
149  $condition = 'rev_page >= ' . intval( $start );
150  if ( $end ) {
151  $condition .= ' AND rev_page < ' . intval( $end );
152  }
153  } else {
154  $condition = 'page_id >= ' . intval( $start );
155  if ( $end ) {
156  $condition .= ' AND page_id < ' . intval( $end );
157  }
158  }
159  $this->dumpFrom( $condition, $orderRevs );
160  }
161 
169  public function revsByRange( $start, $end ) {
170  $condition = 'rev_id >= ' . intval( $start );
171  if ( $end ) {
172  $condition .= ' AND rev_id < ' . intval( $end );
173  }
174  $this->dumpFrom( $condition );
175  }
176 
180  public function pageByTitle( $title ) {
181  $this->dumpFrom(
182  'page_namespace=' . $title->getNamespace() .
183  ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
184  }
185 
190  public function pageByName( $name ) {
192  if ( is_null( $title ) ) {
193  throw new MWException( "Can't export invalid title" );
194  } else {
195  $this->pageByTitle( $title );
196  }
197  }
198 
202  public function pagesByName( $names ) {
203  foreach ( $names as $name ) {
204  $this->pageByName( $name );
205  }
206  }
207 
208  public function allLogs() {
209  $this->dumpFrom( '' );
210  }
211 
216  public function logsByRange( $start, $end ) {
217  $condition = 'log_id >= ' . intval( $start );
218  if ( $end ) {
219  $condition .= ' AND log_id < ' . intval( $end );
220  }
221  $this->dumpFrom( $condition );
222  }
223 
231  protected function do_list_authors( $cond ) {
232  $this->author_list = "<contributors>";
233  // rev_deleted
234 
235  $revQuery = Revision::getQueryInfo( [ 'page' ] );
236  $res = $this->db->select(
237  $revQuery['tables'],
238  [
239  'rev_user_text' => $revQuery['fields']['rev_user_text'],
240  'rev_user' => $revQuery['fields']['rev_user'],
241  ],
242  [
243  $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
244  $cond,
245  ],
246  __METHOD__,
247  [ 'DISTINCT' ],
248  $revQuery['joins']
249  );
250 
251  foreach ( $res as $row ) {
252  $this->author_list .= "<contributor>" .
253  "<username>" .
254  htmlspecialchars( $row->rev_user_text ) .
255  "</username>" .
256  "<id>" .
257  ( (int)$row->rev_user ) .
258  "</id>" .
259  "</contributor>";
260  }
261  $this->author_list .= "</contributors>";
262  }
263 
270  protected function dumpFrom( $cond = '', $orderRevs = false ) {
271  if ( $this->history & self::LOGS ) {
272  $this->dumpLogs( $cond );
273  } else {
274  $this->dumpPages( $cond, $orderRevs );
275  }
276  }
277 
282  protected function dumpLogs( $cond ) {
283  $where = [];
284  # Hide private logs
285  $hideLogs = LogEventsList::getExcludeClause( $this->db );
286  if ( $hideLogs ) {
287  $where[] = $hideLogs;
288  }
289  # Add on any caller specified conditions
290  if ( $cond ) {
291  $where[] = $cond;
292  }
293  # Get logging table name for logging.* clause
294  $logging = $this->db->tableName( 'logging' );
295 
296  $result = null; // Assuring $result is not undefined, if exception occurs early
297 
298  $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
299  $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
300 
301  $lastLogId = 0;
302  while ( true ) {
303  $result = $this->db->select(
304  array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
305  [ "{$logging}.*", 'user_name' ] + $commentQuery['fields'] + $actorQuery['fields'],
306  array_merge( $where, [ 'log_id > ' . intval( $lastLogId ) ] ),
307  __METHOD__,
308  [
309  'ORDER BY' => 'log_id',
310  'USE INDEX' => [ 'logging' => 'PRIMARY' ],
311  'LIMIT' => self::BATCH_SIZE,
312  ],
313  [
314  'user' => [ 'JOIN', 'user_id = ' . $actorQuery['fields']['log_user'] ]
315  ] + $commentQuery['joins'] + $actorQuery['joins']
316  );
317 
318  if ( !$result->numRows() ) {
319  break;
320  }
321 
322  $lastLogId = $this->outputLogStream( $result );
323  };
324  }
325 
332  protected function dumpPages( $cond, $orderRevs ) {
334  if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
335  // TODO: Make XmlDumpWriter use a RevisionStore! (see T198706 and T174031)
336  throw new MWException(
337  'Cannot use WikiExporter with SCHEMA_COMPAT_WRITE_OLD mode disabled!'
338  . ' Support for dumping from the new schema is not implemented yet!'
339  );
340  }
341 
342  $revOpts = [ 'page' ];
343 
344  $revQuery = Revision::getQueryInfo( $revOpts );
345 
346  // We want page primary rather than revision
347  $tables = array_merge( [ 'page' ], array_diff( $revQuery['tables'], [ 'page' ] ) );
348  $join = $revQuery['joins'] + [
349  'revision' => $revQuery['joins']['page']
350  ];
351  unset( $join['page'] );
352 
353  $fields = $revQuery['fields'];
354  $fields[] = 'page_restrictions';
355 
356  if ( $this->text != self::STUB ) {
357  $fields['_load_content'] = '1';
358  }
359 
360  $conds = [];
361  if ( $cond !== '' ) {
362  $conds[] = $cond;
363  }
364  $opts = [ 'ORDER BY' => [ 'rev_page ASC', 'rev_id ASC' ] ];
365  $opts['USE INDEX'] = [];
366 
367  $op = '>';
368  if ( is_array( $this->history ) ) {
369  # Time offset/limit for all pages/history...
370  # Set time order
371  if ( $this->history['dir'] == 'asc' ) {
372  $opts['ORDER BY'] = 'rev_timestamp ASC';
373  } else {
374  $op = '<';
375  $opts['ORDER BY'] = 'rev_timestamp DESC';
376  }
377  # Set offset
378  if ( !empty( $this->history['offset'] ) ) {
379  $conds[] = "rev_timestamp $op " .
380  $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
381  }
382  # Set query limit
383  if ( !empty( $this->history['limit'] ) ) {
384  $maxRowCount = intval( $this->history['limit'] );
385  }
386  } elseif ( $this->history & self::FULL ) {
387  # Full history dumps...
388  # query optimization for history stub dumps
389  if ( $this->text == self::STUB ) {
390  $tables = $revQuery['tables'];
391  $opts[] = 'STRAIGHT_JOIN';
392  $opts['USE INDEX']['revision'] = 'rev_page_id';
393  unset( $join['revision'] );
394  $join['page'] = [ 'JOIN', 'rev_page=page_id' ];
395  }
396  } elseif ( $this->history & self::CURRENT ) {
397  # Latest revision dumps...
398  if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
399  $this->do_list_authors( $cond );
400  }
401  $join['revision'] = [ 'JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
402  } elseif ( $this->history & self::STABLE ) {
403  # "Stable" revision dumps...
404  # Default JOIN, to be overridden...
405  $join['revision'] = [ 'JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
406  # One, and only one hook should set this, and return false
407  if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
408  throw new MWException( __METHOD__ . " given invalid history dump type." );
409  }
410  } elseif ( $this->history & self::RANGE ) {
411  # Dump of revisions within a specified range. Condition already set in revsByRange().
412  } else {
413  # Unknown history specification parameter?
414  throw new MWException( __METHOD__ . " given invalid history dump type." );
415  }
416 
417  $result = null; // Assuring $result is not undefined, if exception occurs early
418  $done = false;
419  $lastRow = null;
420  $revPage = 0;
421  $revId = 0;
422  $rowCount = 0;
423 
424  $opts['LIMIT'] = self::BATCH_SIZE;
425 
426  Hooks::run( 'ModifyExportQuery',
427  [ $this->db, &$tables, &$cond, &$opts, &$join ] );
428 
429  while ( !$done ) {
430  // If necessary, impose the overall maximum and stop looping after this iteration.
431  if ( !empty( $maxRowCount ) && $rowCount + self::BATCH_SIZE > $maxRowCount ) {
432  $opts['LIMIT'] = $maxRowCount - $rowCount;
433  $done = true;
434  }
435 
436  $queryConds = $conds;
437  $queryConds[] = 'rev_page>' . intval( $revPage ) . ' OR (rev_page=' .
438  intval( $revPage ) . ' AND rev_id' . $op . intval( $revId ) . ')';
439 
440  # Do the query and process any results, remembering max ids for the next iteration.
441  $result = $this->db->select(
442  $tables,
443  $fields,
444  $queryConds,
445  __METHOD__,
446  $opts,
447  $join
448  );
449  if ( $result->numRows() > 0 ) {
450  $lastRow = $this->outputPageStreamBatch( $result, $lastRow );
451  $rowCount += $result->numRows();
452  $revPage = $lastRow->rev_page;
453  $revId = $lastRow->rev_id;
454  } else {
455  $done = true;
456  }
457 
458  // If we are finished, close off final page element (if any).
459  if ( $done && $lastRow ) {
460  $this->finishPageStreamOutput( $lastRow );
461  }
462  }
463  }
464 
474  protected function outputPageStreamBatch( $results, $lastRow ) {
475  foreach ( $results as $row ) {
476  if ( $this->limitNamespaces &&
477  !in_array( $row->page_namespace, $this->limitNamespaces ) ) {
478  $lastRow = $row;
479  continue;
480  }
481  if ( $lastRow === null ||
482  $lastRow->page_namespace !== $row->page_namespace ||
483  $lastRow->page_title !== $row->page_title ) {
484  if ( $lastRow !== null ) {
485  $output = '';
486  if ( $this->dumpUploads ) {
487  $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
488  }
489  $output .= $this->writer->closePage();
490  $this->sink->writeClosePage( $output );
491  }
492  $output = $this->writer->openPage( $row );
493  $this->sink->writeOpenPage( $row, $output );
494  }
495  $output = $this->writer->writeRevision( $row );
496  $this->sink->writeRevision( $row, $output );
497  $lastRow = $row;
498  }
499 
500  return $lastRow;
501  }
502 
508  protected function finishPageStreamOutput( $lastRow ) {
509  $output = '';
510  if ( $this->dumpUploads ) {
511  $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
512  }
514  $output .= $this->writer->closePage();
515  $this->sink->writeClosePage( $output );
516  }
517 
522  protected function outputLogStream( $resultset ) {
523  foreach ( $resultset as $row ) {
524  $output = $this->writer->writeLogItem( $row );
525  $this->sink->writeLogItem( $row, $output );
526  }
527  return isset( $row ) ? $row->log_id : null;
528  }
529 }
const SCHEMA_COMPAT_WRITE_OLD
Definition: Defines.php:284
DumpOutput $sink
bool $list_authors
Return distinct author list (when not returning full history)
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables)...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
setOutputSink(&$sink)
Set the DumpOutput or DumpFilter object which will receive various row objects and XML output for fil...
logsByRange( $start, $end)
XmlDumpWriter $writer
allPages()
Dumps a series of page and revision records for all pages in the database, either including complete ...
string $author_list
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
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:979
setSchemaVersion( $schemaVersion)
dumpPages( $cond, $orderRevs)
dumpLogs( $cond)
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
finishPageStreamOutput( $lastRow)
Final page stream output, after all batches are complete.
const BATCH_SIZE
static newMigration()
Static constructor.
outputPageStreamBatch( $results, $lastRow)
Runs through a query result set dumping page and revision records.
$res
Definition: database.txt:21
$wgXmlDumpSchemaVersion
The schema to use per default when generating XML dumps.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
do_list_authors( $cond)
Generates the distinct list of authors of an article Not called by default (depends on $this->list_au...
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object...
Definition: Revision.php:511
pageByTitle( $title)
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
pageByName( $name)
revsByRange( $start, $end)
Dumps a series of page and revision records for those pages in the database with revisions falling wi...
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
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:1766
const DELETED_USER
Definition: Revision.php:48
static getStore()
bool $dumpUploadFileContents
static getExcludeClause( $db, $audience='public', User $user=null)
SQL clause to skip forbidden log types for this user.
An extension writer
Definition: hooks.txt:51
static schemaVersion()
Returns the default export schema version, as defined by $wgXmlDumpSchemaVersion. ...
$revQuery
dumpFrom( $cond='', $orderRevs=false)
__construct( $db, $history=self::CURRENT, $text=self::TEXT, $limitNamespaces=null)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
outputLogStream( $resultset)
pagesByName( $names)
pagesByRange( $start, $end, $orderRevs)
Dumps a series of page and revision records for those pages in the database falling within the page_i...
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319