API * Extra profiling for allpages * better help output
[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 $page = Title::newFromText( wfMsgForContent( 'mainpage' ) );
341 return wfElement( 'base', array(), $page->getFullUrl() );
342 }
343
344 function caseSetting() {
345 global $wgCapitalLinks;
346 // "case-insensitive" option is reserved for future
347 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
348 return wfElement( 'case', array(), $sensitivity );
349 }
350
351 function namespaces() {
352 global $wgContLang;
353 $spaces = " <namespaces>\n";
354 foreach( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
355 $spaces .= ' ' . wfElement( 'namespace', array( 'key' => $ns ), $title ) . "\n";
356 }
357 $spaces .= " </namespaces>";
358 return $spaces;
359 }
360
361 /**
362 * Closes the output stream with the closing root element.
363 * Call when finished dumping things.
364 */
365 function closeStream() {
366 return "</mediawiki>\n";
367 }
368
369
370 /**
371 * Opens a <page> section on the output stream, with data
372 * from the given database row.
373 *
374 * @param object $row
375 * @return string
376 * @access private
377 */
378 function openPage( $row ) {
379 $out = " <page>\n";
380 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
381 $out .= ' ' . wfElementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
382 $out .= ' ' . wfElement( 'id', array(), strval( $row->page_id ) ) . "\n";
383 if( '' != $row->page_restrictions ) {
384 $out .= ' ' . wfElement( 'restrictions', array(),
385 strval( $row->page_restrictions ) ) . "\n";
386 }
387 return $out;
388 }
389
390 /**
391 * Closes a <page> section on the output stream.
392 *
393 * @access private
394 */
395 function closePage() {
396 return " </page>\n";
397 }
398
399 /**
400 * Dumps a <revision> section on the output stream, with
401 * data filled in from the given database row.
402 *
403 * @param object $row
404 * @return string
405 * @access private
406 */
407 function writeRevision( $row ) {
408 $fname = 'WikiExporter::dumpRev';
409 wfProfileIn( $fname );
410
411 $out = " <revision>\n";
412 $out .= " " . wfElement( 'id', null, strval( $row->rev_id ) ) . "\n";
413
414 $ts = wfTimestamp( TS_ISO_8601, $row->rev_timestamp );
415 $out .= " " . wfElement( 'timestamp', null, $ts ) . "\n";
416
417 if( $row->rev_deleted & Revision::DELETED_USER ) {
418 $out .= " " . wfElement( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
419 } else {
420 $out .= " <contributor>\n";
421 if( $row->rev_user ) {
422 $out .= " " . wfElementClean( 'username', null, strval( $row->rev_user_text ) ) . "\n";
423 $out .= " " . wfElement( 'id', null, strval( $row->rev_user ) ) . "\n";
424 } else {
425 $out .= " " . wfElementClean( 'ip', null, strval( $row->rev_user_text ) ) . "\n";
426 }
427 $out .= " </contributor>\n";
428 }
429
430 if( $row->rev_minor_edit ) {
431 $out .= " <minor/>\n";
432 }
433 if( $row->rev_deleted & Revision::DELETED_COMMENT ) {
434 $out .= " " . wfElement( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
435 } elseif( $row->rev_comment != '' ) {
436 $out .= " " . wfElementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
437 }
438
439 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
440 $out .= " " . wfElement( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
441 } elseif( isset( $row->old_text ) ) {
442 // Raw text from the database may have invalid chars
443 $text = strval( Revision::getRevisionText( $row ) );
444 $out .= " " . wfElementClean( 'text',
445 array( 'xml:space' => 'preserve' ),
446 strval( $text ) ) . "\n";
447 } else {
448 // Stub output
449 $out .= " " . wfElement( 'text',
450 array( 'id' => $row->rev_text_id ),
451 "" ) . "\n";
452 }
453
454 $out .= " </revision>\n";
455
456 wfProfileOut( $fname );
457 return $out;
458 }
459
460 }
461
462
463 /**
464 * Base class for output stream; prints to stdout or buffer or whereever.
465 */
466 class DumpOutput {
467 function writeOpenStream( $string ) {
468 $this->write( $string );
469 }
470
471 function writeCloseStream( $string ) {
472 $this->write( $string );
473 }
474
475 function writeOpenPage( $page, $string ) {
476 $this->write( $string );
477 }
478
479 function writeClosePage( $string ) {
480 $this->write( $string );
481 }
482
483 function writeRevision( $rev, $string ) {
484 $this->write( $string );
485 }
486
487 /**
488 * Override to write to a different stream type.
489 * @return bool
490 */
491 function write( $string ) {
492 print $string;
493 }
494 }
495
496 /**
497 * Stream outputter to send data to a file.
498 */
499 class DumpFileOutput extends DumpOutput {
500 var $handle;
501
502 function DumpFileOutput( $file ) {
503 $this->handle = fopen( $file, "wt" );
504 }
505
506 function write( $string ) {
507 fputs( $this->handle, $string );
508 }
509 }
510
511 /**
512 * Stream outputter to send data to a file via some filter program.
513 * Even if compression is available in a library, using a separate
514 * program can allow us to make use of a multi-processor system.
515 */
516 class DumpPipeOutput extends DumpFileOutput {
517 function DumpPipeOutput( $command, $file = null ) {
518 if( !is_null( $file ) ) {
519 $command .= " > " . wfEscapeShellArg( $file );
520 }
521 $this->handle = popen( $command, "w" );
522 }
523 }
524
525 /**
526 * Sends dump output via the gzip compressor.
527 */
528 class DumpGZipOutput extends DumpPipeOutput {
529 function DumpGZipOutput( $file ) {
530 parent::DumpPipeOutput( "gzip", $file );
531 }
532 }
533
534 /**
535 * Sends dump output via the bgzip2 compressor.
536 */
537 class DumpBZip2Output extends DumpPipeOutput {
538 function DumpBZip2Output( $file ) {
539 parent::DumpPipeOutput( "bzip2", $file );
540 }
541 }
542
543 /**
544 * Sends dump output via the p7zip compressor.
545 */
546 class Dump7ZipOutput extends DumpPipeOutput {
547 function Dump7ZipOutput( $file ) {
548 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
549 // Suppress annoying useless crap from p7zip
550 // Unfortunately this could suppress real error messages too
551 $command .= " >/dev/null 2>&1";
552 parent::DumpPipeOutput( $command );
553 }
554 }
555
556
557
558 /**
559 * Dump output filter class.
560 * This just does output filtering and streaming; XML formatting is done
561 * higher up, so be careful in what you do.
562 */
563 class DumpFilter {
564 function DumpFilter( &$sink ) {
565 $this->sink =& $sink;
566 }
567
568 function writeOpenStream( $string ) {
569 $this->sink->writeOpenStream( $string );
570 }
571
572 function writeCloseStream( $string ) {
573 $this->sink->writeCloseStream( $string );
574 }
575
576 function writeOpenPage( $page, $string ) {
577 $this->sendingThisPage = $this->pass( $page, $string );
578 if( $this->sendingThisPage ) {
579 $this->sink->writeOpenPage( $page, $string );
580 }
581 }
582
583 function writeClosePage( $string ) {
584 if( $this->sendingThisPage ) {
585 $this->sink->writeClosePage( $string );
586 $this->sendingThisPage = false;
587 }
588 }
589
590 function writeRevision( $rev, $string ) {
591 if( $this->sendingThisPage ) {
592 $this->sink->writeRevision( $rev, $string );
593 }
594 }
595
596 /**
597 * Override for page-based filter types.
598 * @return bool
599 */
600 function pass( $page, $string ) {
601 return true;
602 }
603 }
604
605 /**
606 * Simple dump output filter to exclude all talk pages.
607 */
608 class DumpNotalkFilter extends DumpFilter {
609 function pass( $page ) {
610 return !Namespace::isTalk( $page->page_namespace );
611 }
612 }
613
614 /**
615 * Dump output filter to include or exclude pages in a given set of namespaces.
616 */
617 class DumpNamespaceFilter extends DumpFilter {
618 var $invert = false;
619 var $namespaces = array();
620
621 function DumpNamespaceFilter( &$sink, $param ) {
622 parent::DumpFilter( $sink );
623
624 $constants = array(
625 "NS_MAIN" => NS_MAIN,
626 "NS_TALK" => NS_TALK,
627 "NS_USER" => NS_USER,
628 "NS_USER_TALK" => NS_USER_TALK,
629 "NS_PROJECT" => NS_PROJECT,
630 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
631 "NS_IMAGE" => NS_IMAGE,
632 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
633 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
634 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
635 "NS_TEMPLATE" => NS_TEMPLATE,
636 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
637 "NS_HELP" => NS_HELP,
638 "NS_HELP_TALK" => NS_HELP_TALK,
639 "NS_CATEGORY" => NS_CATEGORY,
640 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
641
642 if( $param{0} == '!' ) {
643 $this->invert = true;
644 $param = substr( $param, 1 );
645 }
646
647 foreach( explode( ',', $param ) as $key ) {
648 $key = trim( $key );
649 if( isset( $constants[$key] ) ) {
650 $ns = $constants[$key];
651 $this->namespaces[$ns] = true;
652 } elseif( is_numeric( $key ) ) {
653 $ns = intval( $key );
654 $this->namespaces[$ns] = true;
655 } else {
656 throw new MWException( "Unrecognized namespace key '$key'\n" );
657 }
658 }
659 }
660
661 function pass( $page ) {
662 $match = isset( $this->namespaces[$page->page_namespace] );
663 return $this->invert xor $match;
664 }
665 }
666
667
668 /**
669 * Dump output filter to include only the last revision in each page sequence.
670 */
671 class DumpLatestFilter extends DumpFilter {
672 var $page, $pageString, $rev, $revString;
673
674 function writeOpenPage( $page, $string ) {
675 $this->page = $page;
676 $this->pageString = $string;
677 }
678
679 function writeClosePage( $string ) {
680 if( $this->rev ) {
681 $this->sink->writeOpenPage( $this->page, $this->pageString );
682 $this->sink->writeRevision( $this->rev, $this->revString );
683 $this->sink->writeClosePage( $string );
684 }
685 $this->rev = null;
686 $this->revString = null;
687 $this->page = null;
688 $this->pageString = null;
689 }
690
691 function writeRevision( $rev, $string ) {
692 if( $rev->rev_id == $this->page->page_latest ) {
693 $this->rev = $rev;
694 $this->revString = $string;
695 }
696 }
697 }
698
699 /**
700 * Base class for output stream; prints to stdout or buffer or whereever.
701 */
702 class DumpMultiWriter {
703 function DumpMultiWriter( $sinks ) {
704 $this->sinks = $sinks;
705 $this->count = count( $sinks );
706 }
707
708 function writeOpenStream( $string ) {
709 for( $i = 0; $i < $this->count; $i++ ) {
710 $this->sinks[$i]->writeOpenStream( $string );
711 }
712 }
713
714 function writeCloseStream( $string ) {
715 for( $i = 0; $i < $this->count; $i++ ) {
716 $this->sinks[$i]->writeCloseStream( $string );
717 }
718 }
719
720 function writeOpenPage( $page, $string ) {
721 for( $i = 0; $i < $this->count; $i++ ) {
722 $this->sinks[$i]->writeOpenPage( $page, $string );
723 }
724 }
725
726 function writeClosePage( $string ) {
727 for( $i = 0; $i < $this->count; $i++ ) {
728 $this->sinks[$i]->writeClosePage( $string );
729 }
730 }
731
732 function writeRevision( $rev, $string ) {
733 for( $i = 0; $i < $this->count; $i++ ) {
734 $this->sinks[$i]->writeRevision( $rev, $string );
735 }
736 }
737 }
738
739 function xmlsafe( $string ) {
740 $fname = 'xmlsafe';
741 wfProfileIn( $fname );
742
743 /**
744 * The page may contain old data which has not been properly normalized.
745 * Invalid UTF-8 sequences or forbidden control characters will make our
746 * XML output invalid, so be sure to strip them out.
747 */
748 $string = UtfNormal::cleanUp( $string );
749
750 $string = htmlspecialchars( $string );
751 wfProfileOut( $fname );
752 return $string;
753 }
754
755 ?>