rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / export / WikiExporter.php
blobe0ebaa2411125a2b25c040351f9ec42a74f740f2
1 <?php
2 /**
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
23 * @file
26 /**
27 * @defgroup Dump Dump
30 use Wikimedia\Rdbms\ResultWrapper;
31 use Wikimedia\Rdbms\IDatabase;
33 /**
34 * @ingroup SpecialPage Dump
36 class WikiExporter {
37 /** @var bool Return distinct author list (when not returning full history) */
38 public $list_authors = false;
40 /** @var bool */
41 public $dumpUploads = false;
43 /** @var bool */
44 public $dumpUploadFileContents = false;
46 /** @var string */
47 public $author_list = "";
49 const FULL = 1;
50 const CURRENT = 2;
51 const STABLE = 4; // extension defined
52 const LOGS = 8;
53 const RANGE = 16;
55 const BUFFER = 0;
56 const STREAM = 1;
58 const TEXT = 0;
59 const STUB = 1;
61 /** @var int */
62 public $buffer;
64 /** @var int */
65 public $text;
67 /** @var DumpOutput */
68 public $sink;
70 /**
71 * Returns the export schema version.
72 * @return string
74 public static function schemaVersion() {
75 return "0.10";
78 /**
79 * If using WikiExporter::STREAM to stream a large amount of data,
80 * provide a database connection which is not managed by
81 * LoadBalancer to read from: some history blob types will
82 * make additional queries to pull source data while the
83 * main query is still running.
85 * @param IDatabase $db
86 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
87 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
88 * - offset: non-inclusive offset at which to start the query
89 * - limit: maximum number of rows to return
90 * - dir: "asc" or "desc" timestamp order
91 * @param int $buffer One of WikiExporter::BUFFER or WikiExporter::STREAM
92 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
94 function __construct( $db, $history = self::CURRENT,
95 $buffer = self::BUFFER, $text = self::TEXT ) {
96 $this->db = $db;
97 $this->history = $history;
98 $this->buffer = $buffer;
99 $this->writer = new XmlDumpWriter();
100 $this->sink = new DumpOutput();
101 $this->text = $text;
105 * Set the DumpOutput or DumpFilter object which will receive
106 * various row objects and XML output for filtering. Filters
107 * can be chained or used as callbacks.
109 * @param DumpOutput &$sink
111 public function setOutputSink( &$sink ) {
112 $this->sink =& $sink;
115 public function openStream() {
116 $output = $this->writer->openStream();
117 $this->sink->writeOpenStream( $output );
120 public function closeStream() {
121 $output = $this->writer->closeStream();
122 $this->sink->writeCloseStream( $output );
126 * Dumps a series of page and revision records for all pages
127 * in the database, either including complete history or only
128 * the most recent version.
130 public function allPages() {
131 $this->dumpFrom( '' );
135 * Dumps a series of page and revision records for those pages
136 * in the database falling within the page_id range given.
137 * @param int $start Inclusive lower limit (this id is included)
138 * @param int $end Exclusive upper limit (this id is not included)
139 * If 0, no upper limit.
140 * @param bool $orderRevs order revisions within pages in ascending order
142 public function pagesByRange( $start, $end, $orderRevs ) {
143 if ( $orderRevs ) {
144 $condition = 'rev_page >= ' . intval( $start );
145 if ( $end ) {
146 $condition .= ' AND rev_page < ' . intval( $end );
148 } else {
149 $condition = 'page_id >= ' . intval( $start );
150 if ( $end ) {
151 $condition .= ' AND page_id < ' . intval( $end );
154 $this->dumpFrom( $condition, $orderRevs );
158 * Dumps a series of page and revision records for those pages
159 * in the database with revisions falling within the rev_id range given.
160 * @param int $start Inclusive lower limit (this id is included)
161 * @param int $end Exclusive upper limit (this id is not included)
162 * If 0, no upper limit.
164 public function revsByRange( $start, $end ) {
165 $condition = 'rev_id >= ' . intval( $start );
166 if ( $end ) {
167 $condition .= ' AND rev_id < ' . intval( $end );
169 $this->dumpFrom( $condition );
173 * @param Title $title
175 public function pageByTitle( $title ) {
176 $this->dumpFrom(
177 'page_namespace=' . $title->getNamespace() .
178 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
182 * @param string $name
183 * @throws MWException
185 public function pageByName( $name ) {
186 $title = Title::newFromText( $name );
187 if ( is_null( $title ) ) {
188 throw new MWException( "Can't export invalid title" );
189 } else {
190 $this->pageByTitle( $title );
195 * @param array $names
197 public function pagesByName( $names ) {
198 foreach ( $names as $name ) {
199 $this->pageByName( $name );
203 public function allLogs() {
204 $this->dumpFrom( '' );
208 * @param int $start
209 * @param int $end
211 public function logsByRange( $start, $end ) {
212 $condition = 'log_id >= ' . intval( $start );
213 if ( $end ) {
214 $condition .= ' AND log_id < ' . intval( $end );
216 $this->dumpFrom( $condition );
220 * Generates the distinct list of authors of an article
221 * Not called by default (depends on $this->list_authors)
222 * Can be set by Special:Export when not exporting whole history
224 * @param array $cond
226 protected function do_list_authors( $cond ) {
227 $this->author_list = "<contributors>";
228 // rev_deleted
230 $res = $this->db->select(
231 [ 'page', 'revision' ],
232 [ 'DISTINCT rev_user_text', 'rev_user' ],
234 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
235 $cond,
236 'page_id = rev_id',
238 __METHOD__
241 foreach ( $res as $row ) {
242 $this->author_list .= "<contributor>" .
243 "<username>" .
244 htmlentities( $row->rev_user_text ) .
245 "</username>" .
246 "<id>" .
247 $row->rev_user .
248 "</id>" .
249 "</contributor>";
251 $this->author_list .= "</contributors>";
255 * @param string $cond
256 * @param bool $orderRevs
257 * @throws MWException
258 * @throws Exception
260 protected function dumpFrom( $cond = '', $orderRevs = false ) {
261 # For logging dumps...
262 if ( $this->history & self::LOGS ) {
263 $where = [ 'user_id = log_user' ];
264 # Hide private logs
265 $hideLogs = LogEventsList::getExcludeClause( $this->db );
266 if ( $hideLogs ) {
267 $where[] = $hideLogs;
269 # Add on any caller specified conditions
270 if ( $cond ) {
271 $where[] = $cond;
273 # Get logging table name for logging.* clause
274 $logging = $this->db->tableName( 'logging' );
276 if ( $this->buffer == self::STREAM ) {
277 $prev = $this->db->bufferResults( false );
279 $result = null; // Assuring $result is not undefined, if exception occurs early
280 try {
281 $result = $this->db->select( [ 'logging', 'user' ],
282 [ "{$logging}.*", 'user_name' ], // grab the user name
283 $where,
284 __METHOD__,
285 [ 'ORDER BY' => 'log_id', 'USE INDEX' => [ 'logging' => 'PRIMARY' ] ]
287 $this->outputLogStream( $result );
288 if ( $this->buffer == self::STREAM ) {
289 $this->db->bufferResults( $prev );
291 } catch ( Exception $e ) {
292 // Throwing the exception does not reliably free the resultset, and
293 // would also leave the connection in unbuffered mode.
295 // Freeing result
296 try {
297 if ( $result ) {
298 $result->free();
300 } catch ( Exception $e2 ) {
301 // Already in panic mode -> ignoring $e2 as $e has
302 // higher priority
305 // Putting database back in previous buffer mode
306 try {
307 if ( $this->buffer == self::STREAM ) {
308 $this->db->bufferResults( $prev );
310 } catch ( Exception $e2 ) {
311 // Already in panic mode -> ignoring $e2 as $e has
312 // higher priority
315 // Inform caller about problem
316 throw $e;
318 # For page dumps...
319 } else {
320 $tables = [ 'page', 'revision' ];
321 $opts = [ 'ORDER BY' => 'page_id ASC' ];
322 $opts['USE INDEX'] = [];
323 $join = [];
324 if ( is_array( $this->history ) ) {
325 # Time offset/limit for all pages/history...
326 $revJoin = 'page_id=rev_page';
327 # Set time order
328 if ( $this->history['dir'] == 'asc' ) {
329 $op = '>';
330 $opts['ORDER BY'] = 'rev_timestamp ASC';
331 } else {
332 $op = '<';
333 $opts['ORDER BY'] = 'rev_timestamp DESC';
335 # Set offset
336 if ( !empty( $this->history['offset'] ) ) {
337 $revJoin .= " AND rev_timestamp $op " .
338 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
340 $join['revision'] = [ 'INNER JOIN', $revJoin ];
341 # Set query limit
342 if ( !empty( $this->history['limit'] ) ) {
343 $opts['LIMIT'] = intval( $this->history['limit'] );
345 } elseif ( $this->history & self::FULL ) {
346 # Full history dumps...
347 # query optimization for history stub dumps
348 if ( $this->text == self::STUB && $orderRevs ) {
349 $tables = [ 'revision', 'page' ];
350 $opts[] = 'STRAIGHT_JOIN';
351 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
352 $opts['USE INDEX']['revision'] = 'rev_page_id';
353 $join['page'] = [ 'INNER JOIN', 'rev_page=page_id' ];
354 } else {
355 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
357 } elseif ( $this->history & self::CURRENT ) {
358 # Latest revision dumps...
359 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
360 $this->do_list_authors( $cond );
362 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
363 } elseif ( $this->history & self::STABLE ) {
364 # "Stable" revision dumps...
365 # Default JOIN, to be overridden...
366 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
367 # One, and only one hook should set this, and return false
368 if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
369 throw new MWException( __METHOD__ . " given invalid history dump type." );
371 } elseif ( $this->history & self::RANGE ) {
372 # Dump of revisions within a specified range
373 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
374 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
375 } else {
376 # Unknown history specification parameter?
377 throw new MWException( __METHOD__ . " given invalid history dump type." );
379 # Query optimization hacks
380 if ( $cond == '' ) {
381 $opts[] = 'STRAIGHT_JOIN';
382 $opts['USE INDEX']['page'] = 'PRIMARY';
384 # Build text join options
385 if ( $this->text != self::STUB ) { // 1-pass
386 $tables[] = 'text';
387 $join['text'] = [ 'INNER JOIN', 'rev_text_id=old_id' ];
390 if ( $this->buffer == self::STREAM ) {
391 $prev = $this->db->bufferResults( false );
393 $result = null; // Assuring $result is not undefined, if exception occurs early
394 try {
395 Hooks::run( 'ModifyExportQuery',
396 [ $this->db, &$tables, &$cond, &$opts, &$join ] );
398 # Do the query!
399 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
400 # Output dump results
401 $this->outputPageStream( $result );
403 if ( $this->buffer == self::STREAM ) {
404 $this->db->bufferResults( $prev );
406 } catch ( Exception $e ) {
407 // Throwing the exception does not reliably free the resultset, and
408 // would also leave the connection in unbuffered mode.
410 // Freeing result
411 try {
412 if ( $result ) {
413 $result->free();
415 } catch ( Exception $e2 ) {
416 // Already in panic mode -> ignoring $e2 as $e has
417 // higher priority
420 // Putting database back in previous buffer mode
421 try {
422 if ( $this->buffer == self::STREAM ) {
423 $this->db->bufferResults( $prev );
425 } catch ( Exception $e2 ) {
426 // Already in panic mode -> ignoring $e2 as $e has
427 // higher priority
430 // Inform caller about problem
431 throw $e;
437 * Runs through a query result set dumping page and revision records.
438 * The result set should be sorted/grouped by page to avoid duplicate
439 * page records in the output.
441 * Should be safe for
442 * streaming (non-buffered) queries, as long as it was made on a
443 * separate database connection not managed by LoadBalancer; some
444 * blob storage types will make queries to pull source data.
446 * @param ResultWrapper $resultset
448 protected function outputPageStream( $resultset ) {
449 $last = null;
450 foreach ( $resultset as $row ) {
451 if ( $last === null ||
452 $last->page_namespace != $row->page_namespace ||
453 $last->page_title != $row->page_title ) {
454 if ( $last !== null ) {
455 $output = '';
456 if ( $this->dumpUploads ) {
457 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
459 $output .= $this->writer->closePage();
460 $this->sink->writeClosePage( $output );
462 $output = $this->writer->openPage( $row );
463 $this->sink->writeOpenPage( $row, $output );
464 $last = $row;
466 $output = $this->writer->writeRevision( $row );
467 $this->sink->writeRevision( $row, $output );
469 if ( $last !== null ) {
470 $output = '';
471 if ( $this->dumpUploads ) {
472 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
474 $output .= $this->author_list;
475 $output .= $this->writer->closePage();
476 $this->sink->writeClosePage( $output );
481 * @param ResultWrapper $resultset
483 protected function outputLogStream( $resultset ) {
484 foreach ( $resultset as $row ) {
485 $output = $this->writer->writeLogItem( $row );
486 $this->sink->writeLogItem( $row, $output );