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
25 * @ingroup SpecialPage Dump
28 var $list_authors = false ; # Return distinct author list (when not returning full history)
29 var $author_list = "" ;
31 var $dumpUploads = false;
44 * If using WikiExporter::STREAM to stream a large amount of data,
45 * provide a database connection which is not managed by
46 * LoadBalancer to read from: some history blob types will
47 * make additional queries to pull source data while the
48 * main query is still running.
51 * @param $history Mixed: one of WikiExporter::FULL or WikiExporter::CURRENT,
52 * or an associative array:
53 * offset: non-inclusive offset at which to start the query
54 * limit: maximum number of rows to return
55 * dir: "asc" or "desc" timestamp order
56 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
58 function __construct( &$db, $history = WikiExporter
::CURRENT
,
59 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
61 $this->history
= $history;
62 $this->buffer
= $buffer;
63 $this->writer
= new XmlDumpWriter();
64 $this->sink
= new DumpOutput();
69 * Set the DumpOutput or DumpFilter object which will receive
70 * various row objects and XML output for filtering. Filters
71 * can be chained or used as callbacks.
75 public function setOutputSink( &$sink ) {
79 public function openStream() {
80 $output = $this->writer
->openStream();
81 $this->sink
->writeOpenStream( $output );
84 public function closeStream() {
85 $output = $this->writer
->closeStream();
86 $this->sink
->writeCloseStream( $output );
90 * Dumps a series of page and revision records for all pages
91 * in the database, either including complete history or only
92 * the most recent version.
94 public function allPages() {
95 return $this->dumpFrom( '' );
99 * Dumps a series of page and revision records for those pages
100 * in the database falling within the page_id range given.
101 * @param $start Int: inclusive lower limit (this id is included)
102 * @param $end Int: Exclusive upper limit (this id is not included)
103 * If 0, no upper limit.
105 public function pagesByRange( $start, $end ) {
106 $condition = 'page_id >= ' . intval( $start );
108 $condition .= ' AND page_id < ' . intval( $end );
110 return $this->dumpFrom( $condition );
114 * @param $title Title
116 public function pageByTitle( $title ) {
117 return $this->dumpFrom(
118 'page_namespace=' . $title->getNamespace() .
119 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
122 public function pageByName( $name ) {
123 $title = Title
::newFromText( $name );
124 if( is_null( $title ) ) {
125 return new WikiError( "Can't export invalid title" );
127 return $this->pageByTitle( $title );
131 public function pagesByName( $names ) {
132 foreach( $names as $name ) {
133 $this->pageByName( $name );
137 public function allLogs() {
138 return $this->dumpFrom( '' );
141 public function logsByRange( $start, $end ) {
142 $condition = 'log_id >= ' . intval( $start );
144 $condition .= ' AND log_id < ' . intval( $end );
146 return $this->dumpFrom( $condition );
149 # Generates the distinct list of authors of an article
150 # Not called by default (depends on $this->list_authors)
151 # Can be set by Special:Export when not exporting whole history
152 protected function do_list_authors( $page , $revision , $cond ) {
153 $fname = "do_list_authors" ;
154 wfProfileIn( $fname );
155 $this->author_list
= "<contributors>";
157 $nothidden = '(rev_deleted & '.Revision
::DELETED_USER
.') = 0';
159 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision}
160 WHERE page_id=rev_page AND $nothidden AND " . $cond ;
161 $result = $this->db
->query( $sql, $fname );
162 $resultset = $this->db
->resultObject( $result );
163 while( $row = $resultset->fetchObject() ) {
164 $this->author_list
.= "<contributor>" .
166 htmlentities( $row->rev_user_text
) .
173 wfProfileOut( $fname );
174 $this->author_list
.= "</contributors>";
177 protected function dumpFrom( $cond = '' ) {
178 $fname = 'WikiExporter::dumpFrom';
179 wfProfileIn( $fname );
182 if( $this->history
& self
::LOGS
) {
183 $where = array( 'user_id = log_user' );
185 $where[] = LogEventsList
::getExcludeClause( $this->db
);
186 if( $cond ) $where[] = $cond;
187 $result = $this->db
->select( array('logging','user'),
191 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array('logging' => 'PRIMARY') )
193 $wrapper = $this->db
->resultObject( $result );
194 $this->outputLogStream( $wrapper );
197 list($page,$revision,$text) = $this->db
->tableNamesN('page','revision','text');
199 $order = 'ORDER BY page_id';
202 if( $this->history
== WikiExporter
::FULL
) {
203 $join = 'page_id=rev_page';
204 } elseif( $this->history
== WikiExporter
::CURRENT
) {
205 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
206 $this->do_list_authors ( $page , $revision , $cond );
208 $join = 'page_id=rev_page AND page_latest=rev_id';
209 } elseif ( is_array( $this->history
) ) {
210 $join = 'page_id=rev_page';
211 if ( $this->history
['dir'] == 'asc' ) {
213 $order .= ', rev_timestamp';
216 $order .= ', rev_timestamp DESC';
218 if ( !empty( $this->history
['offset'] ) ) {
219 $join .= " AND rev_timestamp $op " . $this->db
->addQuotes(
220 $this->db
->timestamp( $this->history
['offset'] ) );
222 if ( !empty( $this->history
['limit'] ) ) {
223 $limitNum = intval( $this->history
['limit'] );
224 if ( $limitNum > 0 ) {
225 $limit = "LIMIT $limitNum";
229 wfProfileOut( $fname );
230 return new WikiError( "$fname given invalid history dump type." );
232 $where = ( $cond == '' ) ?
'' : "$cond AND";
234 if( $this->buffer
== WikiExporter
::STREAM
) {
235 $prev = $this->db
->bufferResults( false );
238 // Optimization hack for full-database dump
239 $revindex = $pageindex = $this->db
->useIndexClause("PRIMARY");
240 $straight = ' /*! STRAIGHT_JOIN */ ';
246 if( $this->text
== WikiExporter
::STUB
) {
247 $sql = "SELECT $straight * FROM
253 $sql = "SELECT $straight * FROM
257 WHERE $where $join AND rev_text_id=old_id
260 $result = $this->db
->query( $sql, $fname );
261 $wrapper = $this->db
->resultObject( $result );
262 $this->outputPageStream( $wrapper );
264 if ( $this->list_authors
) {
265 $this->outputPageStream( $wrapper );
268 if( $this->buffer
== WikiExporter
::STREAM
) {
269 $this->db
->bufferResults( $prev );
272 wfProfileOut( $fname );
276 * Runs through a query result set dumping page and revision records.
277 * The result set should be sorted/grouped by page to avoid duplicate
278 * page records in the output.
280 * The result set will be freed once complete. Should be safe for
281 * streaming (non-buffered) queries, as long as it was made on a
282 * separate database connection not managed by LoadBalancer; some
283 * blob storage types will make queries to pull source data.
285 * @param $resultset ResultWrapper
287 protected function outputPageStream( $resultset ) {
289 while( $row = $resultset->fetchObject() ) {
290 if( is_null( $last ) ||
291 $last->page_namespace
!= $row->page_namespace ||
292 $last->page_title
!= $row->page_title
) {
293 if( isset( $last ) ) {
295 if( $this->dumpUploads
) {
296 $output .= $this->writer
->writeUploads( $last );
298 $output .= $this->writer
->closePage();
299 $this->sink
->writeClosePage( $output );
301 $output = $this->writer
->openPage( $row );
302 $this->sink
->writeOpenPage( $row, $output );
305 $output = $this->writer
->writeRevision( $row );
306 $this->sink
->writeRevision( $row, $output );
308 if( isset( $last ) ) {
310 if( $this->dumpUploads
) {
311 $output .= $this->writer
->writeUploads( $last );
313 $output .= $this->author_list
;
314 $output .= $this->writer
->closePage();
315 $this->sink
->writeClosePage( $output );
320 protected function outputLogStream( $resultset ) {
321 while( $row = $resultset->fetchObject() ) {
322 $output = $this->writer
->writeLogItem( $row );
323 $this->sink
->writeLogItem( $row, $output );
332 class XmlDumpWriter
{
335 * Returns the export schema version.
338 function schemaVersion() {
339 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
343 * Opens the XML output stream's root <mediawiki> element.
344 * This does not include an xml directive, so is safe to include
345 * as a subelement in a larger XML stream. Namespace and XML Schema
346 * references are included.
348 * Output will be encoded in UTF-8.
352 function openStream() {
353 global $wgContLanguageCode;
354 $ver = $this->schemaVersion();
355 return wfElement( 'mediawiki', array(
356 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
357 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
358 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
359 "http://www.mediawiki.org/xml/export-$ver.xsd",
361 'xml:lang' => $wgContLanguageCode ),
367 function siteInfo() {
372 $this->caseSetting(),
373 $this->namespaces() );
374 return " <siteinfo>\n " .
375 implode( "\n ", $info ) .
379 function sitename() {
381 return wfElement( 'sitename', array(), $wgSitename );
384 function generator() {
386 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
389 function homelink() {
390 return wfElement( 'base', array(), Title
::newMainPage()->getFullUrl() );
393 function caseSetting() {
394 global $wgCapitalLinks;
395 // "case-insensitive" option is reserved for future
396 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
397 return wfElement( 'case', array(), $sensitivity );
400 function namespaces() {
402 $spaces = " <namespaces>\n";
403 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
404 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
406 $spaces .= " </namespaces>";
411 * Closes the output stream with the closing root element.
412 * Call when finished dumping things.
414 function closeStream() {
415 return "</mediawiki>\n";
420 * Opens a <page> section on the output stream, with data
421 * from the given database row.
427 function openPage( $row ) {
429 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
430 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
431 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id
) ) . "\n";
432 if( '' != $row->page_restrictions
) {
433 $out .= ' ' . wfElement( 'restrictions', array(),
434 strval( $row->page_restrictions
) ) . "\n";
440 * Closes a <page> section on the output stream.
444 function closePage() {
449 * Dumps a <revision> section on the output stream, with
450 * data filled in from the given database row.
456 function writeRevision( $row ) {
457 $fname = 'WikiExporter::dumpRev';
458 wfProfileIn( $fname );
460 $out = " <revision>\n";
461 $out .= " " . wfElement( 'id', null, strval( $row->rev_id
) ) . "\n";
463 $out .= $this->writeTimestamp( $row->rev_timestamp
);
465 if( $row->rev_deleted
& Revision
::DELETED_USER
) {
466 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
468 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
471 if( $row->rev_minor_edit
) {
472 $out .= " <minor/>\n";
474 if( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
475 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
476 } elseif( $row->rev_comment
!= '' ) {
477 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment
) ) . "\n";
480 if( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
481 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
482 } elseif( isset( $row->old_text
) ) {
483 // Raw text from the database may have invalid chars
484 $text = strval( Revision
::getRevisionText( $row ) );
485 $out .= " " . wfElementClean( 'text',
486 array( 'xml:space' => 'preserve' ),
487 strval( $text ) ) . "\n";
490 $out .= " " . wfElement( 'text',
491 array( 'id' => $row->rev_text_id
),
495 $out .= " </revision>\n";
497 wfProfileOut( $fname );
502 * Dumps a <logitem> section on the output stream, with
503 * data filled in from the given database row.
509 function writeLogItem( $row ) {
510 $fname = 'WikiExporter::writeLogItem';
511 wfProfileIn( $fname );
513 $out = " <logitem>\n";
514 $out .= " " . wfElement( 'id', null, strval( $row->log_id
) ) . "\n";
516 $out .= $this->writeTimestamp( $row->log_timestamp
);
518 if( $row->log_deleted
& LogPage
::DELETED_USER
) {
519 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
521 $out .= $this->writeContributor( $row->log_user
, $row->user_name
);
524 if( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
525 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
526 } elseif( $row->log_comment
!= '' ) {
527 $out .= " " . wfElementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
530 $out .= " " . wfElement( 'type', null, strval( $row->log_type
) ) . "\n";
531 $out .= " " . wfElement( 'action', null, strval( $row->log_action
) ) . "\n";
533 if( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
534 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
536 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
537 $out .= " " . wfElementClean( 'logtitle', null, $title->getPrefixedText() ) . "\n";
538 $out .= " " . wfElementClean( 'params',
539 array( 'xml:space' => 'preserve' ),
540 strval( $row->log_params
) ) . "\n";
543 $out .= " </logitem>\n";
545 wfProfileOut( $fname );
549 function writeTimestamp( $timestamp ) {
550 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
551 return " " . wfElement( 'timestamp', null, $ts ) . "\n";
554 function writeContributor( $id, $text ) {
555 $out = " <contributor>\n";
557 $out .= " " . wfElementClean( 'username', null, strval( $text ) ) . "\n";
558 $out .= " " . wfElement( 'id', null, strval( $id ) ) . "\n";
560 $out .= " " . wfElementClean( 'ip', null, strval( $text ) ) . "\n";
562 $out .= " </contributor>\n";
567 * Warning! This data is potentially inconsistent. :(
569 function writeUploads( $row ) {
570 if( $row->page_namespace
== NS_IMAGE
) {
571 $img = wfFindFile( $row->page_title
);
574 foreach( array_reverse( $img->getHistory() ) as $ver ) {
575 $out .= $this->writeUpload( $ver );
577 $out .= $this->writeUpload( $img );
584 function writeUpload( $file ) {
585 return " <upload>\n" .
586 $this->writeTimestamp( $file->getTimestamp() ) .
587 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
588 " " . wfElementClean( 'comment', null, $file->getDescription() ) . "\n" .
589 " " . wfElement( 'filename', null, $file->getName() ) . "\n" .
590 " " . wfElement( 'src', null, $file->getFullUrl() ) . "\n" .
591 " " . wfElement( 'size', null, $file->getSize() ) . "\n" .
599 * Base class for output stream; prints to stdout or buffer or whereever.
603 function writeOpenStream( $string ) {
604 $this->write( $string );
607 function writeCloseStream( $string ) {
608 $this->write( $string );
611 function writeOpenPage( $page, $string ) {
612 $this->write( $string );
615 function writeClosePage( $string ) {
616 $this->write( $string );
619 function writeRevision( $rev, $string ) {
620 $this->write( $string );
623 function writeLogItem( $rev, $string ) {
624 $this->write( $string );
628 * Override to write to a different stream type.
631 function write( $string ) {
637 * Stream outputter to send data to a file.
640 class DumpFileOutput
extends DumpOutput
{
643 function DumpFileOutput( $file ) {
644 $this->handle
= fopen( $file, "wt" );
647 function write( $string ) {
648 fputs( $this->handle
, $string );
653 * Stream outputter to send data to a file via some filter program.
654 * Even if compression is available in a library, using a separate
655 * program can allow us to make use of a multi-processor system.
658 class DumpPipeOutput
extends DumpFileOutput
{
659 function DumpPipeOutput( $command, $file = null ) {
660 if( !is_null( $file ) ) {
661 $command .= " > " . wfEscapeShellArg( $file );
663 $this->handle
= popen( $command, "w" );
668 * Sends dump output via the gzip compressor.
671 class DumpGZipOutput
extends DumpPipeOutput
{
672 function DumpGZipOutput( $file ) {
673 parent
::DumpPipeOutput( "gzip", $file );
678 * Sends dump output via the bgzip2 compressor.
681 class DumpBZip2Output
extends DumpPipeOutput
{
682 function DumpBZip2Output( $file ) {
683 parent
::DumpPipeOutput( "bzip2", $file );
688 * Sends dump output via the p7zip compressor.
691 class Dump7ZipOutput
extends DumpPipeOutput
{
692 function Dump7ZipOutput( $file ) {
693 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
694 // Suppress annoying useless crap from p7zip
695 // Unfortunately this could suppress real error messages too
696 $command .= ' >' . wfGetNull() . ' 2>&1';
697 parent
::DumpPipeOutput( $command );
704 * Dump output filter class.
705 * This just does output filtering and streaming; XML formatting is done
706 * higher up, so be careful in what you do.
710 function DumpFilter( &$sink ) {
711 $this->sink
=& $sink;
714 function writeOpenStream( $string ) {
715 $this->sink
->writeOpenStream( $string );
718 function writeCloseStream( $string ) {
719 $this->sink
->writeCloseStream( $string );
722 function writeOpenPage( $page, $string ) {
723 $this->sendingThisPage
= $this->pass( $page, $string );
724 if( $this->sendingThisPage
) {
725 $this->sink
->writeOpenPage( $page, $string );
729 function writeClosePage( $string ) {
730 if( $this->sendingThisPage
) {
731 $this->sink
->writeClosePage( $string );
732 $this->sendingThisPage
= false;
736 function writeRevision( $rev, $string ) {
737 if( $this->sendingThisPage
) {
738 $this->sink
->writeRevision( $rev, $string );
742 function writeLogItem( $rev, $string ) {
743 $this->sink
->writeRevision( $rev, $string );
747 * Override for page-based filter types.
750 function pass( $page ) {
756 * Simple dump output filter to exclude all talk pages.
759 class DumpNotalkFilter
extends DumpFilter
{
760 function pass( $page ) {
761 return !MWNamespace
::isTalk( $page->page_namespace
);
766 * Dump output filter to include or exclude pages in a given set of namespaces.
769 class DumpNamespaceFilter
extends DumpFilter
{
771 var $namespaces = array();
773 function DumpNamespaceFilter( &$sink, $param ) {
774 parent
::DumpFilter( $sink );
777 "NS_MAIN" => NS_MAIN
,
778 "NS_TALK" => NS_TALK
,
779 "NS_USER" => NS_USER
,
780 "NS_USER_TALK" => NS_USER_TALK
,
781 "NS_PROJECT" => NS_PROJECT
,
782 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
783 "NS_IMAGE" => NS_IMAGE
,
784 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
785 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
786 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
787 "NS_TEMPLATE" => NS_TEMPLATE
,
788 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
789 "NS_HELP" => NS_HELP
,
790 "NS_HELP_TALK" => NS_HELP_TALK
,
791 "NS_CATEGORY" => NS_CATEGORY
,
792 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
794 if( $param{0} == '!' ) {
795 $this->invert
= true;
796 $param = substr( $param, 1 );
799 foreach( explode( ',', $param ) as $key ) {
801 if( isset( $constants[$key] ) ) {
802 $ns = $constants[$key];
803 $this->namespaces
[$ns] = true;
804 } elseif( is_numeric( $key ) ) {
805 $ns = intval( $key );
806 $this->namespaces
[$ns] = true;
808 throw new MWException( "Unrecognized namespace key '$key'\n" );
813 function pass( $page ) {
814 $match = isset( $this->namespaces
[$page->page_namespace
] );
815 return $this->invert
xor $match;
821 * Dump output filter to include only the last revision in each page sequence.
824 class DumpLatestFilter
extends DumpFilter
{
825 var $page, $pageString, $rev, $revString;
827 function writeOpenPage( $page, $string ) {
829 $this->pageString
= $string;
832 function writeClosePage( $string ) {
834 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
835 $this->sink
->writeRevision( $this->rev
, $this->revString
);
836 $this->sink
->writeClosePage( $string );
839 $this->revString
= null;
841 $this->pageString
= null;
844 function writeRevision( $rev, $string ) {
845 if( $rev->rev_id
== $this->page
->page_latest
) {
847 $this->revString
= $string;
853 * Base class for output stream; prints to stdout or buffer or whereever.
856 class DumpMultiWriter
{
857 function DumpMultiWriter( $sinks ) {
858 $this->sinks
= $sinks;
859 $this->count
= count( $sinks );
862 function writeOpenStream( $string ) {
863 for( $i = 0; $i < $this->count
; $i++
) {
864 $this->sinks
[$i]->writeOpenStream( $string );
868 function writeCloseStream( $string ) {
869 for( $i = 0; $i < $this->count
; $i++
) {
870 $this->sinks
[$i]->writeCloseStream( $string );
874 function writeOpenPage( $page, $string ) {
875 for( $i = 0; $i < $this->count
; $i++
) {
876 $this->sinks
[$i]->writeOpenPage( $page, $string );
880 function writeClosePage( $string ) {
881 for( $i = 0; $i < $this->count
; $i++
) {
882 $this->sinks
[$i]->writeClosePage( $string );
886 function writeRevision( $rev, $string ) {
887 for( $i = 0; $i < $this->count
; $i++
) {
888 $this->sinks
[$i]->writeRevision( $rev, $string );
893 function xmlsafe( $string ) {
895 wfProfileIn( $fname );
898 * The page may contain old data which has not been properly normalized.
899 * Invalid UTF-8 sequences or forbidden control characters will make our
900 * XML output invalid, so be sure to strip them out.
902 $string = UtfNormal
::cleanUp( $string );
904 $string = htmlspecialchars( $string );
905 wfProfileOut( $fname );