listFiles() returns false when empty. Special:UplaodStash now deals with that correctly
[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 global $wgVersion;
410 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
411 }
412
413 function homelink() {
414 return Xml::element( 'base', array(), Title::newMainPage()->getFullUrl() );
415 }
416
417 function caseSetting() {
418 global $wgCapitalLinks;
419 // "case-insensitive" option is reserved for future
420 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
421 return Xml::element( 'case', array(), $sensitivity );
422 }
423
424 function namespaces() {
425 global $wgContLang;
426 $spaces = "<namespaces>\n";
427 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
428 $spaces .= ' ' .
429 Xml::element( 'namespace',
430 array( 'key' => $ns,
431 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
432 ), $title ) . "\n";
433 }
434 $spaces .= " </namespaces>";
435 return $spaces;
436 }
437
438 /**
439 * Closes the output stream with the closing root element.
440 * Call when finished dumping things.
441 *
442 * @return string
443 */
444 function closeStream() {
445 return "</mediawiki>\n";
446 }
447
448 /**
449 * Opens a <page> section on the output stream, with data
450 * from the given database row.
451 *
452 * @param $row object
453 * @return string
454 * @access private
455 */
456 function openPage( $row ) {
457 $out = " <page>\n";
458 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
459 $out .= ' ' . Xml::elementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
460 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
461 if ( $row->page_is_redirect ) {
462 $out .= ' ' . Xml::element( 'redirect', array() ) . "\n";
463 }
464 if ( $row->page_restrictions != '' ) {
465 $out .= ' ' . Xml::element( 'restrictions', array(),
466 strval( $row->page_restrictions ) ) . "\n";
467 }
468
469 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
470
471 return $out;
472 }
473
474 /**
475 * Closes a <page> section on the output stream.
476 *
477 * @access private
478 */
479 function closePage() {
480 return " </page>\n";
481 }
482
483 /**
484 * Dumps a <revision> section on the output stream, with
485 * data filled in from the given database row.
486 *
487 * @param $row object
488 * @return string
489 * @access private
490 */
491 function writeRevision( $row ) {
492 wfProfileIn( __METHOD__ );
493
494 $out = " <revision>\n";
495 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
496
497 $out .= $this->writeTimestamp( $row->rev_timestamp );
498
499 if ( $row->rev_deleted & Revision::DELETED_USER ) {
500 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
501 } else {
502 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
503 }
504
505 if ( $row->rev_minor_edit ) {
506 $out .= " <minor/>\n";
507 }
508 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
509 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
510 } elseif ( $row->rev_comment != '' ) {
511 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
512 }
513
514 $text = '';
515 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
516 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
517 } elseif ( isset( $row->old_text ) ) {
518 // Raw text from the database may have invalid chars
519 $text = strval( Revision::getRevisionText( $row ) );
520 $out .= " " . Xml::elementClean( 'text',
521 array( 'xml:space' => 'preserve', 'bytes' => $row->rev_len ),
522 strval( $text ) ) . "\n";
523 } else {
524 // Stub output
525 $out .= " " . Xml::element( 'text',
526 array( 'id' => $row->rev_text_id, 'bytes' => $row->rev_len ),
527 "" ) . "\n";
528 }
529
530 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
531
532 $out .= " </revision>\n";
533
534 wfProfileOut( __METHOD__ );
535 return $out;
536 }
537
538 /**
539 * Dumps a <logitem> section on the output stream, with
540 * data filled in from the given database row.
541 *
542 * @param $row object
543 * @return string
544 * @access private
545 */
546 function writeLogItem( $row ) {
547 wfProfileIn( __METHOD__ );
548
549 $out = " <logitem>\n";
550 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
551
552 $out .= $this->writeTimestamp( $row->log_timestamp );
553
554 if ( $row->log_deleted & LogPage::DELETED_USER ) {
555 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
556 } else {
557 $out .= $this->writeContributor( $row->log_user, $row->user_name );
558 }
559
560 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
561 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
562 } elseif ( $row->log_comment != '' ) {
563 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
564 }
565
566 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
567 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
568
569 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
570 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
571 } else {
572 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
573 $out .= " " . Xml::elementClean( 'logtitle', null, $title->getPrefixedText() ) . "\n";
574 $out .= " " . Xml::elementClean( 'params',
575 array( 'xml:space' => 'preserve' ),
576 strval( $row->log_params ) ) . "\n";
577 }
578
579 $out .= " </logitem>\n";
580
581 wfProfileOut( __METHOD__ );
582 return $out;
583 }
584
585 function writeTimestamp( $timestamp ) {
586 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
587 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
588 }
589
590 function writeContributor( $id, $text ) {
591 $out = " <contributor>\n";
592 if ( $id ) {
593 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
594 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
595 } else {
596 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
597 }
598 $out .= " </contributor>\n";
599 return $out;
600 }
601
602 /**
603 * Warning! This data is potentially inconsistent. :(
604 */
605 function writeUploads( $row, $dumpContents = false ) {
606 if ( $row->page_namespace == NS_IMAGE ) {
607 $img = wfLocalFile( $row->page_title );
608 if ( $img && $img->exists() ) {
609 $out = '';
610 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
611 $out .= $this->writeUpload( $ver, $dumpContents );
612 }
613 $out .= $this->writeUpload( $img, $dumpContents );
614 return $out;
615 }
616 }
617 return '';
618 }
619
620 /**
621 * @param $file File
622 * @param $dumpContents bool
623 * @return string
624 */
625 function writeUpload( $file, $dumpContents = false ) {
626 if ( $file->isOld() ) {
627 $archiveName = " " .
628 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
629 } else {
630 $archiveName = '';
631 }
632 if ( $dumpContents ) {
633 # Dump file as base64
634 # Uses only XML-safe characters, so does not need escaping
635 $contents = ' <contents encoding="base64">' .
636 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
637 " </contents>\n";
638 } else {
639 $contents = '';
640 }
641 return " <upload>\n" .
642 $this->writeTimestamp( $file->getTimestamp() ) .
643 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
644 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
645 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
646 $archiveName .
647 " " . Xml::element( 'src', null, $file->getFullUrl() ) . "\n" .
648 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
649 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
650 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
651 $contents .
652 " </upload>\n";
653 }
654
655 }
656
657
658 /**
659 * Base class for output stream; prints to stdout or buffer or whereever.
660 * @ingroup Dump
661 */
662 class DumpOutput {
663 function writeOpenStream( $string ) {
664 $this->write( $string );
665 }
666
667 function writeCloseStream( $string ) {
668 $this->write( $string );
669 }
670
671 function writeOpenPage( $page, $string ) {
672 $this->write( $string );
673 }
674
675 function writeClosePage( $string ) {
676 $this->write( $string );
677 }
678
679 function writeRevision( $rev, $string ) {
680 $this->write( $string );
681 }
682
683 function writeLogItem( $rev, $string ) {
684 $this->write( $string );
685 }
686
687 /**
688 * Override to write to a different stream type.
689 * @return bool
690 */
691 function write( $string ) {
692 print $string;
693 }
694 }
695
696 /**
697 * Stream outputter to send data to a file.
698 * @ingroup Dump
699 */
700 class DumpFileOutput extends DumpOutput {
701 var $handle;
702
703 function __construct( $file ) {
704 $this->handle = fopen( $file, "wt" );
705 }
706
707 function write( $string ) {
708 fputs( $this->handle, $string );
709 }
710 }
711
712 /**
713 * Stream outputter to send data to a file via some filter program.
714 * Even if compression is available in a library, using a separate
715 * program can allow us to make use of a multi-processor system.
716 * @ingroup Dump
717 */
718 class DumpPipeOutput extends DumpFileOutput {
719 function __construct( $command, $file = null ) {
720 if ( !is_null( $file ) ) {
721 $command .= " > " . wfEscapeShellArg( $file );
722 }
723 $this->handle = popen( $command, "w" );
724 }
725 }
726
727 /**
728 * Sends dump output via the gzip compressor.
729 * @ingroup Dump
730 */
731 class DumpGZipOutput extends DumpPipeOutput {
732 function __construct( $file ) {
733 parent::__construct( "gzip", $file );
734 }
735 }
736
737 /**
738 * Sends dump output via the bgzip2 compressor.
739 * @ingroup Dump
740 */
741 class DumpBZip2Output extends DumpPipeOutput {
742 function __construct( $file ) {
743 parent::__construct( "bzip2", $file );
744 }
745 }
746
747 /**
748 * Sends dump output via the p7zip compressor.
749 * @ingroup Dump
750 */
751 class Dump7ZipOutput extends DumpPipeOutput {
752 function __construct( $file ) {
753 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
754 // Suppress annoying useless crap from p7zip
755 // Unfortunately this could suppress real error messages too
756 $command .= ' >' . wfGetNull() . ' 2>&1';
757 parent::__construct( $command );
758 }
759 }
760
761
762
763 /**
764 * Dump output filter class.
765 * This just does output filtering and streaming; XML formatting is done
766 * higher up, so be careful in what you do.
767 * @ingroup Dump
768 */
769 class DumpFilter {
770 function __construct( &$sink ) {
771 $this->sink =& $sink;
772 }
773
774 function writeOpenStream( $string ) {
775 $this->sink->writeOpenStream( $string );
776 }
777
778 function writeCloseStream( $string ) {
779 $this->sink->writeCloseStream( $string );
780 }
781
782 function writeOpenPage( $page, $string ) {
783 $this->sendingThisPage = $this->pass( $page, $string );
784 if ( $this->sendingThisPage ) {
785 $this->sink->writeOpenPage( $page, $string );
786 }
787 }
788
789 function writeClosePage( $string ) {
790 if ( $this->sendingThisPage ) {
791 $this->sink->writeClosePage( $string );
792 $this->sendingThisPage = false;
793 }
794 }
795
796 function writeRevision( $rev, $string ) {
797 if ( $this->sendingThisPage ) {
798 $this->sink->writeRevision( $rev, $string );
799 }
800 }
801
802 function writeLogItem( $rev, $string ) {
803 $this->sink->writeRevision( $rev, $string );
804 }
805
806 /**
807 * Override for page-based filter types.
808 * @return bool
809 */
810 function pass( $page ) {
811 return true;
812 }
813 }
814
815 /**
816 * Simple dump output filter to exclude all talk pages.
817 * @ingroup Dump
818 */
819 class DumpNotalkFilter extends DumpFilter {
820 function pass( $page ) {
821 return !MWNamespace::isTalk( $page->page_namespace );
822 }
823 }
824
825 /**
826 * Dump output filter to include or exclude pages in a given set of namespaces.
827 * @ingroup Dump
828 */
829 class DumpNamespaceFilter extends DumpFilter {
830 var $invert = false;
831 var $namespaces = array();
832
833 function __construct( &$sink, $param ) {
834 parent::__construct( $sink );
835
836 $constants = array(
837 "NS_MAIN" => NS_MAIN,
838 "NS_TALK" => NS_TALK,
839 "NS_USER" => NS_USER,
840 "NS_USER_TALK" => NS_USER_TALK,
841 "NS_PROJECT" => NS_PROJECT,
842 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
843 "NS_FILE" => NS_FILE,
844 "NS_FILE_TALK" => NS_FILE_TALK,
845 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
846 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
847 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
848 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
849 "NS_TEMPLATE" => NS_TEMPLATE,
850 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
851 "NS_HELP" => NS_HELP,
852 "NS_HELP_TALK" => NS_HELP_TALK,
853 "NS_CATEGORY" => NS_CATEGORY,
854 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
855
856 if ( $param { 0 } == '!' ) {
857 $this->invert = true;
858 $param = substr( $param, 1 );
859 }
860
861 foreach ( explode( ',', $param ) as $key ) {
862 $key = trim( $key );
863 if ( isset( $constants[$key] ) ) {
864 $ns = $constants[$key];
865 $this->namespaces[$ns] = true;
866 } elseif ( is_numeric( $key ) ) {
867 $ns = intval( $key );
868 $this->namespaces[$ns] = true;
869 } else {
870 throw new MWException( "Unrecognized namespace key '$key'\n" );
871 }
872 }
873 }
874
875 function pass( $page ) {
876 $match = isset( $this->namespaces[$page->page_namespace] );
877 return $this->invert xor $match;
878 }
879 }
880
881
882 /**
883 * Dump output filter to include only the last revision in each page sequence.
884 * @ingroup Dump
885 */
886 class DumpLatestFilter extends DumpFilter {
887 var $page, $pageString, $rev, $revString;
888
889 function writeOpenPage( $page, $string ) {
890 $this->page = $page;
891 $this->pageString = $string;
892 }
893
894 function writeClosePage( $string ) {
895 if ( $this->rev ) {
896 $this->sink->writeOpenPage( $this->page, $this->pageString );
897 $this->sink->writeRevision( $this->rev, $this->revString );
898 $this->sink->writeClosePage( $string );
899 }
900 $this->rev = null;
901 $this->revString = null;
902 $this->page = null;
903 $this->pageString = null;
904 }
905
906 function writeRevision( $rev, $string ) {
907 if ( $rev->rev_id == $this->page->page_latest ) {
908 $this->rev = $rev;
909 $this->revString = $string;
910 }
911 }
912 }
913
914 /**
915 * Base class for output stream; prints to stdout or buffer or whereever.
916 * @ingroup Dump
917 */
918 class DumpMultiWriter {
919 function __construct( $sinks ) {
920 $this->sinks = $sinks;
921 $this->count = count( $sinks );
922 }
923
924 function writeOpenStream( $string ) {
925 for ( $i = 0; $i < $this->count; $i++ ) {
926 $this->sinks[$i]->writeOpenStream( $string );
927 }
928 }
929
930 function writeCloseStream( $string ) {
931 for ( $i = 0; $i < $this->count; $i++ ) {
932 $this->sinks[$i]->writeCloseStream( $string );
933 }
934 }
935
936 function writeOpenPage( $page, $string ) {
937 for ( $i = 0; $i < $this->count; $i++ ) {
938 $this->sinks[$i]->writeOpenPage( $page, $string );
939 }
940 }
941
942 function writeClosePage( $string ) {
943 for ( $i = 0; $i < $this->count; $i++ ) {
944 $this->sinks[$i]->writeClosePage( $string );
945 }
946 }
947
948 function writeRevision( $rev, $string ) {
949 for ( $i = 0; $i < $this->count; $i++ ) {
950 $this->sinks[$i]->writeRevision( $rev, $string );
951 }
952 }
953 }
954
955 function xmlsafe( $string ) {
956 wfProfileIn( __FUNCTION__ );
957
958 /**
959 * The page may contain old data which has not been properly normalized.
960 * Invalid UTF-8 sequences or forbidden control characters will make our
961 * XML output invalid, so be sure to strip them out.
962 */
963 $string = UtfNormal::cleanUp( $string );
964
965 $string = htmlspecialchars( $string );
966 wfProfileOut( __FUNCTION__ );
967 return $string;
968 }