AutoLoad Revision
[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
27 define( 'MW_EXPORT_FULL', 0 );
28 define( 'MW_EXPORT_CURRENT', 1 );
29
30 define( 'MW_EXPORT_BUFFER', 0 );
31 define( 'MW_EXPORT_STREAM', 1 );
32
33 define( 'MW_EXPORT_TEXT', 0 );
34 define( 'MW_EXPORT_STUB', 1 );
35
36
37 /**
38 * @package MediaWiki
39 * @subpackage SpecialPage
40 */
41 class WikiExporter {
42
43 var $list_authors = false ; # Return distinct author list (when not returning full history)
44 var $author_list = "" ;
45
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.
52 *
53 * @param Database $db
54 * @param int $history one of MW_EXPORT_FULL or MW_EXPORT_CURRENT
55 * @param int $buffer one of MW_EXPORT_BUFFER or MW_EXPORT_STREAM
56 */
57 function WikiExporter( &$db, $history = MW_EXPORT_CURRENT,
58 $buffer = MW_EXPORT_BUFFER, $text = MW_EXPORT_TEXT ) {
59 $this->db =& $db;
60 $this->history = $history;
61 $this->buffer = $buffer;
62 $this->writer = new XmlDumpWriter();
63 $this->sink = new DumpOutput();
64 $this->text = $text;
65 }
66
67 /**
68 * Set the DumpOutput or DumpFilter object which will receive
69 * various row objects and XML output for filtering. Filters
70 * can be chained or used as callbacks.
71 *
72 * @param mixed $callback
73 */
74 function setOutputSink( &$sink ) {
75 $this->sink =& $sink;
76 }
77
78 function openStream() {
79 $output = $this->writer->openStream();
80 $this->sink->writeOpenStream( $output );
81 }
82
83 function closeStream() {
84 $output = $this->writer->closeStream();
85 $this->sink->writeCloseStream( $output );
86 }
87
88 /**
89 * Dumps a series of page and revision records for all pages
90 * in the database, either including complete history or only
91 * the most recent version.
92 */
93 function allPages() {
94 return $this->dumpFrom( '' );
95 }
96
97 /**
98 * Dumps a series of page and revision records for those pages
99 * in the database falling within the page_id range given.
100 * @param int $start Inclusive lower limit (this id is included)
101 * @param int $end Exclusive upper limit (this id is not included)
102 * If 0, no upper limit.
103 */
104 function pagesByRange( $start, $end ) {
105 $condition = 'page_id >= ' . intval( $start );
106 if( $end ) {
107 $condition .= ' AND page_id < ' . intval( $end );
108 }
109 return $this->dumpFrom( $condition );
110 }
111
112 /**
113 * @param Title $title
114 */
115 function pageByTitle( $title ) {
116 return $this->dumpFrom(
117 'page_namespace=' . $title->getNamespace() .
118 ' AND page_title=' . $this->db->addQuotes( $title->getDbKey() ) );
119 }
120
121 function pageByName( $name ) {
122 $title = Title::newFromText( $name );
123 if( is_null( $title ) ) {
124 return new WikiError( "Can't export invalid title" );
125 } else {
126 return $this->pageByTitle( $title );
127 }
128 }
129
130 function pagesByName( $names ) {
131 foreach( $names as $name ) {
132 $this->pageByName( $name );
133 }
134 }
135
136
137 // -------------------- private implementation below --------------------
138
139 # Generates the distinct list of authors of an article
140 # Not called by default (depends on $this->list_authors)
141 # Can be set by Special:Export when not exporting whole history
142 function do_list_authors ( $page , $revision , $cond ) {
143 $fname = "do_list_authors" ;
144 wfProfileIn( $fname );
145 $this->author_list = "<contributors>";
146 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision} WHERE page_id=rev_page AND " . $cond ;
147 $result = $this->db->query( $sql, $fname );
148 $resultset = $this->db->resultObject( $result );
149 while( $row = $resultset->fetchObject() ) {
150 $this->author_list .= "<contributor>" .
151 "<username>" .
152 htmlentities( $row->rev_user_text ) .
153 "</username>" .
154 "<id>" .
155 $row->rev_user .
156 "</id>" .
157 "</contributor>";
158 }
159 wfProfileOut( $fname );
160 $this->author_list .= "</contributors>";
161 }
162
163 function dumpFrom( $cond = '' ) {
164 $fname = 'WikiExporter::dumpFrom';
165 wfProfileIn( $fname );
166
167 $page = $this->db->tableName( 'page' );
168 $revision = $this->db->tableName( 'revision' );
169 $text = $this->db->tableName( 'text' );
170
171 if( $this->history == MW_EXPORT_FULL ) {
172 $join = 'page_id=rev_page';
173 } elseif( $this->history == MW_EXPORT_CURRENT ) {
174 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
175 $this->do_list_authors ( $page , $revision , $cond );
176 }
177 $join = 'page_id=rev_page AND page_latest=rev_id';
178 } else {
179 wfProfileOut( $fname );
180 return new WikiError( "$fname given invalid history dump type." );
181 }
182 $where = ( $cond == '' ) ? '' : "$cond AND";
183
184 if( $this->buffer == MW_EXPORT_STREAM ) {
185 $prev = $this->db->bufferResults( false );
186 }
187 if( $cond == '' ) {
188 // Optimization hack for full-database dump
189 $revindex = $pageindex = $this->db->useIndexClause("PRIMARY");
190 $straight = ' /*! STRAIGHT_JOIN */ ';
191 } else {
192 $pageindex = '';
193 $revindex = '';
194 $straight = '';
195 }
196 if( $this->text == MW_EXPORT_STUB ) {
197 $sql = "SELECT $straight * FROM
198 $page $pageindex,
199 $revision $revindex
200 WHERE $where $join
201 ORDER BY page_id";
202 } else {
203 $sql = "SELECT $straight * FROM
204 $page $pageindex,
205 $revision $revindex,
206 $text
207 WHERE $where $join AND rev_text_id=old_id
208 ORDER BY page_id";
209 }
210 $result = $this->db->query( $sql, $fname );
211 $wrapper = $this->db->resultObject( $result );
212 $this->outputStream( $wrapper );
213
214 if ( $this->list_authors ) {
215 $this->outputStream( $wrapper );
216 }
217
218 if( $this->buffer == MW_EXPORT_STREAM ) {
219 $this->db->bufferResults( $prev );
220 }
221
222 wfProfileOut( $fname );
223 }
224
225 /**
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.
229 *
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.
234 *
235 * @param ResultWrapper $resultset
236 * @access private
237 */
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 );
247 }
248 $output = $this->writer->openPage( $row );
249 $this->sink->writeOpenPage( $row, $output );
250 $last = $row;
251 }
252 $output = $this->writer->writeRevision( $row );
253 $this->sink->writeRevision( $row, $output );
254 }
255 if( isset( $last ) ) {
256 $output = $this->author_list . $this->writer->closePage();
257 $this->sink->writeClosePage( $output );
258 }
259 $resultset->free();
260 }
261 }
262
263 class XmlDumpWriter {
264
265 /**
266 * Returns the export schema version.
267 * @return string
268 */
269 function schemaVersion() {
270 return "0.3"; // FIXME: upgrade to 0.4 when updated XSD is ready, for the revision deletion bits
271 }
272
273 /**
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.
278 *
279 * Output will be encoded in UTF-8.
280 *
281 * @return string
282 */
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();
296 }
297
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";
308 }
309
310 function sitename() {
311 global $wgSitename;
312 return wfElement( 'sitename', array(), $wgSitename );
313 }
314
315 function generator() {
316 global $wgVersion;
317 return wfElement( 'generator', array(), "MediaWiki $wgVersion" );
318 }
319
320 function homelink() {
321 $page = Title::newFromText( wfMsgForContent( 'mainpage' ) );
322 return wfElement( 'base', array(), $page->getFullUrl() );
323 }
324
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 );
330 }
331
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";
337 }
338 $spaces .= " </namespaces>";
339 return $spaces;
340 }
341
342 /**
343 * Closes the output stream with the closing root element.
344 * Call when finished dumping things.
345 */
346 function closeStream() {
347 return "</mediawiki>\n";
348 }
349
350
351 /**
352 * Opens a <page> section on the output stream, with data
353 * from the given database row.
354 *
355 * @param object $row
356 * @return string
357 * @access private
358 */
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";
367 }
368 return $out;
369 }
370
371 /**
372 * Closes a <page> section on the output stream.
373 *
374 * @access private
375 */
376 function closePage() {
377 return " </page>\n";
378 }
379
380 /**
381 * Dumps a <revision> section on the output stream, with
382 * data filled in from the given database row.
383 *
384 * @param object $row
385 * @return string
386 * @access private
387 */
388 function writeRevision( $row ) {
389 $fname = 'WikiExporter::dumpRev';
390 wfProfileIn( $fname );
391
392 $out = " <revision>\n";
393 $out .= " " . wfElement( 'id', null, strval( $row->rev_id ) ) . "\n";
394
395 $ts = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
396 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
397
398 if( $row->rev_deleted & Revision::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";
407 }
408 $out .= " </contributor>\n";
409 }
410
411 if( $row->rev_minor_edit ) {
412 $out .= " <minor/>\n";
413 }
414 if( $row->rev_deleted & Revision::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";
418 }
419
420 if( $row->rev_deleted & Revision::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";
433 }
434
435 $out .= " </revision>\n";
436
437 wfProfileOut( $fname );
438 return $out;
439 }
440
441 }
442
443
444 /**
445 * Base class for output stream; prints to stdout or buffer or whereever.
446 */
447 class DumpOutput {
448 function writeOpenStream( $string ) {
449 $this->write( $string );
450 }
451
452 function writeCloseStream( $string ) {
453 $this->write( $string );
454 }
455
456 function writeOpenPage( $page, $string ) {
457 $this->write( $string );
458 }
459
460 function writeClosePage( $string ) {
461 $this->write( $string );
462 }
463
464 function writeRevision( $rev, $string ) {
465 $this->write( $string );
466 }
467
468 /**
469 * Override to write to a different stream type.
470 * @return bool
471 */
472 function write( $string ) {
473 print $string;
474 }
475 }
476
477 /**
478 * Stream outputter to send data to a file.
479 */
480 class DumpFileOutput extends DumpOutput {
481 var $handle;
482
483 function DumpFileOutput( $file ) {
484 $this->handle = fopen( $file, "wt" );
485 }
486
487 function write( $string ) {
488 fputs( $this->handle, $string );
489 }
490 }
491
492 /**
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.
496 */
497 class DumpPipeOutput extends DumpFileOutput {
498 function DumpPipeOutput( $command, $file = null ) {
499 if( !is_null( $file ) ) {
500 $command .= " > " . wfEscapeShellArg( $file );
501 }
502 $this->handle = popen( $command, "w" );
503 }
504 }
505
506 /**
507 * Sends dump output via the gzip compressor.
508 */
509 class DumpGZipOutput extends DumpPipeOutput {
510 function DumpGZipOutput( $file ) {
511 parent::DumpPipeOutput( "gzip", $file );
512 }
513 }
514
515 /**
516 * Sends dump output via the bgzip2 compressor.
517 */
518 class DumpBZip2Output extends DumpPipeOutput {
519 function DumpBZip2Output( $file ) {
520 parent::DumpPipeOutput( "bzip2", $file );
521 }
522 }
523
524 /**
525 * Sends dump output via the p7zip compressor.
526 */
527 class Dump7ZipOutput extends DumpPipeOutput {
528 function Dump7ZipOutput( $file ) {
529 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
530 // Suppress annoying useless crap from p7zip
531 // Unfortunately this could suppress real error messages too
532 $command .= " >/dev/null 2>&1";
533 parent::DumpPipeOutput( $command );
534 }
535 }
536
537
538
539 /**
540 * Dump output filter class.
541 * This just does output filtering and streaming; XML formatting is done
542 * higher up, so be careful in what you do.
543 */
544 class DumpFilter {
545 function DumpFilter( &$sink ) {
546 $this->sink =& $sink;
547 }
548
549 function writeOpenStream( $string ) {
550 $this->sink->writeOpenStream( $string );
551 }
552
553 function writeCloseStream( $string ) {
554 $this->sink->writeCloseStream( $string );
555 }
556
557 function writeOpenPage( $page, $string ) {
558 $this->sendingThisPage = $this->pass( $page, $string );
559 if( $this->sendingThisPage ) {
560 $this->sink->writeOpenPage( $page, $string );
561 }
562 }
563
564 function writeClosePage( $string ) {
565 if( $this->sendingThisPage ) {
566 $this->sink->writeClosePage( $string );
567 $this->sendingThisPage = false;
568 }
569 }
570
571 function writeRevision( $rev, $string ) {
572 if( $this->sendingThisPage ) {
573 $this->sink->writeRevision( $rev, $string );
574 }
575 }
576
577 /**
578 * Override for page-based filter types.
579 * @return bool
580 */
581 function pass( $page, $string ) {
582 return true;
583 }
584 }
585
586 /**
587 * Simple dump output filter to exclude all talk pages.
588 */
589 class DumpNotalkFilter extends DumpFilter {
590 function pass( $page ) {
591 return !Namespace::isTalk( $page->page_namespace );
592 }
593 }
594
595 /**
596 * Dump output filter to include or exclude pages in a given set of namespaces.
597 */
598 class DumpNamespaceFilter extends DumpFilter {
599 var $invert = false;
600 var $namespaces = array();
601
602 function DumpNamespaceFilter( &$sink, $param ) {
603 parent::DumpFilter( $sink );
604
605 $constants = array(
606 "NS_MAIN" => NS_MAIN,
607 "NS_TALK" => NS_TALK,
608 "NS_USER" => NS_USER,
609 "NS_USER_TALK" => NS_USER_TALK,
610 "NS_PROJECT" => NS_PROJECT,
611 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
612 "NS_IMAGE" => NS_IMAGE,
613 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
614 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
615 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
616 "NS_TEMPLATE" => NS_TEMPLATE,
617 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
618 "NS_HELP" => NS_HELP,
619 "NS_HELP_TALK" => NS_HELP_TALK,
620 "NS_CATEGORY" => NS_CATEGORY,
621 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
622
623 if( $param{0} == '!' ) {
624 $this->invert = true;
625 $param = substr( $param, 1 );
626 }
627
628 foreach( explode( ',', $param ) as $key ) {
629 $key = trim( $key );
630 if( isset( $constants[$key] ) ) {
631 $ns = $constants[$key];
632 $this->namespaces[$ns] = true;
633 } elseif( is_numeric( $key ) ) {
634 $ns = intval( $key );
635 $this->namespaces[$ns] = true;
636 } else {
637 wfDie( "Unrecognized namespace key '$key'\n" );
638 }
639 }
640 }
641
642 function pass( $page ) {
643 $match = isset( $this->namespaces[$page->page_namespace] );
644 return $this->invert xor $match;
645 }
646 }
647
648
649 /**
650 * Dump output filter to include only the last revision in each page sequence.
651 */
652 class DumpLatestFilter extends DumpFilter {
653 var $page, $pageString, $rev, $revString;
654
655 function writeOpenPage( $page, $string ) {
656 $this->page = $page;
657 $this->pageString = $string;
658 }
659
660 function writeClosePage( $string ) {
661 if( $this->rev ) {
662 $this->sink->writeOpenPage( $this->page, $this->pageString );
663 $this->sink->writeRevision( $this->rev, $this->revString );
664 $this->sink->writeClosePage( $string );
665 }
666 $this->rev = null;
667 $this->revString = null;
668 $this->page = null;
669 $this->pageString = null;
670 }
671
672 function writeRevision( $rev, $string ) {
673 if( $rev->rev_id == $this->page->page_latest ) {
674 $this->rev = $rev;
675 $this->revString = $string;
676 }
677 }
678 }
679
680 /**
681 * Base class for output stream; prints to stdout or buffer or whereever.
682 */
683 class DumpMultiWriter {
684 function DumpMultiWriter( $sinks ) {
685 $this->sinks = $sinks;
686 $this->count = count( $sinks );
687 }
688
689 function writeOpenStream( $string ) {
690 for( $i = 0; $i < $this->count; $i++ ) {
691 $this->sinks[$i]->writeOpenStream( $string );
692 }
693 }
694
695 function writeCloseStream( $string ) {
696 for( $i = 0; $i < $this->count; $i++ ) {
697 $this->sinks[$i]->writeCloseStream( $string );
698 }
699 }
700
701 function writeOpenPage( $page, $string ) {
702 for( $i = 0; $i < $this->count; $i++ ) {
703 $this->sinks[$i]->writeOpenPage( $page, $string );
704 }
705 }
706
707 function writeClosePage( $string ) {
708 for( $i = 0; $i < $this->count; $i++ ) {
709 $this->sinks[$i]->writeClosePage( $string );
710 }
711 }
712
713 function writeRevision( $rev, $string ) {
714 for( $i = 0; $i < $this->count; $i++ ) {
715 $this->sinks[$i]->writeRevision( $rev, $string );
716 }
717 }
718 }
719
720 function xmlsafe( $string ) {
721 $fname = 'xmlsafe';
722 wfProfileIn( $fname );
723
724 /**
725 * The page may contain old data which has not been properly normalized.
726 * Invalid UTF-8 sequences or forbidden control characters will make our
727 * XML output invalid, so be sure to strip them out.
728 */
729 $string = UtfNormal::cleanUp( $string );
730
731 $string = htmlspecialchars( $string );
732 wfProfileOut( $fname );
733 return $string;
734 }
735
736 ?>