Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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 TEXT = 0;
56 const STUB = 1;
57
58 const BATCH_SIZE = 50000;
59
60 /** @var int */
61 public $text;
62
63 /** @var DumpOutput */
64 public $sink;
65
66 /** @var XmlDumpWriter */
67 private $writer;
68
69 /**
70 * Returns the default export schema version, as defined by $wgXmlDumpSchemaVersion.
71 * @return string
72 */
73 public static function schemaVersion() {
74 global $wgXmlDumpSchemaVersion;
75 return $wgXmlDumpSchemaVersion;
76 }
77
78 /**
79 * @param IDatabase $db
80 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
81 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
82 * - offset: non-inclusive offset at which to start the query
83 * - limit: maximum number of rows to return
84 * - dir: "asc" or "desc" timestamp order
85 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
86 */
87 function __construct( $db, $history = self::CURRENT, $text = self::TEXT ) {
88 $this->db = $db;
89 $this->history = $history;
90 $this->writer = new XmlDumpWriter( $text, self::schemaVersion() );
91 $this->sink = new DumpOutput();
92 $this->text = $text;
93 }
94
95 /**
96 * @param string $schemaVersion which schema version the generated XML should comply to.
97 * One of the values from self::$supportedSchemas, using the XML_DUMP_SCHEMA_VERSION_XX
98 * constants.
99 */
100 public function setSchemaVersion( $schemaVersion ) {
101 $this->writer = new XmlDumpWriter( $this->text, $schemaVersion );
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 htmlspecialchars( $row->rev_user_text ) .
250 "</username>" .
251 "<id>" .
252 ( (int)$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 if ( $this->history & self::LOGS ) {
267 $this->dumpLogs( $cond );
268 } else {
269 $this->dumpPages( $cond, $orderRevs );
270 }
271 }
272
273 /**
274 * @param string $cond
275 * @throws Exception
276 */
277 protected function dumpLogs( $cond ) {
278 $where = [];
279 # Hide private logs
280 $hideLogs = LogEventsList::getExcludeClause( $this->db );
281 if ( $hideLogs ) {
282 $where[] = $hideLogs;
283 }
284 # Add on any caller specified conditions
285 if ( $cond ) {
286 $where[] = $cond;
287 }
288 # Get logging table name for logging.* clause
289 $logging = $this->db->tableName( 'logging' );
290
291 $result = null; // Assuring $result is not undefined, if exception occurs early
292
293 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
294 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
295
296 $lastLogId = 0;
297 while ( true ) {
298 $result = $this->db->select(
299 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
300 [ "{$logging}.*", 'user_name' ] + $commentQuery['fields'] + $actorQuery['fields'],
301 array_merge( $where, [ 'log_id > ' . intval( $lastLogId ) ] ),
302 __METHOD__,
303 [
304 'ORDER BY' => 'log_id',
305 'USE INDEX' => [ 'logging' => 'PRIMARY' ],
306 'LIMIT' => self::BATCH_SIZE,
307 ],
308 [
309 'user' => [ 'JOIN', 'user_id = ' . $actorQuery['fields']['log_user'] ]
310 ] + $commentQuery['joins'] + $actorQuery['joins']
311 );
312
313 if ( !$result->numRows() ) {
314 break;
315 }
316
317 $lastLogId = $this->outputLogStream( $result );
318 };
319 }
320
321 /**
322 * @param string $cond
323 * @param bool $orderRevs
324 * @throws MWException
325 * @throws Exception
326 */
327 protected function dumpPages( $cond, $orderRevs ) {
328 global $wgMultiContentRevisionSchemaMigrationStage;
329 if ( !( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) ) {
330 // TODO: Make XmlDumpWriter use a RevisionStore! (see T198706 and T174031)
331 throw new MWException(
332 'Cannot use WikiExporter with SCHEMA_COMPAT_WRITE_OLD mode disabled!'
333 . ' Support for dumping from the new schema is not implemented yet!'
334 );
335 }
336
337 $revOpts = [ 'page' ];
338
339 $revQuery = Revision::getQueryInfo( $revOpts );
340
341 // We want page primary rather than revision
342 $tables = array_merge( [ 'page' ], array_diff( $revQuery['tables'], [ 'page' ] ) );
343 $join = $revQuery['joins'] + [
344 'revision' => $revQuery['joins']['page']
345 ];
346 unset( $join['page'] );
347
348 $fields = $revQuery['fields'];
349 $fields[] = 'page_restrictions';
350
351 if ( $this->text != self::STUB ) {
352 $fields['_load_content'] = '1';
353 }
354
355 $conds = [];
356 if ( $cond !== '' ) {
357 $conds[] = $cond;
358 }
359 $opts = [ 'ORDER BY' => [ 'rev_page ASC', 'rev_id ASC' ] ];
360 $opts['USE INDEX'] = [];
361
362 $op = '>';
363 if ( is_array( $this->history ) ) {
364 # Time offset/limit for all pages/history...
365 # Set time order
366 if ( $this->history['dir'] == 'asc' ) {
367 $opts['ORDER BY'] = 'rev_timestamp ASC';
368 } else {
369 $op = '<';
370 $opts['ORDER BY'] = 'rev_timestamp DESC';
371 }
372 # Set offset
373 if ( !empty( $this->history['offset'] ) ) {
374 $conds[] = "rev_timestamp $op " .
375 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
376 }
377 # Set query limit
378 if ( !empty( $this->history['limit'] ) ) {
379 $maxRowCount = intval( $this->history['limit'] );
380 }
381 } elseif ( $this->history & self::FULL ) {
382 # Full history dumps...
383 # query optimization for history stub dumps
384 if ( $this->text == self::STUB ) {
385 $tables = $revQuery['tables'];
386 $opts[] = 'STRAIGHT_JOIN';
387 $opts['USE INDEX']['revision'] = 'rev_page_id';
388 unset( $join['revision'] );
389 $join['page'] = [ 'JOIN', 'rev_page=page_id' ];
390 }
391 } elseif ( $this->history & self::CURRENT ) {
392 # Latest revision dumps...
393 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
394 $this->do_list_authors( $cond );
395 }
396 $join['revision'] = [ 'JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
397 } elseif ( $this->history & self::STABLE ) {
398 # "Stable" revision dumps...
399 # Default JOIN, to be overridden...
400 $join['revision'] = [ 'JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
401 # One, and only one hook should set this, and return false
402 if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
403 throw new MWException( __METHOD__ . " given invalid history dump type." );
404 }
405 } elseif ( $this->history & self::RANGE ) {
406 # Dump of revisions within a specified range. Condition already set in revsByRange().
407 } else {
408 # Unknown history specification parameter?
409 throw new MWException( __METHOD__ . " given invalid history dump type." );
410 }
411
412 $result = null; // Assuring $result is not undefined, if exception occurs early
413 $done = false;
414 $lastRow = null;
415 $revPage = 0;
416 $revId = 0;
417 $rowCount = 0;
418
419 $opts['LIMIT'] = self::BATCH_SIZE;
420
421 Hooks::run( 'ModifyExportQuery',
422 [ $this->db, &$tables, &$cond, &$opts, &$join ] );
423
424 while ( !$done ) {
425 // If necessary, impose the overall maximum and stop looping after this iteration.
426 if ( !empty( $maxRowCount ) && $rowCount + self::BATCH_SIZE > $maxRowCount ) {
427 $opts['LIMIT'] = $maxRowCount - $rowCount;
428 $done = true;
429 }
430
431 $queryConds = $conds;
432 $queryConds[] = 'rev_page>' . intval( $revPage ) . ' OR (rev_page=' .
433 intval( $revPage ) . ' AND rev_id' . $op . intval( $revId ) . ')';
434
435 # Do the query and process any results, remembering max ids for the next iteration.
436 $result = $this->db->select(
437 $tables,
438 $fields,
439 $queryConds,
440 __METHOD__,
441 $opts,
442 $join
443 );
444 if ( $result->numRows() > 0 ) {
445 $lastRow = $this->outputPageStreamBatch( $result, $lastRow );
446 $rowCount += $result->numRows();
447 $revPage = $lastRow->rev_page;
448 $revId = $lastRow->rev_id;
449 } else {
450 $done = true;
451 }
452
453 // If we are finished, close off final page element (if any).
454 if ( $done && $lastRow ) {
455 $this->finishPageStreamOutput( $lastRow );
456 }
457 }
458 }
459
460 /**
461 * Runs through a query result set dumping page and revision records.
462 * The result set should be sorted/grouped by page to avoid duplicate
463 * page records in the output.
464 *
465 * @param ResultWrapper $results
466 * @param object $lastRow the last row output from the previous call (or null if none)
467 * @return object the last row processed
468 */
469 protected function outputPageStreamBatch( $results, $lastRow ) {
470 foreach ( $results as $row ) {
471 if ( $lastRow === null ||
472 $lastRow->page_namespace !== $row->page_namespace ||
473 $lastRow->page_title !== $row->page_title ) {
474 if ( $lastRow !== null ) {
475 $output = '';
476 if ( $this->dumpUploads ) {
477 $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
478 }
479 $output .= $this->writer->closePage();
480 $this->sink->writeClosePage( $output );
481 }
482 $output = $this->writer->openPage( $row );
483 $this->sink->writeOpenPage( $row, $output );
484 }
485 $output = $this->writer->writeRevision( $row );
486 $this->sink->writeRevision( $row, $output );
487 $lastRow = $row;
488 }
489
490 return $lastRow;
491 }
492
493 /**
494 * Final page stream output, after all batches are complete
495 *
496 * @param object $lastRow the last row output from the last batch (or null if none)
497 */
498 protected function finishPageStreamOutput( $lastRow ) {
499 $output = '';
500 if ( $this->dumpUploads ) {
501 $output .= $this->writer->writeUploads( $lastRow, $this->dumpUploadFileContents );
502 }
503 $output .= $this->author_list;
504 $output .= $this->writer->closePage();
505 $this->sink->writeClosePage( $output );
506 }
507
508 /**
509 * @param ResultWrapper $resultset
510 * @return int the log_id value of the last item output, or null if none
511 */
512 protected function outputLogStream( $resultset ) {
513 foreach ( $resultset as $row ) {
514 $output = $this->writer->writeLogItem( $row );
515 $this->sink->writeLogItem( $row, $output );
516 }
517 return isset( $row ) ? $row->log_id : null;
518 }
519 }