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
31 * @ingroup SpecialPage Dump
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;
42 const STABLE
= 4; // extension defined
62 * Returns the export schema version.
65 public static function schemaVersion() {
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 DatabaseBase $db
77 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
78 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
79 * - offset: non-inclusive offset at which to start the query
80 * - limit: maximum number of rows to return
81 * - dir: "asc" or "desc" timestamp order
82 * @param int $buffer One of WikiExporter::BUFFER or WikiExporter::STREAM
83 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
85 function __construct( $db, $history = WikiExporter
::CURRENT
,
86 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
88 $this->history
= $history;
89 $this->buffer
= $buffer;
90 $this->writer
= new XmlDumpWriter();
91 $this->sink
= new DumpOutput();
96 * Set the DumpOutput or DumpFilter object which will receive
97 * various row objects and XML output for filtering. Filters
98 * can be chained or used as callbacks.
100 * @param DumpOutput $sink
102 public function setOutputSink( &$sink ) {
103 $this->sink
=& $sink;
106 public function openStream() {
107 $output = $this->writer
->openStream();
108 $this->sink
->writeOpenStream( $output );
111 public function closeStream() {
112 $output = $this->writer
->closeStream();
113 $this->sink
->writeCloseStream( $output );
117 * Dumps a series of page and revision records for all pages
118 * in the database, either including complete history or only
119 * the most recent version.
121 public function allPages() {
122 $this->dumpFrom( '' );
126 * Dumps a series of page and revision records for those pages
127 * in the database falling within the page_id range given.
128 * @param int $start Inclusive lower limit (this id is included)
129 * @param int $end Exclusive upper limit (this id is not included)
130 * If 0, no upper limit.
132 public function pagesByRange( $start, $end ) {
133 $condition = 'page_id >= ' . intval( $start );
135 $condition .= ' AND page_id < ' . intval( $end );
137 $this->dumpFrom( $condition );
141 * Dumps a series of page and revision records for those pages
142 * in the database with revisions falling within the rev_id range given.
143 * @param int $start Inclusive lower limit (this id is included)
144 * @param int $end Exclusive upper limit (this id is not included)
145 * If 0, no upper limit.
147 public function revsByRange( $start, $end ) {
148 $condition = 'rev_id >= ' . intval( $start );
150 $condition .= ' AND rev_id < ' . intval( $end );
152 $this->dumpFrom( $condition );
156 * @param Title $title
158 public function pageByTitle( $title ) {
160 'page_namespace=' . $title->getNamespace() .
161 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
165 * @param string $name
166 * @throws MWException
168 public function pageByName( $name ) {
169 $title = Title
::newFromText( $name );
170 if ( is_null( $title ) ) {
171 throw new MWException( "Can't export invalid title" );
173 $this->pageByTitle( $title );
178 * @param array $names
180 public function pagesByName( $names ) {
181 foreach ( $names as $name ) {
182 $this->pageByName( $name );
186 public function allLogs() {
187 $this->dumpFrom( '' );
194 public function logsByRange( $start, $end ) {
195 $condition = 'log_id >= ' . intval( $start );
197 $condition .= ' AND log_id < ' . intval( $end );
199 $this->dumpFrom( $condition );
203 * Generates the distinct list of authors of an article
204 * Not called by default (depends on $this->list_authors)
205 * Can be set by Special:Export when not exporting whole history
209 protected function do_list_authors( $cond ) {
210 wfProfileIn( __METHOD__
);
211 $this->author_list
= "<contributors>";
214 $res = $this->db
->select(
215 array( 'page', 'revision' ),
216 array( 'DISTINCT rev_user_text', 'rev_user' ),
218 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
225 foreach ( $res as $row ) {
226 $this->author_list
.= "<contributor>" .
228 htmlentities( $row->rev_user_text
) .
235 $this->author_list
.= "</contributors>";
236 wfProfileOut( __METHOD__
);
240 * @param string $cond
241 * @throws MWException
244 protected function dumpFrom( $cond = '' ) {
245 wfProfileIn( __METHOD__
);
246 # For logging dumps...
247 if ( $this->history
& self
::LOGS
) {
248 $where = array( 'user_id = log_user' );
250 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
252 $where[] = $hideLogs;
254 # Add on any caller specified conditions
258 # Get logging table name for logging.* clause
259 $logging = $this->db
->tableName( 'logging' );
261 if ( $this->buffer
== WikiExporter
::STREAM
) {
262 $prev = $this->db
->bufferResults( false );
264 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
266 $result = $this->db
->select( array( 'logging', 'user' ),
267 array( "{$logging}.*", 'user_name' ), // grab the user name
270 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
272 $wrapper = $this->db
->resultObject( $result );
273 $this->outputLogStream( $wrapper );
274 if ( $this->buffer
== WikiExporter
::STREAM
) {
275 $this->db
->bufferResults( $prev );
277 } catch ( Exception
$e ) {
278 // Throwing the exception does not reliably free the resultset, and
279 // would also leave the connection in unbuffered mode.
286 } catch ( Exception
$e2 ) {
287 // Already in panic mode -> ignoring $e2 as $e has
291 // Putting database back in previous buffer mode
293 if ( $this->buffer
== WikiExporter
::STREAM
) {
294 $this->db
->bufferResults( $prev );
296 } catch ( Exception
$e2 ) {
297 // Already in panic mode -> ignoring $e2 as $e has
301 // Inform caller about problem
302 wfProfileOut( __METHOD__
);
307 $tables = array( 'page', 'revision' );
308 $opts = array( 'ORDER BY' => 'page_id ASC' );
309 $opts['USE INDEX'] = array();
311 if ( is_array( $this->history
) ) {
312 # Time offset/limit for all pages/history...
313 $revJoin = 'page_id=rev_page';
315 if ( $this->history
['dir'] == 'asc' ) {
317 $opts['ORDER BY'] = 'rev_timestamp ASC';
320 $opts['ORDER BY'] = 'rev_timestamp DESC';
323 if ( !empty( $this->history
['offset'] ) ) {
324 $revJoin .= " AND rev_timestamp $op " .
325 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
327 $join['revision'] = array( 'INNER JOIN', $revJoin );
329 if ( !empty( $this->history
['limit'] ) ) {
330 $opts['LIMIT'] = intval( $this->history
['limit'] );
332 } elseif ( $this->history
& WikiExporter
::FULL
) {
333 # Full history dumps...
334 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
335 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
336 # Latest revision dumps...
337 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
338 $this->do_list_authors( $cond );
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
341 } elseif ( $this->history
& WikiExporter
::STABLE
) {
342 # "Stable" revision dumps...
343 # Default JOIN, to be overridden...
344 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
345 # One, and only one hook should set this, and return false
346 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
347 wfProfileOut( __METHOD__
);
348 throw new MWException( __METHOD__
. " given invalid history dump type." );
350 } elseif ( $this->history
& WikiExporter
::RANGE
) {
351 # Dump of revisions within a specified range
352 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
353 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
355 # Unknown history specification parameter?
356 wfProfileOut( __METHOD__
);
357 throw new MWException( __METHOD__
. " given invalid history dump type." );
359 # Query optimization hacks
361 $opts[] = 'STRAIGHT_JOIN';
362 $opts['USE INDEX']['page'] = 'PRIMARY';
364 # Build text join options
365 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
367 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
370 if ( $this->buffer
== WikiExporter
::STREAM
) {
371 $prev = $this->db
->bufferResults( false );
374 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
376 wfRunHooks( 'ModifyExportQuery',
377 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
380 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
381 $wrapper = $this->db
->resultObject( $result );
382 # Output dump results
383 $this->outputPageStream( $wrapper );
385 if ( $this->buffer
== WikiExporter
::STREAM
) {
386 $this->db
->bufferResults( $prev );
388 } catch ( Exception
$e ) {
389 // Throwing the exception does not reliably free the resultset, and
390 // would also leave the connection in unbuffered mode.
397 } catch ( Exception
$e2 ) {
398 // Already in panic mode -> ignoring $e2 as $e has
402 // Putting database back in previous buffer mode
404 if ( $this->buffer
== WikiExporter
::STREAM
) {
405 $this->db
->bufferResults( $prev );
407 } catch ( Exception
$e2 ) {
408 // Already in panic mode -> ignoring $e2 as $e has
412 // Inform caller about problem
416 wfProfileOut( __METHOD__
);
420 * Runs through a query result set dumping page and revision records.
421 * The result set should be sorted/grouped by page to avoid duplicate
422 * page records in the output.
425 * streaming (non-buffered) queries, as long as it was made on a
426 * separate database connection not managed by LoadBalancer; some
427 * blob storage types will make queries to pull source data.
429 * @param ResultWrapper $resultset
431 protected function outputPageStream( $resultset ) {
433 foreach ( $resultset as $row ) {
434 if ( $last === null ||
435 $last->page_namespace
!= $row->page_namespace ||
436 $last->page_title
!= $row->page_title
) {
437 if ( $last !== null ) {
439 if ( $this->dumpUploads
) {
440 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
442 $output .= $this->writer
->closePage();
443 $this->sink
->writeClosePage( $output );
445 $output = $this->writer
->openPage( $row );
446 $this->sink
->writeOpenPage( $row, $output );
449 $output = $this->writer
->writeRevision( $row );
450 $this->sink
->writeRevision( $row, $output );
452 if ( $last !== null ) {
454 if ( $this->dumpUploads
) {
455 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
457 $output .= $this->author_list
;
458 $output .= $this->writer
->closePage();
459 $this->sink
->writeClosePage( $output );
464 * @param array $resultset
466 protected function outputLogStream( $resultset ) {
467 foreach ( $resultset as $row ) {
468 $output = $this->writer
->writeLogItem( $row );
469 $this->sink
->writeLogItem( $row, $output );
477 class XmlDumpWriter
{
479 * Returns the export schema version.
480 * @deprecated since 1.20; use WikiExporter::schemaVersion() instead
483 function schemaVersion() {
484 wfDeprecated( __METHOD__
, '1.20' );
485 return WikiExporter
::schemaVersion();
489 * Opens the XML output stream's root "<mediawiki>" element.
490 * This does not include an xml directive, so is safe to include
491 * as a subelement in a larger XML stream. Namespace and XML Schema
492 * references are included.
494 * Output will be encoded in UTF-8.
498 function openStream() {
499 global $wgLanguageCode;
500 $ver = WikiExporter
::schemaVersion();
501 return Xml
::element( 'mediawiki', array(
502 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
503 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
504 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
505 #TODO: how do we get a new version up there?
506 "http://www.mediawiki.org/xml/export-$ver.xsd",
508 'xml:lang' => $wgLanguageCode ),
517 function siteInfo() {
522 $this->caseSetting(),
523 $this->namespaces() );
524 return " <siteinfo>\n " .
525 implode( "\n ", $info ) .
532 function sitename() {
534 return Xml
::element( 'sitename', array(), $wgSitename );
540 function generator() {
542 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
548 function homelink() {
549 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalURL() );
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 );
565 function namespaces() {
567 $spaces = "<namespaces>\n";
568 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
570 Xml
::element( 'namespace',
573 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
576 $spaces .= " </namespaces>";
581 * Closes the output stream with the closing root element.
582 * Call when finished dumping things.
586 function closeStream() {
587 return "</mediawiki>\n";
591 * Opens a "<page>" section on the output stream, with data
592 * from the given database row.
597 public function openPage( $row ) {
599 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
600 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
601 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
602 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
603 if ( $row->page_is_redirect
) {
604 $page = WikiPage
::factory( $title );
605 $redirect = $page->getRedirectTarget();
606 if ( $redirect instanceof Title
&& $redirect->isValidRedirectTarget() ) {
608 $out .= Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) );
613 if ( $row->page_restrictions
!= '' ) {
614 $out .= ' ' . Xml
::element( 'restrictions', array(),
615 strval( $row->page_restrictions
) ) . "\n";
618 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
624 * Closes a "<page>" section on the output stream.
629 function closePage() {
634 * Dumps a "<revision>" section on the output stream, with
635 * data filled in from the given database row.
641 function writeRevision( $row ) {
642 wfProfileIn( __METHOD__
);
644 $out = " <revision>\n";
645 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
646 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
647 $out .= " " . Xml
::element( 'parentid', null, strval( $row->rev_parent_id
) ) . "\n";
650 $out .= $this->writeTimestamp( $row->rev_timestamp
);
652 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_USER
) ) {
653 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
655 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
658 if ( isset( $row->rev_minor_edit
) && $row->rev_minor_edit
) {
659 $out .= " <minor/>\n";
661 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) ) {
662 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
663 } elseif ( $row->rev_comment
!= '' ) {
664 $out .= " " . Xml
::elementClean( 'comment', array(), strval( $row->rev_comment
) ) . "\n";
668 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
669 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
670 } elseif ( isset( $row->old_text
) ) {
671 // Raw text from the database may have invalid chars
672 $text = strval( Revision
::getRevisionText( $row ) );
673 $out .= " " . Xml
::elementClean( 'text',
674 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
675 strval( $text ) ) . "\n";
678 $out .= " " . Xml
::element( 'text',
679 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
683 if ( isset( $row->rev_sha1
)
685 && !( $row->rev_deleted
& Revision
::DELETED_TEXT
)
687 $out .= " " . Xml
::element( 'sha1', null, strval( $row->rev_sha1
) ) . "\n";
689 $out .= " <sha1/>\n";
692 if ( isset( $row->rev_content_model
) && !is_null( $row->rev_content_model
) ) {
693 $content_model = strval( $row->rev_content_model
);
695 // probably using $wgContentHandlerUseDB = false;
697 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
698 $content_model = ContentHandler
::getDefaultModelFor( $title );
701 $out .= " " . Xml
::element( 'model', null, strval( $content_model ) ) . "\n";
703 if ( isset( $row->rev_content_format
) && !is_null( $row->rev_content_format
) ) {
704 $content_format = strval( $row->rev_content_format
);
706 // probably using $wgContentHandlerUseDB = false;
708 $content_handler = ContentHandler
::getForModelID( $content_model );
709 $content_format = $content_handler->getDefaultFormat();
712 $out .= " " . Xml
::element( 'format', null, strval( $content_format ) ) . "\n";
714 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
716 $out .= " </revision>\n";
718 wfProfileOut( __METHOD__
);
723 * Dumps a "<logitem>" section on the output stream, with
724 * data filled in from the given database row.
730 function writeLogItem( $row ) {
731 wfProfileIn( __METHOD__
);
733 $out = " <logitem>\n";
734 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
736 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
738 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
739 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
741 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
744 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
745 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
746 } elseif ( $row->log_comment
!= '' ) {
747 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
750 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
751 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
753 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
754 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
756 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
757 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
758 $out .= " " . Xml
::elementClean( 'params',
759 array( 'xml:space' => 'preserve' ),
760 strval( $row->log_params
) ) . "\n";
763 $out .= " </logitem>\n";
765 wfProfileOut( __METHOD__
);
770 * @param string $timestamp
771 * @param string $indent Default to six spaces
774 function writeTimestamp( $timestamp, $indent = " " ) {
775 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
776 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
781 * @param string $text
782 * @param string $indent Default to six spaces
785 function writeContributor( $id, $text, $indent = " " ) {
786 $out = $indent . "<contributor>\n";
787 if ( $id ||
!IP
::isValid( $text ) ) {
788 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
789 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
791 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
793 $out .= $indent . "</contributor>\n";
798 * Warning! This data is potentially inconsistent. :(
800 * @param bool $dumpContents
803 function writeUploads( $row, $dumpContents = false ) {
804 if ( $row->page_namespace
== NS_FILE
) {
805 $img = wfLocalFile( $row->page_title
);
806 if ( $img && $img->exists() ) {
808 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
809 $out .= $this->writeUpload( $ver, $dumpContents );
811 $out .= $this->writeUpload( $img, $dumpContents );
820 * @param bool $dumpContents
823 function writeUpload( $file, $dumpContents = false ) {
824 if ( $file->isOld() ) {
826 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
830 if ( $dumpContents ) {
831 $be = $file->getRepo()->getBackend();
832 # Dump file as base64
833 # Uses only XML-safe characters, so does not need escaping
834 # @todo Too bad this loads the contents into memory (script might swap)
835 $contents = ' <contents encoding="base64">' .
836 chunk_split( base64_encode(
837 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
842 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
843 $comment = Xml
::element( 'comment', array( 'deleted' => 'deleted' ) );
845 $comment = Xml
::elementClean( 'comment', null, $file->getDescription() );
847 return " <upload>\n" .
848 $this->writeTimestamp( $file->getTimestamp() ) .
849 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
850 " " . $comment . "\n" .
851 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
853 " " . Xml
::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
854 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
855 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
856 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
862 * Return prefixed text form of title, but using the content language's
863 * canonical namespace. This skips any special-casing such as gendered
864 * user namespaces -- which while useful, are not yet listed in the
865 * XML "<siteinfo>" data so are unsafe in export.
867 * @param Title $title
871 public static function canonicalTitle( Title
$title ) {
872 if ( $title->isExternal() ) {
873 return $title->getPrefixedText();
877 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
879 if ( $prefix !== '' ) {
883 return $prefix . $title->getText();
888 * Base class for output stream; prints to stdout or buffer or wherever.
894 * @param string $string
896 function writeOpenStream( $string ) {
897 $this->write( $string );
901 * @param string $string
903 function writeCloseStream( $string ) {
904 $this->write( $string );
908 * @param object $page
909 * @param string $string
911 function writeOpenPage( $page, $string ) {
912 $this->write( $string );
916 * @param string $string
918 function writeClosePage( $string ) {
919 $this->write( $string );
924 * @param string $string
926 function writeRevision( $rev, $string ) {
927 $this->write( $string );
932 * @param string $string
934 function writeLogItem( $rev, $string ) {
935 $this->write( $string );
939 * Override to write to a different stream type.
940 * @param string $string
943 function write( $string ) {
948 * Close the old file, move it to a specified name,
949 * and reopen new file with the old name. Use this
950 * for writing out a file in multiple pieces
951 * at specified checkpoints (e.g. every n hours).
952 * @param string|array $newname File name. May be a string or an array with one element
954 function closeRenameAndReopen( $newname ) {
958 * Close the old file, and move it to a specified name.
959 * Use this for the last piece of a file written out
960 * at specified checkpoints (e.g. every n hours).
961 * @param string|array $newname File name. May be a string or an array with one element
962 * @param bool $open If true, a new file with the old filename will be opened
963 * again for writing (default: false)
965 function closeAndRename( $newname, $open = false ) {
969 * Returns the name of the file or files which are
970 * being written to, if there are any.
973 function getFilenames() {
979 * Stream outputter to send data to a file.
982 class DumpFileOutput
extends DumpOutput
{
983 protected $handle = false, $filename;
986 * @param string $file
988 function __construct( $file ) {
989 $this->handle
= fopen( $file, "wt" );
990 $this->filename
= $file;
994 * @param string $string
996 function writeCloseStream( $string ) {
997 parent
::writeCloseStream( $string );
998 if ( $this->handle
) {
999 fclose( $this->handle
);
1000 $this->handle
= false;
1005 * @param string $string
1007 function write( $string ) {
1008 fputs( $this->handle
, $string );
1012 * @param string $newname
1014 function closeRenameAndReopen( $newname ) {
1015 $this->closeAndRename( $newname, true );
1019 * @param string $newname
1020 * @throws MWException
1022 function renameOrException( $newname ) {
1023 if ( !rename( $this->filename
, $newname ) ) {
1024 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
1029 * @param array $newname
1031 * @throws MWException
1033 function checkRenameArgCount( $newname ) {
1034 if ( is_array( $newname ) ) {
1035 if ( count( $newname ) > 1 ) {
1036 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
1038 $newname = $newname[0];
1045 * @param string $newname
1048 function closeAndRename( $newname, $open = false ) {
1049 $newname = $this->checkRenameArgCount( $newname );
1051 if ( $this->handle
) {
1052 fclose( $this->handle
);
1053 $this->handle
= false;
1055 $this->renameOrException( $newname );
1057 $this->handle
= fopen( $this->filename
, "wt" );
1063 * @return string|null
1065 function getFilenames() {
1066 return $this->filename
;
1071 * Stream outputter to send data to a file via some filter program.
1072 * Even if compression is available in a library, using a separate
1073 * program can allow us to make use of a multi-processor system.
1076 class DumpPipeOutput
extends DumpFileOutput
{
1077 protected $command, $filename;
1078 protected $procOpenResource = false;
1081 * @param string $command
1082 * @param string $file
1084 function __construct( $command, $file = null ) {
1085 if ( !is_null( $file ) ) {
1086 $command .= " > " . wfEscapeShellArg( $file );
1089 $this->startCommand( $command );
1090 $this->command
= $command;
1091 $this->filename
= $file;
1095 * @param string $string
1097 function writeCloseStream( $string ) {
1098 parent
::writeCloseStream( $string );
1099 if ( $this->procOpenResource
) {
1100 proc_close( $this->procOpenResource
);
1101 $this->procOpenResource
= false;
1106 * @param string $command
1108 function startCommand( $command ) {
1110 0 => array( "pipe", "r" ),
1113 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
1114 $this->handle
= $pipes[0];
1118 * @param string $newname
1120 function closeRenameAndReopen( $newname ) {
1121 $this->closeAndRename( $newname, true );
1125 * @param string $newname
1128 function closeAndRename( $newname, $open = false ) {
1129 $newname = $this->checkRenameArgCount( $newname );
1131 if ( $this->handle
) {
1132 fclose( $this->handle
);
1133 $this->handle
= false;
1135 if ( $this->procOpenResource
) {
1136 proc_close( $this->procOpenResource
);
1137 $this->procOpenResource
= false;
1139 $this->renameOrException( $newname );
1141 $command = $this->command
;
1142 $command .= " > " . wfEscapeShellArg( $this->filename
);
1143 $this->startCommand( $command );
1151 * Sends dump output via the gzip compressor.
1154 class DumpGZipOutput
extends DumpPipeOutput
{
1157 * @param string $file
1159 function __construct( $file ) {
1160 parent
::__construct( "gzip", $file );
1165 * Sends dump output via the bgzip2 compressor.
1168 class DumpBZip2Output
extends DumpPipeOutput
{
1171 * @param string $file
1173 function __construct( $file ) {
1174 parent
::__construct( "bzip2", $file );
1179 * Sends dump output via the p7zip compressor.
1182 class Dump7ZipOutput
extends DumpPipeOutput
{
1185 * @param string $file
1187 function __construct( $file ) {
1188 $command = $this->setup7zCommand( $file );
1189 parent
::__construct( $command );
1190 $this->filename
= $file;
1194 * @param string $file
1197 function setup7zCommand( $file ) {
1198 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1199 // Suppress annoying useless crap from p7zip
1200 // Unfortunately this could suppress real error messages too
1201 $command .= ' >' . wfGetNull() . ' 2>&1';
1206 * @param string $newname
1209 function closeAndRename( $newname, $open = false ) {
1210 $newname = $this->checkRenameArgCount( $newname );
1212 fclose( $this->handle
);
1213 proc_close( $this->procOpenResource
);
1214 $this->renameOrException( $newname );
1216 $command = $this->setup7zCommand( $this->filename
);
1217 $this->startCommand( $command );
1224 * Dump output filter class.
1225 * This just does output filtering and streaming; XML formatting is done
1226 * higher up, so be careful in what you do.
1233 * FIXME will need to be made protected whenever legacy code
1241 protected $sendingThisPage;
1244 * @param DumpOutput $sink
1246 function __construct( &$sink ) {
1247 $this->sink
=& $sink;
1251 * @param string $string
1253 function writeOpenStream( $string ) {
1254 $this->sink
->writeOpenStream( $string );
1258 * @param string $string
1260 function writeCloseStream( $string ) {
1261 $this->sink
->writeCloseStream( $string );
1265 * @param object $page
1266 * @param string $string
1268 function writeOpenPage( $page, $string ) {
1269 $this->sendingThisPage
= $this->pass( $page, $string );
1270 if ( $this->sendingThisPage
) {
1271 $this->sink
->writeOpenPage( $page, $string );
1276 * @param string $string
1278 function writeClosePage( $string ) {
1279 if ( $this->sendingThisPage
) {
1280 $this->sink
->writeClosePage( $string );
1281 $this->sendingThisPage
= false;
1286 * @param object $rev
1287 * @param string $string
1289 function writeRevision( $rev, $string ) {
1290 if ( $this->sendingThisPage
) {
1291 $this->sink
->writeRevision( $rev, $string );
1296 * @param object $rev
1297 * @param string $string
1299 function writeLogItem( $rev, $string ) {
1300 $this->sink
->writeRevision( $rev, $string );
1304 * @param string $newname
1306 function closeRenameAndReopen( $newname ) {
1307 $this->sink
->closeRenameAndReopen( $newname );
1311 * @param string $newname
1314 function closeAndRename( $newname, $open = false ) {
1315 $this->sink
->closeAndRename( $newname, $open );
1321 function getFilenames() {
1322 return $this->sink
->getFilenames();
1326 * Override for page-based filter types.
1327 * @param object $page
1330 function pass( $page ) {
1336 * Simple dump output filter to exclude all talk pages.
1339 class DumpNotalkFilter
extends DumpFilter
{
1342 * @param object $page
1345 function pass( $page ) {
1346 return !MWNamespace
::isTalk( $page->page_namespace
);
1351 * Dump output filter to include or exclude pages in a given set of namespaces.
1354 class DumpNamespaceFilter
extends DumpFilter
{
1355 var $invert = false;
1356 var $namespaces = array();
1359 * @param DumpOutput $sink
1360 * @param array $param
1361 * @throws MWException
1363 function __construct( &$sink, $param ) {
1364 parent
::__construct( $sink );
1367 "NS_MAIN" => NS_MAIN
,
1368 "NS_TALK" => NS_TALK
,
1369 "NS_USER" => NS_USER
,
1370 "NS_USER_TALK" => NS_USER_TALK
,
1371 "NS_PROJECT" => NS_PROJECT
,
1372 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1373 "NS_FILE" => NS_FILE
,
1374 "NS_FILE_TALK" => NS_FILE_TALK
,
1375 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1376 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1377 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1378 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1379 "NS_TEMPLATE" => NS_TEMPLATE
,
1380 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1381 "NS_HELP" => NS_HELP
,
1382 "NS_HELP_TALK" => NS_HELP_TALK
,
1383 "NS_CATEGORY" => NS_CATEGORY
,
1384 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1386 if ( $param { 0 } == '!' ) {
1387 $this->invert
= true;
1388 $param = substr( $param, 1 );
1391 foreach ( explode( ',', $param ) as $key ) {
1392 $key = trim( $key );
1393 if ( isset( $constants[$key] ) ) {
1394 $ns = $constants[$key];
1395 $this->namespaces
[$ns] = true;
1396 } elseif ( is_numeric( $key ) ) {
1397 $ns = intval( $key );
1398 $this->namespaces
[$ns] = true;
1400 throw new MWException( "Unrecognized namespace key '$key'\n" );
1406 * @param object $page
1409 function pass( $page ) {
1410 $match = isset( $this->namespaces
[$page->page_namespace
] );
1411 return $this->invert
xor $match;
1416 * Dump output filter to include only the last revision in each page sequence.
1419 class DumpLatestFilter
extends DumpFilter
{
1420 var $page, $pageString, $rev, $revString;
1423 * @param object $page
1424 * @param string $string
1426 function writeOpenPage( $page, $string ) {
1427 $this->page
= $page;
1428 $this->pageString
= $string;
1432 * @param string $string
1434 function writeClosePage( $string ) {
1436 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1437 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1438 $this->sink
->writeClosePage( $string );
1441 $this->revString
= null;
1443 $this->pageString
= null;
1447 * @param object $rev
1448 * @param string $string
1450 function writeRevision( $rev, $string ) {
1451 if ( $rev->rev_id
== $this->page
->page_latest
) {
1453 $this->revString
= $string;
1459 * Base class for output stream; prints to stdout or buffer or wherever.
1462 class DumpMultiWriter
{
1465 * @param array $sinks
1467 function __construct( $sinks ) {
1468 $this->sinks
= $sinks;
1469 $this->count
= count( $sinks );
1473 * @param string $string
1475 function writeOpenStream( $string ) {
1476 for ( $i = 0; $i < $this->count
; $i++
) {
1477 $this->sinks
[$i]->writeOpenStream( $string );
1482 * @param string $string
1484 function writeCloseStream( $string ) {
1485 for ( $i = 0; $i < $this->count
; $i++
) {
1486 $this->sinks
[$i]->writeCloseStream( $string );
1491 * @param object $page
1492 * @param string $string
1494 function writeOpenPage( $page, $string ) {
1495 for ( $i = 0; $i < $this->count
; $i++
) {
1496 $this->sinks
[$i]->writeOpenPage( $page, $string );
1501 * @param string $string
1503 function writeClosePage( $string ) {
1504 for ( $i = 0; $i < $this->count
; $i++
) {
1505 $this->sinks
[$i]->writeClosePage( $string );
1510 * @param object $rev
1511 * @param string $string
1513 function writeRevision( $rev, $string ) {
1514 for ( $i = 0; $i < $this->count
; $i++
) {
1515 $this->sinks
[$i]->writeRevision( $rev, $string );
1520 * @param array $newnames
1522 function closeRenameAndReopen( $newnames ) {
1523 $this->closeAndRename( $newnames, true );
1527 * @param array $newnames
1530 function closeAndRename( $newnames, $open = false ) {
1531 for ( $i = 0; $i < $this->count
; $i++
) {
1532 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1539 function getFilenames() {
1540 $filenames = array();
1541 for ( $i = 0; $i < $this->count
; $i++
) {
1542 $filenames[] = $this->sinks
[$i]->getFilenames();
1550 * @param string $string
1553 function xmlsafe( $string ) {
1554 wfProfileIn( __FUNCTION__
);
1557 * The page may contain old data which has not been properly normalized.
1558 * Invalid UTF-8 sequences or forbidden control characters will make our
1559 * XML output invalid, so be sure to strip them out.
1561 $string = UtfNormal
::cleanUp( $string );
1563 $string = htmlspecialchars( $string );
1564 wfProfileOut( __FUNCTION__
);