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
23 * @subpackage SpecialPage
27 var $list_authors = false ; # Return distinct author list (when not returning full history)
28 var $author_list = "" ;
40 * If using WikiExporter::STREAM to stream a large amount of data,
41 * provide a database connection which is not managed by
42 * LoadBalancer to read from: some history blob types will
43 * make additional queries to pull source data while the
44 * main query is still running.
47 * @param mixed $history one of WikiExporter::FULL or WikiExporter::CURRENT, or an
49 * offset: non-inclusive offset at which to start the query
50 * limit: maximum number of rows to return
51 * dir: "asc" or "desc" timestamp order
52 * @param int $buffer one of WikiExporter::BUFFER or WikiExporter::STREAM
54 function WikiExporter( &$db, $history = WikiExporter
::CURRENT
,
55 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
57 $this->history
= $history;
58 $this->buffer
= $buffer;
59 $this->writer
= new XmlDumpWriter();
60 $this->sink
= new DumpOutput();
65 * Set the DumpOutput or DumpFilter object which will receive
66 * various row objects and XML output for filtering. Filters
67 * can be chained or used as callbacks.
69 * @param mixed $callback
71 function setOutputSink( &$sink ) {
75 function openStream() {
76 $output = $this->writer
->openStream();
77 $this->sink
->writeOpenStream( $output );
80 function closeStream() {
81 $output = $this->writer
->closeStream();
82 $this->sink
->writeCloseStream( $output );
86 * Dumps a series of page and revision records for all pages
87 * in the database, either including complete history or only
88 * the most recent version.
91 return $this->dumpFrom( '' );
95 * Dumps a series of page and revision records for those pages
96 * in the database falling within the page_id range given.
97 * @param int $start Inclusive lower limit (this id is included)
98 * @param int $end Exclusive upper limit (this id is not included)
99 * If 0, no upper limit.
101 function pagesByRange( $start, $end ) {
102 $condition = 'page_id >= ' . intval( $start );
104 $condition .= ' AND page_id < ' . intval( $end );
106 return $this->dumpFrom( $condition );
110 * @param Title $title
112 function pageByTitle( $title ) {
113 return $this->dumpFrom(
114 'page_namespace=' . $title->getNamespace() .
115 ' AND page_title=' . $this->db
->addQuotes( $title->getDbKey() ) );
118 function pageByName( $name ) {
119 $title = Title
::newFromText( $name );
120 if( is_null( $title ) ) {
121 return new WikiError( "Can't export invalid title" );
123 return $this->pageByTitle( $title );
127 function pagesByName( $names ) {
128 foreach( $names as $name ) {
129 $this->pageByName( $name );
134 // -------------------- private implementation below --------------------
136 # Generates the distinct list of authors of an article
137 # Not called by default (depends on $this->list_authors)
138 # Can be set by Special:Export when not exporting whole history
139 function do_list_authors ( $page , $revision , $cond ) {
140 $fname = "do_list_authors" ;
141 wfProfileIn( $fname );
142 $this->author_list
= "<contributors>";
143 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
144 $result = $this->db
->query( $sql, $fname );
145 $resultset = $this->db
->resultObject( $result );
146 while( $row = $resultset->fetchObject() ) {
147 $this->author_list
.= "<contributor>" .
149 htmlentities( $row->rev_user_text
) .
156 wfProfileOut( $fname );
157 $this->author_list
.= "</contributors>";
160 function dumpFrom( $cond = '' ) {
161 $fname = 'WikiExporter::dumpFrom';
162 wfProfileIn( $fname );
164 $page = $this->db
->tableName( 'page' );
165 $revision = $this->db
->tableName( 'revision' );
166 $text = $this->db
->tableName( 'text' );
168 $order = 'ORDER BY page_id';
171 if( $this->history
== WikiExporter
::FULL
) {
172 $join = 'page_id=rev_page';
173 } elseif( $this->history
== WikiExporter
::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';
178 } elseif ( is_array( $this->history
) ) {
179 $join = 'page_id=rev_page';
180 if ( $this->history
['dir'] == 'asc' ) {
182 $order .= ', rev_timestamp';
185 $order .= ', rev_timestamp DESC';
187 if ( !empty( $this->history
['offset'] ) ) {
188 $join .= " AND rev_timestamp $op " . $this->db
->addQuotes(
189 $this->db
->timestamp( $this->history
['offset'] ) );
191 if ( !empty( $this->history
['limit'] ) ) {
192 $limitNum = intval( $this->history
['limit'] );
193 if ( $limitNum > 0 ) {
194 $limit = "LIMIT $limitNum";
198 wfProfileOut( $fname );
199 return new WikiError( "$fname given invalid history dump type." );
201 $where = ( $cond == '' ) ?
'' : "$cond AND";
203 if( $this->buffer
== WikiExporter
::STREAM
) {
204 $prev = $this->db
->bufferResults( false );
207 // Optimization hack for full-database dump
208 $revindex = $pageindex = $this->db
->useIndexClause("PRIMARY");
209 $straight = ' /*! STRAIGHT_JOIN */ ';
215 if( $this->text
== WikiExporter
::STUB
) {
216 $sql = "SELECT $straight * FROM
222 $sql = "SELECT $straight * FROM
226 WHERE $where $join AND rev_text_id=old_id
229 $result = $this->db
->query( $sql, $fname );
230 $wrapper = $this->db
->resultObject( $result );
231 $this->outputStream( $wrapper );
233 if ( $this->list_authors
) {
234 $this->outputStream( $wrapper );
237 if( $this->buffer
== WikiExporter
::STREAM
) {
238 $this->db
->bufferResults( $prev );
241 wfProfileOut( $fname );
245 * Runs through a query result set dumping page and revision records.
246 * The result set should be sorted/grouped by page to avoid duplicate
247 * page records in the output.
249 * The result set will be freed once complete. Should be safe for
250 * streaming (non-buffered) queries, as long as it was made on a
251 * separate database connection not managed by LoadBalancer; some
252 * blob storage types will make queries to pull source data.
254 * @param ResultWrapper $resultset
257 function outputStream( $resultset ) {
259 while( $row = $resultset->fetchObject() ) {
260 if( is_null( $last ) ||
261 $last->page_namespace
!= $row->page_namespace ||
262 $last->page_title
!= $row->page_title
) {
263 if( isset( $last ) ) {
264 $output = $this->writer
->closePage();
265 $this->sink
->writeClosePage( $output );
267 $output = $this->writer
->openPage( $row );
268 $this->sink
->writeOpenPage( $row, $output );
271 $output = $this->writer
->writeRevision( $row );
272 $this->sink
->writeRevision( $row, $output );
274 if( isset( $last ) ) {
275 $output = $this->author_list
. $this->writer
->closePage();
276 $this->sink
->writeClosePage( $output );
282 class XmlDumpWriter
{
285 * Returns the export schema version.
288 function schemaVersion() {
289 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
293 * Opens the XML output stream's root <mediawiki> element.
294 * This does not include an xml directive, so is safe to include
295 * as a subelement in a larger XML stream. Namespace and XML Schema
296 * references are included.
298 * Output will be encoded in UTF-8.
302 function openStream() {
303 global $wgContLanguageCode;
304 $ver = $this->schemaVersion();
305 return wfElement( 'mediawiki', array(
306 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
307 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
308 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
309 "http://www.mediawiki.org/xml/export-$ver.xsd",
311 'xml:lang' => $wgContLanguageCode ),
317 function siteInfo() {
322 $this->caseSetting(),
323 $this->namespaces() );
324 return " <siteinfo>\n " .
325 implode( "\n ", $info ) .
329 function sitename() {
331 return wfElement( 'sitename', array(), $wgSitename );
334 function generator() {
336 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
339 function homelink() {
340 $page = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
341 return wfElement( 'base', array(), $page->getFullUrl() );
344 function caseSetting() {
345 global $wgCapitalLinks;
346 // "case-insensitive" option is reserved for future
347 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
348 return wfElement( 'case', array(), $sensitivity );
351 function namespaces() {
353 $spaces = " <namespaces>\n";
354 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
355 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
357 $spaces .= " </namespaces>";
362 * Closes the output stream with the closing root element.
363 * Call when finished dumping things.
365 function closeStream() {
366 return "</mediawiki>\n";
371 * Opens a <page> section on the output stream, with data
372 * from the given database row.
378 function openPage( $row ) {
380 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
381 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
382 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id
) ) . "\n";
383 if( '' != $row->page_restrictions
) {
384 $out .= ' ' . wfElement( 'restrictions', array(),
385 strval( $row->page_restrictions
) ) . "\n";
391 * Closes a <page> section on the output stream.
395 function closePage() {
400 * Dumps a <revision> section on the output stream, with
401 * data filled in from the given database row.
407 function writeRevision( $row ) {
408 $fname = 'WikiExporter::dumpRev';
409 wfProfileIn( $fname );
411 $out = " <revision>\n";
412 $out .= " " . wfElement( 'id', null, strval( $row->rev_id
) ) . "\n";
414 $ts = wfTimestamp( TS_ISO_8601
, $row->rev_timestamp
);
415 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
417 if( $row->rev_deleted
& Revision
::DELETED_USER
) {
418 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
420 $out .= " <contributor>\n";
421 if( $row->rev_user
) {
422 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text
) ) . "\n";
423 $out .= " " . wfElement( 'id', null, strval( $row->rev_user
) ) . "\n";
425 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text
) ) . "\n";
427 $out .= " </contributor>\n";
430 if( $row->rev_minor_edit
) {
431 $out .= " <minor/>\n";
433 if( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
434 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
435 } elseif( $row->rev_comment
!= '' ) {
436 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment
) ) . "\n";
439 if( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
440 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
441 } elseif( isset( $row->old_text
) ) {
442 // Raw text from the database may have invalid chars
443 $text = strval( Revision
::getRevisionText( $row ) );
444 $out .= " " . wfElementClean( 'text',
445 array( 'xml:space' => 'preserve' ),
446 strval( $text ) ) . "\n";
449 $out .= " " . wfElement( 'text',
450 array( 'id' => $row->rev_text_id
),
454 $out .= " </revision>\n";
456 wfProfileOut( $fname );
464 * Base class for output stream; prints to stdout or buffer or whereever.
467 function writeOpenStream( $string ) {
468 $this->write( $string );
471 function writeCloseStream( $string ) {
472 $this->write( $string );
475 function writeOpenPage( $page, $string ) {
476 $this->write( $string );
479 function writeClosePage( $string ) {
480 $this->write( $string );
483 function writeRevision( $rev, $string ) {
484 $this->write( $string );
488 * Override to write to a different stream type.
491 function write( $string ) {
497 * Stream outputter to send data to a file.
499 class DumpFileOutput
extends DumpOutput
{
502 function DumpFileOutput( $file ) {
503 $this->handle
= fopen( $file, "wt" );
506 function write( $string ) {
507 fputs( $this->handle
, $string );
512 * Stream outputter to send data to a file via some filter program.
513 * Even if compression is available in a library, using a separate
514 * program can allow us to make use of a multi-processor system.
516 class DumpPipeOutput
extends DumpFileOutput
{
517 function DumpPipeOutput( $command, $file = null ) {
518 if( !is_null( $file ) ) {
519 $command .= " > " . wfEscapeShellArg( $file );
521 $this->handle
= popen( $command, "w" );
526 * Sends dump output via the gzip compressor.
528 class DumpGZipOutput
extends DumpPipeOutput
{
529 function DumpGZipOutput( $file ) {
530 parent
::DumpPipeOutput( "gzip", $file );
535 * Sends dump output via the bgzip2 compressor.
537 class DumpBZip2Output
extends DumpPipeOutput
{
538 function DumpBZip2Output( $file ) {
539 parent
::DumpPipeOutput( "bzip2", $file );
544 * Sends dump output via the p7zip compressor.
546 class Dump7ZipOutput
extends DumpPipeOutput
{
547 function Dump7ZipOutput( $file ) {
548 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
549 // Suppress annoying useless crap from p7zip
550 // Unfortunately this could suppress real error messages too
551 $command .= " >/dev/null 2>&1";
552 parent
::DumpPipeOutput( $command );
559 * Dump output filter class.
560 * This just does output filtering and streaming; XML formatting is done
561 * higher up, so be careful in what you do.
564 function DumpFilter( &$sink ) {
565 $this->sink
=& $sink;
568 function writeOpenStream( $string ) {
569 $this->sink
->writeOpenStream( $string );
572 function writeCloseStream( $string ) {
573 $this->sink
->writeCloseStream( $string );
576 function writeOpenPage( $page, $string ) {
577 $this->sendingThisPage
= $this->pass( $page, $string );
578 if( $this->sendingThisPage
) {
579 $this->sink
->writeOpenPage( $page, $string );
583 function writeClosePage( $string ) {
584 if( $this->sendingThisPage
) {
585 $this->sink
->writeClosePage( $string );
586 $this->sendingThisPage
= false;
590 function writeRevision( $rev, $string ) {
591 if( $this->sendingThisPage
) {
592 $this->sink
->writeRevision( $rev, $string );
597 * Override for page-based filter types.
600 function pass( $page, $string ) {
606 * Simple dump output filter to exclude all talk pages.
608 class DumpNotalkFilter
extends DumpFilter
{
609 function pass( $page ) {
610 return !Namespace::isTalk( $page->page_namespace
);
615 * Dump output filter to include or exclude pages in a given set of namespaces.
617 class DumpNamespaceFilter
extends DumpFilter
{
619 var $namespaces = array();
621 function DumpNamespaceFilter( &$sink, $param ) {
622 parent
::DumpFilter( $sink );
625 "NS_MAIN" => NS_MAIN
,
626 "NS_TALK" => NS_TALK
,
627 "NS_USER" => NS_USER
,
628 "NS_USER_TALK" => NS_USER_TALK
,
629 "NS_PROJECT" => NS_PROJECT
,
630 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
631 "NS_IMAGE" => NS_IMAGE
,
632 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
633 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
634 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
635 "NS_TEMPLATE" => NS_TEMPLATE
,
636 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
637 "NS_HELP" => NS_HELP
,
638 "NS_HELP_TALK" => NS_HELP_TALK
,
639 "NS_CATEGORY" => NS_CATEGORY
,
640 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
642 if( $param{0} == '!' ) {
643 $this->invert
= true;
644 $param = substr( $param, 1 );
647 foreach( explode( ',', $param ) as $key ) {
649 if( isset( $constants[$key] ) ) {
650 $ns = $constants[$key];
651 $this->namespaces
[$ns] = true;
652 } elseif( is_numeric( $key ) ) {
653 $ns = intval( $key );
654 $this->namespaces
[$ns] = true;
656 throw new MWException( "Unrecognized namespace key '$key'\n" );
661 function pass( $page ) {
662 $match = isset( $this->namespaces
[$page->page_namespace
] );
663 return $this->invert
xor $match;
669 * Dump output filter to include only the last revision in each page sequence.
671 class DumpLatestFilter
extends DumpFilter
{
672 var $page, $pageString, $rev, $revString;
674 function writeOpenPage( $page, $string ) {
676 $this->pageString
= $string;
679 function writeClosePage( $string ) {
681 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
682 $this->sink
->writeRevision( $this->rev
, $this->revString
);
683 $this->sink
->writeClosePage( $string );
686 $this->revString
= null;
688 $this->pageString
= null;
691 function writeRevision( $rev, $string ) {
692 if( $rev->rev_id
== $this->page
->page_latest
) {
694 $this->revString
= $string;
700 * Base class for output stream; prints to stdout or buffer or whereever.
702 class DumpMultiWriter
{
703 function DumpMultiWriter( $sinks ) {
704 $this->sinks
= $sinks;
705 $this->count
= count( $sinks );
708 function writeOpenStream( $string ) {
709 for( $i = 0; $i < $this->count
; $i++
) {
710 $this->sinks
[$i]->writeOpenStream( $string );
714 function writeCloseStream( $string ) {
715 for( $i = 0; $i < $this->count
; $i++
) {
716 $this->sinks
[$i]->writeCloseStream( $string );
720 function writeOpenPage( $page, $string ) {
721 for( $i = 0; $i < $this->count
; $i++
) {
722 $this->sinks
[$i]->writeOpenPage( $page, $string );
726 function writeClosePage( $string ) {
727 for( $i = 0; $i < $this->count
; $i++
) {
728 $this->sinks
[$i]->writeClosePage( $string );
732 function writeRevision( $rev, $string ) {
733 for( $i = 0; $i < $this->count
; $i++
) {
734 $this->sinks
[$i]->writeRevision( $rev, $string );
739 function xmlsafe( $string ) {
741 wfProfileIn( $fname );
744 * The page may contain old data which has not been properly normalized.
745 * Invalid UTF-8 sequences or forbidden control characters will make our
746 * XML output invalid, so be sure to strip them out.
748 $string = UtfNormal
::cleanUp( $string );
750 $string = htmlspecialchars( $string );
751 wfProfileOut( $fname );