Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / export / WikiExporter.php
blobc1f2d59dcc4737cb99c19e1d4502e1ddebca536f
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 /**
31 * @ingroup SpecialPage Dump
33 class WikiExporter {
34 /** @var bool Return distinct author list (when not returning full history) */
35 public $list_authors = false;
37 /** @var bool */
38 public $dumpUploads = false;
40 /** @var bool */
41 public $dumpUploadFileContents = false;
43 /** @var string */
44 public $author_list = "";
46 const FULL = 1;
47 const CURRENT = 2;
48 const STABLE = 4; // extension defined
49 const LOGS = 8;
50 const RANGE = 16;
52 const BUFFER = 0;
53 const STREAM = 1;
55 const TEXT = 0;
56 const STUB = 1;
58 /** @var int */
59 public $buffer;
61 /** @var int */
62 public $text;
64 /** @var DumpOutput */
65 public $sink;
67 /**
68 * Returns the export schema version.
69 * @return string
71 public static function schemaVersion() {
72 return "0.10";
75 /**
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 ) {
93 $this->db = $db;
94 $this->history = $history;
95 $this->buffer = $buffer;
96 $this->writer = new XmlDumpWriter();
97 $this->sink = new DumpOutput();
98 $this->text = $text;
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 ) {
140 if ( $orderRevs ) {
141 $condition = 'rev_page >= ' . intval( $start );
142 if ( $end ) {
143 $condition .= ' AND rev_page < ' . intval( $end );
145 } else {
146 $condition = 'page_id >= ' . intval( $start );
147 if ( $end ) {
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 );
163 if ( $end ) {
164 $condition .= ' AND rev_id < ' . intval( $end );
166 $this->dumpFrom( $condition );
170 * @param Title $title
172 public function pageByTitle( $title ) {
173 $this->dumpFrom(
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" );
186 } else {
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( '' );
205 * @param int $start
206 * @param int $end
208 public function logsByRange( $start, $end ) {
209 $condition = 'log_id >= ' . intval( $start );
210 if ( $end ) {
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
221 * @param array $cond
223 protected function do_list_authors( $cond ) {
224 $this->author_list = "<contributors>";
225 // rev_deleted
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',
232 $cond,
233 'page_id = rev_id',
235 __METHOD__
238 foreach ( $res as $row ) {
239 $this->author_list .= "<contributor>" .
240 "<username>" .
241 htmlentities( $row->rev_user_text ) .
242 "</username>" .
243 "<id>" .
244 $row->rev_user .
245 "</id>" .
246 "</contributor>";
248 $this->author_list .= "</contributors>";
252 * @param string $cond
253 * @throws MWException
254 * @throws Exception
256 protected function dumpFrom( $cond = '', $orderRevs = false ) {
257 # For logging dumps...
258 if ( $this->history & self::LOGS ) {
259 $where = [ 'user_id = log_user' ];
260 # Hide private logs
261 $hideLogs = LogEventsList::getExcludeClause( $this->db );
262 if ( $hideLogs ) {
263 $where[] = $hideLogs;
265 # Add on any caller specified conditions
266 if ( $cond ) {
267 $where[] = $cond;
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
276 try {
277 $result = $this->db->select( [ 'logging', 'user' ],
278 [ "{$logging}.*", 'user_name' ], // grab the user name
279 $where,
280 __METHOD__,
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.
291 // Freeing result
292 try {
293 if ( $result ) {
294 $result->free();
296 } catch ( Exception $e2 ) {
297 // Already in panic mode -> ignoring $e2 as $e has
298 // higher priority
301 // Putting database back in previous buffer mode
302 try {
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
308 // higher priority
311 // Inform caller about problem
312 throw $e;
314 # For page dumps...
315 } else {
316 $tables = [ 'page', 'revision' ];
317 $opts = [ 'ORDER BY' => 'page_id ASC' ];
318 $opts['USE INDEX'] = [];
319 $join = [];
320 if ( is_array( $this->history ) ) {
321 # Time offset/limit for all pages/history...
322 $revJoin = 'page_id=rev_page';
323 # Set time order
324 if ( $this->history['dir'] == 'asc' ) {
325 $op = '>';
326 $opts['ORDER BY'] = 'rev_timestamp ASC';
327 } else {
328 $op = '<';
329 $opts['ORDER BY'] = 'rev_timestamp DESC';
331 # Set offset
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 ];
337 # Set query limit
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' ];
350 } else {
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' ];
371 } else {
372 # Unknown history specification parameter?
373 throw new MWException( __METHOD__ . " given invalid history dump type." );
375 # Query optimization hacks
376 if ( $cond == '' ) {
377 $opts[] = 'STRAIGHT_JOIN';
378 $opts['USE INDEX']['page'] = 'PRIMARY';
380 # Build text join options
381 if ( $this->text != WikiExporter::STUB ) { // 1-pass
382 $tables[] = 'text';
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
390 try {
391 Hooks::run( 'ModifyExportQuery',
392 [ $this->db, &$tables, &$cond, &$opts, &$join ] );
394 # Do the query!
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.
406 // Freeing result
407 try {
408 if ( $result ) {
409 $result->free();
411 } catch ( Exception $e2 ) {
412 // Already in panic mode -> ignoring $e2 as $e has
413 // higher priority
416 // Putting database back in previous buffer mode
417 try {
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
423 // higher priority
426 // Inform caller about problem
427 throw $e;
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.
437 * Should be safe for
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 ) {
445 $last = null;
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 ) {
451 $output = '';
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 );
460 $last = $row;
462 $output = $this->writer->writeRevision( $row );
463 $this->sink->writeRevision( $row, $output );
465 if ( $last !== null ) {
466 $output = '';
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 );