Fixing bug 30973. Strip off subpages when determining the username who the current...
[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 protected $firstPageWritten = 0, $lastPageWritten = 0, $pageInProgress = 0;
358
359 /**
360 * Returns the export schema version.
361 * @return string
362 */
363 function schemaVersion() {
364 return "0.5";
365 }
366
367 /**
368 * Opens the XML output stream's root <mediawiki> element.
369 * This does not include an xml directive, so is safe to include
370 * as a subelement in a larger XML stream. Namespace and XML Schema
371 * references are included.
372 *
373 * Output will be encoded in UTF-8.
374 *
375 * @return string
376 */
377 function openStream() {
378 global $wgLanguageCode;
379 $ver = $this->schemaVersion();
380 return Xml::element( 'mediawiki', array(
381 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
382 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
383 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
384 "http://www.mediawiki.org/xml/export-$ver.xsd",
385 'version' => $ver,
386 'xml:lang' => $wgLanguageCode ),
387 null ) .
388 "\n" .
389 $this->siteInfo();
390 }
391
392 function siteInfo() {
393 $info = array(
394 $this->sitename(),
395 $this->homelink(),
396 $this->generator(),
397 $this->caseSetting(),
398 $this->namespaces() );
399 return " <siteinfo>\n " .
400 implode( "\n ", $info ) .
401 "\n </siteinfo>\n";
402 }
403
404 function sitename() {
405 global $wgSitename;
406 return Xml::element( 'sitename', array(), $wgSitename );
407 }
408
409 function generator() {
410 global $wgVersion;
411 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
412 }
413
414 function homelink() {
415 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalUrl() );
416 }
417
418 function caseSetting() {
419 global $wgCapitalLinks;
420 // "case-insensitive" option is reserved for future
421 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
422 return Xml::element( 'case', array(), $sensitivity );
423 }
424
425 function namespaces() {
426 global $wgContLang;
427 $spaces = "<namespaces>\n";
428 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
429 $spaces .= ' ' .
430 Xml::element( 'namespace',
431 array( 'key' => $ns,
432 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
433 ), $title ) . "\n";
434 }
435 $spaces .= " </namespaces>";
436 return $spaces;
437 }
438
439 /**
440 * Closes the output stream with the closing root element.
441 * Call when finished dumping things.
442 *
443 * @return string
444 */
445 function closeStream() {
446 return "</mediawiki>\n";
447 }
448
449 /**
450 * Opens a <page> section on the output stream, with data
451 * from the given database row.
452 *
453 * @param $row object
454 * @return string
455 * @access private
456 */
457 function openPage( $row ) {
458 $out = " <page>\n";
459 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
460 $out .= ' ' . Xml::elementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
461 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
462 $this->pageInProgress = $row->page_id;
463 if ( $row->page_is_redirect ) {
464 $out .= ' ' . Xml::element( 'redirect', array() ) . "\n";
465 }
466 if ( $row->page_restrictions != '' ) {
467 $out .= ' ' . Xml::element( 'restrictions', array(),
468 strval( $row->page_restrictions ) ) . "\n";
469 }
470
471 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
472
473 return $out;
474 }
475
476 /**
477 * Closes a <page> section on the output stream.
478 *
479 * @access private
480 */
481 function closePage() {
482 return " </page>\n";
483 if ( !$this->firstPageWritten ) {
484 $this->firstPageWritten = $this->pageInProgress;
485 }
486 $this->lastPageWritten = $this->pageInProgress;
487 }
488
489 /**
490 * Dumps a <revision> section on the output stream, with
491 * data filled in from the given database row.
492 *
493 * @param $row object
494 * @return string
495 * @access private
496 */
497 function writeRevision( $row ) {
498 wfProfileIn( __METHOD__ );
499
500 $out = " <revision>\n";
501 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
502
503 $out .= $this->writeTimestamp( $row->rev_timestamp );
504
505 if ( $row->rev_deleted & Revision::DELETED_USER ) {
506 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
507 } else {
508 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
509 }
510
511 if ( $row->rev_minor_edit ) {
512 $out .= " <minor/>\n";
513 }
514 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
515 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
516 } elseif ( $row->rev_comment != '' ) {
517 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
518 }
519
520 $text = '';
521 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
522 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
523 } elseif ( isset( $row->old_text ) ) {
524 // Raw text from the database may have invalid chars
525 $text = strval( Revision::getRevisionText( $row ) );
526 $out .= " " . Xml::elementClean( 'text',
527 array( 'xml:space' => 'preserve', 'bytes' => $row->rev_len ),
528 strval( $text ) ) . "\n";
529 } else {
530 // Stub output
531 $out .= " " . Xml::element( 'text',
532 array( 'id' => $row->rev_text_id, 'bytes' => $row->rev_len ),
533 "" ) . "\n";
534 }
535
536 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
537
538 $out .= " </revision>\n";
539
540 wfProfileOut( __METHOD__ );
541 return $out;
542 }
543
544 /**
545 * Dumps a <logitem> section on the output stream, with
546 * data filled in from the given database row.
547 *
548 * @param $row object
549 * @return string
550 * @access private
551 */
552 function writeLogItem( $row ) {
553 wfProfileIn( __METHOD__ );
554
555 $out = " <logitem>\n";
556 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
557
558 $out .= $this->writeTimestamp( $row->log_timestamp );
559
560 if ( $row->log_deleted & LogPage::DELETED_USER ) {
561 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
562 } else {
563 $out .= $this->writeContributor( $row->log_user, $row->user_name );
564 }
565
566 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
567 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
568 } elseif ( $row->log_comment != '' ) {
569 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
570 }
571
572 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
573 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
574
575 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
576 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
577 } else {
578 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
579 $out .= " " . Xml::elementClean( 'logtitle', null, $title->getPrefixedText() ) . "\n";
580 $out .= " " . Xml::elementClean( 'params',
581 array( 'xml:space' => 'preserve' ),
582 strval( $row->log_params ) ) . "\n";
583 }
584
585 $out .= " </logitem>\n";
586
587 wfProfileOut( __METHOD__ );
588 return $out;
589 }
590
591 function writeTimestamp( $timestamp ) {
592 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
593 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
594 }
595
596 function writeContributor( $id, $text ) {
597 $out = " <contributor>\n";
598 if ( $id ) {
599 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
600 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
601 } else {
602 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
603 }
604 $out .= " </contributor>\n";
605 return $out;
606 }
607
608 /**
609 * Warning! This data is potentially inconsistent. :(
610 */
611 function writeUploads( $row, $dumpContents = false ) {
612 if ( $row->page_namespace == NS_IMAGE ) {
613 $img = wfLocalFile( $row->page_title );
614 if ( $img && $img->exists() ) {
615 $out = '';
616 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
617 $out .= $this->writeUpload( $ver, $dumpContents );
618 }
619 $out .= $this->writeUpload( $img, $dumpContents );
620 return $out;
621 }
622 }
623 return '';
624 }
625
626 /**
627 * @param $file File
628 * @param $dumpContents bool
629 * @return string
630 */
631 function writeUpload( $file, $dumpContents = false ) {
632 if ( $file->isOld() ) {
633 $archiveName = " " .
634 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
635 } else {
636 $archiveName = '';
637 }
638 if ( $dumpContents ) {
639 # Dump file as base64
640 # Uses only XML-safe characters, so does not need escaping
641 $contents = ' <contents encoding="base64">' .
642 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
643 " </contents>\n";
644 } else {
645 $contents = '';
646 }
647 return " <upload>\n" .
648 $this->writeTimestamp( $file->getTimestamp() ) .
649 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
650 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
651 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
652 $archiveName .
653 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
654 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
655 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
656 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
657 $contents .
658 " </upload>\n";
659 }
660
661 }
662
663
664 /**
665 * Base class for output stream; prints to stdout or buffer or whereever.
666 * @ingroup Dump
667 */
668 class DumpOutput {
669 function writeOpenStream( $string ) {
670 $this->write( $string );
671 }
672
673 function writeCloseStream( $string ) {
674 $this->write( $string );
675 }
676
677 function writeOpenPage( $page, $string ) {
678 $this->write( $string );
679 }
680
681 function writeClosePage( $string ) {
682 $this->write( $string );
683 }
684
685 function writeRevision( $rev, $string ) {
686 $this->write( $string );
687 }
688
689 function writeLogItem( $rev, $string ) {
690 $this->write( $string );
691 }
692
693 /**
694 * Override to write to a different stream type.
695 * @return bool
696 */
697 function write( $string ) {
698 print $string;
699 }
700
701 /**
702 * Close the old file, move it to a specified name,
703 * and reopen new file with the old name. Use this
704 * for writing out a file in multiple pieces
705 * at specified checkpoints (e.g. every n hours).
706 * @param $newname mixed File name. May be a string or an array with one element
707 */
708 function closeRenameAndReopen( $newname ) {
709 return;
710 }
711
712 /**
713 * Close the old file, and move it to a specified name.
714 * Use this for the last piece of a file written out
715 * at specified checkpoints (e.g. every n hours).
716 * @param $newname mixed File name. May be a string or an array with one element
717 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
718 */
719 function closeAndRename( $newname, $open = false ) {
720 return;
721 }
722
723 /**
724 * Returns the name of the file or files which are
725 * being written to, if there are any.
726 */
727 function getFilenames() {
728 return NULL;
729 }
730 }
731
732 /**
733 * Stream outputter to send data to a file.
734 * @ingroup Dump
735 */
736 class DumpFileOutput extends DumpOutput {
737 protected $handle, $filename;
738
739 function __construct( $file ) {
740 $this->handle = fopen( $file, "wt" );
741 $this->filename = $file;
742 }
743
744 function write( $string ) {
745 fputs( $this->handle, $string );
746 }
747
748 function closeRenameAndReopen( $newname ) {
749 $this->closeAndRename( $newname, true );
750 }
751
752 function closeAndRename( $newname, $open = false ) {
753 if ( is_array( $newname ) ) {
754 if ( count( $newname ) > 1 ) {
755 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
756 } else {
757 $newname = $newname[0];
758 }
759 }
760 if ( $newname ) {
761 fclose( $this->handle );
762 if (! rename( $this->filename, $newname ) ) {
763 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
764 }
765 elseif ( $open ) {
766 $this->handle = fopen( $this->filename, "wt" );
767 }
768 }
769 }
770
771 function getFilenames() {
772 return $this->filename;
773 }
774 }
775
776 /**
777 * Stream outputter to send data to a file via some filter program.
778 * Even if compression is available in a library, using a separate
779 * program can allow us to make use of a multi-processor system.
780 * @ingroup Dump
781 */
782 class DumpPipeOutput extends DumpFileOutput {
783 protected $command, $filename;
784
785 function __construct( $command, $file = null ) {
786 if ( !is_null( $file ) ) {
787 $command .= " > " . wfEscapeShellArg( $file );
788 }
789
790 $this->startCommand( $command );
791 $this->command = $command;
792 $this->filename = $file;
793 }
794
795 function startCommand( $command ) {
796 $spec = array(
797 0 => array( "pipe", "r" ),
798 );
799 $pipes = array();
800 $this->procOpenResource = proc_open( $command, $spec, $pipes );
801 $this->handle = $pipes[0];
802 }
803
804 function closeRenameAndReopen( $newname ) {
805 $this->closeAndRename( $newname, true );
806 }
807
808 function closeAndRename( $newname, $open = false ) {
809 if ( is_array( $newname ) ) {
810 if ( count( $newname ) > 1 ) {
811 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
812 } else {
813 $newname = $newname[0];
814 }
815 }
816 if ( $newname ) {
817 fclose( $this->handle );
818 proc_close( $this->procOpenResource );
819 if (! rename( $this->filename, $newname ) ) {
820 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
821 }
822 elseif ( $open ) {
823 $command = $this->command;
824 $command .= " > " . wfEscapeShellArg( $this->filename );
825 $this->startCommand( $command );
826 }
827 }
828 }
829
830 }
831
832 /**
833 * Sends dump output via the gzip compressor.
834 * @ingroup Dump
835 */
836 class DumpGZipOutput extends DumpPipeOutput {
837 function __construct( $file ) {
838 parent::__construct( "gzip", $file );
839 }
840 }
841
842 /**
843 * Sends dump output via the bgzip2 compressor.
844 * @ingroup Dump
845 */
846 class DumpBZip2Output extends DumpPipeOutput {
847 function __construct( $file ) {
848 parent::__construct( "bzip2", $file );
849 }
850 }
851
852 /**
853 * Sends dump output via the p7zip compressor.
854 * @ingroup Dump
855 */
856 class Dump7ZipOutput extends DumpPipeOutput {
857 protected $filename;
858
859 function __construct( $file ) {
860 $command = setup7zCommand( $file );
861 parent::__construct( $command );
862 $this->filename = $file;
863 }
864
865 function closeRenameAndReopen( $newname ) {
866 $this->closeAndRename( $newname, true );
867 }
868
869 function closeAndRename( $newname, $open = false ) {
870 if ( is_array( $newname ) ) {
871 if ( count( $newname ) > 1 ) {
872 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
873 } else {
874 $newname = $newname[0];
875 }
876 }
877 if ( $newname ) {
878 fclose( $this->handle );
879 proc_close( $this->procOpenResource );
880 if (! rename( $this->filename, $newname ) ) {
881 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
882 }
883 elseif ( $open ) {
884 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
885 // Suppress annoying useless crap from p7zip
886 // Unfortunately this could suppress real error messages too
887 $command .= ' >' . wfGetNull() . ' 2>&1';
888 $this->startCommand( $command );
889 }
890 }
891 }
892 }
893
894
895
896 /**
897 * Dump output filter class.
898 * This just does output filtering and streaming; XML formatting is done
899 * higher up, so be careful in what you do.
900 * @ingroup Dump
901 */
902 class DumpFilter {
903 function __construct( &$sink ) {
904 $this->sink =& $sink;
905 }
906
907 function writeOpenStream( $string ) {
908 $this->sink->writeOpenStream( $string );
909 }
910
911 function writeCloseStream( $string ) {
912 $this->sink->writeCloseStream( $string );
913 }
914
915 function writeOpenPage( $page, $string ) {
916 $this->sendingThisPage = $this->pass( $page, $string );
917 if ( $this->sendingThisPage ) {
918 $this->sink->writeOpenPage( $page, $string );
919 }
920 }
921
922 function writeClosePage( $string ) {
923 if ( $this->sendingThisPage ) {
924 $this->sink->writeClosePage( $string );
925 $this->sendingThisPage = false;
926 }
927 }
928
929 function writeRevision( $rev, $string ) {
930 if ( $this->sendingThisPage ) {
931 $this->sink->writeRevision( $rev, $string );
932 }
933 }
934
935 function writeLogItem( $rev, $string ) {
936 $this->sink->writeRevision( $rev, $string );
937 }
938
939 function closeRenameAndReopen( $newname ) {
940 $this->sink->closeRenameAndReopen( $newname );
941 }
942
943 function closeAndRename( $newname, $open = false ) {
944 $this->sink->closeAndRename( $newname, $open );
945 }
946
947 function getFilenames() {
948 return $this->sink->getFilenames();
949 }
950
951 /**
952 * Override for page-based filter types.
953 * @return bool
954 */
955 function pass( $page ) {
956 return true;
957 }
958 }
959
960 /**
961 * Simple dump output filter to exclude all talk pages.
962 * @ingroup Dump
963 */
964 class DumpNotalkFilter extends DumpFilter {
965 function pass( $page ) {
966 return !MWNamespace::isTalk( $page->page_namespace );
967 }
968 }
969
970 /**
971 * Dump output filter to include or exclude pages in a given set of namespaces.
972 * @ingroup Dump
973 */
974 class DumpNamespaceFilter extends DumpFilter {
975 var $invert = false;
976 var $namespaces = array();
977
978 function __construct( &$sink, $param ) {
979 parent::__construct( $sink );
980
981 $constants = array(
982 "NS_MAIN" => NS_MAIN,
983 "NS_TALK" => NS_TALK,
984 "NS_USER" => NS_USER,
985 "NS_USER_TALK" => NS_USER_TALK,
986 "NS_PROJECT" => NS_PROJECT,
987 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
988 "NS_FILE" => NS_FILE,
989 "NS_FILE_TALK" => NS_FILE_TALK,
990 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
991 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
992 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
993 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
994 "NS_TEMPLATE" => NS_TEMPLATE,
995 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
996 "NS_HELP" => NS_HELP,
997 "NS_HELP_TALK" => NS_HELP_TALK,
998 "NS_CATEGORY" => NS_CATEGORY,
999 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1000
1001 if ( $param { 0 } == '!' ) {
1002 $this->invert = true;
1003 $param = substr( $param, 1 );
1004 }
1005
1006 foreach ( explode( ',', $param ) as $key ) {
1007 $key = trim( $key );
1008 if ( isset( $constants[$key] ) ) {
1009 $ns = $constants[$key];
1010 $this->namespaces[$ns] = true;
1011 } elseif ( is_numeric( $key ) ) {
1012 $ns = intval( $key );
1013 $this->namespaces[$ns] = true;
1014 } else {
1015 throw new MWException( "Unrecognized namespace key '$key'\n" );
1016 }
1017 }
1018 }
1019
1020 function pass( $page ) {
1021 $match = isset( $this->namespaces[$page->page_namespace] );
1022 return $this->invert xor $match;
1023 }
1024 }
1025
1026
1027 /**
1028 * Dump output filter to include only the last revision in each page sequence.
1029 * @ingroup Dump
1030 */
1031 class DumpLatestFilter extends DumpFilter {
1032 var $page, $pageString, $rev, $revString;
1033
1034 function writeOpenPage( $page, $string ) {
1035 $this->page = $page;
1036 $this->pageString = $string;
1037 }
1038
1039 function writeClosePage( $string ) {
1040 if ( $this->rev ) {
1041 $this->sink->writeOpenPage( $this->page, $this->pageString );
1042 $this->sink->writeRevision( $this->rev, $this->revString );
1043 $this->sink->writeClosePage( $string );
1044 }
1045 $this->rev = null;
1046 $this->revString = null;
1047 $this->page = null;
1048 $this->pageString = null;
1049 }
1050
1051 function writeRevision( $rev, $string ) {
1052 if ( $rev->rev_id == $this->page->page_latest ) {
1053 $this->rev = $rev;
1054 $this->revString = $string;
1055 }
1056 }
1057 }
1058
1059 /**
1060 * Base class for output stream; prints to stdout or buffer or whereever.
1061 * @ingroup Dump
1062 */
1063 class DumpMultiWriter {
1064 function __construct( $sinks ) {
1065 $this->sinks = $sinks;
1066 $this->count = count( $sinks );
1067 }
1068
1069 function writeOpenStream( $string ) {
1070 for ( $i = 0; $i < $this->count; $i++ ) {
1071 $this->sinks[$i]->writeOpenStream( $string );
1072 }
1073 }
1074
1075 function writeCloseStream( $string ) {
1076 for ( $i = 0; $i < $this->count; $i++ ) {
1077 $this->sinks[$i]->writeCloseStream( $string );
1078 }
1079 }
1080
1081 function writeOpenPage( $page, $string ) {
1082 for ( $i = 0; $i < $this->count; $i++ ) {
1083 $this->sinks[$i]->writeOpenPage( $page, $string );
1084 }
1085 }
1086
1087 function writeClosePage( $string ) {
1088 for ( $i = 0; $i < $this->count; $i++ ) {
1089 $this->sinks[$i]->writeClosePage( $string );
1090 }
1091 }
1092
1093 function writeRevision( $rev, $string ) {
1094 for ( $i = 0; $i < $this->count; $i++ ) {
1095 $this->sinks[$i]->writeRevision( $rev, $string );
1096 }
1097 }
1098
1099 function closeRenameAndReopen( $newnames ) {
1100 $this->closeAndRename( $newnames, true );
1101 }
1102
1103 function closeAndRename( $newnames, $open = false ) {
1104 for ( $i = 0; $i < $this->count; $i++ ) {
1105 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1106 }
1107 }
1108
1109 function getFilenames() {
1110 $filenames = array();
1111 for ( $i = 0; $i < $this->count; $i++ ) {
1112 $filenames[] = $this->sinks[$i]->getFilenames();
1113 }
1114 return $filenames;
1115 }
1116
1117 }
1118
1119 function xmlsafe( $string ) {
1120 wfProfileIn( __FUNCTION__ );
1121
1122 /**
1123 * The page may contain old data which has not been properly normalized.
1124 * Invalid UTF-8 sequences or forbidden control characters will make our
1125 * XML output invalid, so be sure to strip them out.
1126 */
1127 $string = UtfNormal::cleanUp( $string );
1128
1129 $string = htmlspecialchars( $string );
1130 wfProfileOut( __FUNCTION__ );
1131 return $string;
1132 }