MediaWiki REL1_32
WikiExporter.php
Go to the documentation of this file.
1<?php
32
38 public $list_authors = false;
39
41 public $dumpUploads = false;
42
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
70 public static function schemaVersion() {
71 return "0.10";
72 }
73
83 function __construct( $db, $history = self::CURRENT, $text = self::TEXT ) {
84 $this->db = $db;
85 $this->history = $history;
86 $this->writer = new XmlDumpWriter();
87 $this->sink = new DumpOutput();
88 $this->text = $text;
89 }
90
98 public function setOutputSink( &$sink ) {
99 $this->sink =& $sink;
100 }
101
102 public function openStream() {
103 $output = $this->writer->openStream();
104 $this->sink->writeOpenStream( $output );
105 }
106
107 public function closeStream() {
108 $output = $this->writer->closeStream();
109 $this->sink->writeCloseStream( $output );
110 }
111
117 public function allPages() {
118 $this->dumpFrom( '' );
119 }
120
129 public function pagesByRange( $start, $end, $orderRevs ) {
130 if ( $orderRevs ) {
131 $condition = 'rev_page >= ' . intval( $start );
132 if ( $end ) {
133 $condition .= ' AND rev_page < ' . intval( $end );
134 }
135 } else {
136 $condition = 'page_id >= ' . intval( $start );
137 if ( $end ) {
138 $condition .= ' AND page_id < ' . intval( $end );
139 }
140 }
141 $this->dumpFrom( $condition, $orderRevs );
142 }
143
151 public function revsByRange( $start, $end ) {
152 $condition = 'rev_id >= ' . intval( $start );
153 if ( $end ) {
154 $condition .= ' AND rev_id < ' . intval( $end );
155 }
156 $this->dumpFrom( $condition );
157 }
158
162 public function pageByTitle( $title ) {
163 $this->dumpFrom(
164 'page_namespace=' . $title->getNamespace() .
165 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
166 }
167
172 public function pageByName( $name ) {
173 $title = Title::newFromText( $name );
174 if ( is_null( $title ) ) {
175 throw new MWException( "Can't export invalid title" );
176 } else {
177 $this->pageByTitle( $title );
178 }
179 }
180
184 public function pagesByName( $names ) {
185 foreach ( $names as $name ) {
186 $this->pageByName( $name );
187 }
188 }
189
190 public function allLogs() {
191 $this->dumpFrom( '' );
192 }
193
198 public function logsByRange( $start, $end ) {
199 $condition = 'log_id >= ' . intval( $start );
200 if ( $end ) {
201 $condition .= ' AND log_id < ' . intval( $end );
202 }
203 $this->dumpFrom( $condition );
204 }
205
213 protected function do_list_authors( $cond ) {
214 $this->author_list = "<contributors>";
215 // rev_deleted
216
217 $revQuery = Revision::getQueryInfo( [ 'page' ] );
218 $res = $this->db->select(
219 $revQuery['tables'],
220 [
221 'rev_user_text' => $revQuery['fields']['rev_user_text'],
222 'rev_user' => $revQuery['fields']['rev_user'],
223 ],
224 [
225 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
226 $cond,
227 ],
228 __METHOD__,
229 [ 'DISTINCT' ],
230 $revQuery['joins']
231 );
232
233 foreach ( $res as $row ) {
234 $this->author_list .= "<contributor>" .
235 "<username>" .
236 htmlentities( $row->rev_user_text ) .
237 "</username>" .
238 "<id>" .
239 $row->rev_user .
240 "</id>" .
241 "</contributor>";
242 }
243 $this->author_list .= "</contributors>";
244 }
245
252 protected function dumpFrom( $cond = '', $orderRevs = false ) {
253 if ( $this->history & self::LOGS ) {
254 $this->dumpLogs( $cond );
255 } else {
256 $this->dumpPages( $cond, $orderRevs );
257 }
258 }
259
264 protected function dumpLogs( $cond ) {
265 $where = [];
266 # Hide private logs
267 $hideLogs = LogEventsList::getExcludeClause( $this->db );
268 if ( $hideLogs ) {
269 $where[] = $hideLogs;
270 }
271 # Add on any caller specified conditions
272 if ( $cond ) {
273 $where[] = $cond;
274 }
275 # Get logging table name for logging.* clause
276 $logging = $this->db->tableName( 'logging' );
277
278 $result = null; // Assuring $result is not undefined, if exception occurs early
279
280 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
281 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
282
283 $lastLogId = 0;
284 while ( true ) {
285 $result = $this->db->select(
286 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
287 [ "{$logging}.*", 'user_name' ] + $commentQuery['fields'] + $actorQuery['fields'],
288 array_merge( $where, [ 'log_id > ' . intval( $lastLogId ) ] ),
289 __METHOD__,
290 [
291 'ORDER BY' => 'log_id',
292 'USE INDEX' => [ 'logging' => 'PRIMARY' ],
293 'LIMIT' => self::BATCH_SIZE,
294 ],
295 [
296 'user' => [ 'JOIN', 'user_id = ' . $actorQuery['fields']['log_user'] ]
297 ] + $commentQuery['joins'] + $actorQuery['joins']
298 );
299
300 if ( !$result->numRows() ) {
301 break;
302 }
303
304 $lastLogId = $this->outputLogStream( $result );
305 };
306 }
307
314 protected function dumpPages( $cond, $orderRevs ) {
317 // TODO: Make XmlDumpWriter use a RevisionStore! (see T198706 and T174031)
318 throw new MWException(
319 'Cannot use WikiExporter with SCHEMA_COMPAT_WRITE_OLD mode disabled!'
320 . ' Support for dumping from the new schema is not implemented yet!'
321 );
322 }
323
324 $revOpts = [ 'page' ];
325 if ( $this->text != self::STUB ) {
326 // TODO: remove the text and make XmlDumpWriter use a RevisionStore instead! (T198706)
327 $revOpts[] = 'text';
328 }
329 $revQuery = Revision::getQueryInfo( $revOpts );
330
331 // We want page primary rather than revision
332 $tables = array_merge( [ 'page' ], array_diff( $revQuery['tables'], [ 'page' ] ) );
333 $join = $revQuery['joins'] + [
334 'revision' => $revQuery['joins']['page']
335 ];
336 unset( $join['page'] );
337
338 // TODO: remove rev_text_id and make XmlDumpWriter use a RevisionStore instead! (T198706)
339 $fields = array_merge( $revQuery['fields'], [ 'page_restrictions, rev_text_id' ] );
340
341 $conds = [];
342 if ( $cond !== '' ) {
343 $conds[] = $cond;
344 }
345 $opts = [ 'ORDER BY' => [ 'rev_page ASC', 'rev_id ASC' ] ];
346 $opts['USE INDEX'] = [];
347
348 $op = '>';
349 if ( is_array( $this->history ) ) {
350 # Time offset/limit for all pages/history...
351 # Set time order
352 if ( $this->history['dir'] == 'asc' ) {
353 $opts['ORDER BY'] = 'rev_timestamp ASC';
354 } else {
355 $op = '<';
356 $opts['ORDER BY'] = 'rev_timestamp DESC';
357 }
358 # Set offset
359 if ( !empty( $this->history['offset'] ) ) {
360 $conds[] = "rev_timestamp $op " .
361 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
362 }
363 # Set query limit
364 if ( !empty( $this->history['limit'] ) ) {
365 $maxRowCount = intval( $this->history['limit'] );
366 }
367 } elseif ( $this->history & self::FULL ) {
368 # Full history dumps...
369 # query optimization for history stub dumps
370 if ( $this->text == self::STUB ) {
371 $tables = $revQuery['tables'];
372 $opts[] = 'STRAIGHT_JOIN';
373 $opts['USE INDEX']['revision'] = 'rev_page_id';
374 unset( $join['revision'] );
375 $join['page'] = [ 'INNER JOIN', 'rev_page=page_id' ];
376 }
377 } elseif ( $this->history & self::CURRENT ) {
378 # Latest revision dumps...
379 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
380 $this->do_list_authors( $cond );
381 }
382 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
383 } elseif ( $this->history & self::STABLE ) {
384 # "Stable" revision dumps...
385 # Default JOIN, to be overridden...
386 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
387 # One, and only one hook should set this, and return false
388 if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
389 throw new MWException( __METHOD__ . " given invalid history dump type." );
390 }
391 } elseif ( $this->history & self::RANGE ) {
392 # Dump of revisions within a specified range. Condition already set in revsByRange().
393 } else {
394 # Unknown history specification parameter?
395 throw new MWException( __METHOD__ . " given invalid history dump type." );
396 }
397
398 $result = null; // Assuring $result is not undefined, if exception occurs early
399 $done = false;
400 $lastRow = null;
401 $revPage = 0;
402 $revId = 0;
403 $rowCount = 0;
404
405 $opts['LIMIT'] = self::BATCH_SIZE;
406
407 Hooks::run( 'ModifyExportQuery',
408 [ $this->db, &$tables, &$cond, &$opts, &$join ] );
409
410 while ( !$done ) {
411 // If necessary, impose the overall maximum and stop looping after this iteration.
412 if ( !empty( $maxRowCount ) && $rowCount + self::BATCH_SIZE > $maxRowCount ) {
413 $opts['LIMIT'] = $maxRowCount - $rowCount;
414 $done = true;
415 }
416
417 $queryConds = $conds;
418 $queryConds[] = 'rev_page>' . intval( $revPage ) . ' OR (rev_page=' .
419 intval( $revPage ) . ' AND rev_id' . $op . intval( $revId ) . ')';
420
421 # Do the query!
422 $result = $this->db->select(
423 $tables,
424 $fields,
425 $queryConds,
426 __METHOD__,
427 $opts,
428 $join
429 );
430 # Output dump results, get new max ids.
431 $lastRow = $this->outputPageStream( $result, $lastRow );
432
433 if ( !$result->numRows() || !$lastRow ) {
434 $done = true;
435 } else {
436 $rowCount += $result->numRows();
437 $revPage = $lastRow->rev_page;
438 $revId = $lastRow->rev_id;
439 }
440 }
441 }
442
452 protected function outputPageStream( $resultset, $lastRow ) {
453 if ( $resultset->numRows() ) {
454 foreach ( $resultset as $row ) {
455 if ( $lastRow === null ||
456 $lastRow->page_namespace != $row->page_namespace ||
457 $lastRow->page_title != $row->page_title ) {
458 if ( $lastRow !== null ) {
459 $output = '';
460 if ( $this->dumpUploads ) {
461 $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
462 }
463 $output .= $this->writer->closePage();
464 $this->sink->writeClosePage( $output );
465 }
466 $output = $this->writer->openPage( $row );
467 $this->sink->writeOpenPage( $row, $output );
468 }
469 $output = $this->writer->writeRevision( $row );
470 $this->sink->writeRevision( $row, $output );
471 $lastRow = $row;
472 }
473 } elseif ( $lastRow !== null ) {
474 // Empty resultset means done with all batches Close off final page element (if any).
475 $output = '';
476 if ( $this->dumpUploads ) {
477 $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
478 }
479 $output .= $this->author_list;
480 $output .= $this->writer->closePage();
481 $this->sink->writeClosePage( $output );
482 $lastRow = null;
483 }
484
485 return $lastRow;
486 }
487
492 protected function outputLogStream( $resultset ) {
493 foreach ( $resultset as $row ) {
494 $output = $this->writer->writeLogItem( $row );
495 $this->sink->writeLogItem( $row, $output );
496 }
497 return isset( $row ) ? $row->log_id : null;
498 }
499}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables).
static getExcludeClause( $db, $audience='public', User $user=null)
SQL clause to skip forbidden log types for this user.
MediaWiki exception.
const DELETED_USER
Definition Revision.php:49
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
Definition Revision.php:521
revsByRange( $start, $end)
Dumps a series of page and revision records for those pages in the database with revisions falling wi...
dumpFrom( $cond='', $orderRevs=false)
pageByName( $name)
pagesByName( $names)
setOutputSink(&$sink)
Set the DumpOutput or DumpFilter object which will receive various row objects and XML output for fil...
pageByTitle( $title)
outputPageStream( $resultset, $lastRow)
Runs through a query result set dumping page and revision records.
pagesByRange( $start, $end, $orderRevs)
Dumps a series of page and revision records for those pages in the database falling within the page_i...
bool $dumpUploadFileContents
DumpOutput $sink
allPages()
Dumps a series of page and revision records for all pages in the database, either including complete ...
logsByRange( $start, $end)
do_list_authors( $cond)
Generates the distinct list of authors of an article Not called by default (depends on $this->list_au...
dumpPages( $cond, $orderRevs)
__construct( $db, $history=self::CURRENT, $text=self::TEXT)
outputLogStream( $resultset)
static schemaVersion()
Returns the export schema version.
string $author_list
bool $list_authors
Return distinct author list (when not returning full history)
Result wrapper for grabbing data queried from an IDatabase object.
$res
Definition database.txt:21
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
const SCHEMA_COMPAT_WRITE_OLD
Definition Defines.php:284
An extension writer
Definition hooks.txt:51
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:2042
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:1818
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
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:1035
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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:2317
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:37
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38