Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / Export.php
blob4600feb5ad7e61e9900768ad81cdb815c4d06bac
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 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 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 $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 );
472 * @ingroup Dump
474 class XmlDumpWriter {
476 * Opens the XML output stream's root "<mediawiki>" element.
477 * This does not include an xml directive, so is safe to include
478 * as a subelement in a larger XML stream. Namespace and XML Schema
479 * references are included.
481 * Output will be encoded in UTF-8.
483 * @return string
485 function openStream() {
486 global $wgLanguageCode;
487 $ver = WikiExporter::schemaVersion();
488 return Xml::element( 'mediawiki', array(
489 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
490 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
492 * When a new version of the schema is created, it needs staging on mediawiki.org.
493 * This requires a change in the operations/mediawiki-config git repo.
495 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
496 * you copy in the new xsd file.
498 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
499 * echo "http://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
501 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
502 "http://www.mediawiki.org/xml/export-$ver.xsd",
503 'version' => $ver,
504 'xml:lang' => $wgLanguageCode ),
505 null ) .
506 "\n" .
507 $this->siteInfo();
511 * @return string
513 function siteInfo() {
514 $info = array(
515 $this->sitename(),
516 $this->dbname(),
517 $this->homelink(),
518 $this->generator(),
519 $this->caseSetting(),
520 $this->namespaces() );
521 return " <siteinfo>\n " .
522 implode( "\n ", $info ) .
523 "\n </siteinfo>\n";
527 * @return string
529 function sitename() {
530 global $wgSitename;
531 return Xml::element( 'sitename', array(), $wgSitename );
535 * @return string
537 function dbname() {
538 global $wgDBname;
539 return Xml::element( 'dbname', array(), $wgDBname );
543 * @return string
545 function generator() {
546 global $wgVersion;
547 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
551 * @return string
553 function homelink() {
554 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalURL() );
558 * @return string
560 function caseSetting() {
561 global $wgCapitalLinks;
562 // "case-insensitive" option is reserved for future
563 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
564 return Xml::element( 'case', array(), $sensitivity );
568 * @return string
570 function namespaces() {
571 global $wgContLang;
572 $spaces = "<namespaces>\n";
573 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
574 $spaces .= ' ' .
575 Xml::element( 'namespace',
576 array(
577 'key' => $ns,
578 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
579 ), $title ) . "\n";
581 $spaces .= " </namespaces>";
582 return $spaces;
586 * Closes the output stream with the closing root element.
587 * Call when finished dumping things.
589 * @return string
591 function closeStream() {
592 return "</mediawiki>\n";
596 * Opens a "<page>" section on the output stream, with data
597 * from the given database row.
599 * @param object $row
600 * @return string
602 public function openPage( $row ) {
603 $out = " <page>\n";
604 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
605 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
606 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace ) ) . "\n";
607 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
608 if ( $row->page_is_redirect ) {
609 $page = WikiPage::factory( $title );
610 $redirect = $page->getRedirectTarget();
611 if ( $redirect instanceof Title && $redirect->isValidRedirectTarget() ) {
612 $out .= ' ';
613 $out .= Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) );
614 $out .= "\n";
618 if ( $row->page_restrictions != '' ) {
619 $out .= ' ' . Xml::element( 'restrictions', array(),
620 strval( $row->page_restrictions ) ) . "\n";
623 Hooks::run( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
625 return $out;
629 * Closes a "<page>" section on the output stream.
631 * @access private
632 * @return string
634 function closePage() {
635 return " </page>\n";
639 * Dumps a "<revision>" section on the output stream, with
640 * data filled in from the given database row.
642 * @param object $row
643 * @return string
644 * @access private
646 function writeRevision( $row ) {
648 $out = " <revision>\n";
649 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
650 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
651 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
654 $out .= $this->writeTimestamp( $row->rev_timestamp );
656 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
657 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
658 } else {
659 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
662 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
663 $out .= " <minor/>\n";
665 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
666 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
667 } elseif ( $row->rev_comment != '' ) {
668 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
671 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
672 $content_model = strval( $row->rev_content_model );
673 } else {
674 // probably using $wgContentHandlerUseDB = false;
675 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
676 $content_model = ContentHandler::getDefaultModelFor( $title );
679 $content_handler = ContentHandler::getForModelID( $content_model );
681 if ( isset( $row->rev_content_format ) && !is_null( $row->rev_content_format ) ) {
682 $content_format = strval( $row->rev_content_format );
683 } else {
684 // probably using $wgContentHandlerUseDB = false;
685 $content_format = $content_handler->getDefaultFormat();
688 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
689 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
691 $text = '';
692 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
693 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
694 } elseif ( isset( $row->old_text ) ) {
695 // Raw text from the database may have invalid chars
696 $text = strval( Revision::getRevisionText( $row ) );
697 $text = $content_handler->exportTransform( $text, $content_format );
698 $out .= " " . Xml::elementClean( 'text',
699 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
700 strval( $text ) ) . "\n";
701 } else {
702 // Stub output
703 $out .= " " . Xml::element( 'text',
704 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
705 "" ) . "\n";
708 if ( isset( $row->rev_sha1 )
709 && $row->rev_sha1
710 && !( $row->rev_deleted & Revision::DELETED_TEXT )
712 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
713 } else {
714 $out .= " <sha1/>\n";
717 Hooks::run( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
719 $out .= " </revision>\n";
721 return $out;
725 * Dumps a "<logitem>" section on the output stream, with
726 * data filled in from the given database row.
728 * @param object $row
729 * @return string
730 * @access private
732 function writeLogItem( $row ) {
734 $out = " <logitem>\n";
735 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
737 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
739 if ( $row->log_deleted & LogPage::DELETED_USER ) {
740 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
741 } else {
742 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
745 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
746 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
747 } elseif ( $row->log_comment != '' ) {
748 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
751 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
752 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
754 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
755 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
756 } else {
757 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
758 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
759 $out .= " " . Xml::elementClean( 'params',
760 array( 'xml:space' => 'preserve' ),
761 strval( $row->log_params ) ) . "\n";
764 $out .= " </logitem>\n";
766 return $out;
770 * @param string $timestamp
771 * @param string $indent Default to six spaces
772 * @return string
774 function writeTimestamp( $timestamp, $indent = " " ) {
775 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
776 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
780 * @param int $id
781 * @param string $text
782 * @param string $indent Default to six spaces
783 * @return string
785 function writeContributor( $id, $text, $indent = " " ) {
786 $out = $indent . "<contributor>\n";
787 if ( $id || !IP::isValid( $text ) ) {
788 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
789 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
790 } else {
791 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
793 $out .= $indent . "</contributor>\n";
794 return $out;
798 * Warning! This data is potentially inconsistent. :(
799 * @param object $row
800 * @param bool $dumpContents
801 * @return string
803 function writeUploads( $row, $dumpContents = false ) {
804 if ( $row->page_namespace == NS_FILE ) {
805 $img = wfLocalFile( $row->page_title );
806 if ( $img && $img->exists() ) {
807 $out = '';
808 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
809 $out .= $this->writeUpload( $ver, $dumpContents );
811 $out .= $this->writeUpload( $img, $dumpContents );
812 return $out;
815 return '';
819 * @param File $file
820 * @param bool $dumpContents
821 * @return string
823 function writeUpload( $file, $dumpContents = false ) {
824 if ( $file->isOld() ) {
825 $archiveName = " " .
826 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
827 } else {
828 $archiveName = '';
830 if ( $dumpContents ) {
831 $be = $file->getRepo()->getBackend();
832 # Dump file as base64
833 # Uses only XML-safe characters, so does not need escaping
834 # @todo Too bad this loads the contents into memory (script might swap)
835 $contents = ' <contents encoding="base64">' .
836 chunk_split( base64_encode(
837 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
838 " </contents>\n";
839 } else {
840 $contents = '';
842 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
843 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
844 } else {
845 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
847 return " <upload>\n" .
848 $this->writeTimestamp( $file->getTimestamp() ) .
849 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
850 " " . $comment . "\n" .
851 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
852 $archiveName .
853 " " . Xml::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
854 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
855 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
856 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
857 $contents .
858 " </upload>\n";
862 * Return prefixed text form of title, but using the content language's
863 * canonical namespace. This skips any special-casing such as gendered
864 * user namespaces -- which while useful, are not yet listed in the
865 * XML "<siteinfo>" data so are unsafe in export.
867 * @param Title $title
868 * @return string
869 * @since 1.18
871 public static function canonicalTitle( Title $title ) {
872 if ( $title->isExternal() ) {
873 return $title->getPrefixedText();
876 global $wgContLang;
877 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
879 if ( $prefix !== '' ) {
880 $prefix .= ':';
883 return $prefix . $title->getText();
888 * Base class for output stream; prints to stdout or buffer or wherever.
889 * @ingroup Dump
891 class DumpOutput {
894 * @param string $string
896 function writeOpenStream( $string ) {
897 $this->write( $string );
901 * @param string $string
903 function writeCloseStream( $string ) {
904 $this->write( $string );
908 * @param object $page
909 * @param string $string
911 function writeOpenPage( $page, $string ) {
912 $this->write( $string );
916 * @param string $string
918 function writeClosePage( $string ) {
919 $this->write( $string );
923 * @param object $rev
924 * @param string $string
926 function writeRevision( $rev, $string ) {
927 $this->write( $string );
931 * @param object $rev
932 * @param string $string
934 function writeLogItem( $rev, $string ) {
935 $this->write( $string );
939 * Override to write to a different stream type.
940 * @param string $string
941 * @return bool
943 function write( $string ) {
944 print $string;
948 * Close the old file, move it to a specified name,
949 * and reopen new file with the old name. Use this
950 * for writing out a file in multiple pieces
951 * at specified checkpoints (e.g. every n hours).
952 * @param string|array $newname File name. May be a string or an array with one element
954 function closeRenameAndReopen( $newname ) {
958 * Close the old file, and move it to a specified name.
959 * Use this for the last piece of a file written out
960 * at specified checkpoints (e.g. every n hours).
961 * @param string|array $newname File name. May be a string or an array with one element
962 * @param bool $open If true, a new file with the old filename will be opened
963 * again for writing (default: false)
965 function closeAndRename( $newname, $open = false ) {
969 * Returns the name of the file or files which are
970 * being written to, if there are any.
971 * @return null
973 function getFilenames() {
974 return null;
979 * Stream outputter to send data to a file.
980 * @ingroup Dump
982 class DumpFileOutput extends DumpOutput {
983 protected $handle = false, $filename;
986 * @param string $file
988 function __construct( $file ) {
989 $this->handle = fopen( $file, "wt" );
990 $this->filename = $file;
994 * @param string $string
996 function writeCloseStream( $string ) {
997 parent::writeCloseStream( $string );
998 if ( $this->handle ) {
999 fclose( $this->handle );
1000 $this->handle = false;
1005 * @param string $string
1007 function write( $string ) {
1008 fputs( $this->handle, $string );
1012 * @param string $newname
1014 function closeRenameAndReopen( $newname ) {
1015 $this->closeAndRename( $newname, true );
1019 * @param string $newname
1020 * @throws MWException
1022 function renameOrException( $newname ) {
1023 if ( !rename( $this->filename, $newname ) ) {
1024 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
1029 * @param array $newname
1030 * @return string
1031 * @throws MWException
1033 function checkRenameArgCount( $newname ) {
1034 if ( is_array( $newname ) ) {
1035 if ( count( $newname ) > 1 ) {
1036 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
1037 } else {
1038 $newname = $newname[0];
1041 return $newname;
1045 * @param string $newname
1046 * @param bool $open
1048 function closeAndRename( $newname, $open = false ) {
1049 $newname = $this->checkRenameArgCount( $newname );
1050 if ( $newname ) {
1051 if ( $this->handle ) {
1052 fclose( $this->handle );
1053 $this->handle = false;
1055 $this->renameOrException( $newname );
1056 if ( $open ) {
1057 $this->handle = fopen( $this->filename, "wt" );
1063 * @return string|null
1065 function getFilenames() {
1066 return $this->filename;
1071 * Stream outputter to send data to a file via some filter program.
1072 * Even if compression is available in a library, using a separate
1073 * program can allow us to make use of a multi-processor system.
1074 * @ingroup Dump
1076 class DumpPipeOutput extends DumpFileOutput {
1077 protected $command, $filename;
1078 protected $procOpenResource = false;
1081 * @param string $command
1082 * @param string $file
1084 function __construct( $command, $file = null ) {
1085 if ( !is_null( $file ) ) {
1086 $command .= " > " . wfEscapeShellArg( $file );
1089 $this->startCommand( $command );
1090 $this->command = $command;
1091 $this->filename = $file;
1095 * @param string $string
1097 function writeCloseStream( $string ) {
1098 parent::writeCloseStream( $string );
1099 if ( $this->procOpenResource ) {
1100 proc_close( $this->procOpenResource );
1101 $this->procOpenResource = false;
1106 * @param string $command
1108 function startCommand( $command ) {
1109 $spec = array(
1110 0 => array( "pipe", "r" ),
1112 $pipes = array();
1113 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1114 $this->handle = $pipes[0];
1118 * @param string $newname
1120 function closeRenameAndReopen( $newname ) {
1121 $this->closeAndRename( $newname, true );
1125 * @param string $newname
1126 * @param bool $open
1128 function closeAndRename( $newname, $open = false ) {
1129 $newname = $this->checkRenameArgCount( $newname );
1130 if ( $newname ) {
1131 if ( $this->handle ) {
1132 fclose( $this->handle );
1133 $this->handle = false;
1135 if ( $this->procOpenResource ) {
1136 proc_close( $this->procOpenResource );
1137 $this->procOpenResource = false;
1139 $this->renameOrException( $newname );
1140 if ( $open ) {
1141 $command = $this->command;
1142 $command .= " > " . wfEscapeShellArg( $this->filename );
1143 $this->startCommand( $command );
1150 * Sends dump output via the gzip compressor.
1151 * @ingroup Dump
1153 class DumpGZipOutput extends DumpPipeOutput {
1155 * @param string $file
1157 function __construct( $file ) {
1158 parent::__construct( "gzip", $file );
1163 * Sends dump output via the bgzip2 compressor.
1164 * @ingroup Dump
1166 class DumpBZip2Output extends DumpPipeOutput {
1168 * @param string $file
1170 function __construct( $file ) {
1171 parent::__construct( "bzip2", $file );
1176 * Sends dump output via the p7zip compressor.
1177 * @ingroup Dump
1179 class Dump7ZipOutput extends DumpPipeOutput {
1181 * @param string $file
1183 function __construct( $file ) {
1184 $command = $this->setup7zCommand( $file );
1185 parent::__construct( $command );
1186 $this->filename = $file;
1190 * @param string $file
1191 * @return string
1193 function setup7zCommand( $file ) {
1194 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1195 // Suppress annoying useless crap from p7zip
1196 // Unfortunately this could suppress real error messages too
1197 $command .= ' >' . wfGetNull() . ' 2>&1';
1198 return $command;
1202 * @param string $newname
1203 * @param bool $open
1205 function closeAndRename( $newname, $open = false ) {
1206 $newname = $this->checkRenameArgCount( $newname );
1207 if ( $newname ) {
1208 fclose( $this->handle );
1209 proc_close( $this->procOpenResource );
1210 $this->renameOrException( $newname );
1211 if ( $open ) {
1212 $command = $this->setup7zCommand( $this->filename );
1213 $this->startCommand( $command );
1220 * Dump output filter class.
1221 * This just does output filtering and streaming; XML formatting is done
1222 * higher up, so be careful in what you do.
1223 * @ingroup Dump
1225 class DumpFilter {
1227 * @var DumpOutput
1228 * FIXME will need to be made protected whenever legacy code
1229 * is updated.
1231 public $sink;
1234 * @var bool
1236 protected $sendingThisPage;
1239 * @param DumpOutput $sink
1241 function __construct( &$sink ) {
1242 $this->sink =& $sink;
1246 * @param string $string
1248 function writeOpenStream( $string ) {
1249 $this->sink->writeOpenStream( $string );
1253 * @param string $string
1255 function writeCloseStream( $string ) {
1256 $this->sink->writeCloseStream( $string );
1260 * @param object $page
1261 * @param string $string
1263 function writeOpenPage( $page, $string ) {
1264 $this->sendingThisPage = $this->pass( $page, $string );
1265 if ( $this->sendingThisPage ) {
1266 $this->sink->writeOpenPage( $page, $string );
1271 * @param string $string
1273 function writeClosePage( $string ) {
1274 if ( $this->sendingThisPage ) {
1275 $this->sink->writeClosePage( $string );
1276 $this->sendingThisPage = false;
1281 * @param object $rev
1282 * @param string $string
1284 function writeRevision( $rev, $string ) {
1285 if ( $this->sendingThisPage ) {
1286 $this->sink->writeRevision( $rev, $string );
1291 * @param object $rev
1292 * @param string $string
1294 function writeLogItem( $rev, $string ) {
1295 $this->sink->writeRevision( $rev, $string );
1299 * @param string $newname
1301 function closeRenameAndReopen( $newname ) {
1302 $this->sink->closeRenameAndReopen( $newname );
1306 * @param string $newname
1307 * @param bool $open
1309 function closeAndRename( $newname, $open = false ) {
1310 $this->sink->closeAndRename( $newname, $open );
1314 * @return array
1316 function getFilenames() {
1317 return $this->sink->getFilenames();
1321 * Override for page-based filter types.
1322 * @param object $page
1323 * @return bool
1325 function pass( $page ) {
1326 return true;
1331 * Simple dump output filter to exclude all talk pages.
1332 * @ingroup Dump
1334 class DumpNotalkFilter extends DumpFilter {
1336 * @param object $page
1337 * @return bool
1339 function pass( $page ) {
1340 return !MWNamespace::isTalk( $page->page_namespace );
1345 * Dump output filter to include or exclude pages in a given set of namespaces.
1346 * @ingroup Dump
1348 class DumpNamespaceFilter extends DumpFilter {
1349 /** @var bool */
1350 public $invert = false;
1352 /** @var array */
1353 public $namespaces = array();
1356 * @param DumpOutput $sink
1357 * @param array $param
1358 * @throws MWException
1360 function __construct( &$sink, $param ) {
1361 parent::__construct( $sink );
1363 $constants = array(
1364 "NS_MAIN" => NS_MAIN,
1365 "NS_TALK" => NS_TALK,
1366 "NS_USER" => NS_USER,
1367 "NS_USER_TALK" => NS_USER_TALK,
1368 "NS_PROJECT" => NS_PROJECT,
1369 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1370 "NS_FILE" => NS_FILE,
1371 "NS_FILE_TALK" => NS_FILE_TALK,
1372 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1373 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1374 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1375 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1376 "NS_TEMPLATE" => NS_TEMPLATE,
1377 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1378 "NS_HELP" => NS_HELP,
1379 "NS_HELP_TALK" => NS_HELP_TALK,
1380 "NS_CATEGORY" => NS_CATEGORY,
1381 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1383 if ( $param { 0 } == '!' ) {
1384 $this->invert = true;
1385 $param = substr( $param, 1 );
1388 foreach ( explode( ',', $param ) as $key ) {
1389 $key = trim( $key );
1390 if ( isset( $constants[$key] ) ) {
1391 $ns = $constants[$key];
1392 $this->namespaces[$ns] = true;
1393 } elseif ( is_numeric( $key ) ) {
1394 $ns = intval( $key );
1395 $this->namespaces[$ns] = true;
1396 } else {
1397 throw new MWException( "Unrecognized namespace key '$key'\n" );
1403 * @param object $page
1404 * @return bool
1406 function pass( $page ) {
1407 $match = isset( $this->namespaces[$page->page_namespace] );
1408 return $this->invert xor $match;
1413 * Dump output filter to include only the last revision in each page sequence.
1414 * @ingroup Dump
1416 class DumpLatestFilter extends DumpFilter {
1417 public $page;
1419 public $pageString;
1421 public $rev;
1423 public $revString;
1426 * @param object $page
1427 * @param string $string
1429 function writeOpenPage( $page, $string ) {
1430 $this->page = $page;
1431 $this->pageString = $string;
1435 * @param string $string
1437 function writeClosePage( $string ) {
1438 if ( $this->rev ) {
1439 $this->sink->writeOpenPage( $this->page, $this->pageString );
1440 $this->sink->writeRevision( $this->rev, $this->revString );
1441 $this->sink->writeClosePage( $string );
1443 $this->rev = null;
1444 $this->revString = null;
1445 $this->page = null;
1446 $this->pageString = null;
1450 * @param object $rev
1451 * @param string $string
1453 function writeRevision( $rev, $string ) {
1454 if ( $rev->rev_id == $this->page->page_latest ) {
1455 $this->rev = $rev;
1456 $this->revString = $string;
1462 * Base class for output stream; prints to stdout or buffer or wherever.
1463 * @ingroup Dump
1465 class DumpMultiWriter {
1468 * @param array $sinks
1470 function __construct( $sinks ) {
1471 $this->sinks = $sinks;
1472 $this->count = count( $sinks );
1476 * @param string $string
1478 function writeOpenStream( $string ) {
1479 for ( $i = 0; $i < $this->count; $i++ ) {
1480 $this->sinks[$i]->writeOpenStream( $string );
1485 * @param string $string
1487 function writeCloseStream( $string ) {
1488 for ( $i = 0; $i < $this->count; $i++ ) {
1489 $this->sinks[$i]->writeCloseStream( $string );
1494 * @param object $page
1495 * @param string $string
1497 function writeOpenPage( $page, $string ) {
1498 for ( $i = 0; $i < $this->count; $i++ ) {
1499 $this->sinks[$i]->writeOpenPage( $page, $string );
1504 * @param string $string
1506 function writeClosePage( $string ) {
1507 for ( $i = 0; $i < $this->count; $i++ ) {
1508 $this->sinks[$i]->writeClosePage( $string );
1513 * @param object $rev
1514 * @param string $string
1516 function writeRevision( $rev, $string ) {
1517 for ( $i = 0; $i < $this->count; $i++ ) {
1518 $this->sinks[$i]->writeRevision( $rev, $string );
1523 * @param array $newnames
1525 function closeRenameAndReopen( $newnames ) {
1526 $this->closeAndRename( $newnames, true );
1530 * @param array $newnames
1531 * @param bool $open
1533 function closeAndRename( $newnames, $open = false ) {
1534 for ( $i = 0; $i < $this->count; $i++ ) {
1535 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1540 * @return array
1542 function getFilenames() {
1543 $filenames = array();
1544 for ( $i = 0; $i < $this->count; $i++ ) {
1545 $filenames[] = $this->sinks[$i]->getFilenames();
1547 return $filenames;