Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Export.php
blob98de4c001b6f5536de3ee4c7cd01db3259890054
1 <?php
2 /**
3 * Base classes for dumps and export
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * http://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 $list_authors = false; # Return distinct author list (when not returning full history)
35 var $author_list = "";
37 var $dumpUploads = false;
38 var $dumpUploadFileContents = false;
40 const FULL = 1;
41 const CURRENT = 2;
42 const STABLE = 4; // extension defined
43 const LOGS = 8;
44 const RANGE = 16;
46 const BUFFER = 0;
47 const STREAM = 1;
49 const TEXT = 0;
50 const STUB = 1;
52 var $buffer;
54 var $text;
56 /**
57 * @var DumpOutput
59 var $sink;
61 /**
62 * Returns the export schema version.
63 * @return string
65 public static function schemaVersion() {
66 return "0.8";
69 /**
70 * If using WikiExporter::STREAM to stream a large amount of data,
71 * provide a database connection which is not managed by
72 * LoadBalancer to read from: some history blob types will
73 * make additional queries to pull source data while the
74 * main query is still running.
76 * @param $db DatabaseBase
77 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
78 * WikiExporter::RANGE or WikiExporter::STABLE,
79 * or an associative array:
80 * offset: non-inclusive offset at which to start the query
81 * limit: maximum number of rows to return
82 * dir: "asc" or "desc" timestamp order
83 * @param int $buffer one of WikiExporter::BUFFER or WikiExporter::STREAM
84 * @param int $text one of WikiExporter::TEXT or WikiExporter::STUB
86 function __construct( $db, $history = WikiExporter::CURRENT,
87 $buffer = WikiExporter::BUFFER, $text = WikiExporter::TEXT ) {
88 $this->db = $db;
89 $this->history = $history;
90 $this->buffer = $buffer;
91 $this->writer = new XmlDumpWriter();
92 $this->sink = new DumpOutput();
93 $this->text = $text;
96 /**
97 * Set the DumpOutput or DumpFilter object which will receive
98 * various row objects and XML output for filtering. Filters
99 * can be chained or used as callbacks.
101 * @param $sink mixed
103 public function setOutputSink( &$sink ) {
104 $this->sink =& $sink;
107 public function openStream() {
108 $output = $this->writer->openStream();
109 $this->sink->writeOpenStream( $output );
112 public function closeStream() {
113 $output = $this->writer->closeStream();
114 $this->sink->writeCloseStream( $output );
118 * Dumps a series of page and revision records for all pages
119 * in the database, either including complete history or only
120 * the most recent version.
122 public function allPages() {
123 $this->dumpFrom( '' );
127 * Dumps a series of page and revision records for those pages
128 * in the database falling within the page_id range given.
129 * @param int $start inclusive lower limit (this id is included)
130 * @param $end Int: Exclusive upper limit (this id is not included)
131 * If 0, no upper limit.
133 public function pagesByRange( $start, $end ) {
134 $condition = 'page_id >= ' . intval( $start );
135 if ( $end ) {
136 $condition .= ' AND page_id < ' . intval( $end );
138 $this->dumpFrom( $condition );
142 * Dumps a series of page and revision records for those pages
143 * in the database with revisions falling within the rev_id range given.
144 * @param int $start inclusive lower limit (this id is included)
145 * @param $end Int: Exclusive upper limit (this id is not included)
146 * If 0, no upper limit.
148 public function revsByRange( $start, $end ) {
149 $condition = 'rev_id >= ' . intval( $start );
150 if ( $end ) {
151 $condition .= ' AND rev_id < ' . intval( $end );
153 $this->dumpFrom( $condition );
157 * @param $title Title
159 public function pageByTitle( $title ) {
160 $this->dumpFrom(
161 'page_namespace=' . $title->getNamespace() .
162 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
166 * @param $name string
167 * @throws MWException
169 public function pageByName( $name ) {
170 $title = Title::newFromText( $name );
171 if ( is_null( $title ) ) {
172 throw new MWException( "Can't export invalid title" );
173 } else {
174 $this->pageByTitle( $title );
179 * @param $names array
181 public function pagesByName( $names ) {
182 foreach ( $names as $name ) {
183 $this->pageByName( $name );
187 public function allLogs() {
188 $this->dumpFrom( '' );
192 * @param $start int
193 * @param $end int
195 public function logsByRange( $start, $end ) {
196 $condition = 'log_id >= ' . intval( $start );
197 if ( $end ) {
198 $condition .= ' AND log_id < ' . intval( $end );
200 $this->dumpFrom( $condition );
204 * Generates the distinct list of authors of an article
205 * Not called by default (depends on $this->list_authors)
206 * Can be set by Special:Export when not exporting whole history
208 * @param $cond
210 protected function do_list_authors( $cond ) {
211 wfProfileIn( __METHOD__ );
212 $this->author_list = "<contributors>";
213 // rev_deleted
215 $res = $this->db->select(
216 array( 'page', 'revision' ),
217 array( 'DISTINCT rev_user_text', 'rev_user' ),
218 array(
219 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
220 $cond,
221 'page_id = rev_id',
223 __METHOD__
226 foreach ( $res as $row ) {
227 $this->author_list .= "<contributor>" .
228 "<username>" .
229 htmlentities( $row->rev_user_text ) .
230 "</username>" .
231 "<id>" .
232 $row->rev_user .
233 "</id>" .
234 "</contributor>";
236 $this->author_list .= "</contributors>";
237 wfProfileOut( __METHOD__ );
241 * @param $cond string
242 * @throws MWException
243 * @throws Exception
245 protected function dumpFrom( $cond = '' ) {
246 wfProfileIn( __METHOD__ );
247 # For logging dumps...
248 if ( $this->history & self::LOGS ) {
249 $where = array( 'user_id = log_user' );
250 # Hide private logs
251 $hideLogs = LogEventsList::getExcludeClause( $this->db );
252 if ( $hideLogs ) {
253 $where[] = $hideLogs;
255 # Add on any caller specified conditions
256 if ( $cond ) {
257 $where[] = $cond;
259 # Get logging table name for logging.* clause
260 $logging = $this->db->tableName( 'logging' );
262 if ( $this->buffer == WikiExporter::STREAM ) {
263 $prev = $this->db->bufferResults( false );
265 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
266 try {
267 $result = $this->db->select( array( 'logging', 'user' ),
268 array( "{$logging}.*", 'user_name' ), // grab the user name
269 $where,
270 __METHOD__,
271 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
273 $wrapper = $this->db->resultObject( $result );
274 $this->outputLogStream( $wrapper );
275 if ( $this->buffer == WikiExporter::STREAM ) {
276 $this->db->bufferResults( $prev );
278 } catch ( Exception $e ) {
279 // Throwing the exception does not reliably free the resultset, and
280 // would also leave the connection in unbuffered mode.
282 // Freeing result
283 try {
284 if ( $wrapper ) {
285 $wrapper->free();
287 } catch ( Exception $e2 ) {
288 // Already in panic mode -> ignoring $e2 as $e has
289 // higher priority
292 // Putting database back in previous buffer mode
293 try {
294 if ( $this->buffer == WikiExporter::STREAM ) {
295 $this->db->bufferResults( $prev );
297 } catch ( Exception $e2 ) {
298 // Already in panic mode -> ignoring $e2 as $e has
299 // higher priority
302 // Inform caller about problem
303 wfProfileOut( __METHOD__ );
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 ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
348 wfProfileOut( __METHOD__ );
349 throw new MWException( __METHOD__ . " given invalid history dump type." );
351 } elseif ( $this->history & WikiExporter::RANGE ) {
352 # Dump of revisions within a specified range
353 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
354 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
355 } else {
356 # Unknown history specification parameter?
357 wfProfileOut( __METHOD__ );
358 throw new MWException( __METHOD__ . " given invalid history dump type." );
360 # Query optimization hacks
361 if ( $cond == '' ) {
362 $opts[] = 'STRAIGHT_JOIN';
363 $opts['USE INDEX']['page'] = 'PRIMARY';
365 # Build text join options
366 if ( $this->text != WikiExporter::STUB ) { // 1-pass
367 $tables[] = 'text';
368 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
371 if ( $this->buffer == WikiExporter::STREAM ) {
372 $prev = $this->db->bufferResults( false );
375 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
376 try {
377 wfRunHooks( 'ModifyExportQuery',
378 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
380 # Do the query!
381 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
382 $wrapper = $this->db->resultObject( $result );
383 # Output dump results
384 $this->outputPageStream( $wrapper );
386 if ( $this->buffer == WikiExporter::STREAM ) {
387 $this->db->bufferResults( $prev );
389 } catch ( Exception $e ) {
390 // Throwing the exception does not reliably free the resultset, and
391 // would also leave the connection in unbuffered mode.
393 // Freeing result
394 try {
395 if ( $wrapper ) {
396 $wrapper->free();
398 } catch ( Exception $e2 ) {
399 // Already in panic mode -> ignoring $e2 as $e has
400 // higher priority
403 // Putting database back in previous buffer mode
404 try {
405 if ( $this->buffer == WikiExporter::STREAM ) {
406 $this->db->bufferResults( $prev );
408 } catch ( Exception $e2 ) {
409 // Already in panic mode -> ignoring $e2 as $e has
410 // higher priority
413 // Inform caller about problem
414 throw $e;
417 wfProfileOut( __METHOD__ );
421 * Runs through a query result set dumping page and revision records.
422 * The result set should be sorted/grouped by page to avoid duplicate
423 * page records in the output.
425 * Should be safe for
426 * streaming (non-buffered) queries, as long as it was made on a
427 * separate database connection not managed by LoadBalancer; some
428 * blob storage types will make queries to pull source data.
430 * @param $resultset ResultWrapper
432 protected function outputPageStream( $resultset ) {
433 $last = null;
434 foreach ( $resultset as $row ) {
435 if ( $last === null ||
436 $last->page_namespace != $row->page_namespace ||
437 $last->page_title != $row->page_title ) {
438 if ( $last !== null ) {
439 $output = '';
440 if ( $this->dumpUploads ) {
441 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
443 $output .= $this->writer->closePage();
444 $this->sink->writeClosePage( $output );
446 $output = $this->writer->openPage( $row );
447 $this->sink->writeOpenPage( $row, $output );
448 $last = $row;
450 $output = $this->writer->writeRevision( $row );
451 $this->sink->writeRevision( $row, $output );
453 if ( $last !== null ) {
454 $output = '';
455 if ( $this->dumpUploads ) {
456 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
458 $output .= $this->author_list;
459 $output .= $this->writer->closePage();
460 $this->sink->writeClosePage( $output );
465 * @param $resultset array
467 protected function outputLogStream( $resultset ) {
468 foreach ( $resultset as $row ) {
469 $output = $this->writer->writeLogItem( $row );
470 $this->sink->writeLogItem( $row, $output );
476 * @ingroup Dump
478 class XmlDumpWriter {
480 * Returns the export schema version.
481 * @deprecated in 1.20; use WikiExporter::schemaVersion() instead
482 * @return string
484 function schemaVersion() {
485 wfDeprecated( __METHOD__, '1.20' );
486 return WikiExporter::schemaVersion();
490 * Opens the XML output stream's root "<mediawiki>" element.
491 * This does not include an xml directive, so is safe to include
492 * as a subelement in a larger XML stream. Namespace and XML Schema
493 * references are included.
495 * Output will be encoded in UTF-8.
497 * @return string
499 function openStream() {
500 global $wgLanguageCode;
501 $ver = WikiExporter::schemaVersion();
502 return Xml::element( 'mediawiki', array(
503 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
504 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
505 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
506 "http://www.mediawiki.org/xml/export-$ver.xsd", #TODO: how do we get a new version up there?
507 'version' => $ver,
508 'xml:lang' => $wgLanguageCode ),
509 null ) .
510 "\n" .
511 $this->siteInfo();
515 * @return string
517 function siteInfo() {
518 $info = array(
519 $this->sitename(),
520 $this->homelink(),
521 $this->generator(),
522 $this->caseSetting(),
523 $this->namespaces() );
524 return " <siteinfo>\n " .
525 implode( "\n ", $info ) .
526 "\n </siteinfo>\n";
530 * @return string
532 function sitename() {
533 global $wgSitename;
534 return Xml::element( 'sitename', array(), $wgSitename );
538 * @return string
540 function generator() {
541 global $wgVersion;
542 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
546 * @return string
548 function homelink() {
549 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalURL() );
553 * @return string
555 function caseSetting() {
556 global $wgCapitalLinks;
557 // "case-insensitive" option is reserved for future
558 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
559 return Xml::element( 'case', array(), $sensitivity );
563 * @return string
565 function namespaces() {
566 global $wgContLang;
567 $spaces = "<namespaces>\n";
568 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
569 $spaces .= ' ' .
570 Xml::element( 'namespace',
571 array(
572 'key' => $ns,
573 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
574 ), $title ) . "\n";
576 $spaces .= " </namespaces>";
577 return $spaces;
581 * Closes the output stream with the closing root element.
582 * Call when finished dumping things.
584 * @return string
586 function closeStream() {
587 return "</mediawiki>\n";
591 * Opens a "<page>" section on the output stream, with data
592 * from the given database row.
594 * @param $row object
595 * @return string
596 * @access private
598 function openPage( $row ) {
599 $out = " <page>\n";
600 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
601 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
602 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace ) ) . "\n";
603 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
604 if ( $row->page_is_redirect ) {
605 $page = WikiPage::factory( $title );
606 $redirect = $page->getRedirectTarget();
607 if ( $redirect instanceOf Title && $redirect->isValidRedirectTarget() ) {
608 $out .= ' ' . Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) ) . "\n";
612 if ( $row->page_restrictions != '' ) {
613 $out .= ' ' . Xml::element( 'restrictions', array(),
614 strval( $row->page_restrictions ) ) . "\n";
617 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
619 return $out;
623 * Closes a "<page>" section on the output stream.
625 * @access private
626 * @return string
628 function closePage() {
629 return " </page>\n";
633 * Dumps a "<revision>" section on the output stream, with
634 * data filled in from the given database row.
636 * @param $row object
637 * @return string
638 * @access private
640 function writeRevision( $row ) {
641 wfProfileIn( __METHOD__ );
643 $out = " <revision>\n";
644 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
645 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
646 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
649 $out .= $this->writeTimestamp( $row->rev_timestamp );
651 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
652 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
653 } else {
654 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
657 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
658 $out .= " <minor/>\n";
660 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
661 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
662 } elseif ( $row->rev_comment != '' ) {
663 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
666 $text = '';
667 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
668 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
669 } elseif ( isset( $row->old_text ) ) {
670 // Raw text from the database may have invalid chars
671 $text = strval( Revision::getRevisionText( $row ) );
672 $out .= " " . Xml::elementClean( 'text',
673 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
674 strval( $text ) ) . "\n";
675 } else {
676 // Stub output
677 $out .= " " . Xml::element( 'text',
678 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
679 "" ) . "\n";
682 if ( isset( $row->rev_sha1 ) && $row->rev_sha1 && !( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
683 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
684 } else {
685 $out .= " <sha1/>\n";
688 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
689 $content_model = strval( $row->rev_content_model );
690 } else {
691 // probably using $wgContentHandlerUseDB = false;
692 // @todo test!
693 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
694 $content_model = ContentHandler::getDefaultModelFor( $title );
697 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
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 // @todo test!
704 $content_handler = ContentHandler::getForModelID( $content_model );
705 $content_format = $content_handler->getDefaultFormat();
708 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
710 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
712 $out .= " </revision>\n";
714 wfProfileOut( __METHOD__ );
715 return $out;
719 * Dumps a "<logitem>" section on the output stream, with
720 * data filled in from the given database row.
722 * @param $row object
723 * @return string
724 * @access private
726 function writeLogItem( $row ) {
727 wfProfileIn( __METHOD__ );
729 $out = " <logitem>\n";
730 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
732 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
734 if ( $row->log_deleted & LogPage::DELETED_USER ) {
735 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
736 } else {
737 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
740 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
741 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
742 } elseif ( $row->log_comment != '' ) {
743 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
746 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
747 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
749 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
750 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
751 } else {
752 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
753 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
754 $out .= " " . Xml::elementClean( 'params',
755 array( 'xml:space' => 'preserve' ),
756 strval( $row->log_params ) ) . "\n";
759 $out .= " </logitem>\n";
761 wfProfileOut( __METHOD__ );
762 return $out;
766 * @param $timestamp string
767 * @param string $indent Default to six spaces
768 * @return string
770 function writeTimestamp( $timestamp, $indent = " " ) {
771 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
772 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
776 * @param $id
777 * @param $text string
778 * @param string $indent Default to six spaces
779 * @return string
781 function writeContributor( $id, $text, $indent = " " ) {
782 $out = $indent . "<contributor>\n";
783 if ( $id || !IP::isValid( $text ) ) {
784 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
785 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
786 } else {
787 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
789 $out .= $indent . "</contributor>\n";
790 return $out;
794 * Warning! This data is potentially inconsistent. :(
795 * @param $row
796 * @param $dumpContents bool
797 * @return string
799 function writeUploads( $row, $dumpContents = false ) {
800 if ( $row->page_namespace == NS_FILE ) {
801 $img = wfLocalFile( $row->page_title );
802 if ( $img && $img->exists() ) {
803 $out = '';
804 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
805 $out .= $this->writeUpload( $ver, $dumpContents );
807 $out .= $this->writeUpload( $img, $dumpContents );
808 return $out;
811 return '';
815 * @param $file File
816 * @param $dumpContents bool
817 * @return string
819 function writeUpload( $file, $dumpContents = false ) {
820 if ( $file->isOld() ) {
821 $archiveName = " " .
822 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
823 } else {
824 $archiveName = '';
826 if ( $dumpContents ) {
827 $be = $file->getRepo()->getBackend();
828 # Dump file as base64
829 # Uses only XML-safe characters, so does not need escaping
830 # @TODO: too bad this loads the contents into memory (script might swap)
831 $contents = ' <contents encoding="base64">' .
832 chunk_split( base64_encode(
833 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
834 " </contents>\n";
835 } else {
836 $contents = '';
838 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
839 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
840 } else {
841 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
843 return " <upload>\n" .
844 $this->writeTimestamp( $file->getTimestamp() ) .
845 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
846 " " . $comment . "\n" .
847 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
848 $archiveName .
849 " " . Xml::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
850 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
851 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
852 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
853 $contents .
854 " </upload>\n";
858 * Return prefixed text form of title, but using the content language's
859 * canonical namespace. This skips any special-casing such as gendered
860 * user namespaces -- which while useful, are not yet listed in the
861 * XML "<siteinfo>" data so are unsafe in export.
863 * @param Title $title
864 * @return string
865 * @since 1.18
867 public static function canonicalTitle( Title $title ) {
868 if ( $title->getInterwiki() ) {
869 return $title->getPrefixedText();
872 global $wgContLang;
873 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
875 if ( $prefix !== '' ) {
876 $prefix .= ':';
879 return $prefix . $title->getText();
884 * Base class for output stream; prints to stdout or buffer or wherever.
885 * @ingroup Dump
887 class DumpOutput {
890 * @param $string string
892 function writeOpenStream( $string ) {
893 $this->write( $string );
897 * @param $string string
899 function writeCloseStream( $string ) {
900 $this->write( $string );
904 * @param $page
905 * @param $string string
907 function writeOpenPage( $page, $string ) {
908 $this->write( $string );
912 * @param $string string
914 function writeClosePage( $string ) {
915 $this->write( $string );
919 * @param $rev
920 * @param $string string
922 function writeRevision( $rev, $string ) {
923 $this->write( $string );
927 * @param $rev
928 * @param $string string
930 function writeLogItem( $rev, $string ) {
931 $this->write( $string );
935 * Override to write to a different stream type.
936 * @param $string string
937 * @return bool
939 function write( $string ) {
940 print $string;
944 * Close the old file, move it to a specified name,
945 * and reopen new file with the old name. Use this
946 * for writing out a file in multiple pieces
947 * at specified checkpoints (e.g. every n hours).
948 * @param $newname mixed File name. May be a string or an array with one element
950 function closeRenameAndReopen( $newname ) {
954 * Close the old file, and move it to a specified name.
955 * Use this for the last piece of a file written out
956 * at specified checkpoints (e.g. every n hours).
957 * @param $newname mixed File name. May be a string or an array with one element
958 * @param bool $open If true, a new file with the old filename will be opened again for writing (default: false)
960 function closeAndRename( $newname, $open = false ) {
964 * Returns the name of the file or files which are
965 * being written to, if there are any.
966 * @return null
968 function getFilenames() {
969 return null;
974 * Stream outputter to send data to a file.
975 * @ingroup Dump
977 class DumpFileOutput extends DumpOutput {
978 protected $handle = false, $filename;
981 * @param $file
983 function __construct( $file ) {
984 $this->handle = fopen( $file, "wt" );
985 $this->filename = $file;
989 * @param $string string
991 function writeCloseStream( $string ) {
992 parent::writeCloseStream( $string );
993 if ( $this->handle ) {
994 fclose( $this->handle );
995 $this->handle = false;
1000 * @param $string string
1002 function write( $string ) {
1003 fputs( $this->handle, $string );
1007 * @param $newname
1009 function closeRenameAndReopen( $newname ) {
1010 $this->closeAndRename( $newname, true );
1014 * @param $newname
1015 * @throws MWException
1017 function renameOrException( $newname ) {
1018 if ( !rename( $this->filename, $newname ) ) {
1019 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
1024 * @param $newname array
1025 * @return mixed
1026 * @throws MWException
1028 function checkRenameArgCount( $newname ) {
1029 if ( is_array( $newname ) ) {
1030 if ( count( $newname ) > 1 ) {
1031 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
1032 } else {
1033 $newname = $newname[0];
1036 return $newname;
1040 * @param $newname mixed
1041 * @param $open bool
1043 function closeAndRename( $newname, $open = false ) {
1044 $newname = $this->checkRenameArgCount( $newname );
1045 if ( $newname ) {
1046 if ( $this->handle ) {
1047 fclose( $this->handle );
1048 $this->handle = false;
1050 $this->renameOrException( $newname );
1051 if ( $open ) {
1052 $this->handle = fopen( $this->filename, "wt" );
1058 * @return string|null
1060 function getFilenames() {
1061 return $this->filename;
1066 * Stream outputter to send data to a file via some filter program.
1067 * Even if compression is available in a library, using a separate
1068 * program can allow us to make use of a multi-processor system.
1069 * @ingroup Dump
1071 class DumpPipeOutput extends DumpFileOutput {
1072 protected $command, $filename;
1073 protected $procOpenResource = false;
1076 * @param $command
1077 * @param $file null
1079 function __construct( $command, $file = null ) {
1080 if ( !is_null( $file ) ) {
1081 $command .= " > " . wfEscapeShellArg( $file );
1084 $this->startCommand( $command );
1085 $this->command = $command;
1086 $this->filename = $file;
1090 * @param $string string
1092 function writeCloseStream( $string ) {
1093 parent::writeCloseStream( $string );
1094 if ( $this->procOpenResource ) {
1095 proc_close( $this->procOpenResource );
1096 $this->procOpenResource = false;
1101 * @param $command
1103 function startCommand( $command ) {
1104 $spec = array(
1105 0 => array( "pipe", "r" ),
1107 $pipes = array();
1108 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1109 $this->handle = $pipes[0];
1113 * @param mixed $newname
1115 function closeRenameAndReopen( $newname ) {
1116 $this->closeAndRename( $newname, true );
1120 * @param $newname mixed
1121 * @param $open bool
1123 function closeAndRename( $newname, $open = false ) {
1124 $newname = $this->checkRenameArgCount( $newname );
1125 if ( $newname ) {
1126 if ( $this->handle ) {
1127 fclose( $this->handle );
1128 $this->handle = false;
1130 if ( $this->procOpenResource ) {
1131 proc_close( $this->procOpenResource );
1132 $this->procOpenResource = false;
1134 $this->renameOrException( $newname );
1135 if ( $open ) {
1136 $command = $this->command;
1137 $command .= " > " . wfEscapeShellArg( $this->filename );
1138 $this->startCommand( $command );
1146 * Sends dump output via the gzip compressor.
1147 * @ingroup Dump
1149 class DumpGZipOutput extends DumpPipeOutput {
1152 * @param $file string
1154 function __construct( $file ) {
1155 parent::__construct( "gzip", $file );
1160 * Sends dump output via the bgzip2 compressor.
1161 * @ingroup Dump
1163 class DumpBZip2Output extends DumpPipeOutput {
1166 * @param $file string
1168 function __construct( $file ) {
1169 parent::__construct( "bzip2", $file );
1174 * Sends dump output via the p7zip compressor.
1175 * @ingroup Dump
1177 class Dump7ZipOutput extends DumpPipeOutput {
1180 * @param $file string
1182 function __construct( $file ) {
1183 $command = $this->setup7zCommand( $file );
1184 parent::__construct( $command );
1185 $this->filename = $file;
1189 * @param $file string
1190 * @return string
1192 function setup7zCommand( $file ) {
1193 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1194 // Suppress annoying useless crap from p7zip
1195 // Unfortunately this could suppress real error messages too
1196 $command .= ' >' . wfGetNull() . ' 2>&1';
1197 return $command;
1201 * @param $newname string
1202 * @param $open bool
1204 function closeAndRename( $newname, $open = false ) {
1205 $newname = $this->checkRenameArgCount( $newname );
1206 if ( $newname ) {
1207 fclose( $this->handle );
1208 proc_close( $this->procOpenResource );
1209 $this->renameOrException( $newname );
1210 if ( $open ) {
1211 $command = $this->setup7zCommand( $this->filename );
1212 $this->startCommand( $command );
1219 * Dump output filter class.
1220 * This just does output filtering and streaming; XML formatting is done
1221 * higher up, so be careful in what you do.
1222 * @ingroup Dump
1224 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 $sink DumpOutput
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 $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 $rev
1282 * @param $string string
1284 function writeRevision( $rev, $string ) {
1285 if ( $this->sendingThisPage ) {
1286 $this->sink->writeRevision( $rev, $string );
1291 * @param $rev
1292 * @param $string string
1294 function writeLogItem( $rev, $string ) {
1295 $this->sink->writeRevision( $rev, $string );
1299 * @param $newname string
1301 function closeRenameAndReopen( $newname ) {
1302 $this->sink->closeRenameAndReopen( $newname );
1306 * @param $newname string
1307 * @param $open bool
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 $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 {
1337 * @param $page
1338 * @return bool
1340 function pass( $page ) {
1341 return !MWNamespace::isTalk( $page->page_namespace );
1346 * Dump output filter to include or exclude pages in a given set of namespaces.
1347 * @ingroup Dump
1349 class DumpNamespaceFilter extends DumpFilter {
1350 var $invert = false;
1351 var $namespaces = array();
1354 * @param $sink DumpOutput
1355 * @param $param
1356 * @throws MWException
1358 function __construct( &$sink, $param ) {
1359 parent::__construct( $sink );
1361 $constants = array(
1362 "NS_MAIN" => NS_MAIN,
1363 "NS_TALK" => NS_TALK,
1364 "NS_USER" => NS_USER,
1365 "NS_USER_TALK" => NS_USER_TALK,
1366 "NS_PROJECT" => NS_PROJECT,
1367 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1368 "NS_FILE" => NS_FILE,
1369 "NS_FILE_TALK" => NS_FILE_TALK,
1370 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1371 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1372 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1373 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1374 "NS_TEMPLATE" => NS_TEMPLATE,
1375 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1376 "NS_HELP" => NS_HELP,
1377 "NS_HELP_TALK" => NS_HELP_TALK,
1378 "NS_CATEGORY" => NS_CATEGORY,
1379 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1381 if ( $param { 0 } == '!' ) {
1382 $this->invert = true;
1383 $param = substr( $param, 1 );
1386 foreach ( explode( ',', $param ) as $key ) {
1387 $key = trim( $key );
1388 if ( isset( $constants[$key] ) ) {
1389 $ns = $constants[$key];
1390 $this->namespaces[$ns] = true;
1391 } elseif ( is_numeric( $key ) ) {
1392 $ns = intval( $key );
1393 $this->namespaces[$ns] = true;
1394 } else {
1395 throw new MWException( "Unrecognized namespace key '$key'\n" );
1401 * @param $page
1402 * @return bool
1404 function pass( $page ) {
1405 $match = isset( $this->namespaces[$page->page_namespace] );
1406 return $this->invert xor $match;
1411 * Dump output filter to include only the last revision in each page sequence.
1412 * @ingroup Dump
1414 class DumpLatestFilter extends DumpFilter {
1415 var $page, $pageString, $rev, $revString;
1418 * @param $page
1419 * @param $string string
1421 function writeOpenPage( $page, $string ) {
1422 $this->page = $page;
1423 $this->pageString = $string;
1427 * @param $string string
1429 function writeClosePage( $string ) {
1430 if ( $this->rev ) {
1431 $this->sink->writeOpenPage( $this->page, $this->pageString );
1432 $this->sink->writeRevision( $this->rev, $this->revString );
1433 $this->sink->writeClosePage( $string );
1435 $this->rev = null;
1436 $this->revString = null;
1437 $this->page = null;
1438 $this->pageString = null;
1442 * @param $rev
1443 * @param $string string
1445 function writeRevision( $rev, $string ) {
1446 if ( $rev->rev_id == $this->page->page_latest ) {
1447 $this->rev = $rev;
1448 $this->revString = $string;
1454 * Base class for output stream; prints to stdout or buffer or wherever.
1455 * @ingroup Dump
1457 class DumpMultiWriter {
1460 * @param $sinks
1462 function __construct( $sinks ) {
1463 $this->sinks = $sinks;
1464 $this->count = count( $sinks );
1468 * @param $string string
1470 function writeOpenStream( $string ) {
1471 for ( $i = 0; $i < $this->count; $i++ ) {
1472 $this->sinks[$i]->writeOpenStream( $string );
1477 * @param $string string
1479 function writeCloseStream( $string ) {
1480 for ( $i = 0; $i < $this->count; $i++ ) {
1481 $this->sinks[$i]->writeCloseStream( $string );
1486 * @param $page
1487 * @param $string string
1489 function writeOpenPage( $page, $string ) {
1490 for ( $i = 0; $i < $this->count; $i++ ) {
1491 $this->sinks[$i]->writeOpenPage( $page, $string );
1496 * @param $string
1498 function writeClosePage( $string ) {
1499 for ( $i = 0; $i < $this->count; $i++ ) {
1500 $this->sinks[$i]->writeClosePage( $string );
1505 * @param $rev
1506 * @param $string
1508 function writeRevision( $rev, $string ) {
1509 for ( $i = 0; $i < $this->count; $i++ ) {
1510 $this->sinks[$i]->writeRevision( $rev, $string );
1515 * @param $newnames
1517 function closeRenameAndReopen( $newnames ) {
1518 $this->closeAndRename( $newnames, true );
1522 * @param $newnames array
1523 * @param bool $open
1525 function closeAndRename( $newnames, $open = false ) {
1526 for ( $i = 0; $i < $this->count; $i++ ) {
1527 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1532 * @return array
1534 function getFilenames() {
1535 $filenames = array();
1536 for ( $i = 0; $i < $this->count; $i++ ) {
1537 $filenames[] = $this->sinks[$i]->getFilenames();
1539 return $filenames;
1545 * @param $string string
1546 * @return string
1548 function xmlsafe( $string ) {
1549 wfProfileIn( __FUNCTION__ );
1552 * The page may contain old data which has not been properly normalized.
1553 * Invalid UTF-8 sequences or forbidden control characters will make our
1554 * XML output invalid, so be sure to strip them out.
1556 $string = UtfNormal::cleanUp( $string );
1558 $string = htmlspecialchars( $string );
1559 wfProfileOut( __FUNCTION__ );
1560 return $string;