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 return wfElement( 'base', array(), Title
::newMainPage()->getFullUrl() );
343 function caseSetting() {
344 global $wgCapitalLinks;
345 // "case-insensitive" option is reserved for future
346 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
347 return wfElement( 'case', array(), $sensitivity );
350 function namespaces() {
352 $spaces = " <namespaces>\n";
353 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
354 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
356 $spaces .= " </namespaces>";
361 * Closes the output stream with the closing root element.
362 * Call when finished dumping things.
364 function closeStream() {
365 return "</mediawiki>\n";
370 * Opens a <page> section on the output stream, with data
371 * from the given database row.
377 function openPage( $row ) {
379 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
380 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
381 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id
) ) . "\n";
382 if( '' != $row->page_restrictions
) {
383 $out .= ' ' . wfElement( 'restrictions', array(),
384 strval( $row->page_restrictions
) ) . "\n";
390 * Closes a <page> section on the output stream.
394 function closePage() {
399 * Dumps a <revision> section on the output stream, with
400 * data filled in from the given database row.
406 function writeRevision( $row ) {
407 $fname = 'WikiExporter::dumpRev';
408 wfProfileIn( $fname );
410 $out = " <revision>\n";
411 $out .= " " . wfElement( 'id', null, strval( $row->rev_id
) ) . "\n";
413 $ts = wfTimestamp( TS_ISO_8601
, $row->rev_timestamp
);
414 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
416 if( $row->rev_deleted
& Revision
::DELETED_USER
) {
417 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
419 $out .= " <contributor>\n";
420 if( $row->rev_user
) {
421 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text
) ) . "\n";
422 $out .= " " . wfElement( 'id', null, strval( $row->rev_user
) ) . "\n";
424 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text
) ) . "\n";
426 $out .= " </contributor>\n";
429 if( $row->rev_minor_edit
) {
430 $out .= " <minor/>\n";
432 if( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
433 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
434 } elseif( $row->rev_comment
!= '' ) {
435 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment
) ) . "\n";
438 if( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
439 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
440 } elseif( isset( $row->old_text
) ) {
441 // Raw text from the database may have invalid chars
442 $text = strval( Revision
::getRevisionText( $row ) );
443 $out .= " " . wfElementClean( 'text',
444 array( 'xml:space' => 'preserve' ),
445 strval( $text ) ) . "\n";
448 $out .= " " . wfElement( 'text',
449 array( 'id' => $row->rev_text_id
),
453 $out .= " </revision>\n";
455 wfProfileOut( $fname );
463 * Base class for output stream; prints to stdout or buffer or whereever.
466 function writeOpenStream( $string ) {
467 $this->write( $string );
470 function writeCloseStream( $string ) {
471 $this->write( $string );
474 function writeOpenPage( $page, $string ) {
475 $this->write( $string );
478 function writeClosePage( $string ) {
479 $this->write( $string );
482 function writeRevision( $rev, $string ) {
483 $this->write( $string );
487 * Override to write to a different stream type.
490 function write( $string ) {
496 * Stream outputter to send data to a file.
498 class DumpFileOutput
extends DumpOutput
{
501 function DumpFileOutput( $file ) {
502 $this->handle
= fopen( $file, "wt" );
505 function write( $string ) {
506 fputs( $this->handle
, $string );
511 * Stream outputter to send data to a file via some filter program.
512 * Even if compression is available in a library, using a separate
513 * program can allow us to make use of a multi-processor system.
515 class DumpPipeOutput
extends DumpFileOutput
{
516 function DumpPipeOutput( $command, $file = null ) {
517 if( !is_null( $file ) ) {
518 $command .= " > " . wfEscapeShellArg( $file );
520 $this->handle
= popen( $command, "w" );
525 * Sends dump output via the gzip compressor.
527 class DumpGZipOutput
extends DumpPipeOutput
{
528 function DumpGZipOutput( $file ) {
529 parent
::DumpPipeOutput( "gzip", $file );
534 * Sends dump output via the bgzip2 compressor.
536 class DumpBZip2Output
extends DumpPipeOutput
{
537 function DumpBZip2Output( $file ) {
538 parent
::DumpPipeOutput( "bzip2", $file );
543 * Sends dump output via the p7zip compressor.
545 class Dump7ZipOutput
extends DumpPipeOutput
{
546 function Dump7ZipOutput( $file ) {
547 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
548 // Suppress annoying useless crap from p7zip
549 // Unfortunately this could suppress real error messages too
550 $command .= " >/dev/null 2>&1";
551 parent
::DumpPipeOutput( $command );
558 * Dump output filter class.
559 * This just does output filtering and streaming; XML formatting is done
560 * higher up, so be careful in what you do.
563 function DumpFilter( &$sink ) {
564 $this->sink
=& $sink;
567 function writeOpenStream( $string ) {
568 $this->sink
->writeOpenStream( $string );
571 function writeCloseStream( $string ) {
572 $this->sink
->writeCloseStream( $string );
575 function writeOpenPage( $page, $string ) {
576 $this->sendingThisPage
= $this->pass( $page, $string );
577 if( $this->sendingThisPage
) {
578 $this->sink
->writeOpenPage( $page, $string );
582 function writeClosePage( $string ) {
583 if( $this->sendingThisPage
) {
584 $this->sink
->writeClosePage( $string );
585 $this->sendingThisPage
= false;
589 function writeRevision( $rev, $string ) {
590 if( $this->sendingThisPage
) {
591 $this->sink
->writeRevision( $rev, $string );
596 * Override for page-based filter types.
599 function pass( $page ) {
605 * Simple dump output filter to exclude all talk pages.
607 class DumpNotalkFilter
extends DumpFilter
{
608 function pass( $page ) {
609 return !Namespace::isTalk( $page->page_namespace
);
614 * Dump output filter to include or exclude pages in a given set of namespaces.
616 class DumpNamespaceFilter
extends DumpFilter
{
618 var $namespaces = array();
620 function DumpNamespaceFilter( &$sink, $param ) {
621 parent
::DumpFilter( $sink );
624 "NS_MAIN" => NS_MAIN
,
625 "NS_TALK" => NS_TALK
,
626 "NS_USER" => NS_USER
,
627 "NS_USER_TALK" => NS_USER_TALK
,
628 "NS_PROJECT" => NS_PROJECT
,
629 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
630 "NS_IMAGE" => NS_IMAGE
,
631 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
632 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
633 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
634 "NS_TEMPLATE" => NS_TEMPLATE
,
635 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
636 "NS_HELP" => NS_HELP
,
637 "NS_HELP_TALK" => NS_HELP_TALK
,
638 "NS_CATEGORY" => NS_CATEGORY
,
639 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
641 if( $param{0} == '!' ) {
642 $this->invert
= true;
643 $param = substr( $param, 1 );
646 foreach( explode( ',', $param ) as $key ) {
648 if( isset( $constants[$key] ) ) {
649 $ns = $constants[$key];
650 $this->namespaces
[$ns] = true;
651 } elseif( is_numeric( $key ) ) {
652 $ns = intval( $key );
653 $this->namespaces
[$ns] = true;
655 throw new MWException( "Unrecognized namespace key '$key'\n" );
660 function pass( $page ) {
661 $match = isset( $this->namespaces
[$page->page_namespace
] );
662 return $this->invert
xor $match;
668 * Dump output filter to include only the last revision in each page sequence.
670 class DumpLatestFilter
extends DumpFilter
{
671 var $page, $pageString, $rev, $revString;
673 function writeOpenPage( $page, $string ) {
675 $this->pageString
= $string;
678 function writeClosePage( $string ) {
680 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
681 $this->sink
->writeRevision( $this->rev
, $this->revString
);
682 $this->sink
->writeClosePage( $string );
685 $this->revString
= null;
687 $this->pageString
= null;
690 function writeRevision( $rev, $string ) {
691 if( $rev->rev_id
== $this->page
->page_latest
) {
693 $this->revString
= $string;
699 * Base class for output stream; prints to stdout or buffer or whereever.
701 class DumpMultiWriter
{
702 function DumpMultiWriter( $sinks ) {
703 $this->sinks
= $sinks;
704 $this->count
= count( $sinks );
707 function writeOpenStream( $string ) {
708 for( $i = 0; $i < $this->count
; $i++
) {
709 $this->sinks
[$i]->writeOpenStream( $string );
713 function writeCloseStream( $string ) {
714 for( $i = 0; $i < $this->count
; $i++
) {
715 $this->sinks
[$i]->writeCloseStream( $string );
719 function writeOpenPage( $page, $string ) {
720 for( $i = 0; $i < $this->count
; $i++
) {
721 $this->sinks
[$i]->writeOpenPage( $page, $string );
725 function writeClosePage( $string ) {
726 for( $i = 0; $i < $this->count
; $i++
) {
727 $this->sinks
[$i]->writeClosePage( $string );
731 function writeRevision( $rev, $string ) {
732 for( $i = 0; $i < $this->count
; $i++
) {
733 $this->sinks
[$i]->writeRevision( $rev, $string );
738 function xmlsafe( $string ) {
740 wfProfileIn( $fname );
743 * The page may contain old data which has not been properly normalized.
744 * Invalid UTF-8 sequences or forbidden control characters will make our
745 * XML output invalid, so be sure to strip them out.
747 $string = UtfNormal
::cleanUp( $string );
749 $string = htmlspecialchars( $string );
750 wfProfileOut( $fname );