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