Properly deprecate srprop=score|hasrelated
[mediawiki.git] / includes / Export.php
blob43dfd171956d0c61ec16e1b92a772d22a8a5cd39
1 <?php
2 /**
3 * Base classes for dumps and export
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 protected $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 protected $buffer;
61 /** @var int */
62 protected $text;
64 /** @var DumpOutput */
65 protected $sink;
67 /**
68 * Returns the export schema version.
69 * @return string
71 public static function schemaVersion() {
72 return "0.9";
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 DatabaseBase $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 wfProfileIn( __METHOD__ );
217 $this->author_list = "<contributors>";
218 // rev_deleted
220 $res = $this->db->select(
221 array( 'page', 'revision' ),
222 array( 'DISTINCT rev_user_text', 'rev_user' ),
223 array(
224 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
225 $cond,
226 'page_id = rev_id',
228 __METHOD__
231 foreach ( $res as $row ) {
232 $this->author_list .= "<contributor>" .
233 "<username>" .
234 htmlentities( $row->rev_user_text ) .
235 "</username>" .
236 "<id>" .
237 $row->rev_user .
238 "</id>" .
239 "</contributor>";
241 $this->author_list .= "</contributors>";
242 wfProfileOut( __METHOD__ );
246 * @param string $cond
247 * @throws MWException
248 * @throws Exception
250 protected function dumpFrom( $cond = '' ) {
251 wfProfileIn( __METHOD__ );
252 # For logging dumps...
253 if ( $this->history & self::LOGS ) {
254 $where = array( 'user_id = log_user' );
255 # Hide private logs
256 $hideLogs = LogEventsList::getExcludeClause( $this->db );
257 if ( $hideLogs ) {
258 $where[] = $hideLogs;
260 # Add on any caller specified conditions
261 if ( $cond ) {
262 $where[] = $cond;
264 # Get logging table name for logging.* clause
265 $logging = $this->db->tableName( 'logging' );
267 if ( $this->buffer == WikiExporter::STREAM ) {
268 $prev = $this->db->bufferResults( false );
270 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
271 try {
272 $result = $this->db->select( array( 'logging', 'user' ),
273 array( "{$logging}.*", 'user_name' ), // grab the user name
274 $where,
275 __METHOD__,
276 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
278 $wrapper = $this->db->resultObject( $result );
279 $this->outputLogStream( $wrapper );
280 if ( $this->buffer == WikiExporter::STREAM ) {
281 $this->db->bufferResults( $prev );
283 } catch ( Exception $e ) {
284 // Throwing the exception does not reliably free the resultset, and
285 // would also leave the connection in unbuffered mode.
287 // Freeing result
288 try {
289 if ( $wrapper ) {
290 $wrapper->free();
292 } catch ( Exception $e2 ) {
293 // Already in panic mode -> ignoring $e2 as $e has
294 // higher priority
297 // Putting database back in previous buffer mode
298 try {
299 if ( $this->buffer == WikiExporter::STREAM ) {
300 $this->db->bufferResults( $prev );
302 } catch ( Exception $e2 ) {
303 // Already in panic mode -> ignoring $e2 as $e has
304 // higher priority
307 // Inform caller about problem
308 wfProfileOut( __METHOD__ );
309 throw $e;
311 # For page dumps...
312 } else {
313 $tables = array( 'page', 'revision' );
314 $opts = array( 'ORDER BY' => 'page_id ASC' );
315 $opts['USE INDEX'] = array();
316 $join = array();
317 if ( is_array( $this->history ) ) {
318 # Time offset/limit for all pages/history...
319 $revJoin = 'page_id=rev_page';
320 # Set time order
321 if ( $this->history['dir'] == 'asc' ) {
322 $op = '>';
323 $opts['ORDER BY'] = 'rev_timestamp ASC';
324 } else {
325 $op = '<';
326 $opts['ORDER BY'] = 'rev_timestamp DESC';
328 # Set offset
329 if ( !empty( $this->history['offset'] ) ) {
330 $revJoin .= " AND rev_timestamp $op " .
331 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
333 $join['revision'] = array( 'INNER JOIN', $revJoin );
334 # Set query limit
335 if ( !empty( $this->history['limit'] ) ) {
336 $opts['LIMIT'] = intval( $this->history['limit'] );
338 } elseif ( $this->history & WikiExporter::FULL ) {
339 # Full history dumps...
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
341 } elseif ( $this->history & WikiExporter::CURRENT ) {
342 # Latest revision dumps...
343 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
344 $this->do_list_authors( $cond );
346 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
347 } elseif ( $this->history & WikiExporter::STABLE ) {
348 # "Stable" revision dumps...
349 # Default JOIN, to be overridden...
350 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
351 # One, and only one hook should set this, and return false
352 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
353 wfProfileOut( __METHOD__ );
354 throw new MWException( __METHOD__ . " given invalid history dump type." );
356 } elseif ( $this->history & WikiExporter::RANGE ) {
357 # Dump of revisions within a specified range
358 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
359 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
360 } else {
361 # Unknown history specification parameter?
362 wfProfileOut( __METHOD__ );
363 throw new MWException( __METHOD__ . " given invalid history dump type." );
365 # Query optimization hacks
366 if ( $cond == '' ) {
367 $opts[] = 'STRAIGHT_JOIN';
368 $opts['USE INDEX']['page'] = 'PRIMARY';
370 # Build text join options
371 if ( $this->text != WikiExporter::STUB ) { // 1-pass
372 $tables[] = 'text';
373 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
376 if ( $this->buffer == WikiExporter::STREAM ) {
377 $prev = $this->db->bufferResults( false );
380 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
381 try {
382 wfRunHooks( 'ModifyExportQuery',
383 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
385 # Do the query!
386 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
387 $wrapper = $this->db->resultObject( $result );
388 # Output dump results
389 $this->outputPageStream( $wrapper );
391 if ( $this->buffer == WikiExporter::STREAM ) {
392 $this->db->bufferResults( $prev );
394 } catch ( Exception $e ) {
395 // Throwing the exception does not reliably free the resultset, and
396 // would also leave the connection in unbuffered mode.
398 // Freeing result
399 try {
400 if ( $wrapper ) {
401 $wrapper->free();
403 } catch ( Exception $e2 ) {
404 // Already in panic mode -> ignoring $e2 as $e has
405 // higher priority
408 // Putting database back in previous buffer mode
409 try {
410 if ( $this->buffer == WikiExporter::STREAM ) {
411 $this->db->bufferResults( $prev );
413 } catch ( Exception $e2 ) {
414 // Already in panic mode -> ignoring $e2 as $e has
415 // higher priority
418 // Inform caller about problem
419 throw $e;
422 wfProfileOut( __METHOD__ );
426 * Runs through a query result set dumping page and revision records.
427 * The result set should be sorted/grouped by page to avoid duplicate
428 * page records in the output.
430 * Should be safe for
431 * streaming (non-buffered) queries, as long as it was made on a
432 * separate database connection not managed by LoadBalancer; some
433 * blob storage types will make queries to pull source data.
435 * @param ResultWrapper $resultset
437 protected function outputPageStream( $resultset ) {
438 $last = null;
439 foreach ( $resultset as $row ) {
440 if ( $last === null ||
441 $last->page_namespace != $row->page_namespace ||
442 $last->page_title != $row->page_title ) {
443 if ( $last !== null ) {
444 $output = '';
445 if ( $this->dumpUploads ) {
446 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
448 $output .= $this->writer->closePage();
449 $this->sink->writeClosePage( $output );
451 $output = $this->writer->openPage( $row );
452 $this->sink->writeOpenPage( $row, $output );
453 $last = $row;
455 $output = $this->writer->writeRevision( $row );
456 $this->sink->writeRevision( $row, $output );
458 if ( $last !== null ) {
459 $output = '';
460 if ( $this->dumpUploads ) {
461 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
463 $output .= $this->author_list;
464 $output .= $this->writer->closePage();
465 $this->sink->writeClosePage( $output );
470 * @param array $resultset
472 protected function outputLogStream( $resultset ) {
473 foreach ( $resultset as $row ) {
474 $output = $this->writer->writeLogItem( $row );
475 $this->sink->writeLogItem( $row, $output );
481 * @ingroup Dump
483 class XmlDumpWriter {
485 * Returns the export schema version.
486 * @deprecated since 1.20; use WikiExporter::schemaVersion() instead
487 * @return string
489 function schemaVersion() {
490 wfDeprecated( __METHOD__, '1.20' );
491 return WikiExporter::schemaVersion();
495 * Opens the XML output stream's root "<mediawiki>" element.
496 * This does not include an xml directive, so is safe to include
497 * as a subelement in a larger XML stream. Namespace and XML Schema
498 * references are included.
500 * Output will be encoded in UTF-8.
502 * @return string
504 function openStream() {
505 global $wgLanguageCode;
506 $ver = WikiExporter::schemaVersion();
507 return Xml::element( 'mediawiki', array(
508 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
509 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
511 * When a new version of the schema is created, it needs staging on mediawiki.org.
512 * This requires a change in the operations/mediawiki-config git repo.
514 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
515 * you copy in the new xsd file.
517 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
518 * echo "http://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
520 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
521 "http://www.mediawiki.org/xml/export-$ver.xsd",
522 'version' => $ver,
523 'xml:lang' => $wgLanguageCode ),
524 null ) .
525 "\n" .
526 $this->siteInfo();
530 * @return string
532 function siteInfo() {
533 $info = array(
534 $this->sitename(),
535 $this->dbname(),
536 $this->homelink(),
537 $this->generator(),
538 $this->caseSetting(),
539 $this->namespaces() );
540 return " <siteinfo>\n " .
541 implode( "\n ", $info ) .
542 "\n </siteinfo>\n";
546 * @return string
548 function sitename() {
549 global $wgSitename;
550 return Xml::element( 'sitename', array(), $wgSitename );
554 * @return string
556 function dbname() {
557 global $wgDBname;
558 return Xml::element( 'dbname', array(), $wgDBname );
562 * @return string
564 function generator() {
565 global $wgVersion;
566 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
570 * @return string
572 function homelink() {
573 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalURL() );
577 * @return string
579 function caseSetting() {
580 global $wgCapitalLinks;
581 // "case-insensitive" option is reserved for future
582 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
583 return Xml::element( 'case', array(), $sensitivity );
587 * @return string
589 function namespaces() {
590 global $wgContLang;
591 $spaces = "<namespaces>\n";
592 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
593 $spaces .= ' ' .
594 Xml::element( 'namespace',
595 array(
596 'key' => $ns,
597 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
598 ), $title ) . "\n";
600 $spaces .= " </namespaces>";
601 return $spaces;
605 * Closes the output stream with the closing root element.
606 * Call when finished dumping things.
608 * @return string
610 function closeStream() {
611 return "</mediawiki>\n";
615 * Opens a "<page>" section on the output stream, with data
616 * from the given database row.
618 * @param object $row
619 * @return string
621 public function openPage( $row ) {
622 $out = " <page>\n";
623 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
624 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
625 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace ) ) . "\n";
626 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
627 if ( $row->page_is_redirect ) {
628 $page = WikiPage::factory( $title );
629 $redirect = $page->getRedirectTarget();
630 if ( $redirect instanceof Title && $redirect->isValidRedirectTarget() ) {
631 $out .= ' ';
632 $out .= Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) );
633 $out .= "\n";
637 if ( $row->page_restrictions != '' ) {
638 $out .= ' ' . Xml::element( 'restrictions', array(),
639 strval( $row->page_restrictions ) ) . "\n";
642 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
644 return $out;
648 * Closes a "<page>" section on the output stream.
650 * @access private
651 * @return string
653 function closePage() {
654 return " </page>\n";
658 * Dumps a "<revision>" section on the output stream, with
659 * data filled in from the given database row.
661 * @param object $row
662 * @return string
663 * @access private
665 function writeRevision( $row ) {
666 wfProfileIn( __METHOD__ );
668 $out = " <revision>\n";
669 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
670 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
671 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
674 $out .= $this->writeTimestamp( $row->rev_timestamp );
676 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
677 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
678 } else {
679 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
682 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
683 $out .= " <minor/>\n";
685 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
686 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
687 } elseif ( $row->rev_comment != '' ) {
688 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
691 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
692 $content_model = strval( $row->rev_content_model );
693 } else {
694 // probably using $wgContentHandlerUseDB = false;
695 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
696 $content_model = ContentHandler::getDefaultModelFor( $title );
699 $content_handler = ContentHandler::getForModelID( $content_model );
701 if ( isset( $row->rev_content_format ) && !is_null( $row->rev_content_format ) ) {
702 $content_format = strval( $row->rev_content_format );
703 } else {
704 // probably using $wgContentHandlerUseDB = false;
705 $content_format = $content_handler->getDefaultFormat();
708 $text = '';
709 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
710 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
711 } elseif ( isset( $row->old_text ) ) {
712 // Raw text from the database may have invalid chars
713 $text = strval( Revision::getRevisionText( $row ) );
714 $text = $content_handler->exportTransform( $text, $content_format );
715 $out .= " " . Xml::elementClean( 'text',
716 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
717 strval( $text ) ) . "\n";
718 } else {
719 // Stub output
720 $out .= " " . Xml::element( 'text',
721 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
722 "" ) . "\n";
725 if ( isset( $row->rev_sha1 )
726 && $row->rev_sha1
727 && !( $row->rev_deleted & Revision::DELETED_TEXT )
729 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
730 } else {
731 $out .= " <sha1/>\n";
734 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
735 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
737 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
739 $out .= " </revision>\n";
741 wfProfileOut( __METHOD__ );
742 return $out;
746 * Dumps a "<logitem>" section on the output stream, with
747 * data filled in from the given database row.
749 * @param object $row
750 * @return string
751 * @access private
753 function writeLogItem( $row ) {
754 wfProfileIn( __METHOD__ );
756 $out = " <logitem>\n";
757 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
759 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
761 if ( $row->log_deleted & LogPage::DELETED_USER ) {
762 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
763 } else {
764 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
767 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
768 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
769 } elseif ( $row->log_comment != '' ) {
770 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
773 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
774 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
776 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
777 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
778 } else {
779 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
780 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
781 $out .= " " . Xml::elementClean( 'params',
782 array( 'xml:space' => 'preserve' ),
783 strval( $row->log_params ) ) . "\n";
786 $out .= " </logitem>\n";
788 wfProfileOut( __METHOD__ );
789 return $out;
793 * @param string $timestamp
794 * @param string $indent Default to six spaces
795 * @return string
797 function writeTimestamp( $timestamp, $indent = " " ) {
798 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
799 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
803 * @param int $id
804 * @param string $text
805 * @param string $indent Default to six spaces
806 * @return string
808 function writeContributor( $id, $text, $indent = " " ) {
809 $out = $indent . "<contributor>\n";
810 if ( $id || !IP::isValid( $text ) ) {
811 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
812 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
813 } else {
814 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
816 $out .= $indent . "</contributor>\n";
817 return $out;
821 * Warning! This data is potentially inconsistent. :(
822 * @param object $row
823 * @param bool $dumpContents
824 * @return string
826 function writeUploads( $row, $dumpContents = false ) {
827 if ( $row->page_namespace == NS_FILE ) {
828 $img = wfLocalFile( $row->page_title );
829 if ( $img && $img->exists() ) {
830 $out = '';
831 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
832 $out .= $this->writeUpload( $ver, $dumpContents );
834 $out .= $this->writeUpload( $img, $dumpContents );
835 return $out;
838 return '';
842 * @param File $file
843 * @param bool $dumpContents
844 * @return string
846 function writeUpload( $file, $dumpContents = false ) {
847 if ( $file->isOld() ) {
848 $archiveName = " " .
849 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
850 } else {
851 $archiveName = '';
853 if ( $dumpContents ) {
854 $be = $file->getRepo()->getBackend();
855 # Dump file as base64
856 # Uses only XML-safe characters, so does not need escaping
857 # @todo Too bad this loads the contents into memory (script might swap)
858 $contents = ' <contents encoding="base64">' .
859 chunk_split( base64_encode(
860 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
861 " </contents>\n";
862 } else {
863 $contents = '';
865 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
866 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
867 } else {
868 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
870 return " <upload>\n" .
871 $this->writeTimestamp( $file->getTimestamp() ) .
872 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
873 " " . $comment . "\n" .
874 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
875 $archiveName .
876 " " . Xml::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
877 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
878 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
879 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
880 $contents .
881 " </upload>\n";
885 * Return prefixed text form of title, but using the content language's
886 * canonical namespace. This skips any special-casing such as gendered
887 * user namespaces -- which while useful, are not yet listed in the
888 * XML "<siteinfo>" data so are unsafe in export.
890 * @param Title $title
891 * @return string
892 * @since 1.18
894 public static function canonicalTitle( Title $title ) {
895 if ( $title->isExternal() ) {
896 return $title->getPrefixedText();
899 global $wgContLang;
900 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
902 if ( $prefix !== '' ) {
903 $prefix .= ':';
906 return $prefix . $title->getText();
911 * Base class for output stream; prints to stdout or buffer or wherever.
912 * @ingroup Dump
914 class DumpOutput {
917 * @param string $string
919 function writeOpenStream( $string ) {
920 $this->write( $string );
924 * @param string $string
926 function writeCloseStream( $string ) {
927 $this->write( $string );
931 * @param object $page
932 * @param string $string
934 function writeOpenPage( $page, $string ) {
935 $this->write( $string );
939 * @param string $string
941 function writeClosePage( $string ) {
942 $this->write( $string );
946 * @param object $rev
947 * @param string $string
949 function writeRevision( $rev, $string ) {
950 $this->write( $string );
954 * @param object $rev
955 * @param string $string
957 function writeLogItem( $rev, $string ) {
958 $this->write( $string );
962 * Override to write to a different stream type.
963 * @param string $string
964 * @return bool
966 function write( $string ) {
967 print $string;
971 * Close the old file, move it to a specified name,
972 * and reopen new file with the old name. Use this
973 * for writing out a file in multiple pieces
974 * at specified checkpoints (e.g. every n hours).
975 * @param string|array $newname File name. May be a string or an array with one element
977 function closeRenameAndReopen( $newname ) {
981 * Close the old file, and move it to a specified name.
982 * Use this for the last piece of a file written out
983 * at specified checkpoints (e.g. every n hours).
984 * @param string|array $newname File name. May be a string or an array with one element
985 * @param bool $open If true, a new file with the old filename will be opened
986 * again for writing (default: false)
988 function closeAndRename( $newname, $open = false ) {
992 * Returns the name of the file or files which are
993 * being written to, if there are any.
994 * @return null
996 function getFilenames() {
997 return null;
1002 * Stream outputter to send data to a file.
1003 * @ingroup Dump
1005 class DumpFileOutput extends DumpOutput {
1006 protected $handle = false, $filename;
1009 * @param string $file
1011 function __construct( $file ) {
1012 $this->handle = fopen( $file, "wt" );
1013 $this->filename = $file;
1017 * @param string $string
1019 function writeCloseStream( $string ) {
1020 parent::writeCloseStream( $string );
1021 if ( $this->handle ) {
1022 fclose( $this->handle );
1023 $this->handle = false;
1028 * @param string $string
1030 function write( $string ) {
1031 fputs( $this->handle, $string );
1035 * @param string $newname
1037 function closeRenameAndReopen( $newname ) {
1038 $this->closeAndRename( $newname, true );
1042 * @param string $newname
1043 * @throws MWException
1045 function renameOrException( $newname ) {
1046 if ( !rename( $this->filename, $newname ) ) {
1047 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
1052 * @param array $newname
1053 * @return string
1054 * @throws MWException
1056 function checkRenameArgCount( $newname ) {
1057 if ( is_array( $newname ) ) {
1058 if ( count( $newname ) > 1 ) {
1059 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
1060 } else {
1061 $newname = $newname[0];
1064 return $newname;
1068 * @param string $newname
1069 * @param bool $open
1071 function closeAndRename( $newname, $open = false ) {
1072 $newname = $this->checkRenameArgCount( $newname );
1073 if ( $newname ) {
1074 if ( $this->handle ) {
1075 fclose( $this->handle );
1076 $this->handle = false;
1078 $this->renameOrException( $newname );
1079 if ( $open ) {
1080 $this->handle = fopen( $this->filename, "wt" );
1086 * @return string|null
1088 function getFilenames() {
1089 return $this->filename;
1094 * Stream outputter to send data to a file via some filter program.
1095 * Even if compression is available in a library, using a separate
1096 * program can allow us to make use of a multi-processor system.
1097 * @ingroup Dump
1099 class DumpPipeOutput extends DumpFileOutput {
1100 protected $command, $filename;
1101 protected $procOpenResource = false;
1104 * @param string $command
1105 * @param string $file
1107 function __construct( $command, $file = null ) {
1108 if ( !is_null( $file ) ) {
1109 $command .= " > " . wfEscapeShellArg( $file );
1112 $this->startCommand( $command );
1113 $this->command = $command;
1114 $this->filename = $file;
1118 * @param string $string
1120 function writeCloseStream( $string ) {
1121 parent::writeCloseStream( $string );
1122 if ( $this->procOpenResource ) {
1123 proc_close( $this->procOpenResource );
1124 $this->procOpenResource = false;
1129 * @param string $command
1131 function startCommand( $command ) {
1132 $spec = array(
1133 0 => array( "pipe", "r" ),
1135 $pipes = array();
1136 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1137 $this->handle = $pipes[0];
1141 * @param string $newname
1143 function closeRenameAndReopen( $newname ) {
1144 $this->closeAndRename( $newname, true );
1148 * @param string $newname
1149 * @param bool $open
1151 function closeAndRename( $newname, $open = false ) {
1152 $newname = $this->checkRenameArgCount( $newname );
1153 if ( $newname ) {
1154 if ( $this->handle ) {
1155 fclose( $this->handle );
1156 $this->handle = false;
1158 if ( $this->procOpenResource ) {
1159 proc_close( $this->procOpenResource );
1160 $this->procOpenResource = false;
1162 $this->renameOrException( $newname );
1163 if ( $open ) {
1164 $command = $this->command;
1165 $command .= " > " . wfEscapeShellArg( $this->filename );
1166 $this->startCommand( $command );
1173 * Sends dump output via the gzip compressor.
1174 * @ingroup Dump
1176 class DumpGZipOutput extends DumpPipeOutput {
1178 * @param string $file
1180 function __construct( $file ) {
1181 parent::__construct( "gzip", $file );
1186 * Sends dump output via the bgzip2 compressor.
1187 * @ingroup Dump
1189 class DumpBZip2Output extends DumpPipeOutput {
1191 * @param string $file
1193 function __construct( $file ) {
1194 parent::__construct( "bzip2", $file );
1199 * Sends dump output via the p7zip compressor.
1200 * @ingroup Dump
1202 class Dump7ZipOutput extends DumpPipeOutput {
1204 * @param string $file
1206 function __construct( $file ) {
1207 $command = $this->setup7zCommand( $file );
1208 parent::__construct( $command );
1209 $this->filename = $file;
1213 * @param string $file
1214 * @return string
1216 function setup7zCommand( $file ) {
1217 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1218 // Suppress annoying useless crap from p7zip
1219 // Unfortunately this could suppress real error messages too
1220 $command .= ' >' . wfGetNull() . ' 2>&1';
1221 return $command;
1225 * @param string $newname
1226 * @param bool $open
1228 function closeAndRename( $newname, $open = false ) {
1229 $newname = $this->checkRenameArgCount( $newname );
1230 if ( $newname ) {
1231 fclose( $this->handle );
1232 proc_close( $this->procOpenResource );
1233 $this->renameOrException( $newname );
1234 if ( $open ) {
1235 $command = $this->setup7zCommand( $this->filename );
1236 $this->startCommand( $command );
1243 * Dump output filter class.
1244 * This just does output filtering and streaming; XML formatting is done
1245 * higher up, so be careful in what you do.
1246 * @ingroup Dump
1248 class DumpFilter {
1250 * @var DumpOutput
1251 * FIXME will need to be made protected whenever legacy code
1252 * is updated.
1254 public $sink;
1257 * @var bool
1259 protected $sendingThisPage;
1262 * @param DumpOutput $sink
1264 function __construct( &$sink ) {
1265 $this->sink =& $sink;
1269 * @param string $string
1271 function writeOpenStream( $string ) {
1272 $this->sink->writeOpenStream( $string );
1276 * @param string $string
1278 function writeCloseStream( $string ) {
1279 $this->sink->writeCloseStream( $string );
1283 * @param object $page
1284 * @param string $string
1286 function writeOpenPage( $page, $string ) {
1287 $this->sendingThisPage = $this->pass( $page, $string );
1288 if ( $this->sendingThisPage ) {
1289 $this->sink->writeOpenPage( $page, $string );
1294 * @param string $string
1296 function writeClosePage( $string ) {
1297 if ( $this->sendingThisPage ) {
1298 $this->sink->writeClosePage( $string );
1299 $this->sendingThisPage = false;
1304 * @param object $rev
1305 * @param string $string
1307 function writeRevision( $rev, $string ) {
1308 if ( $this->sendingThisPage ) {
1309 $this->sink->writeRevision( $rev, $string );
1314 * @param object $rev
1315 * @param string $string
1317 function writeLogItem( $rev, $string ) {
1318 $this->sink->writeRevision( $rev, $string );
1322 * @param string $newname
1324 function closeRenameAndReopen( $newname ) {
1325 $this->sink->closeRenameAndReopen( $newname );
1329 * @param string $newname
1330 * @param bool $open
1332 function closeAndRename( $newname, $open = false ) {
1333 $this->sink->closeAndRename( $newname, $open );
1337 * @return array
1339 function getFilenames() {
1340 return $this->sink->getFilenames();
1344 * Override for page-based filter types.
1345 * @param object $page
1346 * @return bool
1348 function pass( $page ) {
1349 return true;
1354 * Simple dump output filter to exclude all talk pages.
1355 * @ingroup Dump
1357 class DumpNotalkFilter extends DumpFilter {
1359 * @param object $page
1360 * @return bool
1362 function pass( $page ) {
1363 return !MWNamespace::isTalk( $page->page_namespace );
1368 * Dump output filter to include or exclude pages in a given set of namespaces.
1369 * @ingroup Dump
1371 class DumpNamespaceFilter extends DumpFilter {
1372 /** @var bool */
1373 protected $invert = false;
1375 /** @var array */
1376 protected $namespaces = array();
1379 * @param DumpOutput $sink
1380 * @param array $param
1381 * @throws MWException
1383 function __construct( &$sink, $param ) {
1384 parent::__construct( $sink );
1386 $constants = array(
1387 "NS_MAIN" => NS_MAIN,
1388 "NS_TALK" => NS_TALK,
1389 "NS_USER" => NS_USER,
1390 "NS_USER_TALK" => NS_USER_TALK,
1391 "NS_PROJECT" => NS_PROJECT,
1392 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1393 "NS_FILE" => NS_FILE,
1394 "NS_FILE_TALK" => NS_FILE_TALK,
1395 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1396 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1397 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1398 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1399 "NS_TEMPLATE" => NS_TEMPLATE,
1400 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1401 "NS_HELP" => NS_HELP,
1402 "NS_HELP_TALK" => NS_HELP_TALK,
1403 "NS_CATEGORY" => NS_CATEGORY,
1404 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1406 if ( $param { 0 } == '!' ) {
1407 $this->invert = true;
1408 $param = substr( $param, 1 );
1411 foreach ( explode( ',', $param ) as $key ) {
1412 $key = trim( $key );
1413 if ( isset( $constants[$key] ) ) {
1414 $ns = $constants[$key];
1415 $this->namespaces[$ns] = true;
1416 } elseif ( is_numeric( $key ) ) {
1417 $ns = intval( $key );
1418 $this->namespaces[$ns] = true;
1419 } else {
1420 throw new MWException( "Unrecognized namespace key '$key'\n" );
1426 * @param object $page
1427 * @return bool
1429 function pass( $page ) {
1430 $match = isset( $this->namespaces[$page->page_namespace] );
1431 return $this->invert xor $match;
1436 * Dump output filter to include only the last revision in each page sequence.
1437 * @ingroup Dump
1439 class DumpLatestFilter extends DumpFilter {
1440 protected $page;
1442 protected $pageString;
1444 protected $rev;
1446 protected $revString;
1449 * @param object $page
1450 * @param string $string
1452 function writeOpenPage( $page, $string ) {
1453 $this->page = $page;
1454 $this->pageString = $string;
1458 * @param string $string
1460 function writeClosePage( $string ) {
1461 if ( $this->rev ) {
1462 $this->sink->writeOpenPage( $this->page, $this->pageString );
1463 $this->sink->writeRevision( $this->rev, $this->revString );
1464 $this->sink->writeClosePage( $string );
1466 $this->rev = null;
1467 $this->revString = null;
1468 $this->page = null;
1469 $this->pageString = null;
1473 * @param object $rev
1474 * @param string $string
1476 function writeRevision( $rev, $string ) {
1477 if ( $rev->rev_id == $this->page->page_latest ) {
1478 $this->rev = $rev;
1479 $this->revString = $string;
1485 * Base class for output stream; prints to stdout or buffer or wherever.
1486 * @ingroup Dump
1488 class DumpMultiWriter {
1491 * @param array $sinks
1493 function __construct( $sinks ) {
1494 $this->sinks = $sinks;
1495 $this->count = count( $sinks );
1499 * @param string $string
1501 function writeOpenStream( $string ) {
1502 for ( $i = 0; $i < $this->count; $i++ ) {
1503 $this->sinks[$i]->writeOpenStream( $string );
1508 * @param string $string
1510 function writeCloseStream( $string ) {
1511 for ( $i = 0; $i < $this->count; $i++ ) {
1512 $this->sinks[$i]->writeCloseStream( $string );
1517 * @param object $page
1518 * @param string $string
1520 function writeOpenPage( $page, $string ) {
1521 for ( $i = 0; $i < $this->count; $i++ ) {
1522 $this->sinks[$i]->writeOpenPage( $page, $string );
1527 * @param string $string
1529 function writeClosePage( $string ) {
1530 for ( $i = 0; $i < $this->count; $i++ ) {
1531 $this->sinks[$i]->writeClosePage( $string );
1536 * @param object $rev
1537 * @param string $string
1539 function writeRevision( $rev, $string ) {
1540 for ( $i = 0; $i < $this->count; $i++ ) {
1541 $this->sinks[$i]->writeRevision( $rev, $string );
1546 * @param array $newnames
1548 function closeRenameAndReopen( $newnames ) {
1549 $this->closeAndRename( $newnames, true );
1553 * @param array $newnames
1554 * @param bool $open
1556 function closeAndRename( $newnames, $open = false ) {
1557 for ( $i = 0; $i < $this->count; $i++ ) {
1558 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1563 * @return array
1565 function getFilenames() {
1566 $filenames = array();
1567 for ( $i = 0; $i < $this->count; $i++ ) {
1568 $filenames[] = $this->sinks[$i]->getFilenames();
1570 return $filenames;