Don't rely on $wgTitle in WebRequest
[mediawiki.git] / includes / Export.php
blob84f5c60cecfbd16a7e758af01308fa35aba98622
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.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 $result = null; // Assuring $result 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 $this->outputLogStream( $result );
279 if ( $this->buffer == WikiExporter::STREAM ) {
280 $this->db->bufferResults( $prev );
282 } catch ( Exception $e ) {
283 // Throwing the exception does not reliably free the resultset, and
284 // would also leave the connection in unbuffered mode.
286 // Freeing result
287 try {
288 if ( $result ) {
289 $result->free();
291 } catch ( Exception $e2 ) {
292 // Already in panic mode -> ignoring $e2 as $e has
293 // higher priority
296 // Putting database back in previous buffer mode
297 try {
298 if ( $this->buffer == WikiExporter::STREAM ) {
299 $this->db->bufferResults( $prev );
301 } catch ( Exception $e2 ) {
302 // Already in panic mode -> ignoring $e2 as $e has
303 // higher priority
306 // Inform caller about problem
307 wfProfileOut( __METHOD__ );
308 throw $e;
310 # For page dumps...
311 } else {
312 $tables = array( 'page', 'revision' );
313 $opts = array( 'ORDER BY' => 'page_id ASC' );
314 $opts['USE INDEX'] = array();
315 $join = array();
316 if ( is_array( $this->history ) ) {
317 # Time offset/limit for all pages/history...
318 $revJoin = 'page_id=rev_page';
319 # Set time order
320 if ( $this->history['dir'] == 'asc' ) {
321 $op = '>';
322 $opts['ORDER BY'] = 'rev_timestamp ASC';
323 } else {
324 $op = '<';
325 $opts['ORDER BY'] = 'rev_timestamp DESC';
327 # Set offset
328 if ( !empty( $this->history['offset'] ) ) {
329 $revJoin .= " AND rev_timestamp $op " .
330 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
332 $join['revision'] = array( 'INNER JOIN', $revJoin );
333 # Set query limit
334 if ( !empty( $this->history['limit'] ) ) {
335 $opts['LIMIT'] = intval( $this->history['limit'] );
337 } elseif ( $this->history & WikiExporter::FULL ) {
338 # Full history dumps...
339 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
340 } elseif ( $this->history & WikiExporter::CURRENT ) {
341 # Latest revision dumps...
342 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
343 $this->do_list_authors( $cond );
345 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
346 } elseif ( $this->history & WikiExporter::STABLE ) {
347 # "Stable" revision dumps...
348 # Default JOIN, to be overridden...
349 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
350 # One, and only one hook should set this, and return false
351 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
352 wfProfileOut( __METHOD__ );
353 throw new MWException( __METHOD__ . " given invalid history dump type." );
355 } elseif ( $this->history & WikiExporter::RANGE ) {
356 # Dump of revisions within a specified range
357 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
358 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
359 } else {
360 # Unknown history specification parameter?
361 wfProfileOut( __METHOD__ );
362 throw new MWException( __METHOD__ . " given invalid history dump type." );
364 # Query optimization hacks
365 if ( $cond == '' ) {
366 $opts[] = 'STRAIGHT_JOIN';
367 $opts['USE INDEX']['page'] = 'PRIMARY';
369 # Build text join options
370 if ( $this->text != WikiExporter::STUB ) { // 1-pass
371 $tables[] = 'text';
372 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
375 if ( $this->buffer == WikiExporter::STREAM ) {
376 $prev = $this->db->bufferResults( false );
379 $result = null; // Assuring $result is not undefined, if exception occurs early
380 try {
381 wfRunHooks( 'ModifyExportQuery',
382 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
384 # Do the query!
385 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
386 # Output dump results
387 $this->outputPageStream( $result );
389 if ( $this->buffer == WikiExporter::STREAM ) {
390 $this->db->bufferResults( $prev );
392 } catch ( Exception $e ) {
393 // Throwing the exception does not reliably free the resultset, and
394 // would also leave the connection in unbuffered mode.
396 // Freeing result
397 try {
398 if ( $result ) {
399 $result->free();
401 } catch ( Exception $e2 ) {
402 // Already in panic mode -> ignoring $e2 as $e has
403 // higher priority
406 // Putting database back in previous buffer mode
407 try {
408 if ( $this->buffer == WikiExporter::STREAM ) {
409 $this->db->bufferResults( $prev );
411 } catch ( Exception $e2 ) {
412 // Already in panic mode -> ignoring $e2 as $e has
413 // higher priority
416 // Inform caller about problem
417 throw $e;
420 wfProfileOut( __METHOD__ );
424 * Runs through a query result set dumping page and revision records.
425 * The result set should be sorted/grouped by page to avoid duplicate
426 * page records in the output.
428 * Should be safe for
429 * streaming (non-buffered) queries, as long as it was made on a
430 * separate database connection not managed by LoadBalancer; some
431 * blob storage types will make queries to pull source data.
433 * @param ResultWrapper $resultset
435 protected function outputPageStream( $resultset ) {
436 $last = null;
437 foreach ( $resultset as $row ) {
438 if ( $last === null ||
439 $last->page_namespace != $row->page_namespace ||
440 $last->page_title != $row->page_title ) {
441 if ( $last !== null ) {
442 $output = '';
443 if ( $this->dumpUploads ) {
444 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
446 $output .= $this->writer->closePage();
447 $this->sink->writeClosePage( $output );
449 $output = $this->writer->openPage( $row );
450 $this->sink->writeOpenPage( $row, $output );
451 $last = $row;
453 $output = $this->writer->writeRevision( $row );
454 $this->sink->writeRevision( $row, $output );
456 if ( $last !== null ) {
457 $output = '';
458 if ( $this->dumpUploads ) {
459 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
461 $output .= $this->author_list;
462 $output .= $this->writer->closePage();
463 $this->sink->writeClosePage( $output );
468 * @param ResultWrapper $resultset
470 protected function outputLogStream( $resultset ) {
471 foreach ( $resultset as $row ) {
472 $output = $this->writer->writeLogItem( $row );
473 $this->sink->writeLogItem( $row, $output );
479 * @ingroup Dump
481 class XmlDumpWriter {
483 * Returns the export schema version.
484 * @deprecated since 1.20; use WikiExporter::schemaVersion() instead
485 * @return string
487 function schemaVersion() {
488 wfDeprecated( __METHOD__, '1.20' );
489 return WikiExporter::schemaVersion();
493 * Opens the XML output stream's root "<mediawiki>" element.
494 * This does not include an xml directive, so is safe to include
495 * as a subelement in a larger XML stream. Namespace and XML Schema
496 * references are included.
498 * Output will be encoded in UTF-8.
500 * @return string
502 function openStream() {
503 global $wgLanguageCode;
504 $ver = WikiExporter::schemaVersion();
505 return Xml::element( 'mediawiki', array(
506 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
507 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
509 * When a new version of the schema is created, it needs staging on mediawiki.org.
510 * This requires a change in the operations/mediawiki-config git repo.
512 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
513 * you copy in the new xsd file.
515 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
516 * echo "http://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
518 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
519 "http://www.mediawiki.org/xml/export-$ver.xsd",
520 'version' => $ver,
521 'xml:lang' => $wgLanguageCode ),
522 null ) .
523 "\n" .
524 $this->siteInfo();
528 * @return string
530 function siteInfo() {
531 $info = array(
532 $this->sitename(),
533 $this->dbname(),
534 $this->homelink(),
535 $this->generator(),
536 $this->caseSetting(),
537 $this->namespaces() );
538 return " <siteinfo>\n " .
539 implode( "\n ", $info ) .
540 "\n </siteinfo>\n";
544 * @return string
546 function sitename() {
547 global $wgSitename;
548 return Xml::element( 'sitename', array(), $wgSitename );
552 * @return string
554 function dbname() {
555 global $wgDBname;
556 return Xml::element( 'dbname', array(), $wgDBname );
560 * @return string
562 function generator() {
563 global $wgVersion;
564 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
568 * @return string
570 function homelink() {
571 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalURL() );
575 * @return string
577 function caseSetting() {
578 global $wgCapitalLinks;
579 // "case-insensitive" option is reserved for future
580 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
581 return Xml::element( 'case', array(), $sensitivity );
585 * @return string
587 function namespaces() {
588 global $wgContLang;
589 $spaces = "<namespaces>\n";
590 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
591 $spaces .= ' ' .
592 Xml::element( 'namespace',
593 array(
594 'key' => $ns,
595 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
596 ), $title ) . "\n";
598 $spaces .= " </namespaces>";
599 return $spaces;
603 * Closes the output stream with the closing root element.
604 * Call when finished dumping things.
606 * @return string
608 function closeStream() {
609 return "</mediawiki>\n";
613 * Opens a "<page>" section on the output stream, with data
614 * from the given database row.
616 * @param object $row
617 * @return string
619 public function openPage( $row ) {
620 $out = " <page>\n";
621 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
622 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
623 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace ) ) . "\n";
624 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
625 if ( $row->page_is_redirect ) {
626 $page = WikiPage::factory( $title );
627 $redirect = $page->getRedirectTarget();
628 if ( $redirect instanceof Title && $redirect->isValidRedirectTarget() ) {
629 $out .= ' ';
630 $out .= Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) );
631 $out .= "\n";
635 if ( $row->page_restrictions != '' ) {
636 $out .= ' ' . Xml::element( 'restrictions', array(),
637 strval( $row->page_restrictions ) ) . "\n";
640 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
642 return $out;
646 * Closes a "<page>" section on the output stream.
648 * @access private
649 * @return string
651 function closePage() {
652 return " </page>\n";
656 * Dumps a "<revision>" section on the output stream, with
657 * data filled in from the given database row.
659 * @param object $row
660 * @return string
661 * @access private
663 function writeRevision( $row ) {
664 wfProfileIn( __METHOD__ );
666 $out = " <revision>\n";
667 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
668 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
669 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
672 $out .= $this->writeTimestamp( $row->rev_timestamp );
674 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
675 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
676 } else {
677 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
680 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
681 $out .= " <minor/>\n";
683 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
684 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
685 } elseif ( $row->rev_comment != '' ) {
686 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
689 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
690 $content_model = strval( $row->rev_content_model );
691 } else {
692 // probably using $wgContentHandlerUseDB = false;
693 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
694 $content_model = ContentHandler::getDefaultModelFor( $title );
697 $content_handler = ContentHandler::getForModelID( $content_model );
699 if ( isset( $row->rev_content_format ) && !is_null( $row->rev_content_format ) ) {
700 $content_format = strval( $row->rev_content_format );
701 } else {
702 // probably using $wgContentHandlerUseDB = false;
703 $content_format = $content_handler->getDefaultFormat();
706 $text = '';
707 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
708 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
709 } elseif ( isset( $row->old_text ) ) {
710 // Raw text from the database may have invalid chars
711 $text = strval( Revision::getRevisionText( $row ) );
712 $text = $content_handler->exportTransform( $text, $content_format );
713 $out .= " " . Xml::elementClean( 'text',
714 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
715 strval( $text ) ) . "\n";
716 } else {
717 // Stub output
718 $out .= " " . Xml::element( 'text',
719 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
720 "" ) . "\n";
723 if ( isset( $row->rev_sha1 )
724 && $row->rev_sha1
725 && !( $row->rev_deleted & Revision::DELETED_TEXT )
727 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
728 } else {
729 $out .= " <sha1/>\n";
732 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
733 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
735 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
737 $out .= " </revision>\n";
739 wfProfileOut( __METHOD__ );
740 return $out;
744 * Dumps a "<logitem>" section on the output stream, with
745 * data filled in from the given database row.
747 * @param object $row
748 * @return string
749 * @access private
751 function writeLogItem( $row ) {
752 wfProfileIn( __METHOD__ );
754 $out = " <logitem>\n";
755 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
757 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
759 if ( $row->log_deleted & LogPage::DELETED_USER ) {
760 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
761 } else {
762 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
765 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
766 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
767 } elseif ( $row->log_comment != '' ) {
768 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
771 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
772 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
774 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
775 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
776 } else {
777 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
778 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
779 $out .= " " . Xml::elementClean( 'params',
780 array( 'xml:space' => 'preserve' ),
781 strval( $row->log_params ) ) . "\n";
784 $out .= " </logitem>\n";
786 wfProfileOut( __METHOD__ );
787 return $out;
791 * @param string $timestamp
792 * @param string $indent Default to six spaces
793 * @return string
795 function writeTimestamp( $timestamp, $indent = " " ) {
796 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
797 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
801 * @param int $id
802 * @param string $text
803 * @param string $indent Default to six spaces
804 * @return string
806 function writeContributor( $id, $text, $indent = " " ) {
807 $out = $indent . "<contributor>\n";
808 if ( $id || !IP::isValid( $text ) ) {
809 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
810 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
811 } else {
812 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
814 $out .= $indent . "</contributor>\n";
815 return $out;
819 * Warning! This data is potentially inconsistent. :(
820 * @param object $row
821 * @param bool $dumpContents
822 * @return string
824 function writeUploads( $row, $dumpContents = false ) {
825 if ( $row->page_namespace == NS_FILE ) {
826 $img = wfLocalFile( $row->page_title );
827 if ( $img && $img->exists() ) {
828 $out = '';
829 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
830 $out .= $this->writeUpload( $ver, $dumpContents );
832 $out .= $this->writeUpload( $img, $dumpContents );
833 return $out;
836 return '';
840 * @param File $file
841 * @param bool $dumpContents
842 * @return string
844 function writeUpload( $file, $dumpContents = false ) {
845 if ( $file->isOld() ) {
846 $archiveName = " " .
847 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
848 } else {
849 $archiveName = '';
851 if ( $dumpContents ) {
852 $be = $file->getRepo()->getBackend();
853 # Dump file as base64
854 # Uses only XML-safe characters, so does not need escaping
855 # @todo Too bad this loads the contents into memory (script might swap)
856 $contents = ' <contents encoding="base64">' .
857 chunk_split( base64_encode(
858 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
859 " </contents>\n";
860 } else {
861 $contents = '';
863 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
864 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
865 } else {
866 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
868 return " <upload>\n" .
869 $this->writeTimestamp( $file->getTimestamp() ) .
870 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
871 " " . $comment . "\n" .
872 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
873 $archiveName .
874 " " . Xml::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
875 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
876 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
877 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
878 $contents .
879 " </upload>\n";
883 * Return prefixed text form of title, but using the content language's
884 * canonical namespace. This skips any special-casing such as gendered
885 * user namespaces -- which while useful, are not yet listed in the
886 * XML "<siteinfo>" data so are unsafe in export.
888 * @param Title $title
889 * @return string
890 * @since 1.18
892 public static function canonicalTitle( Title $title ) {
893 if ( $title->isExternal() ) {
894 return $title->getPrefixedText();
897 global $wgContLang;
898 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
900 if ( $prefix !== '' ) {
901 $prefix .= ':';
904 return $prefix . $title->getText();
909 * Base class for output stream; prints to stdout or buffer or wherever.
910 * @ingroup Dump
912 class DumpOutput {
915 * @param string $string
917 function writeOpenStream( $string ) {
918 $this->write( $string );
922 * @param string $string
924 function writeCloseStream( $string ) {
925 $this->write( $string );
929 * @param object $page
930 * @param string $string
932 function writeOpenPage( $page, $string ) {
933 $this->write( $string );
937 * @param string $string
939 function writeClosePage( $string ) {
940 $this->write( $string );
944 * @param object $rev
945 * @param string $string
947 function writeRevision( $rev, $string ) {
948 $this->write( $string );
952 * @param object $rev
953 * @param string $string
955 function writeLogItem( $rev, $string ) {
956 $this->write( $string );
960 * Override to write to a different stream type.
961 * @param string $string
962 * @return bool
964 function write( $string ) {
965 print $string;
969 * Close the old file, move it to a specified name,
970 * and reopen new file with the old name. Use this
971 * for writing out a file in multiple pieces
972 * at specified checkpoints (e.g. every n hours).
973 * @param string|array $newname File name. May be a string or an array with one element
975 function closeRenameAndReopen( $newname ) {
979 * Close the old file, and move it to a specified name.
980 * Use this for the last piece of a file written out
981 * at specified checkpoints (e.g. every n hours).
982 * @param string|array $newname File name. May be a string or an array with one element
983 * @param bool $open If true, a new file with the old filename will be opened
984 * again for writing (default: false)
986 function closeAndRename( $newname, $open = false ) {
990 * Returns the name of the file or files which are
991 * being written to, if there are any.
992 * @return null
994 function getFilenames() {
995 return null;
1000 * Stream outputter to send data to a file.
1001 * @ingroup Dump
1003 class DumpFileOutput extends DumpOutput {
1004 protected $handle = false, $filename;
1007 * @param string $file
1009 function __construct( $file ) {
1010 $this->handle = fopen( $file, "wt" );
1011 $this->filename = $file;
1015 * @param string $string
1017 function writeCloseStream( $string ) {
1018 parent::writeCloseStream( $string );
1019 if ( $this->handle ) {
1020 fclose( $this->handle );
1021 $this->handle = false;
1026 * @param string $string
1028 function write( $string ) {
1029 fputs( $this->handle, $string );
1033 * @param string $newname
1035 function closeRenameAndReopen( $newname ) {
1036 $this->closeAndRename( $newname, true );
1040 * @param string $newname
1041 * @throws MWException
1043 function renameOrException( $newname ) {
1044 if ( !rename( $this->filename, $newname ) ) {
1045 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
1050 * @param array $newname
1051 * @return string
1052 * @throws MWException
1054 function checkRenameArgCount( $newname ) {
1055 if ( is_array( $newname ) ) {
1056 if ( count( $newname ) > 1 ) {
1057 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
1058 } else {
1059 $newname = $newname[0];
1062 return $newname;
1066 * @param string $newname
1067 * @param bool $open
1069 function closeAndRename( $newname, $open = false ) {
1070 $newname = $this->checkRenameArgCount( $newname );
1071 if ( $newname ) {
1072 if ( $this->handle ) {
1073 fclose( $this->handle );
1074 $this->handle = false;
1076 $this->renameOrException( $newname );
1077 if ( $open ) {
1078 $this->handle = fopen( $this->filename, "wt" );
1084 * @return string|null
1086 function getFilenames() {
1087 return $this->filename;
1092 * Stream outputter to send data to a file via some filter program.
1093 * Even if compression is available in a library, using a separate
1094 * program can allow us to make use of a multi-processor system.
1095 * @ingroup Dump
1097 class DumpPipeOutput extends DumpFileOutput {
1098 protected $command, $filename;
1099 protected $procOpenResource = false;
1102 * @param string $command
1103 * @param string $file
1105 function __construct( $command, $file = null ) {
1106 if ( !is_null( $file ) ) {
1107 $command .= " > " . wfEscapeShellArg( $file );
1110 $this->startCommand( $command );
1111 $this->command = $command;
1112 $this->filename = $file;
1116 * @param string $string
1118 function writeCloseStream( $string ) {
1119 parent::writeCloseStream( $string );
1120 if ( $this->procOpenResource ) {
1121 proc_close( $this->procOpenResource );
1122 $this->procOpenResource = false;
1127 * @param string $command
1129 function startCommand( $command ) {
1130 $spec = array(
1131 0 => array( "pipe", "r" ),
1133 $pipes = array();
1134 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1135 $this->handle = $pipes[0];
1139 * @param string $newname
1141 function closeRenameAndReopen( $newname ) {
1142 $this->closeAndRename( $newname, true );
1146 * @param string $newname
1147 * @param bool $open
1149 function closeAndRename( $newname, $open = false ) {
1150 $newname = $this->checkRenameArgCount( $newname );
1151 if ( $newname ) {
1152 if ( $this->handle ) {
1153 fclose( $this->handle );
1154 $this->handle = false;
1156 if ( $this->procOpenResource ) {
1157 proc_close( $this->procOpenResource );
1158 $this->procOpenResource = false;
1160 $this->renameOrException( $newname );
1161 if ( $open ) {
1162 $command = $this->command;
1163 $command .= " > " . wfEscapeShellArg( $this->filename );
1164 $this->startCommand( $command );
1171 * Sends dump output via the gzip compressor.
1172 * @ingroup Dump
1174 class DumpGZipOutput extends DumpPipeOutput {
1176 * @param string $file
1178 function __construct( $file ) {
1179 parent::__construct( "gzip", $file );
1184 * Sends dump output via the bgzip2 compressor.
1185 * @ingroup Dump
1187 class DumpBZip2Output extends DumpPipeOutput {
1189 * @param string $file
1191 function __construct( $file ) {
1192 parent::__construct( "bzip2", $file );
1197 * Sends dump output via the p7zip compressor.
1198 * @ingroup Dump
1200 class Dump7ZipOutput extends DumpPipeOutput {
1202 * @param string $file
1204 function __construct( $file ) {
1205 $command = $this->setup7zCommand( $file );
1206 parent::__construct( $command );
1207 $this->filename = $file;
1211 * @param string $file
1212 * @return string
1214 function setup7zCommand( $file ) {
1215 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1216 // Suppress annoying useless crap from p7zip
1217 // Unfortunately this could suppress real error messages too
1218 $command .= ' >' . wfGetNull() . ' 2>&1';
1219 return $command;
1223 * @param string $newname
1224 * @param bool $open
1226 function closeAndRename( $newname, $open = false ) {
1227 $newname = $this->checkRenameArgCount( $newname );
1228 if ( $newname ) {
1229 fclose( $this->handle );
1230 proc_close( $this->procOpenResource );
1231 $this->renameOrException( $newname );
1232 if ( $open ) {
1233 $command = $this->setup7zCommand( $this->filename );
1234 $this->startCommand( $command );
1241 * Dump output filter class.
1242 * This just does output filtering and streaming; XML formatting is done
1243 * higher up, so be careful in what you do.
1244 * @ingroup Dump
1246 class DumpFilter {
1248 * @var DumpOutput
1249 * FIXME will need to be made protected whenever legacy code
1250 * is updated.
1252 public $sink;
1255 * @var bool
1257 protected $sendingThisPage;
1260 * @param DumpOutput $sink
1262 function __construct( &$sink ) {
1263 $this->sink =& $sink;
1267 * @param string $string
1269 function writeOpenStream( $string ) {
1270 $this->sink->writeOpenStream( $string );
1274 * @param string $string
1276 function writeCloseStream( $string ) {
1277 $this->sink->writeCloseStream( $string );
1281 * @param object $page
1282 * @param string $string
1284 function writeOpenPage( $page, $string ) {
1285 $this->sendingThisPage = $this->pass( $page, $string );
1286 if ( $this->sendingThisPage ) {
1287 $this->sink->writeOpenPage( $page, $string );
1292 * @param string $string
1294 function writeClosePage( $string ) {
1295 if ( $this->sendingThisPage ) {
1296 $this->sink->writeClosePage( $string );
1297 $this->sendingThisPage = false;
1302 * @param object $rev
1303 * @param string $string
1305 function writeRevision( $rev, $string ) {
1306 if ( $this->sendingThisPage ) {
1307 $this->sink->writeRevision( $rev, $string );
1312 * @param object $rev
1313 * @param string $string
1315 function writeLogItem( $rev, $string ) {
1316 $this->sink->writeRevision( $rev, $string );
1320 * @param string $newname
1322 function closeRenameAndReopen( $newname ) {
1323 $this->sink->closeRenameAndReopen( $newname );
1327 * @param string $newname
1328 * @param bool $open
1330 function closeAndRename( $newname, $open = false ) {
1331 $this->sink->closeAndRename( $newname, $open );
1335 * @return array
1337 function getFilenames() {
1338 return $this->sink->getFilenames();
1342 * Override for page-based filter types.
1343 * @param object $page
1344 * @return bool
1346 function pass( $page ) {
1347 return true;
1352 * Simple dump output filter to exclude all talk pages.
1353 * @ingroup Dump
1355 class DumpNotalkFilter extends DumpFilter {
1357 * @param object $page
1358 * @return bool
1360 function pass( $page ) {
1361 return !MWNamespace::isTalk( $page->page_namespace );
1366 * Dump output filter to include or exclude pages in a given set of namespaces.
1367 * @ingroup Dump
1369 class DumpNamespaceFilter extends DumpFilter {
1370 /** @var bool */
1371 public $invert = false;
1373 /** @var array */
1374 public $namespaces = array();
1377 * @param DumpOutput $sink
1378 * @param array $param
1379 * @throws MWException
1381 function __construct( &$sink, $param ) {
1382 parent::__construct( $sink );
1384 $constants = array(
1385 "NS_MAIN" => NS_MAIN,
1386 "NS_TALK" => NS_TALK,
1387 "NS_USER" => NS_USER,
1388 "NS_USER_TALK" => NS_USER_TALK,
1389 "NS_PROJECT" => NS_PROJECT,
1390 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1391 "NS_FILE" => NS_FILE,
1392 "NS_FILE_TALK" => NS_FILE_TALK,
1393 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1394 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1395 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1396 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1397 "NS_TEMPLATE" => NS_TEMPLATE,
1398 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1399 "NS_HELP" => NS_HELP,
1400 "NS_HELP_TALK" => NS_HELP_TALK,
1401 "NS_CATEGORY" => NS_CATEGORY,
1402 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1404 if ( $param { 0 } == '!' ) {
1405 $this->invert = true;
1406 $param = substr( $param, 1 );
1409 foreach ( explode( ',', $param ) as $key ) {
1410 $key = trim( $key );
1411 if ( isset( $constants[$key] ) ) {
1412 $ns = $constants[$key];
1413 $this->namespaces[$ns] = true;
1414 } elseif ( is_numeric( $key ) ) {
1415 $ns = intval( $key );
1416 $this->namespaces[$ns] = true;
1417 } else {
1418 throw new MWException( "Unrecognized namespace key '$key'\n" );
1424 * @param object $page
1425 * @return bool
1427 function pass( $page ) {
1428 $match = isset( $this->namespaces[$page->page_namespace] );
1429 return $this->invert xor $match;
1434 * Dump output filter to include only the last revision in each page sequence.
1435 * @ingroup Dump
1437 class DumpLatestFilter extends DumpFilter {
1438 public $page;
1440 public $pageString;
1442 public $rev;
1444 public $revString;
1447 * @param object $page
1448 * @param string $string
1450 function writeOpenPage( $page, $string ) {
1451 $this->page = $page;
1452 $this->pageString = $string;
1456 * @param string $string
1458 function writeClosePage( $string ) {
1459 if ( $this->rev ) {
1460 $this->sink->writeOpenPage( $this->page, $this->pageString );
1461 $this->sink->writeRevision( $this->rev, $this->revString );
1462 $this->sink->writeClosePage( $string );
1464 $this->rev = null;
1465 $this->revString = null;
1466 $this->page = null;
1467 $this->pageString = null;
1471 * @param object $rev
1472 * @param string $string
1474 function writeRevision( $rev, $string ) {
1475 if ( $rev->rev_id == $this->page->page_latest ) {
1476 $this->rev = $rev;
1477 $this->revString = $string;
1483 * Base class for output stream; prints to stdout or buffer or wherever.
1484 * @ingroup Dump
1486 class DumpMultiWriter {
1489 * @param array $sinks
1491 function __construct( $sinks ) {
1492 $this->sinks = $sinks;
1493 $this->count = count( $sinks );
1497 * @param string $string
1499 function writeOpenStream( $string ) {
1500 for ( $i = 0; $i < $this->count; $i++ ) {
1501 $this->sinks[$i]->writeOpenStream( $string );
1506 * @param string $string
1508 function writeCloseStream( $string ) {
1509 for ( $i = 0; $i < $this->count; $i++ ) {
1510 $this->sinks[$i]->writeCloseStream( $string );
1515 * @param object $page
1516 * @param string $string
1518 function writeOpenPage( $page, $string ) {
1519 for ( $i = 0; $i < $this->count; $i++ ) {
1520 $this->sinks[$i]->writeOpenPage( $page, $string );
1525 * @param string $string
1527 function writeClosePage( $string ) {
1528 for ( $i = 0; $i < $this->count; $i++ ) {
1529 $this->sinks[$i]->writeClosePage( $string );
1534 * @param object $rev
1535 * @param string $string
1537 function writeRevision( $rev, $string ) {
1538 for ( $i = 0; $i < $this->count; $i++ ) {
1539 $this->sinks[$i]->writeRevision( $rev, $string );
1544 * @param array $newnames
1546 function closeRenameAndReopen( $newnames ) {
1547 $this->closeAndRename( $newnames, true );
1551 * @param array $newnames
1552 * @param bool $open
1554 function closeAndRename( $newnames, $open = false ) {
1555 for ( $i = 0; $i < $this->count; $i++ ) {
1556 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1561 * @return array
1563 function getFilenames() {
1564 $filenames = array();
1565 for ( $i = 0; $i < $this->count; $i++ ) {
1566 $filenames[] = $this->sinks[$i]->getFilenames();
1568 return $filenames;