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}
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
An extension writer
Definition hooks.txt:51
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
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
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
const SCHEMA_COMPAT_WRITE_OLD
Definition Defines.php:284
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38