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