Second part of bug bug 22881: Allow exporting files along with the XML as mimepart...
[lhc/web/wiklou.git] / includes / Export.php
1 <?php
2 /**
3 * Base classes for dumps and export
4 *
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25
26 /**
27 * @defgroup Dump Dump
28 */
29
30 /**
31 * @ingroup SpecialPage Dump
32 */
33 class WikiExporter {
34 var $list_authors = false ; # Return distinct author list (when not returning full history)
35 var $author_list = "" ;
36
37 var $dumpUploads = false;
38 var $multiPart = false;
39 var $files = array();
40
41 const FULL = 1;
42 const CURRENT = 2;
43 const STABLE = 4; // extension defined
44 const LOGS = 8;
45
46 const BUFFER = 0;
47 const STREAM = 1;
48
49 const TEXT = 0;
50 const STUB = 1;
51
52 /**
53 * If using WikiExporter::STREAM to stream a large amount of data,
54 * provide a database connection which is not managed by
55 * LoadBalancer to read from: some history blob types will
56 * make additional queries to pull source data while the
57 * main query is still running.
58 *
59 * @param $db Database
60 * @param $history Mixed: one of WikiExporter::FULL or WikiExporter::CURRENT,
61 * or an associative array:
62 * offset: non-inclusive offset at which to start the query
63 * limit: maximum number of rows to return
64 * dir: "asc" or "desc" timestamp order
65 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
66 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
67 */
68 function __construct( &$db, $history = WikiExporter::CURRENT,
69 $buffer = WikiExporter::BUFFER, $text = WikiExporter::TEXT ) {
70 $this->db =& $db;
71 $this->history = $history;
72 $this->buffer = $buffer;
73 $this->writer = new XmlDumpWriter();
74 $this->sink = new DumpOutput();
75 $this->text = $text;
76 }
77
78 /**
79 * Set the DumpOutput or DumpFilter object which will receive
80 * various row objects and XML output for filtering. Filters
81 * can be chained or used as callbacks.
82 *
83 * @param $sink mixed
84 */
85 public function setOutputSink( &$sink ) {
86 $this->sink =& $sink;
87 }
88
89 public function openStream() {
90 $output = $this->writer->openStream();
91
92 if ( $this->multiPart ) {
93 $this->openMultipart();
94 $this->sink->write( $output );
95 } else {
96 $this->sink->writeOpenStream( $output );
97 }
98 }
99
100 public function closeStream() {
101 $output = $this->writer->closeStream();
102 if ( $this->multiPart ) {
103 $this->sink->write( $output );
104 $this->closeMultipart();
105 } else {
106 $this->sink->writeCloseStream( $output );
107 }
108 }
109
110 /**
111 * Dumps a series of page and revision records for all pages
112 * in the database, either including complete history or only
113 * the most recent version.
114 */
115 public function allPages() {
116 return $this->dumpFrom( '' );
117 }
118
119 /**
120 * Dumps a series of page and revision records for those pages
121 * in the database falling within the page_id range given.
122 * @param $start Int: inclusive lower limit (this id is included)
123 * @param $end Int: Exclusive upper limit (this id is not included)
124 * If 0, no upper limit.
125 */
126 public function pagesByRange( $start, $end ) {
127 $condition = 'page_id >= ' . intval( $start );
128 if ( $end ) {
129 $condition .= ' AND page_id < ' . intval( $end );
130 }
131 return $this->dumpFrom( $condition );
132 }
133
134 /**
135 * @param $title Title
136 */
137 public function pageByTitle( $title ) {
138 return $this->dumpFrom(
139 'page_namespace=' . $title->getNamespace() .
140 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
141 }
142
143 public function pageByName( $name ) {
144 $title = Title::newFromText( $name );
145 if ( is_null( $title ) ) {
146 throw new MWException( "Can't export invalid title" );
147 } else {
148 return $this->pageByTitle( $title );
149 }
150 }
151
152 public function pagesByName( $names ) {
153 foreach ( $names as $name ) {
154 $this->pageByName( $name );
155 }
156 }
157
158 public function allLogs() {
159 return $this->dumpFrom( '' );
160 }
161
162 public function logsByRange( $start, $end ) {
163 $condition = 'log_id >= ' . intval( $start );
164 if ( $end ) {
165 $condition .= ' AND log_id < ' . intval( $end );
166 }
167 return $this->dumpFrom( $condition );
168 }
169
170 # Generates the distinct list of authors of an article
171 # Not called by default (depends on $this->list_authors)
172 # Can be set by Special:Export when not exporting whole history
173 protected function do_list_authors( $page , $revision , $cond ) {
174 wfProfileIn( __METHOD__ );
175 $this->author_list = "<contributors>";
176 // rev_deleted
177 $nothidden = '(' . $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ') = 0';
178
179 $sql = "SELECT DISTINCT rev_user_text,rev_user FROM {$page},{$revision}
180 WHERE page_id=rev_page AND $nothidden AND " . $cond ;
181 $result = $this->db->query( $sql, __METHOD__ );
182 $resultset = $this->db->resultObject( $result );
183 foreach ( $resultset as $row ) {
184 $this->author_list .= "<contributor>" .
185 "<username>" .
186 htmlentities( $row->rev_user_text ) .
187 "</username>" .
188 "<id>" .
189 $row->rev_user .
190 "</id>" .
191 "</contributor>";
192 }
193 $this->author_list .= "</contributors>";
194 wfProfileOut( __METHOD__ );
195 }
196
197 protected function dumpFrom( $cond = '' ) {
198 wfProfileIn( __METHOD__ );
199 # For logging dumps...
200 if ( $this->history & self::LOGS ) {
201 if ( $this->buffer == WikiExporter::STREAM ) {
202 $prev = $this->db->bufferResults( false );
203 }
204 $where = array( 'user_id = log_user' );
205 # Hide private logs
206 $hideLogs = LogEventsList::getExcludeClause( $this->db );
207 if ( $hideLogs ) $where[] = $hideLogs;
208 # Add on any caller specified conditions
209 if ( $cond ) $where[] = $cond;
210 # Get logging table name for logging.* clause
211 $logging = $this->db->tableName( 'logging' );
212 $result = $this->db->select( array( 'logging', 'user' ),
213 array( "{$logging}.*", 'user_name' ), // grab the user name
214 $where,
215 __METHOD__,
216 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
217 );
218 $wrapper = $this->db->resultObject( $result );
219 $this->outputLogStream( $wrapper );
220 if ( $this->buffer == WikiExporter::STREAM ) {
221 $this->db->bufferResults( $prev );
222 }
223 # For page dumps...
224 } else {
225 $tables = array( 'page', 'revision' );
226 $opts = array( 'ORDER BY' => 'page_id ASC' );
227 $opts['USE INDEX'] = array();
228 $join = array();
229 if ( is_array( $this->history ) ) {
230 # Time offset/limit for all pages/history...
231 $revJoin = 'page_id=rev_page';
232 # Set time order
233 if ( $this->history['dir'] == 'asc' ) {
234 $op = '>';
235 $opts['ORDER BY'] = 'rev_timestamp ASC';
236 } else {
237 $op = '<';
238 $opts['ORDER BY'] = 'rev_timestamp DESC';
239 }
240 # Set offset
241 if ( !empty( $this->history['offset'] ) ) {
242 $revJoin .= " AND rev_timestamp $op " .
243 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
244 }
245 $join['revision'] = array( 'INNER JOIN', $revJoin );
246 # Set query limit
247 if ( !empty( $this->history['limit'] ) ) {
248 $opts['LIMIT'] = intval( $this->history['limit'] );
249 }
250 } elseif ( $this->history & WikiExporter::FULL ) {
251 # Full history dumps...
252 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
253 } elseif ( $this->history & WikiExporter::CURRENT ) {
254 # Latest revision dumps...
255 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
256 list( $page, $revision ) = $this->db->tableNamesN( 'page', 'revision' );
257 $this->do_list_authors( $page, $revision, $cond );
258 }
259 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
260 } elseif ( $this->history & WikiExporter::STABLE ) {
261 # "Stable" revision dumps...
262 # Default JOIN, to be overridden...
263 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
264 # One, and only one hook should set this, and return false
265 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
266 wfProfileOut( __METHOD__ );
267 throw new MWException( __METHOD__ . " given invalid history dump type." );
268 }
269 } else {
270 # Uknown history specification parameter?
271 wfProfileOut( __METHOD__ );
272 throw new MWException( __METHOD__ . " given invalid history dump type." );
273 }
274 # Query optimization hacks
275 if ( $cond == '' ) {
276 $opts[] = 'STRAIGHT_JOIN';
277 $opts['USE INDEX']['page'] = 'PRIMARY';
278 }
279 # Build text join options
280 if ( $this->text != WikiExporter::STUB ) { // 1-pass
281 $tables[] = 'text';
282 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
283 }
284
285 if ( $this->buffer == WikiExporter::STREAM ) {
286 $prev = $this->db->bufferResults( false );
287 }
288
289 wfRunHooks( 'ModifyExportQuery',
290 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
291
292 # Do the query!
293 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
294 $wrapper = $this->db->resultObject( $result );
295 # Output dump results
296 $this->outputPageStream( $wrapper );
297 if ( $this->list_authors ) {
298 $this->outputPageStream( $wrapper );
299 }
300
301 if ( $this->buffer == WikiExporter::STREAM ) {
302 $this->db->bufferResults( $prev );
303 }
304 }
305 wfProfileOut( __METHOD__ );
306 }
307
308 /**
309 * Runs through a query result set dumping page and revision records.
310 * The result set should be sorted/grouped by page to avoid duplicate
311 * page records in the output.
312 *
313 * The result set will be freed once complete. Should be safe for
314 * streaming (non-buffered) queries, as long as it was made on a
315 * separate database connection not managed by LoadBalancer; some
316 * blob storage types will make queries to pull source data.
317 *
318 * @param $resultset ResultWrapper
319 */
320 protected function outputPageStream( $resultset ) {
321 $last = null;
322 foreach ( $resultset as $row ) {
323 if ( is_null( $last ) ||
324 $last->page_namespace != $row->page_namespace ||
325 $last->page_title != $row->page_title ) {
326 if ( isset( $last ) ) {
327 $output = '';
328 if ( $this->dumpUploads ) {
329 $output .= $this->writer->writeUploads( $last );
330 $this->attachUploads( $last );
331 }
332 $output .= $this->writer->closePage();
333 $this->sink->writeClosePage( $output );
334 }
335 $output = $this->writer->openPage( $row );
336 $this->sink->writeOpenPage( $row, $output );
337 $last = $row;
338 }
339 $output = $this->writer->writeRevision( $row );
340 $this->sink->writeRevision( $row, $output );
341 }
342 if ( isset( $last ) ) {
343 $output = '';
344 if ( $this->dumpUploads ) {
345 $output .= $this->writer->writeUploads( $last );
346 $this->attachUploads( $last );
347 }
348 $output .= $this->author_list;
349 $output .= $this->writer->closePage();
350 $this->sink->writeClosePage( $output );
351 }
352 }
353
354 protected function outputLogStream( $resultset ) {
355 foreach ( $resultset as $row ) {
356 $output = $this->writer->writeLogItem( $row );
357 $this->sink->writeLogItem( $row, $output );
358 }
359 }
360
361 protected function attachUploads( $row ) {
362 $title = Title::newFromRow( $row );
363 $file = wfLocalFile( $title );
364 $this->files[] = $file;
365 $this->files = array_merge( $this->files, $file->getHistory() );
366 }
367
368 protected function openMultipart() {
369 # Multipart boundary purposely invalid XML
370 $this->boundary = '<' . dechex( mt_rand() ) . dechex( mt_rand() ) . '<';
371 $this->sink->writeOpenStream(
372 "Content-Type: multipart/related; boundary={$this->boundary};" .
373 " type=text/xml\n\n" .
374 "--{$this->boundary}\nContent-Type: text/xml\n\n"
375 );
376 }
377
378 protected function closeMultipart() {
379 $output = '';
380
381 foreach ( $this->files as $file ) {
382 $output .= "\n--{$this->boundary}\n" .
383 'Content-Type: ' . $file->getMimeType() . "\n" .
384 'Content-ID: ' . $file->getRel() . "\n" .
385 'Content-Length: ' . $file->getSize() . "\n" .
386 'X-Sha1Base36: ' . $file->getSha1() . "\n\n";
387 $this->sink->write( $output );
388 $this->sink->write( file_get_contents( $file->getPath() ) );
389 }
390 $this->sink->writeCloseStream( "\n--{$this->boundary}\n" );
391 }
392 }
393
394 /**
395 * @ingroup Dump
396 */
397 class XmlDumpWriter {
398
399 /**
400 * Returns the export schema version.
401 * @return string
402 */
403 function schemaVersion() {
404 return "0.5";
405 }
406
407 /**
408 * Opens the XML output stream's root <mediawiki> element.
409 * This does not include an xml directive, so is safe to include
410 * as a subelement in a larger XML stream. Namespace and XML Schema
411 * references are included.
412 *
413 * Output will be encoded in UTF-8.
414 *
415 * @return string
416 */
417 function openStream() {
418 global $wgLanguageCode;
419 $ver = $this->schemaVersion();
420 return Xml::element( 'mediawiki', array(
421 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
422 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
423 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
424 "http://www.mediawiki.org/xml/export-$ver.xsd",
425 'version' => $ver,
426 'xml:lang' => $wgLanguageCode ),
427 null ) .
428 "\n" .
429 $this->siteInfo();
430 }
431
432 function siteInfo() {
433 $info = array(
434 $this->sitename(),
435 $this->homelink(),
436 $this->generator(),
437 $this->caseSetting(),
438 $this->namespaces() );
439 return " <siteinfo>\n " .
440 implode( "\n ", $info ) .
441 "\n </siteinfo>\n";
442 }
443
444 function sitename() {
445 global $wgSitename;
446 return Xml::element( 'sitename', array(), $wgSitename );
447 }
448
449 function generator() {
450 global $wgVersion;
451 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
452 }
453
454 function homelink() {
455 return Xml::element( 'base', array(), Title::newMainPage()->getFullUrl() );
456 }
457
458 function caseSetting() {
459 global $wgCapitalLinks;
460 // "case-insensitive" option is reserved for future
461 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
462 return Xml::element( 'case', array(), $sensitivity );
463 }
464
465 function namespaces() {
466 global $wgContLang;
467 $spaces = "<namespaces>\n";
468 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
469 $spaces .= ' ' .
470 Xml::element( 'namespace',
471 array( 'key' => $ns,
472 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
473 ), $title ) . "\n";
474 }
475 $spaces .= " </namespaces>";
476 return $spaces;
477 }
478
479 /**
480 * Closes the output stream with the closing root element.
481 * Call when finished dumping things.
482 */
483 function closeStream() {
484 return "</mediawiki>\n";
485 }
486
487
488 /**
489 * Opens a <page> section on the output stream, with data
490 * from the given database row.
491 *
492 * @param $row object
493 * @return string
494 * @access private
495 */
496 function openPage( $row ) {
497 $out = " <page>\n";
498 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
499 $out .= ' ' . Xml::elementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
500 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
501 if ( $row->page_is_redirect ) {
502 $out .= ' ' . Xml::element( 'redirect', array() ) . "\n";
503 }
504 if ( $row->page_restrictions != '' ) {
505 $out .= ' ' . Xml::element( 'restrictions', array(),
506 strval( $row->page_restrictions ) ) . "\n";
507 }
508
509 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
510
511 return $out;
512 }
513
514 /**
515 * Closes a <page> section on the output stream.
516 *
517 * @access private
518 */
519 function closePage() {
520 return " </page>\n";
521 }
522
523 /**
524 * Dumps a <revision> section on the output stream, with
525 * data filled in from the given database row.
526 *
527 * @param $row object
528 * @return string
529 * @access private
530 */
531 function writeRevision( $row ) {
532 wfProfileIn( __METHOD__ );
533
534 $out = " <revision>\n";
535 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
536
537 $out .= $this->writeTimestamp( $row->rev_timestamp );
538
539 if ( $row->rev_deleted & Revision::DELETED_USER ) {
540 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
541 } else {
542 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
543 }
544
545 if ( $row->rev_minor_edit ) {
546 $out .= " <minor/>\n";
547 }
548 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
549 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
550 } elseif ( $row->rev_comment != '' ) {
551 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
552 }
553
554 $text = '';
555 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
556 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
557 } elseif ( isset( $row->old_text ) ) {
558 // Raw text from the database may have invalid chars
559 $text = strval( Revision::getRevisionText( $row ) );
560 $out .= " " . Xml::elementClean( 'text',
561 array( 'xml:space' => 'preserve', 'bytes' => $row->rev_len ),
562 strval( $text ) ) . "\n";
563 } else {
564 // Stub output
565 $out .= " " . Xml::element( 'text',
566 array( 'id' => $row->rev_text_id, 'bytes' => $row->rev_len ),
567 "" ) . "\n";
568 }
569
570 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
571
572 $out .= " </revision>\n";
573
574 wfProfileOut( __METHOD__ );
575 return $out;
576 }
577
578 /**
579 * Dumps a <logitem> section on the output stream, with
580 * data filled in from the given database row.
581 *
582 * @param $row object
583 * @return string
584 * @access private
585 */
586 function writeLogItem( $row ) {
587 wfProfileIn( __METHOD__ );
588
589 $out = " <logitem>\n";
590 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
591
592 $out .= $this->writeTimestamp( $row->log_timestamp );
593
594 if ( $row->log_deleted & LogPage::DELETED_USER ) {
595 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
596 } else {
597 $out .= $this->writeContributor( $row->log_user, $row->user_name );
598 }
599
600 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
601 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
602 } elseif ( $row->log_comment != '' ) {
603 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
604 }
605
606 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
607 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
608
609 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
610 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
611 } else {
612 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
613 $out .= " " . Xml::elementClean( 'logtitle', null, $title->getPrefixedText() ) . "\n";
614 $out .= " " . Xml::elementClean( 'params',
615 array( 'xml:space' => 'preserve' ),
616 strval( $row->log_params ) ) . "\n";
617 }
618
619 $out .= " </logitem>\n";
620
621 wfProfileOut( __METHOD__ );
622 return $out;
623 }
624
625 function writeTimestamp( $timestamp ) {
626 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
627 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
628 }
629
630 function writeContributor( $id, $text ) {
631 $out = " <contributor>\n";
632 if ( $id ) {
633 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
634 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
635 } else {
636 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
637 }
638 $out .= " </contributor>\n";
639 return $out;
640 }
641
642 /**
643 * Warning! This data is potentially inconsistent. :(
644 */
645 function writeUploads( $row ) {
646 if ( $row->page_namespace == NS_IMAGE ) {
647 $img = wfFindFile( $row->page_title );
648 if ( $img ) {
649 $out = '';
650 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
651 $out .= $this->writeUpload( $ver );
652 }
653 $out .= $this->writeUpload( $img );
654 return $out;
655 }
656 }
657 return '';
658 }
659
660 function writeUpload( $file ) {
661 return " <upload>\n" .
662 $this->writeTimestamp( $file->getTimestamp() ) .
663 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
664 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
665 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
666 " " . Xml::element( 'src', null, $file->getFullUrl() ) . "\n" .
667 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
668 " </upload>\n";
669 }
670
671 }
672
673
674 /**
675 * Base class for output stream; prints to stdout or buffer or whereever.
676 * @ingroup Dump
677 */
678 class DumpOutput {
679 function writeOpenStream( $string ) {
680 $this->write( $string );
681 }
682
683 function writeCloseStream( $string ) {
684 $this->write( $string );
685 }
686
687 function writeOpenPage( $page, $string ) {
688 $this->write( $string );
689 }
690
691 function writeClosePage( $string ) {
692 $this->write( $string );
693 }
694
695 function writeRevision( $rev, $string ) {
696 $this->write( $string );
697 }
698
699 function writeLogItem( $rev, $string ) {
700 $this->write( $string );
701 }
702
703 /**
704 * Override to write to a different stream type.
705 * @return bool
706 */
707 function write( $string ) {
708 print $string;
709 }
710 }
711
712 /**
713 * Stream outputter to send data to a file.
714 * @ingroup Dump
715 */
716 class DumpFileOutput extends DumpOutput {
717 var $handle;
718
719 function __construct( $file ) {
720 $this->handle = fopen( $file, "wt" );
721 }
722
723 function write( $string ) {
724 fputs( $this->handle, $string );
725 }
726 }
727
728 /**
729 * Stream outputter to send data to a file via some filter program.
730 * Even if compression is available in a library, using a separate
731 * program can allow us to make use of a multi-processor system.
732 * @ingroup Dump
733 */
734 class DumpPipeOutput extends DumpFileOutput {
735 function __construct( $command, $file = null ) {
736 if ( !is_null( $file ) ) {
737 $command .= " > " . wfEscapeShellArg( $file );
738 }
739 $this->handle = popen( $command, "w" );
740 }
741 }
742
743 /**
744 * Sends dump output via the gzip compressor.
745 * @ingroup Dump
746 */
747 class DumpGZipOutput extends DumpPipeOutput {
748 function __construct( $file ) {
749 parent::__construct( "gzip", $file );
750 }
751 }
752
753 /**
754 * Sends dump output via the bgzip2 compressor.
755 * @ingroup Dump
756 */
757 class DumpBZip2Output extends DumpPipeOutput {
758 function __construct( $file ) {
759 parent::__construct( "bzip2", $file );
760 }
761 }
762
763 /**
764 * Sends dump output via the p7zip compressor.
765 * @ingroup Dump
766 */
767 class Dump7ZipOutput extends DumpPipeOutput {
768 function __construct( $file ) {
769 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
770 // Suppress annoying useless crap from p7zip
771 // Unfortunately this could suppress real error messages too
772 $command .= ' >' . wfGetNull() . ' 2>&1';
773 parent::__construct( $command );
774 }
775 }
776
777
778
779 /**
780 * Dump output filter class.
781 * This just does output filtering and streaming; XML formatting is done
782 * higher up, so be careful in what you do.
783 * @ingroup Dump
784 */
785 class DumpFilter {
786 function __construct( &$sink ) {
787 $this->sink =& $sink;
788 }
789
790 function writeOpenStream( $string ) {
791 $this->sink->writeOpenStream( $string );
792 }
793
794 function writeCloseStream( $string ) {
795 $this->sink->writeCloseStream( $string );
796 }
797
798 function writeOpenPage( $page, $string ) {
799 $this->sendingThisPage = $this->pass( $page, $string );
800 if ( $this->sendingThisPage ) {
801 $this->sink->writeOpenPage( $page, $string );
802 }
803 }
804
805 function writeClosePage( $string ) {
806 if ( $this->sendingThisPage ) {
807 $this->sink->writeClosePage( $string );
808 $this->sendingThisPage = false;
809 }
810 }
811
812 function writeRevision( $rev, $string ) {
813 if ( $this->sendingThisPage ) {
814 $this->sink->writeRevision( $rev, $string );
815 }
816 }
817
818 function writeLogItem( $rev, $string ) {
819 $this->sink->writeRevision( $rev, $string );
820 }
821
822 /**
823 * Override for page-based filter types.
824 * @return bool
825 */
826 function pass( $page ) {
827 return true;
828 }
829 }
830
831 /**
832 * Simple dump output filter to exclude all talk pages.
833 * @ingroup Dump
834 */
835 class DumpNotalkFilter extends DumpFilter {
836 function pass( $page ) {
837 return !MWNamespace::isTalk( $page->page_namespace );
838 }
839 }
840
841 /**
842 * Dump output filter to include or exclude pages in a given set of namespaces.
843 * @ingroup Dump
844 */
845 class DumpNamespaceFilter extends DumpFilter {
846 var $invert = false;
847 var $namespaces = array();
848
849 function __construct( &$sink, $param ) {
850 parent::__construct( $sink );
851
852 $constants = array(
853 "NS_MAIN" => NS_MAIN,
854 "NS_TALK" => NS_TALK,
855 "NS_USER" => NS_USER,
856 "NS_USER_TALK" => NS_USER_TALK,
857 "NS_PROJECT" => NS_PROJECT,
858 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
859 "NS_FILE" => NS_FILE,
860 "NS_FILE_TALK" => NS_FILE_TALK,
861 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
862 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
863 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
864 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
865 "NS_TEMPLATE" => NS_TEMPLATE,
866 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
867 "NS_HELP" => NS_HELP,
868 "NS_HELP_TALK" => NS_HELP_TALK,
869 "NS_CATEGORY" => NS_CATEGORY,
870 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
871
872 if ( $param { 0 } == '!' ) {
873 $this->invert = true;
874 $param = substr( $param, 1 );
875 }
876
877 foreach ( explode( ',', $param ) as $key ) {
878 $key = trim( $key );
879 if ( isset( $constants[$key] ) ) {
880 $ns = $constants[$key];
881 $this->namespaces[$ns] = true;
882 } elseif ( is_numeric( $key ) ) {
883 $ns = intval( $key );
884 $this->namespaces[$ns] = true;
885 } else {
886 throw new MWException( "Unrecognized namespace key '$key'\n" );
887 }
888 }
889 }
890
891 function pass( $page ) {
892 $match = isset( $this->namespaces[$page->page_namespace] );
893 return $this->invert xor $match;
894 }
895 }
896
897
898 /**
899 * Dump output filter to include only the last revision in each page sequence.
900 * @ingroup Dump
901 */
902 class DumpLatestFilter extends DumpFilter {
903 var $page, $pageString, $rev, $revString;
904
905 function writeOpenPage( $page, $string ) {
906 $this->page = $page;
907 $this->pageString = $string;
908 }
909
910 function writeClosePage( $string ) {
911 if ( $this->rev ) {
912 $this->sink->writeOpenPage( $this->page, $this->pageString );
913 $this->sink->writeRevision( $this->rev, $this->revString );
914 $this->sink->writeClosePage( $string );
915 }
916 $this->rev = null;
917 $this->revString = null;
918 $this->page = null;
919 $this->pageString = null;
920 }
921
922 function writeRevision( $rev, $string ) {
923 if ( $rev->rev_id == $this->page->page_latest ) {
924 $this->rev = $rev;
925 $this->revString = $string;
926 }
927 }
928 }
929
930 /**
931 * Base class for output stream; prints to stdout or buffer or whereever.
932 * @ingroup Dump
933 */
934 class DumpMultiWriter {
935 function __construct( $sinks ) {
936 $this->sinks = $sinks;
937 $this->count = count( $sinks );
938 }
939
940 function writeOpenStream( $string ) {
941 for ( $i = 0; $i < $this->count; $i++ ) {
942 $this->sinks[$i]->writeOpenStream( $string );
943 }
944 }
945
946 function writeCloseStream( $string ) {
947 for ( $i = 0; $i < $this->count; $i++ ) {
948 $this->sinks[$i]->writeCloseStream( $string );
949 }
950 }
951
952 function writeOpenPage( $page, $string ) {
953 for ( $i = 0; $i < $this->count; $i++ ) {
954 $this->sinks[$i]->writeOpenPage( $page, $string );
955 }
956 }
957
958 function writeClosePage( $string ) {
959 for ( $i = 0; $i < $this->count; $i++ ) {
960 $this->sinks[$i]->writeClosePage( $string );
961 }
962 }
963
964 function writeRevision( $rev, $string ) {
965 for ( $i = 0; $i < $this->count; $i++ ) {
966 $this->sinks[$i]->writeRevision( $rev, $string );
967 }
968 }
969 }
970
971 function xmlsafe( $string ) {
972 wfProfileIn( __FUNCTION__ );
973
974 /**
975 * The page may contain old data which has not been properly normalized.
976 * Invalid UTF-8 sequences or forbidden control characters will make our
977 * XML output invalid, so be sure to strip them out.
978 */
979 $string = UtfNormal::cleanUp( $string );
980
981 $string = htmlspecialchars( $string );
982 wfProfileOut( __FUNCTION__ );
983 return $string;
984 }