3 * Base class for exporting
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
31 * @ingroup SpecialPage Dump
34 /** @var bool Return distinct author list (when not returning full history) */
35 public $list_authors = false;
38 public $dumpUploads = false;
41 public $dumpUploadFileContents = false;
44 public $author_list = "";
48 const STABLE
= 4; // extension defined
64 /** @var DumpOutput */
68 * Returns the export schema version.
71 public static function schemaVersion() {
76 * If using WikiExporter::STREAM to stream a large amount of data,
77 * provide a database connection which is not managed by
78 * LoadBalancer to read from: some history blob types will
79 * make additional queries to pull source data while the
80 * main query is still running.
82 * @param IDatabase $db
83 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
84 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
85 * - offset: non-inclusive offset at which to start the query
86 * - limit: maximum number of rows to return
87 * - dir: "asc" or "desc" timestamp order
88 * @param int $buffer One of WikiExporter::BUFFER or WikiExporter::STREAM
89 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
91 function __construct( $db, $history = WikiExporter
::CURRENT
,
92 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
94 $this->history
= $history;
95 $this->buffer
= $buffer;
96 $this->writer
= new XmlDumpWriter();
97 $this->sink
= new DumpOutput();
102 * Set the DumpOutput or DumpFilter object which will receive
103 * various row objects and XML output for filtering. Filters
104 * can be chained or used as callbacks.
106 * @param DumpOutput $sink
108 public function setOutputSink( &$sink ) {
109 $this->sink
=& $sink;
112 public function openStream() {
113 $output = $this->writer
->openStream();
114 $this->sink
->writeOpenStream( $output );
117 public function closeStream() {
118 $output = $this->writer
->closeStream();
119 $this->sink
->writeCloseStream( $output );
123 * Dumps a series of page and revision records for all pages
124 * in the database, either including complete history or only
125 * the most recent version.
127 public function allPages() {
128 $this->dumpFrom( '' );
132 * Dumps a series of page and revision records for those pages
133 * in the database falling within the page_id range given.
134 * @param int $start Inclusive lower limit (this id is included)
135 * @param int $end Exclusive upper limit (this id is not included)
136 * If 0, no upper limit.
137 * @param bool $orderRevs order revisions within pages in ascending order
139 public function pagesByRange( $start, $end, $orderRevs ) {
141 $condition = 'rev_page >= ' . intval( $start );
143 $condition .= ' AND rev_page < ' . intval( $end );
146 $condition = 'page_id >= ' . intval( $start );
148 $condition .= ' AND page_id < ' . intval( $end );
151 $this->dumpFrom( $condition, $orderRevs );
155 * Dumps a series of page and revision records for those pages
156 * in the database with revisions falling within the rev_id range given.
157 * @param int $start Inclusive lower limit (this id is included)
158 * @param int $end Exclusive upper limit (this id is not included)
159 * If 0, no upper limit.
161 public function revsByRange( $start, $end ) {
162 $condition = 'rev_id >= ' . intval( $start );
164 $condition .= ' AND rev_id < ' . intval( $end );
166 $this->dumpFrom( $condition );
170 * @param Title $title
172 public function pageByTitle( $title ) {
174 'page_namespace=' . $title->getNamespace() .
175 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
179 * @param string $name
180 * @throws MWException
182 public function pageByName( $name ) {
183 $title = Title
::newFromText( $name );
184 if ( is_null( $title ) ) {
185 throw new MWException( "Can't export invalid title" );
187 $this->pageByTitle( $title );
192 * @param array $names
194 public function pagesByName( $names ) {
195 foreach ( $names as $name ) {
196 $this->pageByName( $name );
200 public function allLogs() {
201 $this->dumpFrom( '' );
208 public function logsByRange( $start, $end ) {
209 $condition = 'log_id >= ' . intval( $start );
211 $condition .= ' AND log_id < ' . intval( $end );
213 $this->dumpFrom( $condition );
217 * Generates the distinct list of authors of an article
218 * Not called by default (depends on $this->list_authors)
219 * Can be set by Special:Export when not exporting whole history
223 protected function do_list_authors( $cond ) {
224 $this->author_list
= "<contributors>";
227 $res = $this->db
->select(
228 [ 'page', 'revision' ],
229 [ 'DISTINCT rev_user_text', 'rev_user' ],
231 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
238 foreach ( $res as $row ) {
239 $this->author_list
.= "<contributor>" .
241 htmlentities( $row->rev_user_text
) .
248 $this->author_list
.= "</contributors>";
252 * @param string $cond
253 * @throws MWException
256 protected function dumpFrom( $cond = '', $orderRevs = false ) {
257 # For logging dumps...
258 if ( $this->history
& self
::LOGS
) {
259 $where = [ 'user_id = log_user' ];
261 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
263 $where[] = $hideLogs;
265 # Add on any caller specified conditions
269 # Get logging table name for logging.* clause
270 $logging = $this->db
->tableName( 'logging' );
272 if ( $this->buffer
== WikiExporter
::STREAM
) {
273 $prev = $this->db
->bufferResults( false );
275 $result = null; // Assuring $result is not undefined, if exception occurs early
277 $result = $this->db
->select( [ 'logging', 'user' ],
278 [ "{$logging}.*", 'user_name' ], // grab the user name
281 [ 'ORDER BY' => 'log_id', 'USE INDEX' => [ 'logging' => 'PRIMARY' ] ]
283 $this->outputLogStream( $result );
284 if ( $this->buffer
== WikiExporter
::STREAM
) {
285 $this->db
->bufferResults( $prev );
287 } catch ( Exception
$e ) {
288 // Throwing the exception does not reliably free the resultset, and
289 // would also leave the connection in unbuffered mode.
296 } catch ( Exception
$e2 ) {
297 // Already in panic mode -> ignoring $e2 as $e has
301 // Putting database back in previous buffer mode
303 if ( $this->buffer
== WikiExporter
::STREAM
) {
304 $this->db
->bufferResults( $prev );
306 } catch ( Exception
$e2 ) {
307 // Already in panic mode -> ignoring $e2 as $e has
311 // Inform caller about problem
316 $tables = [ 'page', 'revision' ];
317 $opts = [ 'ORDER BY' => 'page_id ASC' ];
318 $opts['USE INDEX'] = [];
320 if ( is_array( $this->history
) ) {
321 # Time offset/limit for all pages/history...
322 $revJoin = 'page_id=rev_page';
324 if ( $this->history
['dir'] == 'asc' ) {
326 $opts['ORDER BY'] = 'rev_timestamp ASC';
329 $opts['ORDER BY'] = 'rev_timestamp DESC';
332 if ( !empty( $this->history
['offset'] ) ) {
333 $revJoin .= " AND rev_timestamp $op " .
334 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
336 $join['revision'] = [ 'INNER JOIN', $revJoin ];
338 if ( !empty( $this->history
['limit'] ) ) {
339 $opts['LIMIT'] = intval( $this->history
['limit'] );
341 } elseif ( $this->history
& WikiExporter
::FULL
) {
342 # Full history dumps...
343 # query optimization for history stub dumps
344 if ( $this->text
== WikiExporter
::STUB
&& $orderRevs ) {
345 $tables = [ 'revision', 'page' ];
346 $opts[] = 'STRAIGHT_JOIN';
347 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
348 $opts['USE INDEX']['revision'] = 'rev_page_id';
349 $join['page'] = [ 'INNER JOIN', 'rev_page=page_id' ];
351 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
353 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
354 # Latest revision dumps...
355 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
356 $this->do_list_authors( $cond );
358 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
359 } elseif ( $this->history
& WikiExporter
::STABLE
) {
360 # "Stable" revision dumps...
361 # Default JOIN, to be overridden...
362 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
363 # One, and only one hook should set this, and return false
364 if ( Hooks
::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
365 throw new MWException( __METHOD__
. " given invalid history dump type." );
367 } elseif ( $this->history
& WikiExporter
::RANGE
) {
368 # Dump of revisions within a specified range
369 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
370 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
372 # Unknown history specification parameter?
373 throw new MWException( __METHOD__
. " given invalid history dump type." );
375 # Query optimization hacks
377 $opts[] = 'STRAIGHT_JOIN';
378 $opts['USE INDEX']['page'] = 'PRIMARY';
380 # Build text join options
381 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
383 $join['text'] = [ 'INNER JOIN', 'rev_text_id=old_id' ];
386 if ( $this->buffer
== WikiExporter
::STREAM
) {
387 $prev = $this->db
->bufferResults( false );
389 $result = null; // Assuring $result is not undefined, if exception occurs early
391 Hooks
::run( 'ModifyExportQuery',
392 [ $this->db
, &$tables, &$cond, &$opts, &$join ] );
395 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
396 # Output dump results
397 $this->outputPageStream( $result );
399 if ( $this->buffer
== WikiExporter
::STREAM
) {
400 $this->db
->bufferResults( $prev );
402 } catch ( Exception
$e ) {
403 // Throwing the exception does not reliably free the resultset, and
404 // would also leave the connection in unbuffered mode.
411 } catch ( Exception
$e2 ) {
412 // Already in panic mode -> ignoring $e2 as $e has
416 // Putting database back in previous buffer mode
418 if ( $this->buffer
== WikiExporter
::STREAM
) {
419 $this->db
->bufferResults( $prev );
421 } catch ( Exception
$e2 ) {
422 // Already in panic mode -> ignoring $e2 as $e has
426 // Inform caller about problem
433 * Runs through a query result set dumping page and revision records.
434 * The result set should be sorted/grouped by page to avoid duplicate
435 * page records in the output.
438 * streaming (non-buffered) queries, as long as it was made on a
439 * separate database connection not managed by LoadBalancer; some
440 * blob storage types will make queries to pull source data.
442 * @param ResultWrapper $resultset
444 protected function outputPageStream( $resultset ) {
446 foreach ( $resultset as $row ) {
447 if ( $last === null ||
448 $last->page_namespace
!= $row->page_namespace ||
449 $last->page_title
!= $row->page_title
) {
450 if ( $last !== null ) {
452 if ( $this->dumpUploads
) {
453 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
455 $output .= $this->writer
->closePage();
456 $this->sink
->writeClosePage( $output );
458 $output = $this->writer
->openPage( $row );
459 $this->sink
->writeOpenPage( $row, $output );
462 $output = $this->writer
->writeRevision( $row );
463 $this->sink
->writeRevision( $row, $output );
465 if ( $last !== null ) {
467 if ( $this->dumpUploads
) {
468 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
470 $output .= $this->author_list
;
471 $output .= $this->writer
->closePage();
472 $this->sink
->writeClosePage( $output );
477 * @param ResultWrapper $resultset
479 protected function outputLogStream( $resultset ) {
480 foreach ( $resultset as $row ) {
481 $output = $this->writer
->writeLogItem( $row );
482 $this->sink
->writeLogItem( $row, $output );