wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / export / WikiExporter.php
blobab2632dae55cad341334162e47c8161331e34d1f
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.
138 public function pagesByRange( $start, $end ) {
139 $condition = 'page_id >= ' . intval( $start );
140 if ( $end ) {
141 $condition .= ' AND page_id < ' . intval( $end );
143 $this->dumpFrom( $condition );
147 * Dumps a series of page and revision records for those pages
148 * in the database with revisions falling within the rev_id range given.
149 * @param int $start Inclusive lower limit (this id is included)
150 * @param int $end Exclusive upper limit (this id is not included)
151 * If 0, no upper limit.
153 public function revsByRange( $start, $end ) {
154 $condition = 'rev_id >= ' . intval( $start );
155 if ( $end ) {
156 $condition .= ' AND rev_id < ' . intval( $end );
158 $this->dumpFrom( $condition );
162 * @param Title $title
164 public function pageByTitle( $title ) {
165 $this->dumpFrom(
166 'page_namespace=' . $title->getNamespace() .
167 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
171 * @param string $name
172 * @throws MWException
174 public function pageByName( $name ) {
175 $title = Title::newFromText( $name );
176 if ( is_null( $title ) ) {
177 throw new MWException( "Can't export invalid title" );
178 } else {
179 $this->pageByTitle( $title );
184 * @param array $names
186 public function pagesByName( $names ) {
187 foreach ( $names as $name ) {
188 $this->pageByName( $name );
192 public function allLogs() {
193 $this->dumpFrom( '' );
197 * @param int $start
198 * @param int $end
200 public function logsByRange( $start, $end ) {
201 $condition = 'log_id >= ' . intval( $start );
202 if ( $end ) {
203 $condition .= ' AND log_id < ' . intval( $end );
205 $this->dumpFrom( $condition );
209 * Generates the distinct list of authors of an article
210 * Not called by default (depends on $this->list_authors)
211 * Can be set by Special:Export when not exporting whole history
213 * @param array $cond
215 protected function do_list_authors( $cond ) {
216 $this->author_list = "<contributors>";
217 // rev_deleted
219 $res = $this->db->select(
220 array( 'page', 'revision' ),
221 array( 'DISTINCT rev_user_text', 'rev_user' ),
222 array(
223 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
224 $cond,
225 'page_id = rev_id',
227 __METHOD__
230 foreach ( $res as $row ) {
231 $this->author_list .= "<contributor>" .
232 "<username>" .
233 htmlentities( $row->rev_user_text ) .
234 "</username>" .
235 "<id>" .
236 $row->rev_user .
237 "</id>" .
238 "</contributor>";
240 $this->author_list .= "</contributors>";
244 * @param string $cond
245 * @throws MWException
246 * @throws Exception
248 protected function dumpFrom( $cond = '' ) {
249 # For logging dumps...
250 if ( $this->history & self::LOGS ) {
251 $where = array( 'user_id = log_user' );
252 # Hide private logs
253 $hideLogs = LogEventsList::getExcludeClause( $this->db );
254 if ( $hideLogs ) {
255 $where[] = $hideLogs;
257 # Add on any caller specified conditions
258 if ( $cond ) {
259 $where[] = $cond;
261 # Get logging table name for logging.* clause
262 $logging = $this->db->tableName( 'logging' );
264 if ( $this->buffer == WikiExporter::STREAM ) {
265 $prev = $this->db->bufferResults( false );
267 $result = null; // Assuring $result is not undefined, if exception occurs early
268 try {
269 $result = $this->db->select( array( 'logging', 'user' ),
270 array( "{$logging}.*", 'user_name' ), // grab the user name
271 $where,
272 __METHOD__,
273 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
275 $this->outputLogStream( $result );
276 if ( $this->buffer == WikiExporter::STREAM ) {
277 $this->db->bufferResults( $prev );
279 } catch ( Exception $e ) {
280 // Throwing the exception does not reliably free the resultset, and
281 // would also leave the connection in unbuffered mode.
283 // Freeing result
284 try {
285 if ( $result ) {
286 $result->free();
288 } catch ( Exception $e2 ) {
289 // Already in panic mode -> ignoring $e2 as $e has
290 // higher priority
293 // Putting database back in previous buffer mode
294 try {
295 if ( $this->buffer == WikiExporter::STREAM ) {
296 $this->db->bufferResults( $prev );
298 } catch ( Exception $e2 ) {
299 // Already in panic mode -> ignoring $e2 as $e has
300 // higher priority
303 // Inform caller about problem
304 throw $e;
306 # For page dumps...
307 } else {
308 $tables = array( 'page', 'revision' );
309 $opts = array( 'ORDER BY' => 'page_id ASC' );
310 $opts['USE INDEX'] = array();
311 $join = array();
312 if ( is_array( $this->history ) ) {
313 # Time offset/limit for all pages/history...
314 $revJoin = 'page_id=rev_page';
315 # Set time order
316 if ( $this->history['dir'] == 'asc' ) {
317 $op = '>';
318 $opts['ORDER BY'] = 'rev_timestamp ASC';
319 } else {
320 $op = '<';
321 $opts['ORDER BY'] = 'rev_timestamp DESC';
323 # Set offset
324 if ( !empty( $this->history['offset'] ) ) {
325 $revJoin .= " AND rev_timestamp $op " .
326 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
328 $join['revision'] = array( 'INNER JOIN', $revJoin );
329 # Set query limit
330 if ( !empty( $this->history['limit'] ) ) {
331 $opts['LIMIT'] = intval( $this->history['limit'] );
333 } elseif ( $this->history & WikiExporter::FULL ) {
334 # Full history dumps...
335 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
336 } elseif ( $this->history & WikiExporter::CURRENT ) {
337 # Latest revision dumps...
338 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
339 $this->do_list_authors( $cond );
341 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
342 } elseif ( $this->history & WikiExporter::STABLE ) {
343 # "Stable" revision dumps...
344 # Default JOIN, to be overridden...
345 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
346 # One, and only one hook should set this, and return false
347 if ( Hooks::run( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
348 throw new MWException( __METHOD__ . " given invalid history dump type." );
350 } elseif ( $this->history & WikiExporter::RANGE ) {
351 # Dump of revisions within a specified range
352 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
353 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
354 } else {
355 # Unknown history specification parameter?
356 throw new MWException( __METHOD__ . " given invalid history dump type." );
358 # Query optimization hacks
359 if ( $cond == '' ) {
360 $opts[] = 'STRAIGHT_JOIN';
361 $opts['USE INDEX']['page'] = 'PRIMARY';
363 # Build text join options
364 if ( $this->text != WikiExporter::STUB ) { // 1-pass
365 $tables[] = 'text';
366 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
369 if ( $this->buffer == WikiExporter::STREAM ) {
370 $prev = $this->db->bufferResults( false );
373 $result = null; // Assuring $result is not undefined, if exception occurs early
374 try {
375 Hooks::run( 'ModifyExportQuery',
376 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
378 # Do the query!
379 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
380 # Output dump results
381 $this->outputPageStream( $result );
383 if ( $this->buffer == WikiExporter::STREAM ) {
384 $this->db->bufferResults( $prev );
386 } catch ( Exception $e ) {
387 // Throwing the exception does not reliably free the resultset, and
388 // would also leave the connection in unbuffered mode.
390 // Freeing result
391 try {
392 if ( $result ) {
393 $result->free();
395 } catch ( Exception $e2 ) {
396 // Already in panic mode -> ignoring $e2 as $e has
397 // higher priority
400 // Putting database back in previous buffer mode
401 try {
402 if ( $this->buffer == WikiExporter::STREAM ) {
403 $this->db->bufferResults( $prev );
405 } catch ( Exception $e2 ) {
406 // Already in panic mode -> ignoring $e2 as $e has
407 // higher priority
410 // Inform caller about problem
411 throw $e;
417 * Runs through a query result set dumping page and revision records.
418 * The result set should be sorted/grouped by page to avoid duplicate
419 * page records in the output.
421 * Should be safe for
422 * streaming (non-buffered) queries, as long as it was made on a
423 * separate database connection not managed by LoadBalancer; some
424 * blob storage types will make queries to pull source data.
426 * @param ResultWrapper $resultset
428 protected function outputPageStream( $resultset ) {
429 $last = null;
430 foreach ( $resultset as $row ) {
431 if ( $last === null ||
432 $last->page_namespace != $row->page_namespace ||
433 $last->page_title != $row->page_title ) {
434 if ( $last !== null ) {
435 $output = '';
436 if ( $this->dumpUploads ) {
437 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
439 $output .= $this->writer->closePage();
440 $this->sink->writeClosePage( $output );
442 $output = $this->writer->openPage( $row );
443 $this->sink->writeOpenPage( $row, $output );
444 $last = $row;
446 $output = $this->writer->writeRevision( $row );
447 $this->sink->writeRevision( $row, $output );
449 if ( $last !== null ) {
450 $output = '';
451 if ( $this->dumpUploads ) {
452 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
454 $output .= $this->author_list;
455 $output .= $this->writer->closePage();
456 $this->sink->writeClosePage( $output );
461 * @param ResultWrapper $resultset
463 protected function outputLogStream( $resultset ) {
464 foreach ( $resultset as $row ) {
465 $output = $this->writer->writeLogItem( $row );
466 $this->sink->writeLogItem( $row, $output );