Fix stupid cockup -> $res->user_text not $res_user_text
[mediawiki.git] / includes / Export.php
blob1e2ad7f7a5ec50b381b2681d9001dbefeb248b90
1 <?php
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 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19 /**
21 * @package MediaWiki
22 * @subpackage SpecialPage
25 /** */
26 require_once( 'Revision.php' );
28 define( 'MW_EXPORT_FULL', 0 );
29 define( 'MW_EXPORT_CURRENT', 1 );
31 define( 'MW_EXPORT_BUFFER', 0 );
32 define( 'MW_EXPORT_STREAM', 1 );
34 define( 'MW_EXPORT_TEXT', 0 );
35 define( 'MW_EXPORT_STUB', 1 );
38 /**
39 * @package MediaWiki
40 * @subpackage SpecialPage
42 class WikiExporter {
44 var $list_authors = false ; # Return distinct author list (when not returning full history)
45 var $author_list = "" ;
47 /**
48 * If using MW_EXPORT_STREAM to stream a large amount of data,
49 * provide a database connection which is not managed by
50 * LoadBalancer to read from: some history blob types will
51 * make additional queries to pull source data while the
52 * main query is still running.
54 * @param Database $db
55 * @param int $history one of MW_EXPORT_FULL or MW_EXPORT_CURRENT
56 * @param int $buffer one of MW_EXPORT_BUFFER or MW_EXPORT_STREAM
58 function WikiExporter( &$db, $history = MW_EXPORT_CURRENT,
59 $buffer = MW_EXPORT_BUFFER, $text = MW_EXPORT_TEXT ) {
60 $this->db =& $db;
61 $this->history = $history;
62 $this->buffer = $buffer;
63 $this->writer = new XmlDumpWriter();
64 $this->sink = new DumpOutput();
65 $this->text = $text;
68 /**
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.
73 * @param mixed $callback
75 function setOutputSink( &$sink ) {
76 $this->sink =& $sink;
79 function openStream() {
80 $output = $this->writer->openStream();
81 $this->sink->writeOpenStream( $output );
84 function closeStream() {
85 $output = $this->writer->closeStream();
86 $this->sink->writeCloseStream( $output );
89 /**
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 function allPages() {
95 return $this->dumpFrom( '' );
98 /**
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 int $start Inclusive lower limit (this id is included)
102 * @param int $end Exclusive upper limit (this id is not included)
103 * If 0, no upper limit.
105 function pagesByRange( $start, $end ) {
106 $condition = 'page_id >= ' . intval( $start );
107 if( $end ) {
108 $condition .= ' AND page_id < ' . intval( $end );
110 return $this->dumpFrom( $condition );
114 * @param Title $title
116 function pageByTitle( $title ) {
117 return $this->dumpFrom(
118 'page_namespace=' . $title->getNamespace() .
119 ' AND page_title=' . $this->db->addQuotes( $title->getDbKey() ) );
122 function pageByName( $name ) {
123 $title = Title::newFromText( $name );
124 if( is_null( $title ) ) {
125 return new WikiError( "Can't export invalid title" );
126 } else {
127 return $this->pageByTitle( $title );
131 function pagesByName( $names ) {
132 foreach( $names as $name ) {
133 $this->pageByName( $name );
138 // -------------------- private implementation below --------------------
140 # Generates the distinct list of authors of an article
141 # Not called by default (depends on $this->list_authors)
142 # Can be set by Special:Export when not exporting whole history
143 function do_list_authors ( $page , $revision , $cond ) {
144 $fname = "do_list_authors" ;
145 wfProfileIn( $fname );
146 $this->author_list = "<contributors>";
147 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
148 $result = $this->db->query( $sql, $fname );
149 $resultset = $this->db->resultObject( $result );
150 while( $row = $resultset->fetchObject() ) {
151 $this->author_list .= "<contributor>" .
152 "<username>" .
153 htmlentities( $row->rev_user_text ) .
154 "</username>" .
155 "<id>" .
156 $row->rev_user .
157 "</id>" .
158 "</contributor>";
160 wfProfileOut( $fname );
161 $this->author_list .= "</contributors>";
164 function dumpFrom( $cond = '' ) {
165 $fname = 'WikiExporter::dumpFrom';
166 wfProfileIn( $fname );
168 $page = $this->db->tableName( 'page' );
169 $revision = $this->db->tableName( 'revision' );
170 $text = $this->db->tableName( 'text' );
172 if( $this->history == MW_EXPORT_FULL ) {
173 $join = 'page_id=rev_page';
174 } elseif( $this->history == MW_EXPORT_CURRENT ) {
175 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
176 $this->do_list_authors ( $page , $revision , $cond );
178 $join = 'page_id=rev_page AND page_latest=rev_id';
179 } else {
180 wfProfileOut( $fname );
181 return new WikiError( "$fname given invalid history dump type." );
183 $where = ( $cond == '' ) ? '' : "$cond AND";
185 if( $this->buffer == MW_EXPORT_STREAM ) {
186 $prev = $this->db->bufferResults( false );
188 if( $cond == '' ) {
189 // Optimization hack for full-database dump
190 $pageindex = 'FORCE INDEX (PRIMARY)';
191 $revindex = 'FORCE INDEX(page_timestamp)';
192 } else {
193 $pageindex = '';
194 $revindex = '';
196 if( $this->text == MW_EXPORT_STUB ) {
197 $sql = "SELECT * FROM
198 $page $pageindex,
199 $revision $revindex
200 WHERE $where $join
201 ORDER BY page_id";
202 } else {
203 $sql = "SELECT * FROM
204 $page $pageindex,
205 $revision $revindex,
206 $text
207 WHERE $where $join AND rev_text_id=old_id
208 ORDER BY page_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
236 * @access private
238 function outputStream( $resultset ) {
239 $last = null;
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 );
250 $last = $row;
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 );
259 $resultset->free();
263 class XmlDumpWriter {
266 * Returns the export schema version.
267 * @return string
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.
281 * @return string
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",
291 'version' => $ver,
292 'xml:lang' => $wgContLanguageCode ),
293 null ) .
294 "\n" .
295 $this->siteInfo();
298 function siteInfo() {
299 $info = array(
300 $this->sitename(),
301 $this->homelink(),
302 $this->generator(),
303 $this->caseSetting(),
304 $this->namespaces() );
305 return " <siteinfo>\n " .
306 implode( "\n ", $info ) .
307 "\n </siteinfo>\n";
310 function sitename() {
311 global $wgSitename;
312 return wfElement( 'sitename', array(), $wgSitename );
315 function generator() {
316 global $wgVersion;
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() {
333 global $wgContLang;
334 $spaces = " <namespaces>\n";
335 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
336 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
338 $spaces .= " </namespaces>";
339 return $spaces;
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.
355 * @param object $row
356 * @return string
357 * @access private
359 function openPage( $row ) {
360 $out = " <page>\n";
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";
368 return $out;
372 * Closes a <page> section on the output stream.
374 * @access private
376 function closePage() {
377 return " </page>\n";
381 * Dumps a <revision> section on the output stream, with
382 * data filled in from the given database row.
384 * @param object $row
385 * @return string
386 * @access private
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 & MW_REV_DELETED_USER ) {
399 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
400 } else {
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";
405 } else {
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 & MW_REV_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 & MW_REV_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";
428 } else {
429 // Stub output
430 $out .= " " . wfElement( 'text',
431 array( 'id' => $row->rev_text_id ),
432 "" ) . "\n";
435 $out .= " </revision>\n";
437 wfProfileOut( $fname );
438 return $out;
445 * Base class for output stream; prints to stdout or buffer or whereever.
447 class DumpOutput {
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.
470 * @return bool
472 function write( $string ) {
473 print $string;
478 * Stream outputter to send data to a file.
480 class DumpFileOutput extends DumpOutput {
481 var $handle;
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 parent::DumpPipeOutput( $command );
537 * Dump output filter class.
538 * This just does output filtering and streaming; XML formatting is done
539 * higher up, so be careful in what you do.
541 class DumpFilter {
542 function DumpFilter( &$sink ) {
543 $this->sink =& $sink;
546 function writeOpenStream( $string ) {
547 $this->sink->writeOpenStream( $string );
550 function writeCloseStream( $string ) {
551 $this->sink->writeCloseStream( $string );
554 function writeOpenPage( $page, $string ) {
555 $this->sendingThisPage = $this->pass( $page, $string );
556 if( $this->sendingThisPage ) {
557 $this->sink->writeOpenPage( $page, $string );
561 function writeClosePage( $string ) {
562 if( $this->sendingThisPage ) {
563 $this->sink->writeClosePage( $string );
564 $this->sendingThisPage = false;
568 function writeRevision( $rev, $string ) {
569 if( $this->sendingThisPage ) {
570 $this->sink->writeRevision( $rev, $string );
575 * Override for page-based filter types.
576 * @return bool
578 function pass( $page, $string ) {
579 return true;
584 * Simple dump output filter to exclude all talk pages.
586 class DumpNotalkFilter extends DumpFilter {
587 function pass( $page ) {
588 return !Namespace::isTalk( $page->page_namespace );
593 * Dump output filter to include or exclude pages in a given set of namespaces.
595 class DumpNamespaceFilter extends DumpFilter {
596 var $invert = false;
597 var $namespaces = array();
599 function DumpNamespaceFilter( &$sink, $param ) {
600 parent::DumpFilter( $sink );
602 $constants = array(
603 "NS_MAIN" => NS_MAIN,
604 "NS_TALK" => NS_TALK,
605 "NS_USER" => NS_USER,
606 "NS_USER_TALK" => NS_USER_TALK,
607 "NS_PROJECT" => NS_PROJECT,
608 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
609 "NS_IMAGE" => NS_IMAGE,
610 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
611 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
612 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
613 "NS_TEMPLATE" => NS_TEMPLATE,
614 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
615 "NS_HELP" => NS_HELP,
616 "NS_HELP_TALK" => NS_HELP_TALK,
617 "NS_CATEGORY" => NS_CATEGORY,
618 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
620 if( $param{0} == '!' ) {
621 $this->invert = true;
622 $param = substr( $param, 1 );
625 foreach( explode( ',', $param ) as $key ) {
626 $key = trim( $key );
627 if( isset( $constants[$key] ) ) {
628 $ns = $constants[$key];
629 $this->namespaces[$ns] = true;
630 } elseif( is_numeric( $key ) ) {
631 $ns = intval( $key );
632 $this->namespaces[$ns] = true;
633 } else {
634 wfDie( "Unrecognized namespace key '$key'\n" );
639 function pass( $page ) {
640 $match = isset( $this->namespaces[$page->page_namespace] );
641 return $this->invert xor $match;
647 * Dump output filter to include only the last revision in each page sequence.
649 class DumpLatestFilter extends DumpFilter {
650 var $page, $pageString, $rev, $revString;
652 function writeOpenPage( $page, $string ) {
653 $this->page = $page;
654 $this->pageString = $string;
657 function writeClosePage( $string ) {
658 if( $this->rev ) {
659 $this->sink->writeOpenPage( $this->page, $this->pageString );
660 $this->sink->writeRevision( $this->rev, $this->revString );
661 $this->sink->writeClosePage( $string );
663 $this->rev = null;
664 $this->revString = null;
665 $this->page = null;
666 $this->pageString = null;
669 function writeRevision( $rev, $string ) {
670 if( $rev->rev_id == $this->page->page_latest ) {
671 $this->rev = $rev;
672 $this->revString = $string;
678 * Base class for output stream; prints to stdout or buffer or whereever.
680 class DumpMultiWriter {
681 function DumpMultiWriter( $sinks ) {
682 $this->sinks = $sinks;
683 $this->count = count( $sinks );
686 function writeOpenStream( $string ) {
687 for( $i = 0; $i < $this->count; $i++ ) {
688 $this->sinks[$i]->writeOpenStream( $string );
692 function writeCloseStream( $string ) {
693 for( $i = 0; $i < $this->count; $i++ ) {
694 $this->sinks[$i]->writeCloseStream( $string );
698 function writeOpenPage( $page, $string ) {
699 for( $i = 0; $i < $this->count; $i++ ) {
700 $this->sinks[$i]->writeOpenPage( $page, $string );
704 function writeClosePage( $string ) {
705 for( $i = 0; $i < $this->count; $i++ ) {
706 $this->sinks[$i]->writeClosePage( $string );
710 function writeRevision( $rev, $string ) {
711 for( $i = 0; $i < $this->count; $i++ ) {
712 $this->sinks[$i]->writeRevision( $rev, $string );
717 function xmlsafe( $string ) {
718 $fname = 'xmlsafe';
719 wfProfileIn( $fname );
722 * The page may contain old data which has not been properly normalized.
723 * Invalid UTF-8 sequences or forbidden control characters will make our
724 * XML output invalid, so be sure to strip them out.
726 $string = UtfNormal::cleanUp( $string );
728 $string = htmlspecialchars( $string );
729 wfProfileOut( $fname );
730 return $string;