* (bug 2587) Fix for section editing with comment prefix
[lhc/web/wiklou.git] / includes / Export.php
1 <?php
2 # Copyright (C) 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
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.
9 #
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.
14 #
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 /**
20 *
21 * @package MediaWiki
22 * @subpackage SpecialPage
23 */
24
25 /** */
26 require_once( 'Revision.php' );
27
28 define( 'MW_EXPORT_FULL', 0 );
29 define( 'MW_EXPORT_CURRENT', 1 );
30
31 define( 'MW_EXPORT_BUFFER', 0 );
32 define( 'MW_EXPORT_STREAM', 1 );
33
34 define( 'MW_EXPORT_TEXT', 0 );
35 define( 'MW_EXPORT_STUB', 1 );
36
37
38 /**
39 * @package MediaWiki
40 * @subpackage SpecialPage
41 */
42 class WikiExporter {
43
44 var $list_authors = false ; # Return distinct author list (when not returning full history)
45 var $author_list = "" ;
46
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.
53 *
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
57 */
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;
66 }
67
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.
72 *
73 * @param mixed $callback
74 */
75 function setOutputSink( &$sink ) {
76 $this->sink =& $sink;
77 }
78
79 function openStream() {
80 $output = $this->writer->openStream();
81 $this->sink->writeOpenStream( $output );
82 }
83
84 function closeStream() {
85 $output = $this->writer->closeStream();
86 $this->sink->writeCloseStream( $output );
87 }
88
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.
93 */
94 function allPages() {
95 return $this->dumpFrom( '' );
96 }
97
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.
104 */
105 function pagesByRange( $start, $end ) {
106 $condition = 'page_id >= ' . intval( $start );
107 if( $end ) {
108 $condition .= ' AND page_id < ' . intval( $end );
109 }
110 return $this->dumpFrom( $condition );
111 }
112
113 /**
114 * @param Title $title
115 */
116 function pageByTitle( $title ) {
117 return $this->dumpFrom(
118 'page_namespace=' . $title->getNamespace() .
119 ' AND page_title=' . $this->db->addQuotes( $title->getDbKey() ) );
120 }
121
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 );
128 }
129 }
130
131 function pagesByName( $names ) {
132 foreach( $names as $name ) {
133 $this->pageByName( $name );
134 }
135 }
136
137
138 // -------------------- private implementation below --------------------
139
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>";
159 }
160 wfProfileOut( $fname );
161 $this->author_list .= "</contributors>";
162 }
163
164 function dumpFrom( $cond = '' ) {
165 $fname = 'WikiExporter::dumpFrom';
166 wfProfileIn( $fname );
167
168 $page = $this->db->tableName( 'page' );
169 $revision = $this->db->tableName( 'revision' );
170 $text = $this->db->tableName( 'text' );
171
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 );
177 }
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." );
182 }
183 $where = ( $cond == '' ) ? '' : "$cond AND";
184
185 if( $this->buffer == MW_EXPORT_STREAM ) {
186 $prev = $this->db->bufferResults( false );
187 }
188 if( $cond == '' ) {
189 // Optimization hack for full-database dump
190 $revindex = $pageindex = $this->db->useIndexClause("PRIMARY");
191 $straight = ' /*! STRAIGHT_JOIN */ ';
192 } else {
193 $pageindex = '';
194 $revindex = '';
195 $straight = '';
196 }
197 if( $this->text == MW_EXPORT_STUB ) {
198 $sql = "SELECT $straight * FROM
199 $page $pageindex,
200 $revision $revindex
201 WHERE $where $join
202 ORDER BY page_id";
203 } else {
204 $sql = "SELECT $straight * FROM
205 $page $pageindex,
206 $revision $revindex,
207 $text
208 WHERE $where $join AND rev_text_id=old_id
209 ORDER BY page_id";
210 }
211 $result = $this->db->query( $sql, $fname );
212 $wrapper = $this->db->resultObject( $result );
213 $this->outputStream( $wrapper );
214
215 if ( $this->list_authors ) {
216 $this->outputStream( $wrapper );
217 }
218
219 if( $this->buffer == MW_EXPORT_STREAM ) {
220 $this->db->bufferResults( $prev );
221 }
222
223 wfProfileOut( $fname );
224 }
225
226 /**
227 * Runs through a query result set dumping page and revision records.
228 * The result set should be sorted/grouped by page to avoid duplicate
229 * page records in the output.
230 *
231 * The result set will be freed once complete. Should be safe for
232 * streaming (non-buffered) queries, as long as it was made on a
233 * separate database connection not managed by LoadBalancer; some
234 * blob storage types will make queries to pull source data.
235 *
236 * @param ResultWrapper $resultset
237 * @access private
238 */
239 function outputStream( $resultset ) {
240 $last = null;
241 while( $row = $resultset->fetchObject() ) {
242 if( is_null( $last ) ||
243 $last->page_namespace != $row->page_namespace ||
244 $last->page_title != $row->page_title ) {
245 if( isset( $last ) ) {
246 $output = $this->writer->closePage();
247 $this->sink->writeClosePage( $output );
248 }
249 $output = $this->writer->openPage( $row );
250 $this->sink->writeOpenPage( $row, $output );
251 $last = $row;
252 }
253 $output = $this->writer->writeRevision( $row );
254 $this->sink->writeRevision( $row, $output );
255 }
256 if( isset( $last ) ) {
257 $output = $this->author_list . $this->writer->closePage();
258 $this->sink->writeClosePage( $output );
259 }
260 $resultset->free();
261 }
262 }
263
264 class XmlDumpWriter {
265
266 /**
267 * Returns the export schema version.
268 * @return string
269 */
270 function schemaVersion() {
271 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
272 }
273
274 /**
275 * Opens the XML output stream's root <mediawiki> element.
276 * This does not include an xml directive, so is safe to include
277 * as a subelement in a larger XML stream. Namespace and XML Schema
278 * references are included.
279 *
280 * Output will be encoded in UTF-8.
281 *
282 * @return string
283 */
284 function openStream() {
285 global $wgContLanguageCode;
286 $ver = $this->schemaVersion();
287 return wfElement( 'mediawiki', array(
288 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
289 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
290 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
291 "http://www.mediawiki.org/xml/export-$ver.xsd",
292 'version' => $ver,
293 'xml:lang' => $wgContLanguageCode ),
294 null ) .
295 "\n" .
296 $this->siteInfo();
297 }
298
299 function siteInfo() {
300 $info = array(
301 $this->sitename(),
302 $this->homelink(),
303 $this->generator(),
304 $this->caseSetting(),
305 $this->namespaces() );
306 return " <siteinfo>\n " .
307 implode( "\n ", $info ) .
308 "\n </siteinfo>\n";
309 }
310
311 function sitename() {
312 global $wgSitename;
313 return wfElement( 'sitename', array(), $wgSitename );
314 }
315
316 function generator() {
317 global $wgVersion;
318 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
319 }
320
321 function homelink() {
322 $page = Title::newFromText( wfMsgForContent( 'mainpage' ) );
323 return wfElement( 'base', array(), $page->getFullUrl() );
324 }
325
326 function caseSetting() {
327 global $wgCapitalLinks;
328 // "case-insensitive" option is reserved for future
329 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
330 return wfElement( 'case', array(), $sensitivity );
331 }
332
333 function namespaces() {
334 global $wgContLang;
335 $spaces = " <namespaces>\n";
336 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
337 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
338 }
339 $spaces .= " </namespaces>";
340 return $spaces;
341 }
342
343 /**
344 * Closes the output stream with the closing root element.
345 * Call when finished dumping things.
346 */
347 function closeStream() {
348 return "</mediawiki>\n";
349 }
350
351
352 /**
353 * Opens a <page> section on the output stream, with data
354 * from the given database row.
355 *
356 * @param object $row
357 * @return string
358 * @access private
359 */
360 function openPage( $row ) {
361 $out = " <page>\n";
362 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
363 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
364 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id ) ) . "\n";
365 if( '' != $row->page_restrictions ) {
366 $out .= ' ' . wfElement( 'restrictions', array(),
367 strval( $row->page_restrictions ) ) . "\n";
368 }
369 return $out;
370 }
371
372 /**
373 * Closes a <page> section on the output stream.
374 *
375 * @access private
376 */
377 function closePage() {
378 return " </page>\n";
379 }
380
381 /**
382 * Dumps a <revision> section on the output stream, with
383 * data filled in from the given database row.
384 *
385 * @param object $row
386 * @return string
387 * @access private
388 */
389 function writeRevision( $row ) {
390 $fname = 'WikiExporter::dumpRev';
391 wfProfileIn( $fname );
392
393 $out = " <revision>\n";
394 $out .= " " . wfElement( 'id', null, strval( $row->rev_id ) ) . "\n";
395
396 $ts = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
397 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
398
399 if( $row->rev_deleted & MW_REV_DELETED_USER ) {
400 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
401 } else {
402 $out .= " <contributor>\n";
403 if( $row->rev_user ) {
404 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text ) ) . "\n";
405 $out .= " " . wfElement( 'id', null, strval( $row->rev_user ) ) . "\n";
406 } else {
407 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text ) ) . "\n";
408 }
409 $out .= " </contributor>\n";
410 }
411
412 if( $row->rev_minor_edit ) {
413 $out .= " <minor/>\n";
414 }
415 if( $row->rev_deleted & MW_REV_DELETED_COMMENT ) {
416 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
417 } elseif( $row->rev_comment != '' ) {
418 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
419 }
420
421 if( $row->rev_deleted & MW_REV_DELETED_TEXT ) {
422 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
423 } elseif( isset( $row->old_text ) ) {
424 // Raw text from the database may have invalid chars
425 $text = strval( Revision::getRevisionText( $row ) );
426 $out .= " " . wfElementClean( 'text',
427 array( 'xml:space' => 'preserve' ),
428 strval( $text ) ) . "\n";
429 } else {
430 // Stub output
431 $out .= " " . wfElement( 'text',
432 array( 'id' => $row->rev_text_id ),
433 "" ) . "\n";
434 }
435
436 $out .= " </revision>\n";
437
438 wfProfileOut( $fname );
439 return $out;
440 }
441
442 }
443
444
445 /**
446 * Base class for output stream; prints to stdout or buffer or whereever.
447 */
448 class DumpOutput {
449 function writeOpenStream( $string ) {
450 $this->write( $string );
451 }
452
453 function writeCloseStream( $string ) {
454 $this->write( $string );
455 }
456
457 function writeOpenPage( $page, $string ) {
458 $this->write( $string );
459 }
460
461 function writeClosePage( $string ) {
462 $this->write( $string );
463 }
464
465 function writeRevision( $rev, $string ) {
466 $this->write( $string );
467 }
468
469 /**
470 * Override to write to a different stream type.
471 * @return bool
472 */
473 function write( $string ) {
474 print $string;
475 }
476 }
477
478 /**
479 * Stream outputter to send data to a file.
480 */
481 class DumpFileOutput extends DumpOutput {
482 var $handle;
483
484 function DumpFileOutput( $file ) {
485 $this->handle = fopen( $file, "wt" );
486 }
487
488 function write( $string ) {
489 fputs( $this->handle, $string );
490 }
491 }
492
493 /**
494 * Stream outputter to send data to a file via some filter program.
495 * Even if compression is available in a library, using a separate
496 * program can allow us to make use of a multi-processor system.
497 */
498 class DumpPipeOutput extends DumpFileOutput {
499 function DumpPipeOutput( $command, $file = null ) {
500 if( !is_null( $file ) ) {
501 $command .= " > " . wfEscapeShellArg( $file );
502 }
503 $this->handle = popen( $command, "w" );
504 }
505 }
506
507 /**
508 * Sends dump output via the gzip compressor.
509 */
510 class DumpGZipOutput extends DumpPipeOutput {
511 function DumpGZipOutput( $file ) {
512 parent::DumpPipeOutput( "gzip", $file );
513 }
514 }
515
516 /**
517 * Sends dump output via the bgzip2 compressor.
518 */
519 class DumpBZip2Output extends DumpPipeOutput {
520 function DumpBZip2Output( $file ) {
521 parent::DumpPipeOutput( "bzip2", $file );
522 }
523 }
524
525 /**
526 * Sends dump output via the p7zip compressor.
527 */
528 class Dump7ZipOutput extends DumpPipeOutput {
529 function Dump7ZipOutput( $file ) {
530 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
531 // Suppress annoying useless crap from p7zip
532 // Unfortunately this could suppress real error messages too
533 $command .= " >/dev/null 2>&1";
534 parent::DumpPipeOutput( $command );
535 }
536 }
537
538
539
540 /**
541 * Dump output filter class.
542 * This just does output filtering and streaming; XML formatting is done
543 * higher up, so be careful in what you do.
544 */
545 class DumpFilter {
546 function DumpFilter( &$sink ) {
547 $this->sink =& $sink;
548 }
549
550 function writeOpenStream( $string ) {
551 $this->sink->writeOpenStream( $string );
552 }
553
554 function writeCloseStream( $string ) {
555 $this->sink->writeCloseStream( $string );
556 }
557
558 function writeOpenPage( $page, $string ) {
559 $this->sendingThisPage = $this->pass( $page, $string );
560 if( $this->sendingThisPage ) {
561 $this->sink->writeOpenPage( $page, $string );
562 }
563 }
564
565 function writeClosePage( $string ) {
566 if( $this->sendingThisPage ) {
567 $this->sink->writeClosePage( $string );
568 $this->sendingThisPage = false;
569 }
570 }
571
572 function writeRevision( $rev, $string ) {
573 if( $this->sendingThisPage ) {
574 $this->sink->writeRevision( $rev, $string );
575 }
576 }
577
578 /**
579 * Override for page-based filter types.
580 * @return bool
581 */
582 function pass( $page, $string ) {
583 return true;
584 }
585 }
586
587 /**
588 * Simple dump output filter to exclude all talk pages.
589 */
590 class DumpNotalkFilter extends DumpFilter {
591 function pass( $page ) {
592 return !Namespace::isTalk( $page->page_namespace );
593 }
594 }
595
596 /**
597 * Dump output filter to include or exclude pages in a given set of namespaces.
598 */
599 class DumpNamespaceFilter extends DumpFilter {
600 var $invert = false;
601 var $namespaces = array();
602
603 function DumpNamespaceFilter( &$sink, $param ) {
604 parent::DumpFilter( $sink );
605
606 $constants = array(
607 "NS_MAIN" => NS_MAIN,
608 "NS_TALK" => NS_TALK,
609 "NS_USER" => NS_USER,
610 "NS_USER_TALK" => NS_USER_TALK,
611 "NS_PROJECT" => NS_PROJECT,
612 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
613 "NS_IMAGE" => NS_IMAGE,
614 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
615 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
616 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
617 "NS_TEMPLATE" => NS_TEMPLATE,
618 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
619 "NS_HELP" => NS_HELP,
620 "NS_HELP_TALK" => NS_HELP_TALK,
621 "NS_CATEGORY" => NS_CATEGORY,
622 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
623
624 if( $param{0} == '!' ) {
625 $this->invert = true;
626 $param = substr( $param, 1 );
627 }
628
629 foreach( explode( ',', $param ) as $key ) {
630 $key = trim( $key );
631 if( isset( $constants[$key] ) ) {
632 $ns = $constants[$key];
633 $this->namespaces[$ns] = true;
634 } elseif( is_numeric( $key ) ) {
635 $ns = intval( $key );
636 $this->namespaces[$ns] = true;
637 } else {
638 wfDie( "Unrecognized namespace key '$key'\n" );
639 }
640 }
641 }
642
643 function pass( $page ) {
644 $match = isset( $this->namespaces[$page->page_namespace] );
645 return $this->invert xor $match;
646 }
647 }
648
649
650 /**
651 * Dump output filter to include only the last revision in each page sequence.
652 */
653 class DumpLatestFilter extends DumpFilter {
654 var $page, $pageString, $rev, $revString;
655
656 function writeOpenPage( $page, $string ) {
657 $this->page = $page;
658 $this->pageString = $string;
659 }
660
661 function writeClosePage( $string ) {
662 if( $this->rev ) {
663 $this->sink->writeOpenPage( $this->page, $this->pageString );
664 $this->sink->writeRevision( $this->rev, $this->revString );
665 $this->sink->writeClosePage( $string );
666 }
667 $this->rev = null;
668 $this->revString = null;
669 $this->page = null;
670 $this->pageString = null;
671 }
672
673 function writeRevision( $rev, $string ) {
674 if( $rev->rev_id == $this->page->page_latest ) {
675 $this->rev = $rev;
676 $this->revString = $string;
677 }
678 }
679 }
680
681 /**
682 * Base class for output stream; prints to stdout or buffer or whereever.
683 */
684 class DumpMultiWriter {
685 function DumpMultiWriter( $sinks ) {
686 $this->sinks = $sinks;
687 $this->count = count( $sinks );
688 }
689
690 function writeOpenStream( $string ) {
691 for( $i = 0; $i < $this->count; $i++ ) {
692 $this->sinks[$i]->writeOpenStream( $string );
693 }
694 }
695
696 function writeCloseStream( $string ) {
697 for( $i = 0; $i < $this->count; $i++ ) {
698 $this->sinks[$i]->writeCloseStream( $string );
699 }
700 }
701
702 function writeOpenPage( $page, $string ) {
703 for( $i = 0; $i < $this->count; $i++ ) {
704 $this->sinks[$i]->writeOpenPage( $page, $string );
705 }
706 }
707
708 function writeClosePage( $string ) {
709 for( $i = 0; $i < $this->count; $i++ ) {
710 $this->sinks[$i]->writeClosePage( $string );
711 }
712 }
713
714 function writeRevision( $rev, $string ) {
715 for( $i = 0; $i < $this->count; $i++ ) {
716 $this->sinks[$i]->writeRevision( $rev, $string );
717 }
718 }
719 }
720
721 function xmlsafe( $string ) {
722 $fname = 'xmlsafe';
723 wfProfileIn( $fname );
724
725 /**
726 * The page may contain old data which has not been properly normalized.
727 * Invalid UTF-8 sequences or forbidden control characters will make our
728 * XML output invalid, so be sure to strip them out.
729 */
730 $string = UtfNormal::cleanUp( $string );
731
732 $string = htmlspecialchars( $string );
733 wfProfileOut( $fname );
734 return $string;
735 }
736
737 ?>