Fixed regex in doMagicLinks (broken since r15976)
[mediawiki.git] / includes / Export.php
blob19a6172f138a8c8381e54e4f24ab3b1abdec0b22
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 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19 /**
21 * @package MediaWiki
22 * @subpackage SpecialPage
25 /** */
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 );
37 /**
38 * @package MediaWiki
39 * @subpackage SpecialPage
41 class WikiExporter {
43 var $list_authors = false ; # Return distinct author list (when not returning full history)
44 var $author_list = "" ;
46 /**
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.
53 * @param Database $db
54 * @param mixed $history one of MW_EXPORT_FULL or MW_EXPORT_CURRENT, or an
55 * associative array:
56 * offset: non-inclusive offset at which to start the query
57 * limit: maximum number of rows to return
58 * dir: "asc" or "desc" timestamp order
59 * @param int $buffer one of MW_EXPORT_BUFFER or MW_EXPORT_STREAM
61 function WikiExporter( &$db, $history = MW_EXPORT_CURRENT,
62 $buffer = MW_EXPORT_BUFFER, $text = MW_EXPORT_TEXT ) {
63 $this->db =& $db;
64 $this->history = $history;
65 $this->buffer = $buffer;
66 $this->writer = new XmlDumpWriter();
67 $this->sink = new DumpOutput();
68 $this->text = $text;
71 /**
72 * Set the DumpOutput or DumpFilter object which will receive
73 * various row objects and XML output for filtering. Filters
74 * can be chained or used as callbacks.
76 * @param mixed $callback
78 function setOutputSink( &$sink ) {
79 $this->sink =& $sink;
82 function openStream() {
83 $output = $this->writer->openStream();
84 $this->sink->writeOpenStream( $output );
87 function closeStream() {
88 $output = $this->writer->closeStream();
89 $this->sink->writeCloseStream( $output );
92 /**
93 * Dumps a series of page and revision records for all pages
94 * in the database, either including complete history or only
95 * the most recent version.
97 function allPages() {
98 return $this->dumpFrom( '' );
102 * Dumps a series of page and revision records for those pages
103 * in the database falling within the page_id range given.
104 * @param int $start Inclusive lower limit (this id is included)
105 * @param int $end Exclusive upper limit (this id is not included)
106 * If 0, no upper limit.
108 function pagesByRange( $start, $end ) {
109 $condition = 'page_id >= ' . intval( $start );
110 if( $end ) {
111 $condition .= ' AND page_id < ' . intval( $end );
113 return $this->dumpFrom( $condition );
117 * @param Title $title
119 function pageByTitle( $title ) {
120 return $this->dumpFrom(
121 'page_namespace=' . $title->getNamespace() .
122 ' AND page_title=' . $this->db->addQuotes( $title->getDbKey() ) );
125 function pageByName( $name ) {
126 $title = Title::newFromText( $name );
127 if( is_null( $title ) ) {
128 return new WikiError( "Can't export invalid title" );
129 } else {
130 return $this->pageByTitle( $title );
134 function pagesByName( $names ) {
135 foreach( $names as $name ) {
136 $this->pageByName( $name );
141 // -------------------- private implementation below --------------------
143 # Generates the distinct list of authors of an article
144 # Not called by default (depends on $this->list_authors)
145 # Can be set by Special:Export when not exporting whole history
146 function do_list_authors ( $page , $revision , $cond ) {
147 $fname = "do_list_authors" ;
148 wfProfileIn( $fname );
149 $this->author_list = "<contributors>";
150 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
151 $result = $this->db->query( $sql, $fname );
152 $resultset = $this->db->resultObject( $result );
153 while( $row = $resultset->fetchObject() ) {
154 $this->author_list .= "<contributor>" .
155 "<username>" .
156 htmlentities( $row->rev_user_text ) .
157 "</username>" .
158 "<id>" .
159 $row->rev_user .
160 "</id>" .
161 "</contributor>";
163 wfProfileOut( $fname );
164 $this->author_list .= "</contributors>";
167 function dumpFrom( $cond = '' ) {
168 $fname = 'WikiExporter::dumpFrom';
169 wfProfileIn( $fname );
171 $page = $this->db->tableName( 'page' );
172 $revision = $this->db->tableName( 'revision' );
173 $text = $this->db->tableName( 'text' );
175 $order = 'ORDER BY page_id';
176 $limit = '';
178 if( $this->history == MW_EXPORT_FULL ) {
179 $join = 'page_id=rev_page';
180 } elseif( $this->history == MW_EXPORT_CURRENT ) {
181 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
182 $this->do_list_authors ( $page , $revision , $cond );
184 $join = 'page_id=rev_page AND page_latest=rev_id';
185 } elseif ( is_array( $this->history ) ) {
186 $join = 'page_id=rev_page';
187 if ( $this->history['dir'] == 'asc' ) {
188 $op = '>';
189 $order .= ', rev_timestamp';
190 } else {
191 $op = '<';
192 $order .= ', rev_timestamp DESC';
194 if ( !empty( $this->history['offset'] ) ) {
195 $join .= " AND rev_timestamp $op " . $this->db->addQuotes(
196 $this->db->timestamp( $this->history['offset'] ) );
198 if ( !empty( $this->history['limit'] ) ) {
199 $limitNum = intval( $this->history['limit'] );
200 if ( $limitNum > 0 ) {
201 $limit = "LIMIT $limitNum";
204 } else {
205 wfProfileOut( $fname );
206 return new WikiError( "$fname given invalid history dump type." );
208 $where = ( $cond == '' ) ? '' : "$cond AND";
210 if( $this->buffer == MW_EXPORT_STREAM ) {
211 $prev = $this->db->bufferResults( false );
213 if( $cond == '' ) {
214 // Optimization hack for full-database dump
215 $revindex = $pageindex = $this->db->useIndexClause("PRIMARY");
216 $straight = ' /*! STRAIGHT_JOIN */ ';
217 } else {
218 $pageindex = '';
219 $revindex = '';
220 $straight = '';
222 if( $this->text == MW_EXPORT_STUB ) {
223 $sql = "SELECT $straight * FROM
224 $page $pageindex,
225 $revision $revindex
226 WHERE $where $join
227 $order $limit";
228 } else {
229 $sql = "SELECT $straight * FROM
230 $page $pageindex,
231 $revision $revindex,
232 $text
233 WHERE $where $join AND rev_text_id=old_id
234 $order $limit";
236 $result = $this->db->query( $sql, $fname );
237 $wrapper = $this->db->resultObject( $result );
238 $this->outputStream( $wrapper );
240 if ( $this->list_authors ) {
241 $this->outputStream( $wrapper );
244 if( $this->buffer == MW_EXPORT_STREAM ) {
245 $this->db->bufferResults( $prev );
248 wfProfileOut( $fname );
252 * Runs through a query result set dumping page and revision records.
253 * The result set should be sorted/grouped by page to avoid duplicate
254 * page records in the output.
256 * The result set will be freed once complete. Should be safe for
257 * streaming (non-buffered) queries, as long as it was made on a
258 * separate database connection not managed by LoadBalancer; some
259 * blob storage types will make queries to pull source data.
261 * @param ResultWrapper $resultset
262 * @access private
264 function outputStream( $resultset ) {
265 $last = null;
266 while( $row = $resultset->fetchObject() ) {
267 if( is_null( $last ) ||
268 $last->page_namespace != $row->page_namespace ||
269 $last->page_title != $row->page_title ) {
270 if( isset( $last ) ) {
271 $output = $this->writer->closePage();
272 $this->sink->writeClosePage( $output );
274 $output = $this->writer->openPage( $row );
275 $this->sink->writeOpenPage( $row, $output );
276 $last = $row;
278 $output = $this->writer->writeRevision( $row );
279 $this->sink->writeRevision( $row, $output );
281 if( isset( $last ) ) {
282 $output = $this->author_list . $this->writer->closePage();
283 $this->sink->writeClosePage( $output );
285 $resultset->free();
289 class XmlDumpWriter {
292 * Returns the export schema version.
293 * @return string
295 function schemaVersion() {
296 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
300 * Opens the XML output stream's root <mediawiki> element.
301 * This does not include an xml directive, so is safe to include
302 * as a subelement in a larger XML stream. Namespace and XML Schema
303 * references are included.
305 * Output will be encoded in UTF-8.
307 * @return string
309 function openStream() {
310 global $wgContLanguageCode;
311 $ver = $this->schemaVersion();
312 return wfElement( 'mediawiki', array(
313 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
314 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
315 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
316 "http://www.mediawiki.org/xml/export-$ver.xsd",
317 'version' => $ver,
318 'xml:lang' => $wgContLanguageCode ),
319 null ) .
320 "\n" .
321 $this->siteInfo();
324 function siteInfo() {
325 $info = array(
326 $this->sitename(),
327 $this->homelink(),
328 $this->generator(),
329 $this->caseSetting(),
330 $this->namespaces() );
331 return " <siteinfo>\n " .
332 implode( "\n ", $info ) .
333 "\n </siteinfo>\n";
336 function sitename() {
337 global $wgSitename;
338 return wfElement( 'sitename', array(), $wgSitename );
341 function generator() {
342 global $wgVersion;
343 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
346 function homelink() {
347 $page = Title::newFromText( wfMsgForContent( 'mainpage' ) );
348 return wfElement( 'base', array(), $page->getFullUrl() );
351 function caseSetting() {
352 global $wgCapitalLinks;
353 // "case-insensitive" option is reserved for future
354 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
355 return wfElement( 'case', array(), $sensitivity );
358 function namespaces() {
359 global $wgContLang;
360 $spaces = " <namespaces>\n";
361 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
362 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
364 $spaces .= " </namespaces>";
365 return $spaces;
369 * Closes the output stream with the closing root element.
370 * Call when finished dumping things.
372 function closeStream() {
373 return "</mediawiki>\n";
378 * Opens a <page> section on the output stream, with data
379 * from the given database row.
381 * @param object $row
382 * @return string
383 * @access private
385 function openPage( $row ) {
386 $out = " <page>\n";
387 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
388 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
389 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id ) ) . "\n";
390 if( '' != $row->page_restrictions ) {
391 $out .= ' ' . wfElement( 'restrictions', array(),
392 strval( $row->page_restrictions ) ) . "\n";
394 return $out;
398 * Closes a <page> section on the output stream.
400 * @access private
402 function closePage() {
403 return " </page>\n";
407 * Dumps a <revision> section on the output stream, with
408 * data filled in from the given database row.
410 * @param object $row
411 * @return string
412 * @access private
414 function writeRevision( $row ) {
415 $fname = 'WikiExporter::dumpRev';
416 wfProfileIn( $fname );
418 $out = " <revision>\n";
419 $out .= " " . wfElement( 'id', null, strval( $row->rev_id ) ) . "\n";
421 $ts = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
422 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
424 if( $row->rev_deleted & Revision::DELETED_USER ) {
425 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
426 } else {
427 $out .= " <contributor>\n";
428 if( $row->rev_user ) {
429 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text ) ) . "\n";
430 $out .= " " . wfElement( 'id', null, strval( $row->rev_user ) ) . "\n";
431 } else {
432 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text ) ) . "\n";
434 $out .= " </contributor>\n";
437 if( $row->rev_minor_edit ) {
438 $out .= " <minor/>\n";
440 if( $row->rev_deleted & Revision::DELETED_COMMENT ) {
441 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
442 } elseif( $row->rev_comment != '' ) {
443 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
446 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
447 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
448 } elseif( isset( $row->old_text ) ) {
449 // Raw text from the database may have invalid chars
450 $text = strval( Revision::getRevisionText( $row ) );
451 $out .= " " . wfElementClean( 'text',
452 array( 'xml:space' => 'preserve' ),
453 strval( $text ) ) . "\n";
454 } else {
455 // Stub output
456 $out .= " " . wfElement( 'text',
457 array( 'id' => $row->rev_text_id ),
458 "" ) . "\n";
461 $out .= " </revision>\n";
463 wfProfileOut( $fname );
464 return $out;
471 * Base class for output stream; prints to stdout or buffer or whereever.
473 class DumpOutput {
474 function writeOpenStream( $string ) {
475 $this->write( $string );
478 function writeCloseStream( $string ) {
479 $this->write( $string );
482 function writeOpenPage( $page, $string ) {
483 $this->write( $string );
486 function writeClosePage( $string ) {
487 $this->write( $string );
490 function writeRevision( $rev, $string ) {
491 $this->write( $string );
495 * Override to write to a different stream type.
496 * @return bool
498 function write( $string ) {
499 print $string;
504 * Stream outputter to send data to a file.
506 class DumpFileOutput extends DumpOutput {
507 var $handle;
509 function DumpFileOutput( $file ) {
510 $this->handle = fopen( $file, "wt" );
513 function write( $string ) {
514 fputs( $this->handle, $string );
519 * Stream outputter to send data to a file via some filter program.
520 * Even if compression is available in a library, using a separate
521 * program can allow us to make use of a multi-processor system.
523 class DumpPipeOutput extends DumpFileOutput {
524 function DumpPipeOutput( $command, $file = null ) {
525 if( !is_null( $file ) ) {
526 $command .= " > " . wfEscapeShellArg( $file );
528 $this->handle = popen( $command, "w" );
533 * Sends dump output via the gzip compressor.
535 class DumpGZipOutput extends DumpPipeOutput {
536 function DumpGZipOutput( $file ) {
537 parent::DumpPipeOutput( "gzip", $file );
542 * Sends dump output via the bgzip2 compressor.
544 class DumpBZip2Output extends DumpPipeOutput {
545 function DumpBZip2Output( $file ) {
546 parent::DumpPipeOutput( "bzip2", $file );
551 * Sends dump output via the p7zip compressor.
553 class Dump7ZipOutput extends DumpPipeOutput {
554 function Dump7ZipOutput( $file ) {
555 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
556 // Suppress annoying useless crap from p7zip
557 // Unfortunately this could suppress real error messages too
558 $command .= " >/dev/null 2>&1";
559 parent::DumpPipeOutput( $command );
566 * Dump output filter class.
567 * This just does output filtering and streaming; XML formatting is done
568 * higher up, so be careful in what you do.
570 class DumpFilter {
571 function DumpFilter( &$sink ) {
572 $this->sink =& $sink;
575 function writeOpenStream( $string ) {
576 $this->sink->writeOpenStream( $string );
579 function writeCloseStream( $string ) {
580 $this->sink->writeCloseStream( $string );
583 function writeOpenPage( $page, $string ) {
584 $this->sendingThisPage = $this->pass( $page, $string );
585 if( $this->sendingThisPage ) {
586 $this->sink->writeOpenPage( $page, $string );
590 function writeClosePage( $string ) {
591 if( $this->sendingThisPage ) {
592 $this->sink->writeClosePage( $string );
593 $this->sendingThisPage = false;
597 function writeRevision( $rev, $string ) {
598 if( $this->sendingThisPage ) {
599 $this->sink->writeRevision( $rev, $string );
604 * Override for page-based filter types.
605 * @return bool
607 function pass( $page, $string ) {
608 return true;
613 * Simple dump output filter to exclude all talk pages.
615 class DumpNotalkFilter extends DumpFilter {
616 function pass( $page ) {
617 return !Namespace::isTalk( $page->page_namespace );
622 * Dump output filter to include or exclude pages in a given set of namespaces.
624 class DumpNamespaceFilter extends DumpFilter {
625 var $invert = false;
626 var $namespaces = array();
628 function DumpNamespaceFilter( &$sink, $param ) {
629 parent::DumpFilter( $sink );
631 $constants = array(
632 "NS_MAIN" => NS_MAIN,
633 "NS_TALK" => NS_TALK,
634 "NS_USER" => NS_USER,
635 "NS_USER_TALK" => NS_USER_TALK,
636 "NS_PROJECT" => NS_PROJECT,
637 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
638 "NS_IMAGE" => NS_IMAGE,
639 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
640 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
641 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
642 "NS_TEMPLATE" => NS_TEMPLATE,
643 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
644 "NS_HELP" => NS_HELP,
645 "NS_HELP_TALK" => NS_HELP_TALK,
646 "NS_CATEGORY" => NS_CATEGORY,
647 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
649 if( $param{0} == '!' ) {
650 $this->invert = true;
651 $param = substr( $param, 1 );
654 foreach( explode( ',', $param ) as $key ) {
655 $key = trim( $key );
656 if( isset( $constants[$key] ) ) {
657 $ns = $constants[$key];
658 $this->namespaces[$ns] = true;
659 } elseif( is_numeric( $key ) ) {
660 $ns = intval( $key );
661 $this->namespaces[$ns] = true;
662 } else {
663 throw new MWException( "Unrecognized namespace key '$key'\n" );
668 function pass( $page ) {
669 $match = isset( $this->namespaces[$page->page_namespace] );
670 return $this->invert xor $match;
676 * Dump output filter to include only the last revision in each page sequence.
678 class DumpLatestFilter extends DumpFilter {
679 var $page, $pageString, $rev, $revString;
681 function writeOpenPage( $page, $string ) {
682 $this->page = $page;
683 $this->pageString = $string;
686 function writeClosePage( $string ) {
687 if( $this->rev ) {
688 $this->sink->writeOpenPage( $this->page, $this->pageString );
689 $this->sink->writeRevision( $this->rev, $this->revString );
690 $this->sink->writeClosePage( $string );
692 $this->rev = null;
693 $this->revString = null;
694 $this->page = null;
695 $this->pageString = null;
698 function writeRevision( $rev, $string ) {
699 if( $rev->rev_id == $this->page->page_latest ) {
700 $this->rev = $rev;
701 $this->revString = $string;
707 * Base class for output stream; prints to stdout or buffer or whereever.
709 class DumpMultiWriter {
710 function DumpMultiWriter( $sinks ) {
711 $this->sinks = $sinks;
712 $this->count = count( $sinks );
715 function writeOpenStream( $string ) {
716 for( $i = 0; $i < $this->count; $i++ ) {
717 $this->sinks[$i]->writeOpenStream( $string );
721 function writeCloseStream( $string ) {
722 for( $i = 0; $i < $this->count; $i++ ) {
723 $this->sinks[$i]->writeCloseStream( $string );
727 function writeOpenPage( $page, $string ) {
728 for( $i = 0; $i < $this->count; $i++ ) {
729 $this->sinks[$i]->writeOpenPage( $page, $string );
733 function writeClosePage( $string ) {
734 for( $i = 0; $i < $this->count; $i++ ) {
735 $this->sinks[$i]->writeClosePage( $string );
739 function writeRevision( $rev, $string ) {
740 for( $i = 0; $i < $this->count; $i++ ) {
741 $this->sinks[$i]->writeRevision( $rev, $string );
746 function xmlsafe( $string ) {
747 $fname = 'xmlsafe';
748 wfProfileIn( $fname );
751 * The page may contain old data which has not been properly normalized.
752 * Invalid UTF-8 sequences or forbidden control characters will make our
753 * XML output invalid, so be sure to strip them out.
755 $string = UtfNormal::cleanUp( $string );
757 $string = htmlspecialchars( $string );
758 wfProfileOut( $fname );
759 return $string;