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