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