Merge "Add MessagesBi.php"
[lhc/web/wiklou.git] / includes / export / WikiExporter.php
1 <?php
2 /**
3 * Base class for exporting
4 *
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25
26 /**
27 * @defgroup Dump Dump
28 */
29
30 use Wikimedia\Rdbms\ResultWrapper;
31 use Wikimedia\Rdbms\IDatabase;
32
33 /**
34 * @ingroup SpecialPage Dump
35 */
36 class WikiExporter {
37 /** @var bool Return distinct author list (when not returning full history) */
38 public $list_authors = false;
39
40 /** @var bool */
41 public $dumpUploads = false;
42
43 /** @var bool */
44 public $dumpUploadFileContents = false;
45
46 /** @var string */
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 BUFFER = 0;
56 const STREAM = 1;
57
58 const TEXT = 0;
59 const STUB = 1;
60
61 /** @var int */
62 public $buffer;
63
64 /** @var int */
65 public $text;
66
67 /** @var DumpOutput */
68 public $sink;
69
70 /**
71 * Returns the export schema version.
72 * @return string
73 */
74 public static function schemaVersion() {
75 return "0.10";
76 }
77
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.
84 *
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
93 */
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;
102 }
103
104 /**
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.
108 *
109 * @param DumpOutput &$sink
110 */
111 public function setOutputSink( &$sink ) {
112 $this->sink =& $sink;
113 }
114
115 public function openStream() {
116 $output = $this->writer->openStream();
117 $this->sink->writeOpenStream( $output );
118 }
119
120 public function closeStream() {
121 $output = $this->writer->closeStream();
122 $this->sink->writeCloseStream( $output );
123 }
124
125 /**
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.
129 */
130 public function allPages() {
131 $this->dumpFrom( '' );
132 }
133
134 /**
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
141 */
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 );
147 }
148 } else {
149 $condition = 'page_id >= ' . intval( $start );
150 if ( $end ) {
151 $condition .= ' AND page_id < ' . intval( $end );
152 }
153 }
154 $this->dumpFrom( $condition, $orderRevs );
155 }
156
157 /**
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.
163 */
164 public function revsByRange( $start, $end ) {
165 $condition = 'rev_id >= ' . intval( $start );
166 if ( $end ) {
167 $condition .= ' AND rev_id < ' . intval( $end );
168 }
169 $this->dumpFrom( $condition );
170 }
171
172 /**
173 * @param Title $title
174 */
175 public function pageByTitle( $title ) {
176 $this->dumpFrom(
177 'page_namespace=' . $title->getNamespace() .
178 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
179 }
180
181 /**
182 * @param string $name
183 * @throws MWException
184 */
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 );
191 }
192 }
193
194 /**
195 * @param array $names
196 */
197 public function pagesByName( $names ) {
198 foreach ( $names as $name ) {
199 $this->pageByName( $name );
200 }
201 }
202
203 public function allLogs() {
204 $this->dumpFrom( '' );
205 }
206
207 /**
208 * @param int $start
209 * @param int $end
210 */
211 public function logsByRange( $start, $end ) {
212 $condition = 'log_id >= ' . intval( $start );
213 if ( $end ) {
214 $condition .= ' AND log_id < ' . intval( $end );
215 }
216 $this->dumpFrom( $condition );
217 }
218
219 /**
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
223 *
224 * @param array $cond
225 */
226 protected function do_list_authors( $cond ) {
227 $this->author_list = "<contributors>";
228 // rev_deleted
229
230 $revQuery = Revision::getQueryInfo( [ 'page' ] );
231 $res = $this->db->select(
232 $revQuery['tables'],
233 [
234 'rev_user_text' => $revQuery['fields']['rev_user_text'],
235 'rev_user' => $revQuery['fields']['rev_user'],
236 ],
237 [
238 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
239 $cond,
240 ],
241 __METHOD__,
242 [ 'DISTINCT' ],
243 $revQuery['joins']
244 );
245
246 foreach ( $res as $row ) {
247 $this->author_list .= "<contributor>" .
248 "<username>" .
249 htmlentities( $row->rev_user_text ) .
250 "</username>" .
251 "<id>" .
252 $row->rev_user .
253 "</id>" .
254 "</contributor>";
255 }
256 $this->author_list .= "</contributors>";
257 }
258
259 /**
260 * @param string $cond
261 * @param bool $orderRevs
262 * @throws MWException
263 * @throws Exception
264 */
265 protected function dumpFrom( $cond = '', $orderRevs = false ) {
266 global $wgMultiContentRevisionSchemaMigrationStage;
267
268 # For logging dumps...
269 if ( $this->history & self::LOGS ) {
270 $where = [];
271 # Hide private logs
272 $hideLogs = LogEventsList::getExcludeClause( $this->db );
273 if ( $hideLogs ) {
274 $where[] = $hideLogs;
275 }
276 # Add on any caller specified conditions
277 if ( $cond ) {
278 $where[] = $cond;
279 }
280 # Get logging table name for logging.* clause
281 $logging = $this->db->tableName( 'logging' );
282
283 if ( $this->buffer == self::STREAM ) {
284 $prev = $this->db->bufferResults( false );
285 }
286 $result = null; // Assuring $result is not undefined, if exception occurs early
287
288 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
289 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
290
291 try {
292 $result = $this->db->select(
293 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
294 [ "{$logging}.*", 'user_name' ] + $commentQuery['fields'] + $actorQuery['fields'],
295 $where,
296 __METHOD__,
297 [ 'ORDER BY' => 'log_id', 'USE INDEX' => [ 'logging' => 'PRIMARY' ] ],
298 [
299 'user' => [ 'JOIN', 'user_id = ' . $actorQuery['fields']['log_user'] ]
300 ] + $commentQuery['joins'] + $actorQuery['joins']
301 );
302 $this->outputLogStream( $result );
303 if ( $this->buffer == self::STREAM ) {
304 $this->db->bufferResults( $prev );
305 }
306 } catch ( Exception $e ) {
307 // Throwing the exception does not reliably free the resultset, and
308 // would also leave the connection in unbuffered mode.
309
310 // Freeing result
311 try {
312 if ( $result ) {
313 $result->free();
314 }
315 } catch ( Exception $e2 ) {
316 // Already in panic mode -> ignoring $e2 as $e has
317 // higher priority
318 }
319
320 // Putting database back in previous buffer mode
321 try {
322 if ( $this->buffer == self::STREAM ) {
323 $this->db->bufferResults( $prev );
324 }
325 } catch ( Exception $e2 ) {
326 // Already in panic mode -> ignoring $e2 as $e has
327 // higher priority
328 }
329
330 // Inform caller about problem
331 throw $e;
332 }
333 # For page dumps...
334 } else {
335 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
336 // TODO: Make XmlDumpWriter use a RevisionStore! (see T198706 and T174031)
337 throw new MWException(
338 'Cannot use WikiExporter with SCHEMA_COMPAT_WRITE_OLD mode disabled!'
339 . ' Support for dumping from the new schema is not implemented yet!'
340 );
341 }
342
343 $revOpts = [ 'page' ];
344 if ( $this->text != self::STUB ) {
345 // TODO: remove the text and make XmlDumpWriter use a RevisionStore instead! (T198706)
346 $revOpts[] = 'text';
347 }
348 $revQuery = Revision::getQueryInfo( $revOpts );
349
350 // We want page primary rather than revision
351 $tables = array_merge( [ 'page' ], array_diff( $revQuery['tables'], [ 'page' ] ) );
352 $join = $revQuery['joins'] + [
353 'revision' => $revQuery['joins']['page']
354 ];
355 unset( $join['page'] );
356
357 // TODO: remove rev_text_id and make XmlDumpWriter use a RevisionStore instead! (T198706)
358 $fields = array_merge( $revQuery['fields'], [ 'page_restrictions, rev_text_id' ] );
359
360 $conds = [];
361 if ( $cond !== '' ) {
362 $conds[] = $cond;
363 }
364 $opts = [ 'ORDER BY' => 'page_id ASC' ];
365 $opts['USE INDEX'] = [];
366 if ( is_array( $this->history ) ) {
367 # Time offset/limit for all pages/history...
368 # Set time order
369 if ( $this->history['dir'] == 'asc' ) {
370 $op = '>';
371 $opts['ORDER BY'] = 'rev_timestamp ASC';
372 } else {
373 $op = '<';
374 $opts['ORDER BY'] = 'rev_timestamp DESC';
375 }
376 # Set offset
377 if ( !empty( $this->history['offset'] ) ) {
378 $conds[] = "rev_timestamp $op " .
379 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
380 }
381 # Set query limit
382 if ( !empty( $this->history['limit'] ) ) {
383 $opts['LIMIT'] = intval( $this->history['limit'] );
384 }
385 } elseif ( $this->history & self::FULL ) {
386 # Full history dumps...
387 # query optimization for history stub dumps
388 if ( $this->text == self::STUB && $orderRevs ) {
389 $tables = $revQuery['tables'];
390 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
391 $opts['USE INDEX']['revision'] = 'rev_page_id';
392 unset( $join['revision'] );
393 $join['page'] = [ 'INNER JOIN', 'rev_page=page_id' ];
394 }
395 } elseif ( $this->history & self::CURRENT ) {
396 # Latest revision dumps...
397 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
398 $this->do_list_authors( $cond );
399 }
400 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
401 } elseif ( $this->history & self::STABLE ) {
402 # "Stable" revision dumps...
403 # Default JOIN, to be overridden...
404 $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
405 # One, and only one hook should set this, and return false
406 if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
407 throw new MWException( __METHOD__ . " given invalid history dump type." );
408 }
409 } elseif ( $this->history & self::RANGE ) {
410 # Dump of revisions within a specified range
411 $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
412 } else {
413 # Unknown history specification parameter?
414 throw new MWException( __METHOD__ . " given invalid history dump type." );
415 }
416
417 if ( $this->buffer == self::STREAM ) {
418 $prev = $this->db->bufferResults( false );
419 }
420 $result = null; // Assuring $result is not undefined, if exception occurs early
421 try {
422 Hooks::run( 'ModifyExportQuery',
423 [ $this->db, &$tables, &$cond, &$opts, &$join ] );
424
425 # Do the query!
426 $result = $this->db->select(
427 $tables,
428 $fields,
429 $conds,
430 __METHOD__,
431 $opts,
432 $join
433 );
434 # Output dump results
435 $this->outputPageStream( $result );
436
437 if ( $this->buffer == self::STREAM ) {
438 $this->db->bufferResults( $prev );
439 }
440 } catch ( Exception $e ) {
441 // Throwing the exception does not reliably free the resultset, and
442 // would also leave the connection in unbuffered mode.
443
444 // Freeing result
445 try {
446 if ( $result ) {
447 $result->free();
448 }
449 } catch ( Exception $e2 ) {
450 // Already in panic mode -> ignoring $e2 as $e has
451 // higher priority
452 }
453
454 // Putting database back in previous buffer mode
455 try {
456 if ( $this->buffer == self::STREAM ) {
457 $this->db->bufferResults( $prev );
458 }
459 } catch ( Exception $e2 ) {
460 // Already in panic mode -> ignoring $e2 as $e has
461 // higher priority
462 }
463
464 // Inform caller about problem
465 throw $e;
466 }
467 }
468 }
469
470 /**
471 * Runs through a query result set dumping page and revision records.
472 * The result set should be sorted/grouped by page to avoid duplicate
473 * page records in the output.
474 *
475 * Should be safe for
476 * streaming (non-buffered) queries, as long as it was made on a
477 * separate database connection not managed by LoadBalancer; some
478 * blob storage types will make queries to pull source data.
479 *
480 * @param ResultWrapper $resultset
481 */
482 protected function outputPageStream( $resultset ) {
483 $last = null;
484 foreach ( $resultset as $row ) {
485 if ( $last === null ||
486 $last->page_namespace != $row->page_namespace ||
487 $last->page_title != $row->page_title ) {
488 if ( $last !== null ) {
489 $output = '';
490 if ( $this->dumpUploads ) {
491 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
492 }
493 $output .= $this->writer->closePage();
494 $this->sink->writeClosePage( $output );
495 }
496 $output = $this->writer->openPage( $row );
497 $this->sink->writeOpenPage( $row, $output );
498 $last = $row;
499 }
500 $output = $this->writer->writeRevision( $row );
501 $this->sink->writeRevision( $row, $output );
502 }
503 if ( $last !== null ) {
504 $output = '';
505 if ( $this->dumpUploads ) {
506 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
507 }
508 $output .= $this->author_list;
509 $output .= $this->writer->closePage();
510 $this->sink->writeClosePage( $output );
511 }
512 }
513
514 /**
515 * @param ResultWrapper $resultset
516 */
517 protected function outputLogStream( $resultset ) {
518 foreach ( $resultset as $row ) {
519 $output = $this->writer->writeLogItem( $row );
520 $this->sink->writeLogItem( $row, $output );
521 }
522 }
523 }