Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / Export.php
blob811d716629db4d6b296658456151bd2573afda95
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 * If using WikiExporter::STREAM to stream a large amount of data,
63 * provide a database connection which is not managed by
64 * LoadBalancer to read from: some history blob types will
65 * make additional queries to pull source data while the
66 * main query is still running.
68 * @param $db DatabaseBase
69 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
70 * WikiExporter::RANGE or WikiExporter::STABLE,
71 * or an associative array:
72 * offset: non-inclusive offset at which to start the query
73 * limit: maximum number of rows to return
74 * dir: "asc" or "desc" timestamp order
75 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
76 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
78 function __construct( &$db, $history = WikiExporter::CURRENT,
79 $buffer = WikiExporter::BUFFER, $text = WikiExporter::TEXT ) {
80 $this->db =& $db;
81 $this->history = $history;
82 $this->buffer = $buffer;
83 $this->writer = new XmlDumpWriter();
84 $this->sink = new DumpOutput();
85 $this->text = $text;
88 /**
89 * Set the DumpOutput or DumpFilter object which will receive
90 * various row objects and XML output for filtering. Filters
91 * can be chained or used as callbacks.
93 * @param $sink mixed
95 public function setOutputSink( &$sink ) {
96 $this->sink =& $sink;
99 public function openStream() {
100 $output = $this->writer->openStream();
101 $this->sink->writeOpenStream( $output );
104 public function closeStream() {
105 $output = $this->writer->closeStream();
106 $this->sink->writeCloseStream( $output );
110 * Dumps a series of page and revision records for all pages
111 * in the database, either including complete history or only
112 * the most recent version.
114 public function allPages() {
115 $this->dumpFrom( '' );
119 * Dumps a series of page and revision records for those pages
120 * in the database falling within the page_id range given.
121 * @param $start Int: inclusive lower limit (this id is included)
122 * @param $end Int: Exclusive upper limit (this id is not included)
123 * If 0, no upper limit.
125 public function pagesByRange( $start, $end ) {
126 $condition = 'page_id >= ' . intval( $start );
127 if ( $end ) {
128 $condition .= ' AND page_id < ' . intval( $end );
130 $this->dumpFrom( $condition );
134 * Dumps a series of page and revision records for those pages
135 * in the database with revisions falling within the rev_id range given.
136 * @param $start Int: inclusive lower limit (this id is included)
137 * @param $end Int: Exclusive upper limit (this id is not included)
138 * If 0, no upper limit.
140 public function revsByRange( $start, $end ) {
141 $condition = 'rev_id >= ' . intval( $start );
142 if ( $end ) {
143 $condition .= ' AND rev_id < ' . intval( $end );
145 $this->dumpFrom( $condition );
149 * @param $title Title
151 public function pageByTitle( $title ) {
152 $this->dumpFrom(
153 'page_namespace=' . $title->getNamespace() .
154 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
158 * @param $name string
159 * @throws MWException
161 public function pageByName( $name ) {
162 $title = Title::newFromText( $name );
163 if ( is_null( $title ) ) {
164 throw new MWException( "Can't export invalid title" );
165 } else {
166 $this->pageByTitle( $title );
171 * @param $names array
173 public function pagesByName( $names ) {
174 foreach ( $names as $name ) {
175 $this->pageByName( $name );
179 public function allLogs() {
180 $this->dumpFrom( '' );
184 * @param $start int
185 * @param $end int
187 public function logsByRange( $start, $end ) {
188 $condition = 'log_id >= ' . intval( $start );
189 if ( $end ) {
190 $condition .= ' AND log_id < ' . intval( $end );
192 $this->dumpFrom( $condition );
196 * Generates the distinct list of authors of an article
197 * Not called by default (depends on $this->list_authors)
198 * Can be set by Special:Export when not exporting whole history
200 * @param $cond
202 protected function do_list_authors( $cond ) {
203 wfProfileIn( __METHOD__ );
204 $this->author_list = "<contributors>";
205 // rev_deleted
207 $res = $this->db->select(
208 array( 'page', 'revision' ),
209 array( 'DISTINCT rev_user_text', 'rev_user' ),
210 array(
211 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
212 $cond,
213 'page_id = rev_id',
215 __METHOD__
218 foreach ( $res as $row ) {
219 $this->author_list .= "<contributor>" .
220 "<username>" .
221 htmlentities( $row->rev_user_text ) .
222 "</username>" .
223 "<id>" .
224 $row->rev_user .
225 "</id>" .
226 "</contributor>";
228 $this->author_list .= "</contributors>";
229 wfProfileOut( __METHOD__ );
233 * @param $cond string
234 * @throws MWException
235 * @throws Exception
237 protected function dumpFrom( $cond = '' ) {
238 wfProfileIn( __METHOD__ );
239 # For logging dumps...
240 if ( $this->history & self::LOGS ) {
241 $where = array( 'user_id = log_user' );
242 # Hide private logs
243 $hideLogs = LogEventsList::getExcludeClause( $this->db );
244 if ( $hideLogs ) $where[] = $hideLogs;
245 # Add on any caller specified conditions
246 if ( $cond ) $where[] = $cond;
247 # Get logging table name for logging.* clause
248 $logging = $this->db->tableName( 'logging' );
250 if ( $this->buffer == WikiExporter::STREAM ) {
251 $prev = $this->db->bufferResults( false );
253 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
254 try {
255 $result = $this->db->select( array( 'logging', 'user' ),
256 array( "{$logging}.*", 'user_name' ), // grab the user name
257 $where,
258 __METHOD__,
259 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
261 $wrapper = $this->db->resultObject( $result );
262 $this->outputLogStream( $wrapper );
263 if ( $this->buffer == WikiExporter::STREAM ) {
264 $this->db->bufferResults( $prev );
266 } catch ( Exception $e ) {
267 // Throwing the exception does not reliably free the resultset, and
268 // would also leave the connection in unbuffered mode.
270 // Freeing result
271 try {
272 if ( $wrapper ) {
273 $wrapper->free();
275 } catch ( Exception $e2 ) {
276 // Already in panic mode -> ignoring $e2 as $e has
277 // higher priority
280 // Putting database back in previous buffer mode
281 try {
282 if ( $this->buffer == WikiExporter::STREAM ) {
283 $this->db->bufferResults( $prev );
285 } catch ( Exception $e2 ) {
286 // Already in panic mode -> ignoring $e2 as $e has
287 // higher priority
290 // Inform caller about problem
291 throw $e;
293 # For page dumps...
294 } else {
295 $tables = array( 'page', 'revision' );
296 $opts = array( 'ORDER BY' => 'page_id ASC' );
297 $opts['USE INDEX'] = array();
298 $join = array();
299 if ( is_array( $this->history ) ) {
300 # Time offset/limit for all pages/history...
301 $revJoin = 'page_id=rev_page';
302 # Set time order
303 if ( $this->history['dir'] == 'asc' ) {
304 $op = '>';
305 $opts['ORDER BY'] = 'rev_timestamp ASC';
306 } else {
307 $op = '<';
308 $opts['ORDER BY'] = 'rev_timestamp DESC';
310 # Set offset
311 if ( !empty( $this->history['offset'] ) ) {
312 $revJoin .= " AND rev_timestamp $op " .
313 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
315 $join['revision'] = array( 'INNER JOIN', $revJoin );
316 # Set query limit
317 if ( !empty( $this->history['limit'] ) ) {
318 $opts['LIMIT'] = intval( $this->history['limit'] );
320 } elseif ( $this->history & WikiExporter::FULL ) {
321 # Full history dumps...
322 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
323 } elseif ( $this->history & WikiExporter::CURRENT ) {
324 # Latest revision dumps...
325 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
326 $this->do_list_authors( $cond );
328 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
329 } elseif ( $this->history & WikiExporter::STABLE ) {
330 # "Stable" revision dumps...
331 # Default JOIN, to be overridden...
332 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
333 # One, and only one hook should set this, and return false
334 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
335 wfProfileOut( __METHOD__ );
336 throw new MWException( __METHOD__ . " given invalid history dump type." );
338 } elseif ( $this->history & WikiExporter::RANGE ) {
339 # Dump of revisions within a specified range
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
341 $opts['ORDER BY'] = 'rev_page ASC, rev_id ASC';
342 } else {
343 # Uknown history specification parameter?
344 wfProfileOut( __METHOD__ );
345 throw new MWException( __METHOD__ . " given invalid history dump type." );
347 # Query optimization hacks
348 if ( $cond == '' ) {
349 $opts[] = 'STRAIGHT_JOIN';
350 $opts['USE INDEX']['page'] = 'PRIMARY';
352 # Build text join options
353 if ( $this->text != WikiExporter::STUB ) { // 1-pass
354 $tables[] = 'text';
355 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
358 if ( $this->buffer == WikiExporter::STREAM ) {
359 $prev = $this->db->bufferResults( false );
362 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
363 try {
364 wfRunHooks( 'ModifyExportQuery',
365 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
367 # Do the query!
368 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
369 $wrapper = $this->db->resultObject( $result );
370 # Output dump results
371 $this->outputPageStream( $wrapper );
373 if ( $this->buffer == WikiExporter::STREAM ) {
374 $this->db->bufferResults( $prev );
376 } catch ( Exception $e ) {
377 // Throwing the exception does not reliably free the resultset, and
378 // would also leave the connection in unbuffered mode.
380 // Freeing result
381 try {
382 if ( $wrapper ) {
383 $wrapper->free();
385 } catch ( Exception $e2 ) {
386 // Already in panic mode -> ignoring $e2 as $e has
387 // higher priority
390 // Putting database back in previous buffer mode
391 try {
392 if ( $this->buffer == WikiExporter::STREAM ) {
393 $this->db->bufferResults( $prev );
395 } catch ( Exception $e2 ) {
396 // Already in panic mode -> ignoring $e2 as $e has
397 // higher priority
400 // Inform caller about problem
401 throw $e;
404 wfProfileOut( __METHOD__ );
408 * Runs through a query result set dumping page and revision records.
409 * The result set should be sorted/grouped by page to avoid duplicate
410 * page records in the output.
412 * Should be safe for
413 * streaming (non-buffered) queries, as long as it was made on a
414 * separate database connection not managed by LoadBalancer; some
415 * blob storage types will make queries to pull source data.
417 * @param $resultset ResultWrapper
419 protected function outputPageStream( $resultset ) {
420 $last = null;
421 foreach ( $resultset as $row ) {
422 if ( is_null( $last ) ||
423 $last->page_namespace != $row->page_namespace ||
424 $last->page_title != $row->page_title ) {
425 if ( isset( $last ) ) {
426 $output = '';
427 if ( $this->dumpUploads ) {
428 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
430 $output .= $this->writer->closePage();
431 $this->sink->writeClosePage( $output );
433 $output = $this->writer->openPage( $row );
434 $this->sink->writeOpenPage( $row, $output );
435 $last = $row;
437 $output = $this->writer->writeRevision( $row );
438 $this->sink->writeRevision( $row, $output );
440 if ( isset( $last ) ) {
441 $output = '';
442 if ( $this->dumpUploads ) {
443 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
445 $output .= $this->author_list;
446 $output .= $this->writer->closePage();
447 $this->sink->writeClosePage( $output );
452 * @param $resultset array
454 protected function outputLogStream( $resultset ) {
455 foreach ( $resultset as $row ) {
456 $output = $this->writer->writeLogItem( $row );
457 $this->sink->writeLogItem( $row, $output );
463 * @ingroup Dump
465 class XmlDumpWriter {
467 * Returns the export schema version.
468 * @return string
470 function schemaVersion() {
471 return "0.6";
475 * Opens the XML output stream's root <mediawiki> element.
476 * This does not include an xml directive, so is safe to include
477 * as a subelement in a larger XML stream. Namespace and XML Schema
478 * references are included.
480 * Output will be encoded in UTF-8.
482 * @return string
484 function openStream() {
485 global $wgLanguageCode;
486 $ver = $this->schemaVersion();
487 return Xml::element( 'mediawiki', array(
488 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
489 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
490 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
491 "http://www.mediawiki.org/xml/export-$ver.xsd",
492 'version' => $ver,
493 'xml:lang' => $wgLanguageCode ),
494 null ) .
495 "\n" .
496 $this->siteInfo();
500 * @return string
502 function siteInfo() {
503 $info = array(
504 $this->sitename(),
505 $this->homelink(),
506 $this->generator(),
507 $this->caseSetting(),
508 $this->namespaces() );
509 return " <siteinfo>\n " .
510 implode( "\n ", $info ) .
511 "\n </siteinfo>\n";
515 * @return string
517 function sitename() {
518 global $wgSitename;
519 return Xml::element( 'sitename', array(), $wgSitename );
523 * @return string
525 function generator() {
526 global $wgVersion;
527 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
531 * @return string
533 function homelink() {
534 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalUrl() );
538 * @return string
540 function caseSetting() {
541 global $wgCapitalLinks;
542 // "case-insensitive" option is reserved for future
543 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
544 return Xml::element( 'case', array(), $sensitivity );
548 * @return string
550 function namespaces() {
551 global $wgContLang;
552 $spaces = "<namespaces>\n";
553 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
554 $spaces .= ' ' .
555 Xml::element( 'namespace',
556 array( 'key' => $ns,
557 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
558 ), $title ) . "\n";
560 $spaces .= " </namespaces>";
561 return $spaces;
565 * Closes the output stream with the closing root element.
566 * Call when finished dumping things.
568 * @return string
570 function closeStream() {
571 return "</mediawiki>\n";
575 * Opens a <page> section on the output stream, with data
576 * from the given database row.
578 * @param $row object
579 * @return string
580 * @access private
582 function openPage( $row ) {
583 $out = " <page>\n";
584 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
585 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
586 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace) ) . "\n";
587 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
588 if ( $row->page_is_redirect ) {
589 $page = WikiPage::factory( $title );
590 $redirect = $page->getRedirectTarget();
591 if ( $redirect instanceOf Title && $redirect->isValidRedirectTarget() ) {
592 $out .= ' ' . Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) ) . "\n";
596 if ( $row->page_restrictions != '' ) {
597 $out .= ' ' . Xml::element( 'restrictions', array(),
598 strval( $row->page_restrictions ) ) . "\n";
601 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
603 return $out;
607 * Closes a <page> section on the output stream.
609 * @access private
610 * @return string
612 function closePage() {
613 return " </page>\n";
617 * Dumps a <revision> section on the output stream, with
618 * data filled in from the given database row.
620 * @param $row object
621 * @return string
622 * @access private
624 function writeRevision( $row ) {
625 wfProfileIn( __METHOD__ );
627 $out = " <revision>\n";
628 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
630 $out .= $this->writeTimestamp( $row->rev_timestamp );
632 if ( $row->rev_deleted & Revision::DELETED_USER ) {
633 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
634 } else {
635 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
638 if ( $row->rev_minor_edit ) {
639 $out .= " <minor/>\n";
641 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
642 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
643 } elseif ( $row->rev_comment != '' ) {
644 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
647 $text = '';
648 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
649 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
650 } elseif ( isset( $row->old_text ) ) {
651 // Raw text from the database may have invalid chars
652 $text = strval( Revision::getRevisionText( $row ) );
653 $out .= " " . Xml::elementClean( 'text',
654 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
655 strval( $text ) ) . "\n";
656 } else {
657 // Stub output
658 $out .= " " . Xml::element( 'text',
659 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
660 "" ) . "\n";
663 if ( $row->rev_sha1 && !( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
664 $out .= " " . Xml::element('sha1', null, strval( $row->rev_sha1 ) ) . "\n";
665 } else {
666 $out .= " <sha1/>\n";
669 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
671 $out .= " </revision>\n";
673 wfProfileOut( __METHOD__ );
674 return $out;
678 * Dumps a <logitem> section on the output stream, with
679 * data filled in from the given database row.
681 * @param $row object
682 * @return string
683 * @access private
685 function writeLogItem( $row ) {
686 wfProfileIn( __METHOD__ );
688 $out = " <logitem>\n";
689 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
691 $out .= $this->writeTimestamp( $row->log_timestamp );
693 if ( $row->log_deleted & LogPage::DELETED_USER ) {
694 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
695 } else {
696 $out .= $this->writeContributor( $row->log_user, $row->user_name );
699 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
700 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
701 } elseif ( $row->log_comment != '' ) {
702 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
705 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
706 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
708 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
709 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
710 } else {
711 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
712 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
713 $out .= " " . Xml::elementClean( 'params',
714 array( 'xml:space' => 'preserve' ),
715 strval( $row->log_params ) ) . "\n";
718 $out .= " </logitem>\n";
720 wfProfileOut( __METHOD__ );
721 return $out;
725 * @param $timestamp string
726 * @return string
728 function writeTimestamp( $timestamp ) {
729 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
730 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
734 * @param $id
735 * @param $text string
736 * @return string
738 function writeContributor( $id, $text ) {
739 $out = " <contributor>\n";
740 if ( $id || !IP::isValid( $text ) ) {
741 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
742 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
743 } else {
744 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
746 $out .= " </contributor>\n";
747 return $out;
751 * Warning! This data is potentially inconsistent. :(
752 * @param $row
753 * @param $dumpContents bool
754 * @return string
756 function writeUploads( $row, $dumpContents = false ) {
757 if ( $row->page_namespace == NS_IMAGE ) {
758 $img = wfLocalFile( $row->page_title );
759 if ( $img && $img->exists() ) {
760 $out = '';
761 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
762 $out .= $this->writeUpload( $ver, $dumpContents );
764 $out .= $this->writeUpload( $img, $dumpContents );
765 return $out;
768 return '';
772 * @param $file File
773 * @param $dumpContents bool
774 * @return string
776 function writeUpload( $file, $dumpContents = false ) {
777 if ( $file->isOld() ) {
778 $archiveName = " " .
779 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
780 } else {
781 $archiveName = '';
783 if ( $dumpContents ) {
784 # Dump file as base64
785 # Uses only XML-safe characters, so does not need escaping
786 $contents = ' <contents encoding="base64">' .
787 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
788 " </contents>\n";
789 } else {
790 $contents = '';
792 return " <upload>\n" .
793 $this->writeTimestamp( $file->getTimestamp() ) .
794 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
795 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
796 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
797 $archiveName .
798 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
799 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
800 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
801 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
802 $contents .
803 " </upload>\n";
807 * Return prefixed text form of title, but using the content language's
808 * canonical namespace. This skips any special-casing such as gendered
809 * user namespaces -- which while useful, are not yet listed in the
810 * XML <siteinfo> data so are unsafe in export.
812 * @param Title $title
813 * @return string
814 * @since 1.18
816 public static function canonicalTitle( Title $title ) {
817 if ( $title->getInterwiki() ) {
818 return $title->getPrefixedText();
821 global $wgContLang;
822 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
824 if ( $prefix !== '' ) {
825 $prefix .= ':';
828 return $prefix . $title->getText();
834 * Base class for output stream; prints to stdout or buffer or whereever.
835 * @ingroup Dump
837 class DumpOutput {
840 * @param $string string
842 function writeOpenStream( $string ) {
843 $this->write( $string );
847 * @param $string string
849 function writeCloseStream( $string ) {
850 $this->write( $string );
854 * @param $page
855 * @param $string string
857 function writeOpenPage( $page, $string ) {
858 $this->write( $string );
862 * @param $string string
864 function writeClosePage( $string ) {
865 $this->write( $string );
869 * @param $rev
870 * @param $string string
872 function writeRevision( $rev, $string ) {
873 $this->write( $string );
877 * @param $rev
878 * @param $string string
880 function writeLogItem( $rev, $string ) {
881 $this->write( $string );
885 * Override to write to a different stream type.
886 * @param $string string
887 * @return bool
889 function write( $string ) {
890 print $string;
894 * Close the old file, move it to a specified name,
895 * and reopen new file with the old name. Use this
896 * for writing out a file in multiple pieces
897 * at specified checkpoints (e.g. every n hours).
898 * @param $newname mixed File name. May be a string or an array with one element
900 function closeRenameAndReopen( $newname ) {
901 return;
905 * Close the old file, and move it to a specified name.
906 * Use this for the last piece of a file written out
907 * at specified checkpoints (e.g. every n hours).
908 * @param $newname mixed File name. May be a string or an array with one element
909 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
911 function closeAndRename( $newname, $open = false ) {
912 return;
916 * Returns the name of the file or files which are
917 * being written to, if there are any.
918 * @return null
920 function getFilenames() {
921 return NULL;
926 * Stream outputter to send data to a file.
927 * @ingroup Dump
929 class DumpFileOutput extends DumpOutput {
930 protected $handle = false, $filename;
933 * @param $file
935 function __construct( $file ) {
936 $this->handle = fopen( $file, "wt" );
937 $this->filename = $file;
941 * @param $string string
943 function writeCloseStream( $string ) {
944 parent::writeCloseStream( $string );
945 if ( $this->handle ) {
946 fclose( $this->handle );
947 $this->handle = false;
952 * @param $string string
954 function write( $string ) {
955 fputs( $this->handle, $string );
959 * @param $newname
961 function closeRenameAndReopen( $newname ) {
962 $this->closeAndRename( $newname, true );
966 * @param $newname
967 * @throws MWException
969 function renameOrException( $newname ) {
970 if (! rename( $this->filename, $newname ) ) {
971 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
976 * @param $newname array
977 * @return mixed
978 * @throws MWException
980 function checkRenameArgCount( $newname ) {
981 if ( is_array( $newname ) ) {
982 if ( count( $newname ) > 1 ) {
983 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
984 } else {
985 $newname = $newname[0];
988 return $newname;
992 * @param $newname mixed
993 * @param $open bool
995 function closeAndRename( $newname, $open = false ) {
996 $newname = $this->checkRenameArgCount( $newname );
997 if ( $newname ) {
998 if ( $this->handle ) {
999 fclose( $this->handle );
1000 $this->handle = false;
1002 $this->renameOrException( $newname );
1003 if ( $open ) {
1004 $this->handle = fopen( $this->filename, "wt" );
1010 * @return string|null
1012 function getFilenames() {
1013 return $this->filename;
1018 * Stream outputter to send data to a file via some filter program.
1019 * Even if compression is available in a library, using a separate
1020 * program can allow us to make use of a multi-processor system.
1021 * @ingroup Dump
1023 class DumpPipeOutput extends DumpFileOutput {
1024 protected $command, $filename;
1025 protected $procOpenResource = false;
1028 * @param $command
1029 * @param $file null
1031 function __construct( $command, $file = null ) {
1032 if ( !is_null( $file ) ) {
1033 $command .= " > " . wfEscapeShellArg( $file );
1036 $this->startCommand( $command );
1037 $this->command = $command;
1038 $this->filename = $file;
1042 * @param $string string
1044 function writeCloseStream( $string ) {
1045 parent::writeCloseStream( $string );
1046 if ( $this->procOpenResource ) {
1047 proc_close( $this->procOpenResource );
1048 $this->procOpenResource = false;
1053 * @param $command
1055 function startCommand( $command ) {
1056 $spec = array(
1057 0 => array( "pipe", "r" ),
1059 $pipes = array();
1060 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1061 $this->handle = $pipes[0];
1065 * @param mixed $newname
1067 function closeRenameAndReopen( $newname ) {
1068 $this->closeAndRename( $newname, true );
1072 * @param $newname mixed
1073 * @param $open bool
1075 function closeAndRename( $newname, $open = false ) {
1076 $newname = $this->checkRenameArgCount( $newname );
1077 if ( $newname ) {
1078 if ( $this->handle ) {
1079 fclose( $this->handle );
1080 $this->handle = false;
1082 if ( $this->procOpenResource ) {
1083 proc_close( $this->procOpenResource );
1084 $this->procOpenResource = false;
1086 $this->renameOrException( $newname );
1087 if ( $open ) {
1088 $command = $this->command;
1089 $command .= " > " . wfEscapeShellArg( $this->filename );
1090 $this->startCommand( $command );
1098 * Sends dump output via the gzip compressor.
1099 * @ingroup Dump
1101 class DumpGZipOutput extends DumpPipeOutput {
1104 * @param $file string
1106 function __construct( $file ) {
1107 parent::__construct( "gzip", $file );
1112 * Sends dump output via the bgzip2 compressor.
1113 * @ingroup Dump
1115 class DumpBZip2Output extends DumpPipeOutput {
1118 * @param $file string
1120 function __construct( $file ) {
1121 parent::__construct( "bzip2", $file );
1126 * Sends dump output via the p7zip compressor.
1127 * @ingroup Dump
1129 class Dump7ZipOutput extends DumpPipeOutput {
1132 * @param $file string
1134 function __construct( $file ) {
1135 $command = $this->setup7zCommand( $file );
1136 parent::__construct( $command );
1137 $this->filename = $file;
1141 * @param $file string
1142 * @return string
1144 function setup7zCommand( $file ) {
1145 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1146 // Suppress annoying useless crap from p7zip
1147 // Unfortunately this could suppress real error messages too
1148 $command .= ' >' . wfGetNull() . ' 2>&1';
1149 return( $command );
1153 * @param $newname string
1154 * @param $open bool
1156 function closeAndRename( $newname, $open = false ) {
1157 $newname = $this->checkRenameArgCount( $newname );
1158 if ( $newname ) {
1159 fclose( $this->handle );
1160 proc_close( $this->procOpenResource );
1161 $this->renameOrException( $newname );
1162 if ( $open ) {
1163 $command = $this->setup7zCommand( $this->filename );
1164 $this->startCommand( $command );
1171 * Dump output filter class.
1172 * This just does output filtering and streaming; XML formatting is done
1173 * higher up, so be careful in what you do.
1174 * @ingroup Dump
1176 class DumpFilter {
1179 * @var DumpOutput
1181 protected $sink;
1184 * @var bool
1186 protected $sendingThisPage;
1189 * @param $sink DumpOutput
1191 function __construct( &$sink ) {
1192 $this->sink =& $sink;
1196 * @param $string string
1198 function writeOpenStream( $string ) {
1199 $this->sink->writeOpenStream( $string );
1203 * @param $string string
1205 function writeCloseStream( $string ) {
1206 $this->sink->writeCloseStream( $string );
1210 * @param $page
1211 * @param $string string
1213 function writeOpenPage( $page, $string ) {
1214 $this->sendingThisPage = $this->pass( $page, $string );
1215 if ( $this->sendingThisPage ) {
1216 $this->sink->writeOpenPage( $page, $string );
1221 * @param $string string
1223 function writeClosePage( $string ) {
1224 if ( $this->sendingThisPage ) {
1225 $this->sink->writeClosePage( $string );
1226 $this->sendingThisPage = false;
1231 * @param $rev
1232 * @param $string string
1234 function writeRevision( $rev, $string ) {
1235 if ( $this->sendingThisPage ) {
1236 $this->sink->writeRevision( $rev, $string );
1241 * @param $rev
1242 * @param $string string
1244 function writeLogItem( $rev, $string ) {
1245 $this->sink->writeRevision( $rev, $string );
1249 * @param $newname string
1251 function closeRenameAndReopen( $newname ) {
1252 $this->sink->closeRenameAndReopen( $newname );
1256 * @param $newname string
1257 * @param $open bool
1259 function closeAndRename( $newname, $open = false ) {
1260 $this->sink->closeAndRename( $newname, $open );
1264 * @return array
1266 function getFilenames() {
1267 return $this->sink->getFilenames();
1271 * Override for page-based filter types.
1272 * @param $page
1273 * @return bool
1275 function pass( $page ) {
1276 return true;
1281 * Simple dump output filter to exclude all talk pages.
1282 * @ingroup Dump
1284 class DumpNotalkFilter extends DumpFilter {
1287 * @param $page
1288 * @return bool
1290 function pass( $page ) {
1291 return !MWNamespace::isTalk( $page->page_namespace );
1296 * Dump output filter to include or exclude pages in a given set of namespaces.
1297 * @ingroup Dump
1299 class DumpNamespaceFilter extends DumpFilter {
1300 var $invert = false;
1301 var $namespaces = array();
1304 * @param $sink DumpOutput
1305 * @param $param
1307 function __construct( &$sink, $param ) {
1308 parent::__construct( $sink );
1310 $constants = array(
1311 "NS_MAIN" => NS_MAIN,
1312 "NS_TALK" => NS_TALK,
1313 "NS_USER" => NS_USER,
1314 "NS_USER_TALK" => NS_USER_TALK,
1315 "NS_PROJECT" => NS_PROJECT,
1316 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1317 "NS_FILE" => NS_FILE,
1318 "NS_FILE_TALK" => NS_FILE_TALK,
1319 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1320 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1321 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1322 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1323 "NS_TEMPLATE" => NS_TEMPLATE,
1324 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1325 "NS_HELP" => NS_HELP,
1326 "NS_HELP_TALK" => NS_HELP_TALK,
1327 "NS_CATEGORY" => NS_CATEGORY,
1328 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1330 if ( $param { 0 } == '!' ) {
1331 $this->invert = true;
1332 $param = substr( $param, 1 );
1335 foreach ( explode( ',', $param ) as $key ) {
1336 $key = trim( $key );
1337 if ( isset( $constants[$key] ) ) {
1338 $ns = $constants[$key];
1339 $this->namespaces[$ns] = true;
1340 } elseif ( is_numeric( $key ) ) {
1341 $ns = intval( $key );
1342 $this->namespaces[$ns] = true;
1343 } else {
1344 throw new MWException( "Unrecognized namespace key '$key'\n" );
1350 * @param $page
1351 * @return bool
1353 function pass( $page ) {
1354 $match = isset( $this->namespaces[$page->page_namespace] );
1355 return $this->invert xor $match;
1361 * Dump output filter to include only the last revision in each page sequence.
1362 * @ingroup Dump
1364 class DumpLatestFilter extends DumpFilter {
1365 var $page, $pageString, $rev, $revString;
1368 * @param $page
1369 * @param $string string
1371 function writeOpenPage( $page, $string ) {
1372 $this->page = $page;
1373 $this->pageString = $string;
1377 * @param $string string
1379 function writeClosePage( $string ) {
1380 if ( $this->rev ) {
1381 $this->sink->writeOpenPage( $this->page, $this->pageString );
1382 $this->sink->writeRevision( $this->rev, $this->revString );
1383 $this->sink->writeClosePage( $string );
1385 $this->rev = null;
1386 $this->revString = null;
1387 $this->page = null;
1388 $this->pageString = null;
1392 * @param $rev
1393 * @param $string string
1395 function writeRevision( $rev, $string ) {
1396 if ( $rev->rev_id == $this->page->page_latest ) {
1397 $this->rev = $rev;
1398 $this->revString = $string;
1404 * Base class for output stream; prints to stdout or buffer or whereever.
1405 * @ingroup Dump
1407 class DumpMultiWriter {
1410 * @param $sinks
1412 function __construct( $sinks ) {
1413 $this->sinks = $sinks;
1414 $this->count = count( $sinks );
1418 * @param $string string
1420 function writeOpenStream( $string ) {
1421 for ( $i = 0; $i < $this->count; $i++ ) {
1422 $this->sinks[$i]->writeOpenStream( $string );
1427 * @param $string string
1429 function writeCloseStream( $string ) {
1430 for ( $i = 0; $i < $this->count; $i++ ) {
1431 $this->sinks[$i]->writeCloseStream( $string );
1436 * @param $page
1437 * @param $string string
1439 function writeOpenPage( $page, $string ) {
1440 for ( $i = 0; $i < $this->count; $i++ ) {
1441 $this->sinks[$i]->writeOpenPage( $page, $string );
1446 * @param $string
1448 function writeClosePage( $string ) {
1449 for ( $i = 0; $i < $this->count; $i++ ) {
1450 $this->sinks[$i]->writeClosePage( $string );
1455 * @param $rev
1456 * @param $string
1458 function writeRevision( $rev, $string ) {
1459 for ( $i = 0; $i < $this->count; $i++ ) {
1460 $this->sinks[$i]->writeRevision( $rev, $string );
1465 * @param $newnames
1467 function closeRenameAndReopen( $newnames ) {
1468 $this->closeAndRename( $newnames, true );
1472 * @param $newnames array
1473 * @param bool $open
1475 function closeAndRename( $newnames, $open = false ) {
1476 for ( $i = 0; $i < $this->count; $i++ ) {
1477 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1482 * @return array
1484 function getFilenames() {
1485 $filenames = array();
1486 for ( $i = 0; $i < $this->count; $i++ ) {
1487 $filenames[] = $this->sinks[$i]->getFilenames();
1489 return $filenames;
1495 * @param $string string
1496 * @return string
1498 function xmlsafe( $string ) {
1499 wfProfileIn( __FUNCTION__ );
1502 * The page may contain old data which has not been properly normalized.
1503 * Invalid UTF-8 sequences or forbidden control characters will make our
1504 * XML output invalid, so be sure to strip them out.
1506 $string = UtfNormal::cleanUp( $string );
1508 $string = htmlspecialchars( $string );
1509 wfProfileOut( __FUNCTION__ );
1510 return $string;