2 # Copyright (C) 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
22 * @subpackage SpecialPage
27 define( 'MW_EXPORT_FULL', 0 );
28 define( 'MW_EXPORT_CURRENT', 1 );
30 define( 'MW_EXPORT_BUFFER', 0 );
31 define( 'MW_EXPORT_STREAM', 1 );
33 define( 'MW_EXPORT_TEXT', 0 );
34 define( 'MW_EXPORT_STUB', 1 );
39 * @subpackage SpecialPage
43 var $list_authors = false ; # Return distinct author list (when not returning full history)
44 var $author_list = "" ;
47 * If using MW_EXPORT_STREAM to stream a large amount of data,
48 * provide a database connection which is not managed by
49 * LoadBalancer to read from: some history blob types will
50 * make additional queries to pull source data while the
51 * main query is still running.
54 * @param int $history one of MW_EXPORT_FULL or MW_EXPORT_CURRENT
55 * @param int $buffer one of MW_EXPORT_BUFFER or MW_EXPORT_STREAM
57 function WikiExporter( &$db, $history = MW_EXPORT_CURRENT
,
58 $buffer = MW_EXPORT_BUFFER
, $text = MW_EXPORT_TEXT
) {
60 $this->history
= $history;
61 $this->buffer
= $buffer;
62 $this->writer
= new XmlDumpWriter();
63 $this->sink
= new DumpOutput();
68 * Set the DumpOutput or DumpFilter object which will receive
69 * various row objects and XML output for filtering. Filters
70 * can be chained or used as callbacks.
72 * @param mixed $callback
74 function setOutputSink( &$sink ) {
78 function openStream() {
79 $output = $this->writer
->openStream();
80 $this->sink
->writeOpenStream( $output );
83 function closeStream() {
84 $output = $this->writer
->closeStream();
85 $this->sink
->writeCloseStream( $output );
89 * Dumps a series of page and revision records for all pages
90 * in the database, either including complete history or only
91 * the most recent version.
94 return $this->dumpFrom( '' );
98 * Dumps a series of page and revision records for those pages
99 * in the database falling within the page_id range given.
100 * @param int $start Inclusive lower limit (this id is included)
101 * @param int $end Exclusive upper limit (this id is not included)
102 * If 0, no upper limit.
104 function pagesByRange( $start, $end ) {
105 $condition = 'page_id >= ' . intval( $start );
107 $condition .= ' AND page_id < ' . intval( $end );
109 return $this->dumpFrom( $condition );
113 * @param Title $title
115 function pageByTitle( $title ) {
116 return $this->dumpFrom(
117 'page_namespace=' . $title->getNamespace() .
118 ' AND page_title=' . $this->db
->addQuotes( $title->getDbKey() ) );
121 function pageByName( $name ) {
122 $title = Title
::newFromText( $name );
123 if( is_null( $title ) ) {
124 return new WikiError( "Can't export invalid title" );
126 return $this->pageByTitle( $title );
130 function pagesByName( $names ) {
131 foreach( $names as $name ) {
132 $this->pageByName( $name );
137 // -------------------- private implementation below --------------------
139 # Generates the distinct list of authors of an article
140 # Not called by default (depends on $this->list_authors)
141 # Can be set by Special:Export when not exporting whole history
142 function do_list_authors ( $page , $revision , $cond ) {
143 $fname = "do_list_authors" ;
144 wfProfileIn( $fname );
145 $this->author_list
= "<contributors>";
146 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
147 $result = $this->db
->query( $sql, $fname );
148 $resultset = $this->db
->resultObject( $result );
149 while( $row = $resultset->fetchObject() ) {
150 $this->author_list
.= "<contributor>" .
152 htmlentities( $row->rev_user_text
) .
159 wfProfileOut( $fname );
160 $this->author_list
.= "</contributors>";
163 function dumpFrom( $cond = '' ) {
164 $fname = 'WikiExporter::dumpFrom';
165 wfProfileIn( $fname );
167 $page = $this->db
->tableName( 'page' );
168 $revision = $this->db
->tableName( 'revision' );
169 $text = $this->db
->tableName( 'text' );
171 if( $this->history
== MW_EXPORT_FULL
) {
172 $join = 'page_id=rev_page';
173 } elseif( $this->history
== MW_EXPORT_CURRENT
) {
174 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
175 $this->do_list_authors ( $page , $revision , $cond );
177 $join = 'page_id=rev_page AND page_latest=rev_id';
179 wfProfileOut( $fname );
180 return new WikiError( "$fname given invalid history dump type." );
182 $where = ( $cond == '' ) ?
'' : "$cond AND";
184 if( $this->buffer
== MW_EXPORT_STREAM
) {
185 $prev = $this->db
->bufferResults( false );
188 // Optimization hack for full-database dump
189 $revindex = $pageindex = $this->db
->useIndexClause("PRIMARY");
190 $straight = ' /*! STRAIGHT_JOIN */ ';
196 if( $this->text
== MW_EXPORT_STUB
) {
197 $sql = "SELECT $straight * FROM
203 $sql = "SELECT $straight * FROM
207 WHERE $where $join AND rev_text_id=old_id
210 $result = $this->db
->query( $sql, $fname );
211 $wrapper = $this->db
->resultObject( $result );
212 $this->outputStream( $wrapper );
214 if ( $this->list_authors
) {
215 $this->outputStream( $wrapper );
218 if( $this->buffer
== MW_EXPORT_STREAM
) {
219 $this->db
->bufferResults( $prev );
222 wfProfileOut( $fname );
226 * Runs through a query result set dumping page and revision records.
227 * The result set should be sorted/grouped by page to avoid duplicate
228 * page records in the output.
230 * The result set will be freed once complete. Should be safe for
231 * streaming (non-buffered) queries, as long as it was made on a
232 * separate database connection not managed by LoadBalancer; some
233 * blob storage types will make queries to pull source data.
235 * @param ResultWrapper $resultset
238 function outputStream( $resultset ) {
240 while( $row = $resultset->fetchObject() ) {
241 if( is_null( $last ) ||
242 $last->page_namespace
!= $row->page_namespace ||
243 $last->page_title
!= $row->page_title
) {
244 if( isset( $last ) ) {
245 $output = $this->writer
->closePage();
246 $this->sink
->writeClosePage( $output );
248 $output = $this->writer
->openPage( $row );
249 $this->sink
->writeOpenPage( $row, $output );
252 $output = $this->writer
->writeRevision( $row );
253 $this->sink
->writeRevision( $row, $output );
255 if( isset( $last ) ) {
256 $output = $this->author_list
. $this->writer
->closePage();
257 $this->sink
->writeClosePage( $output );
263 class XmlDumpWriter
{
266 * Returns the export schema version.
269 function schemaVersion() {
270 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
274 * Opens the XML output stream's root <mediawiki> element.
275 * This does not include an xml directive, so is safe to include
276 * as a subelement in a larger XML stream. Namespace and XML Schema
277 * references are included.
279 * Output will be encoded in UTF-8.
283 function openStream() {
284 global $wgContLanguageCode;
285 $ver = $this->schemaVersion();
286 return wfElement( 'mediawiki', array(
287 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
288 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
289 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
290 "http://www.mediawiki.org/xml/export-$ver.xsd",
292 'xml:lang' => $wgContLanguageCode ),
298 function siteInfo() {
303 $this->caseSetting(),
304 $this->namespaces() );
305 return " <siteinfo>\n " .
306 implode( "\n ", $info ) .
310 function sitename() {
312 return wfElement( 'sitename', array(), $wgSitename );
315 function generator() {
317 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
320 function homelink() {
321 $page = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
322 return wfElement( 'base', array(), $page->getFullUrl() );
325 function caseSetting() {
326 global $wgCapitalLinks;
327 // "case-insensitive" option is reserved for future
328 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
329 return wfElement( 'case', array(), $sensitivity );
332 function namespaces() {
334 $spaces = " <namespaces>\n";
335 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
336 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
338 $spaces .= " </namespaces>";
343 * Closes the output stream with the closing root element.
344 * Call when finished dumping things.
346 function closeStream() {
347 return "</mediawiki>\n";
352 * Opens a <page> section on the output stream, with data
353 * from the given database row.
359 function openPage( $row ) {
361 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
362 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
363 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id
) ) . "\n";
364 if( '' != $row->page_restrictions
) {
365 $out .= ' ' . wfElement( 'restrictions', array(),
366 strval( $row->page_restrictions
) ) . "\n";
372 * Closes a <page> section on the output stream.
376 function closePage() {
381 * Dumps a <revision> section on the output stream, with
382 * data filled in from the given database row.
388 function writeRevision( $row ) {
389 $fname = 'WikiExporter::dumpRev';
390 wfProfileIn( $fname );
392 $out = " <revision>\n";
393 $out .= " " . wfElement( 'id', null, strval( $row->rev_id
) ) . "\n";
395 $ts = wfTimestamp( TS_ISO_8601
, $row->rev_timestamp
);
396 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
398 if( $row->rev_deleted
& Revision
::DELETED_USER
) {
399 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
401 $out .= " <contributor>\n";
402 if( $row->rev_user
) {
403 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text
) ) . "\n";
404 $out .= " " . wfElement( 'id', null, strval( $row->rev_user
) ) . "\n";
406 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text
) ) . "\n";
408 $out .= " </contributor>\n";
411 if( $row->rev_minor_edit
) {
412 $out .= " <minor/>\n";
414 if( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
415 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
416 } elseif( $row->rev_comment
!= '' ) {
417 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment
) ) . "\n";
420 if( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
421 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
422 } elseif( isset( $row->old_text
) ) {
423 // Raw text from the database may have invalid chars
424 $text = strval( Revision
::getRevisionText( $row ) );
425 $out .= " " . wfElementClean( 'text',
426 array( 'xml:space' => 'preserve' ),
427 strval( $text ) ) . "\n";
430 $out .= " " . wfElement( 'text',
431 array( 'id' => $row->rev_text_id
),
435 $out .= " </revision>\n";
437 wfProfileOut( $fname );
445 * Base class for output stream; prints to stdout or buffer or whereever.
448 function writeOpenStream( $string ) {
449 $this->write( $string );
452 function writeCloseStream( $string ) {
453 $this->write( $string );
456 function writeOpenPage( $page, $string ) {
457 $this->write( $string );
460 function writeClosePage( $string ) {
461 $this->write( $string );
464 function writeRevision( $rev, $string ) {
465 $this->write( $string );
469 * Override to write to a different stream type.
472 function write( $string ) {
478 * Stream outputter to send data to a file.
480 class DumpFileOutput
extends DumpOutput
{
483 function DumpFileOutput( $file ) {
484 $this->handle
= fopen( $file, "wt" );
487 function write( $string ) {
488 fputs( $this->handle
, $string );
493 * Stream outputter to send data to a file via some filter program.
494 * Even if compression is available in a library, using a separate
495 * program can allow us to make use of a multi-processor system.
497 class DumpPipeOutput
extends DumpFileOutput
{
498 function DumpPipeOutput( $command, $file = null ) {
499 if( !is_null( $file ) ) {
500 $command .= " > " . wfEscapeShellArg( $file );
502 $this->handle
= popen( $command, "w" );
507 * Sends dump output via the gzip compressor.
509 class DumpGZipOutput
extends DumpPipeOutput
{
510 function DumpGZipOutput( $file ) {
511 parent
::DumpPipeOutput( "gzip", $file );
516 * Sends dump output via the bgzip2 compressor.
518 class DumpBZip2Output
extends DumpPipeOutput
{
519 function DumpBZip2Output( $file ) {
520 parent
::DumpPipeOutput( "bzip2", $file );
525 * Sends dump output via the p7zip compressor.
527 class Dump7ZipOutput
extends DumpPipeOutput
{
528 function Dump7ZipOutput( $file ) {
529 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
530 // Suppress annoying useless crap from p7zip
531 // Unfortunately this could suppress real error messages too
532 $command .= " >/dev/null 2>&1";
533 parent
::DumpPipeOutput( $command );
540 * Dump output filter class.
541 * This just does output filtering and streaming; XML formatting is done
542 * higher up, so be careful in what you do.
545 function DumpFilter( &$sink ) {
546 $this->sink
=& $sink;
549 function writeOpenStream( $string ) {
550 $this->sink
->writeOpenStream( $string );
553 function writeCloseStream( $string ) {
554 $this->sink
->writeCloseStream( $string );
557 function writeOpenPage( $page, $string ) {
558 $this->sendingThisPage
= $this->pass( $page, $string );
559 if( $this->sendingThisPage
) {
560 $this->sink
->writeOpenPage( $page, $string );
564 function writeClosePage( $string ) {
565 if( $this->sendingThisPage
) {
566 $this->sink
->writeClosePage( $string );
567 $this->sendingThisPage
= false;
571 function writeRevision( $rev, $string ) {
572 if( $this->sendingThisPage
) {
573 $this->sink
->writeRevision( $rev, $string );
578 * Override for page-based filter types.
581 function pass( $page, $string ) {
587 * Simple dump output filter to exclude all talk pages.
589 class DumpNotalkFilter
extends DumpFilter
{
590 function pass( $page ) {
591 return !Namespace::isTalk( $page->page_namespace
);
596 * Dump output filter to include or exclude pages in a given set of namespaces.
598 class DumpNamespaceFilter
extends DumpFilter
{
600 var $namespaces = array();
602 function DumpNamespaceFilter( &$sink, $param ) {
603 parent
::DumpFilter( $sink );
606 "NS_MAIN" => NS_MAIN
,
607 "NS_TALK" => NS_TALK
,
608 "NS_USER" => NS_USER
,
609 "NS_USER_TALK" => NS_USER_TALK
,
610 "NS_PROJECT" => NS_PROJECT
,
611 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
612 "NS_IMAGE" => NS_IMAGE
,
613 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
614 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
615 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
616 "NS_TEMPLATE" => NS_TEMPLATE
,
617 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
618 "NS_HELP" => NS_HELP
,
619 "NS_HELP_TALK" => NS_HELP_TALK
,
620 "NS_CATEGORY" => NS_CATEGORY
,
621 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
623 if( $param{0} == '!' ) {
624 $this->invert
= true;
625 $param = substr( $param, 1 );
628 foreach( explode( ',', $param ) as $key ) {
630 if( isset( $constants[$key] ) ) {
631 $ns = $constants[$key];
632 $this->namespaces
[$ns] = true;
633 } elseif( is_numeric( $key ) ) {
634 $ns = intval( $key );
635 $this->namespaces
[$ns] = true;
637 throw new MWException( "Unrecognized namespace key '$key'\n" );
642 function pass( $page ) {
643 $match = isset( $this->namespaces
[$page->page_namespace
] );
644 return $this->invert
xor $match;
650 * Dump output filter to include only the last revision in each page sequence.
652 class DumpLatestFilter
extends DumpFilter
{
653 var $page, $pageString, $rev, $revString;
655 function writeOpenPage( $page, $string ) {
657 $this->pageString
= $string;
660 function writeClosePage( $string ) {
662 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
663 $this->sink
->writeRevision( $this->rev
, $this->revString
);
664 $this->sink
->writeClosePage( $string );
667 $this->revString
= null;
669 $this->pageString
= null;
672 function writeRevision( $rev, $string ) {
673 if( $rev->rev_id
== $this->page
->page_latest
) {
675 $this->revString
= $string;
681 * Base class for output stream; prints to stdout or buffer or whereever.
683 class DumpMultiWriter
{
684 function DumpMultiWriter( $sinks ) {
685 $this->sinks
= $sinks;
686 $this->count
= count( $sinks );
689 function writeOpenStream( $string ) {
690 for( $i = 0; $i < $this->count
; $i++
) {
691 $this->sinks
[$i]->writeOpenStream( $string );
695 function writeCloseStream( $string ) {
696 for( $i = 0; $i < $this->count
; $i++
) {
697 $this->sinks
[$i]->writeCloseStream( $string );
701 function writeOpenPage( $page, $string ) {
702 for( $i = 0; $i < $this->count
; $i++
) {
703 $this->sinks
[$i]->writeOpenPage( $page, $string );
707 function writeClosePage( $string ) {
708 for( $i = 0; $i < $this->count
; $i++
) {
709 $this->sinks
[$i]->writeClosePage( $string );
713 function writeRevision( $rev, $string ) {
714 for( $i = 0; $i < $this->count
; $i++
) {
715 $this->sinks
[$i]->writeRevision( $rev, $string );
720 function xmlsafe( $string ) {
722 wfProfileIn( $fname );
725 * The page may contain old data which has not been properly normalized.
726 * Invalid UTF-8 sequences or forbidden control characters will make our
727 * XML output invalid, so be sure to strip them out.
729 $string = UtfNormal
::cleanUp( $string );
731 $string = htmlspecialchars( $string );
732 wfProfileOut( $fname );