3 * Base classes for dumps and export
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
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.
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.
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
31 * @ingroup SpecialPage Dump
34 var $list_authors = false ; # Return distinct author list (when not returning full history)
35 var $author_list = "" ;
37 var $dumpUploads = false;
38 var $dumpUploadFileContents = false;
42 const STABLE
= 4; // extension defined
62 * Returns the export schema version.
65 public static function schemaVersion() {
70 * If using WikiExporter::STREAM to stream a large amount of data,
71 * provide a database connection which is not managed by
72 * LoadBalancer to read from: some history blob types will
73 * make additional queries to pull source data while the
74 * main query is still running.
76 * @param $db DatabaseBase
77 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
78 * WikiExporter::RANGE or WikiExporter::STABLE,
79 * or an associative array:
80 * offset: non-inclusive offset at which to start the query
81 * limit: maximum number of rows to return
82 * dir: "asc" or "desc" timestamp order
83 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
84 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
86 function __construct( $db, $history = WikiExporter
::CURRENT
,
87 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
89 $this->history
= $history;
90 $this->buffer
= $buffer;
91 $this->writer
= new XmlDumpWriter();
92 $this->sink
= new DumpOutput();
97 * Set the DumpOutput or DumpFilter object which will receive
98 * various row objects and XML output for filtering. Filters
99 * can be chained or used as callbacks.
103 public function setOutputSink( &$sink ) {
104 $this->sink
=& $sink;
107 public function openStream() {
108 $output = $this->writer
->openStream();
109 $this->sink
->writeOpenStream( $output );
112 public function closeStream() {
113 $output = $this->writer
->closeStream();
114 $this->sink
->writeCloseStream( $output );
118 * Dumps a series of page and revision records for all pages
119 * in the database, either including complete history or only
120 * the most recent version.
122 public function allPages() {
123 $this->dumpFrom( '' );
127 * Dumps a series of page and revision records for those pages
128 * in the database falling within the page_id range given.
129 * @param $start Int: inclusive lower limit (this id is included)
130 * @param $end Int: Exclusive upper limit (this id is not included)
131 * If 0, no upper limit.
133 public function pagesByRange( $start, $end ) {
134 $condition = 'page_id >= ' . intval( $start );
136 $condition .= ' AND page_id < ' . intval( $end );
138 $this->dumpFrom( $condition );
142 * Dumps a series of page and revision records for those pages
143 * in the database with revisions falling within the rev_id range given.
144 * @param $start Int: inclusive lower limit (this id is included)
145 * @param $end Int: Exclusive upper limit (this id is not included)
146 * If 0, no upper limit.
148 public function revsByRange( $start, $end ) {
149 $condition = 'rev_id >= ' . intval( $start );
151 $condition .= ' AND rev_id < ' . intval( $end );
153 $this->dumpFrom( $condition );
157 * @param $title Title
159 public function pageByTitle( $title ) {
161 'page_namespace=' . $title->getNamespace() .
162 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
166 * @param $name string
167 * @throws MWException
169 public function pageByName( $name ) {
170 $title = Title
::newFromText( $name );
171 if ( is_null( $title ) ) {
172 throw new MWException( "Can't export invalid title" );
174 $this->pageByTitle( $title );
179 * @param $names array
181 public function pagesByName( $names ) {
182 foreach ( $names as $name ) {
183 $this->pageByName( $name );
187 public function allLogs() {
188 $this->dumpFrom( '' );
195 public function logsByRange( $start, $end ) {
196 $condition = 'log_id >= ' . intval( $start );
198 $condition .= ' AND log_id < ' . intval( $end );
200 $this->dumpFrom( $condition );
204 * Generates the distinct list of authors of an article
205 * Not called by default (depends on $this->list_authors)
206 * Can be set by Special:Export when not exporting whole history
210 protected function do_list_authors( $cond ) {
211 wfProfileIn( __METHOD__
);
212 $this->author_list
= "<contributors>";
215 $res = $this->db
->select(
216 array( 'page', 'revision' ),
217 array( 'DISTINCT rev_user_text', 'rev_user' ),
219 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
226 foreach ( $res as $row ) {
227 $this->author_list
.= "<contributor>" .
229 htmlentities( $row->rev_user_text
) .
236 $this->author_list
.= "</contributors>";
237 wfProfileOut( __METHOD__
);
241 * @param $cond string
242 * @throws MWException
245 protected function dumpFrom( $cond = '' ) {
246 wfProfileIn( __METHOD__
);
247 # For logging dumps...
248 if ( $this->history
& self
::LOGS
) {
249 $where = array( 'user_id = log_user' );
251 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
252 if ( $hideLogs ) $where[] = $hideLogs;
253 # Add on any caller specified conditions
254 if ( $cond ) $where[] = $cond;
255 # Get logging table name for logging.* clause
256 $logging = $this->db
->tableName( 'logging' );
258 if ( $this->buffer
== WikiExporter
::STREAM
) {
259 $prev = $this->db
->bufferResults( false );
261 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
263 $result = $this->db
->select( array( 'logging', 'user' ),
264 array( "{$logging}.*", 'user_name' ), // grab the user name
267 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
269 $wrapper = $this->db
->resultObject( $result );
270 $this->outputLogStream( $wrapper );
271 if ( $this->buffer
== WikiExporter
::STREAM
) {
272 $this->db
->bufferResults( $prev );
274 } catch ( Exception
$e ) {
275 // Throwing the exception does not reliably free the resultset, and
276 // would also leave the connection in unbuffered mode.
283 } catch ( Exception
$e2 ) {
284 // Already in panic mode -> ignoring $e2 as $e has
288 // Putting database back in previous buffer mode
290 if ( $this->buffer
== WikiExporter
::STREAM
) {
291 $this->db
->bufferResults( $prev );
293 } catch ( Exception
$e2 ) {
294 // Already in panic mode -> ignoring $e2 as $e has
298 // Inform caller about problem
303 $tables = array( 'page', 'revision' );
304 $opts = array( 'ORDER BY' => 'page_id ASC' );
305 $opts['USE INDEX'] = array();
307 if ( is_array( $this->history
) ) {
308 # Time offset/limit for all pages/history...
309 $revJoin = 'page_id=rev_page';
311 if ( $this->history
['dir'] == 'asc' ) {
313 $opts['ORDER BY'] = 'rev_timestamp ASC';
316 $opts['ORDER BY'] = 'rev_timestamp DESC';
319 if ( !empty( $this->history
['offset'] ) ) {
320 $revJoin .= " AND rev_timestamp $op " .
321 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
323 $join['revision'] = array( 'INNER JOIN', $revJoin );
325 if ( !empty( $this->history
['limit'] ) ) {
326 $opts['LIMIT'] = intval( $this->history
['limit'] );
328 } elseif ( $this->history
& WikiExporter
::FULL
) {
329 # Full history dumps...
330 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
331 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
332 # Latest revision dumps...
333 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
334 $this->do_list_authors( $cond );
336 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
337 } elseif ( $this->history
& WikiExporter
::STABLE
) {
338 # "Stable" revision dumps...
339 # Default JOIN, to be overridden...
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
341 # One, and only one hook should set this, and return false
342 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
343 wfProfileOut( __METHOD__
);
344 throw new MWException( __METHOD__
. " given invalid history dump type." );
346 } elseif ( $this->history
& WikiExporter
::RANGE
) {
347 # Dump of revisions within a specified range
348 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
349 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
351 # Uknown history specification parameter?
352 wfProfileOut( __METHOD__
);
353 throw new MWException( __METHOD__
. " given invalid history dump type." );
355 # Query optimization hacks
357 $opts[] = 'STRAIGHT_JOIN';
358 $opts['USE INDEX']['page'] = 'PRIMARY';
360 # Build text join options
361 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
363 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
366 if ( $this->buffer
== WikiExporter
::STREAM
) {
367 $prev = $this->db
->bufferResults( false );
370 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
372 wfRunHooks( 'ModifyExportQuery',
373 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
376 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
377 $wrapper = $this->db
->resultObject( $result );
378 # Output dump results
379 $this->outputPageStream( $wrapper );
381 if ( $this->buffer
== WikiExporter
::STREAM
) {
382 $this->db
->bufferResults( $prev );
384 } catch ( Exception
$e ) {
385 // Throwing the exception does not reliably free the resultset, and
386 // would also leave the connection in unbuffered mode.
393 } catch ( Exception
$e2 ) {
394 // Already in panic mode -> ignoring $e2 as $e has
398 // Putting database back in previous buffer mode
400 if ( $this->buffer
== WikiExporter
::STREAM
) {
401 $this->db
->bufferResults( $prev );
403 } catch ( Exception
$e2 ) {
404 // Already in panic mode -> ignoring $e2 as $e has
408 // Inform caller about problem
412 wfProfileOut( __METHOD__
);
416 * Runs through a query result set dumping page and revision records.
417 * The result set should be sorted/grouped by page to avoid duplicate
418 * page records in the output.
421 * streaming (non-buffered) queries, as long as it was made on a
422 * separate database connection not managed by LoadBalancer; some
423 * blob storage types will make queries to pull source data.
425 * @param $resultset ResultWrapper
427 protected function outputPageStream( $resultset ) {
429 foreach ( $resultset as $row ) {
430 if ( is_null( $last ) ||
431 $last->page_namespace
!= $row->page_namespace ||
432 $last->page_title
!= $row->page_title
) {
433 if ( isset( $last ) ) {
435 if ( $this->dumpUploads
) {
436 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
438 $output .= $this->writer
->closePage();
439 $this->sink
->writeClosePage( $output );
441 $output = $this->writer
->openPage( $row );
442 $this->sink
->writeOpenPage( $row, $output );
445 $output = $this->writer
->writeRevision( $row );
446 $this->sink
->writeRevision( $row, $output );
448 if ( isset( $last ) ) {
450 if ( $this->dumpUploads
) {
451 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
453 $output .= $this->author_list
;
454 $output .= $this->writer
->closePage();
455 $this->sink
->writeClosePage( $output );
460 * @param $resultset array
462 protected function outputLogStream( $resultset ) {
463 foreach ( $resultset as $row ) {
464 $output = $this->writer
->writeLogItem( $row );
465 $this->sink
->writeLogItem( $row, $output );
473 class XmlDumpWriter
{
475 * Returns the export schema version.
476 * @deprecated in 1.20; use WikiExporter::schemaVersion() instead
479 function schemaVersion() {
480 wfDeprecated( __METHOD__
, '1.20' );
481 return WikiExporter
::schemaVersion();
485 * Opens the XML output stream's root "<mediawiki>" element.
486 * This does not include an xml directive, so is safe to include
487 * as a subelement in a larger XML stream. Namespace and XML Schema
488 * references are included.
490 * Output will be encoded in UTF-8.
494 function openStream() {
495 global $wgLanguageCode;
496 $ver = WikiExporter
::schemaVersion();
497 return Xml
::element( 'mediawiki', array(
498 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
499 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
500 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
501 "http://www.mediawiki.org/xml/export-$ver.xsd",
503 'xml:lang' => $wgLanguageCode ),
512 function siteInfo() {
517 $this->caseSetting(),
518 $this->namespaces() );
519 return " <siteinfo>\n " .
520 implode( "\n ", $info ) .
527 function sitename() {
529 return Xml
::element( 'sitename', array(), $wgSitename );
535 function generator() {
537 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
543 function homelink() {
544 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalUrl() );
550 function caseSetting() {
551 global $wgCapitalLinks;
552 // "case-insensitive" option is reserved for future
553 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
554 return Xml
::element( 'case', array(), $sensitivity );
560 function namespaces() {
562 $spaces = "<namespaces>\n";
563 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
565 Xml
::element( 'namespace',
567 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
570 $spaces .= " </namespaces>";
575 * Closes the output stream with the closing root element.
576 * Call when finished dumping things.
580 function closeStream() {
581 return "</mediawiki>\n";
585 * Opens a "<page>" section on the output stream, with data
586 * from the given database row.
592 function openPage( $row ) {
594 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
595 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
596 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
597 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
598 if ( $row->page_is_redirect
) {
599 $page = WikiPage
::factory( $title );
600 $redirect = $page->getRedirectTarget();
601 if ( $redirect instanceOf Title
&& $redirect->isValidRedirectTarget() ) {
602 $out .= ' ' . Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) ) . "\n";
606 if ( $row->page_restrictions
!= '' ) {
607 $out .= ' ' . Xml
::element( 'restrictions', array(),
608 strval( $row->page_restrictions
) ) . "\n";
611 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
617 * Closes a "<page>" section on the output stream.
622 function closePage() {
627 * Dumps a "<revision>" section on the output stream, with
628 * data filled in from the given database row.
634 function writeRevision( $row ) {
635 wfProfileIn( __METHOD__
);
637 $out = " <revision>\n";
638 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
639 if( $row->rev_parent_id
) {
640 $out .= " " . Xml
::element( 'parentid', null, strval( $row->rev_parent_id
) ) . "\n";
643 $out .= $this->writeTimestamp( $row->rev_timestamp
);
645 if ( $row->rev_deleted
& Revision
::DELETED_USER
) {
646 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
648 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
651 if ( $row->rev_minor_edit
) {
652 $out .= " <minor/>\n";
654 if ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
655 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
656 } elseif ( $row->rev_comment
!= '' ) {
657 $out .= " " . Xml
::elementClean( 'comment', array(), strval( $row->rev_comment
) ) . "\n";
660 if ( $row->rev_sha1
&& !( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
661 $out .= " " . Xml
::element('sha1', null, strval( $row->rev_sha1
) ) . "\n";
663 $out .= " <sha1/>\n";
667 if ( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
668 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
669 } elseif ( isset( $row->old_text
) ) {
670 // Raw text from the database may have invalid chars
671 $text = strval( Revision
::getRevisionText( $row ) );
672 $out .= " " . Xml
::elementClean( 'text',
673 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
674 strval( $text ) ) . "\n";
677 $out .= " " . Xml
::element( 'text',
678 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
682 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
684 $out .= " </revision>\n";
686 wfProfileOut( __METHOD__
);
691 * Dumps a "<logitem>" section on the output stream, with
692 * data filled in from the given database row.
698 function writeLogItem( $row ) {
699 wfProfileIn( __METHOD__
);
701 $out = " <logitem>\n";
702 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
704 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
706 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
707 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
709 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
712 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
713 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
714 } elseif ( $row->log_comment
!= '' ) {
715 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
718 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
719 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
721 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
722 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
724 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
725 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
726 $out .= " " . Xml
::elementClean( 'params',
727 array( 'xml:space' => 'preserve' ),
728 strval( $row->log_params
) ) . "\n";
731 $out .= " </logitem>\n";
733 wfProfileOut( __METHOD__
);
738 * @param $timestamp string
739 * @param $indent string Default to six spaces
742 function writeTimestamp( $timestamp, $indent = " " ) {
743 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
744 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
749 * @param $text string
750 * @param $indent string Default to six spaces
753 function writeContributor( $id, $text, $indent = " " ) {
754 $out = $indent . "<contributor>\n";
755 if ( $id ||
!IP
::isValid( $text ) ) {
756 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
757 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
759 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
761 $out .= $indent . "</contributor>\n";
766 * Warning! This data is potentially inconsistent. :(
768 * @param $dumpContents bool
771 function writeUploads( $row, $dumpContents = false ) {
772 if ( $row->page_namespace
== NS_FILE
) {
773 $img = wfLocalFile( $row->page_title
);
774 if ( $img && $img->exists() ) {
776 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
777 $out .= $this->writeUpload( $ver, $dumpContents );
779 $out .= $this->writeUpload( $img, $dumpContents );
788 * @param $dumpContents bool
791 function writeUpload( $file, $dumpContents = false ) {
792 if ( $file->isOld() ) {
794 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
798 if ( $dumpContents ) {
799 # Dump file as base64
800 # Uses only XML-safe characters, so does not need escaping
801 $contents = ' <contents encoding="base64">' .
802 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
807 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
808 $comment = Xml
::element( 'comment', array( 'deleted' => 'deleted' ) );
810 $comment = Xml
::elementClean( 'comment', null, $file->getDescription() );
812 return " <upload>\n" .
813 $this->writeTimestamp( $file->getTimestamp() ) .
814 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
815 " " . $comment . "\n" .
816 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
818 " " . Xml
::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
819 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
820 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
821 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
827 * Return prefixed text form of title, but using the content language's
828 * canonical namespace. This skips any special-casing such as gendered
829 * user namespaces -- which while useful, are not yet listed in the
830 * XML "<siteinfo>" data so are unsafe in export.
832 * @param Title $title
836 public static function canonicalTitle( Title
$title ) {
837 if ( $title->getInterwiki() ) {
838 return $title->getPrefixedText();
842 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
844 if ( $prefix !== '' ) {
848 return $prefix . $title->getText();
854 * Base class for output stream; prints to stdout or buffer or whereever.
860 * @param $string string
862 function writeOpenStream( $string ) {
863 $this->write( $string );
867 * @param $string string
869 function writeCloseStream( $string ) {
870 $this->write( $string );
875 * @param $string string
877 function writeOpenPage( $page, $string ) {
878 $this->write( $string );
882 * @param $string string
884 function writeClosePage( $string ) {
885 $this->write( $string );
890 * @param $string string
892 function writeRevision( $rev, $string ) {
893 $this->write( $string );
898 * @param $string string
900 function writeLogItem( $rev, $string ) {
901 $this->write( $string );
905 * Override to write to a different stream type.
906 * @param $string string
909 function write( $string ) {
914 * Close the old file, move it to a specified name,
915 * and reopen new file with the old name. Use this
916 * for writing out a file in multiple pieces
917 * at specified checkpoints (e.g. every n hours).
918 * @param $newname mixed File name. May be a string or an array with one element
920 function closeRenameAndReopen( $newname ) {
925 * Close the old file, and move it to a specified name.
926 * Use this for the last piece of a file written out
927 * at specified checkpoints (e.g. every n hours).
928 * @param $newname mixed File name. May be a string or an array with one element
929 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
931 function closeAndRename( $newname, $open = false ) {
936 * Returns the name of the file or files which are
937 * being written to, if there are any.
940 function getFilenames() {
946 * Stream outputter to send data to a file.
949 class DumpFileOutput
extends DumpOutput
{
950 protected $handle = false, $filename;
955 function __construct( $file ) {
956 $this->handle
= fopen( $file, "wt" );
957 $this->filename
= $file;
961 * @param $string string
963 function writeCloseStream( $string ) {
964 parent
::writeCloseStream( $string );
965 if ( $this->handle
) {
966 fclose( $this->handle
);
967 $this->handle
= false;
972 * @param $string string
974 function write( $string ) {
975 fputs( $this->handle
, $string );
981 function closeRenameAndReopen( $newname ) {
982 $this->closeAndRename( $newname, true );
987 * @throws MWException
989 function renameOrException( $newname ) {
990 if (! rename( $this->filename
, $newname ) ) {
991 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
996 * @param $newname array
998 * @throws MWException
1000 function checkRenameArgCount( $newname ) {
1001 if ( is_array( $newname ) ) {
1002 if ( count( $newname ) > 1 ) {
1003 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
1005 $newname = $newname[0];
1012 * @param $newname mixed
1015 function closeAndRename( $newname, $open = false ) {
1016 $newname = $this->checkRenameArgCount( $newname );
1018 if ( $this->handle
) {
1019 fclose( $this->handle
);
1020 $this->handle
= false;
1022 $this->renameOrException( $newname );
1024 $this->handle
= fopen( $this->filename
, "wt" );
1030 * @return string|null
1032 function getFilenames() {
1033 return $this->filename
;
1038 * Stream outputter to send data to a file via some filter program.
1039 * Even if compression is available in a library, using a separate
1040 * program can allow us to make use of a multi-processor system.
1043 class DumpPipeOutput
extends DumpFileOutput
{
1044 protected $command, $filename;
1045 protected $procOpenResource = false;
1051 function __construct( $command, $file = null ) {
1052 if ( !is_null( $file ) ) {
1053 $command .= " > " . wfEscapeShellArg( $file );
1056 $this->startCommand( $command );
1057 $this->command
= $command;
1058 $this->filename
= $file;
1062 * @param $string string
1064 function writeCloseStream( $string ) {
1065 parent
::writeCloseStream( $string );
1066 if ( $this->procOpenResource
) {
1067 proc_close( $this->procOpenResource
);
1068 $this->procOpenResource
= false;
1075 function startCommand( $command ) {
1077 0 => array( "pipe", "r" ),
1080 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
1081 $this->handle
= $pipes[0];
1085 * @param mixed $newname
1087 function closeRenameAndReopen( $newname ) {
1088 $this->closeAndRename( $newname, true );
1092 * @param $newname mixed
1095 function closeAndRename( $newname, $open = false ) {
1096 $newname = $this->checkRenameArgCount( $newname );
1098 if ( $this->handle
) {
1099 fclose( $this->handle
);
1100 $this->handle
= false;
1102 if ( $this->procOpenResource
) {
1103 proc_close( $this->procOpenResource
);
1104 $this->procOpenResource
= false;
1106 $this->renameOrException( $newname );
1108 $command = $this->command
;
1109 $command .= " > " . wfEscapeShellArg( $this->filename
);
1110 $this->startCommand( $command );
1118 * Sends dump output via the gzip compressor.
1121 class DumpGZipOutput
extends DumpPipeOutput
{
1124 * @param $file string
1126 function __construct( $file ) {
1127 parent
::__construct( "gzip", $file );
1132 * Sends dump output via the bgzip2 compressor.
1135 class DumpBZip2Output
extends DumpPipeOutput
{
1138 * @param $file string
1140 function __construct( $file ) {
1141 parent
::__construct( "bzip2", $file );
1146 * Sends dump output via the p7zip compressor.
1149 class Dump7ZipOutput
extends DumpPipeOutput
{
1152 * @param $file string
1154 function __construct( $file ) {
1155 $command = $this->setup7zCommand( $file );
1156 parent
::__construct( $command );
1157 $this->filename
= $file;
1161 * @param $file string
1164 function setup7zCommand( $file ) {
1165 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1166 // Suppress annoying useless crap from p7zip
1167 // Unfortunately this could suppress real error messages too
1168 $command .= ' >' . wfGetNull() . ' 2>&1';
1173 * @param $newname string
1176 function closeAndRename( $newname, $open = false ) {
1177 $newname = $this->checkRenameArgCount( $newname );
1179 fclose( $this->handle
);
1180 proc_close( $this->procOpenResource
);
1181 $this->renameOrException( $newname );
1183 $command = $this->setup7zCommand( $this->filename
);
1184 $this->startCommand( $command );
1191 * Dump output filter class.
1192 * This just does output filtering and streaming; XML formatting is done
1193 * higher up, so be careful in what you do.
1200 * FIXME will need to be made protected whenever legacy code
1208 protected $sendingThisPage;
1211 * @param $sink DumpOutput
1213 function __construct( &$sink ) {
1214 $this->sink
=& $sink;
1218 * @param $string string
1220 function writeOpenStream( $string ) {
1221 $this->sink
->writeOpenStream( $string );
1225 * @param $string string
1227 function writeCloseStream( $string ) {
1228 $this->sink
->writeCloseStream( $string );
1233 * @param $string string
1235 function writeOpenPage( $page, $string ) {
1236 $this->sendingThisPage
= $this->pass( $page, $string );
1237 if ( $this->sendingThisPage
) {
1238 $this->sink
->writeOpenPage( $page, $string );
1243 * @param $string string
1245 function writeClosePage( $string ) {
1246 if ( $this->sendingThisPage
) {
1247 $this->sink
->writeClosePage( $string );
1248 $this->sendingThisPage
= false;
1254 * @param $string string
1256 function writeRevision( $rev, $string ) {
1257 if ( $this->sendingThisPage
) {
1258 $this->sink
->writeRevision( $rev, $string );
1264 * @param $string string
1266 function writeLogItem( $rev, $string ) {
1267 $this->sink
->writeRevision( $rev, $string );
1271 * @param $newname string
1273 function closeRenameAndReopen( $newname ) {
1274 $this->sink
->closeRenameAndReopen( $newname );
1278 * @param $newname string
1281 function closeAndRename( $newname, $open = false ) {
1282 $this->sink
->closeAndRename( $newname, $open );
1288 function getFilenames() {
1289 return $this->sink
->getFilenames();
1293 * Override for page-based filter types.
1297 function pass( $page ) {
1303 * Simple dump output filter to exclude all talk pages.
1306 class DumpNotalkFilter
extends DumpFilter
{
1312 function pass( $page ) {
1313 return !MWNamespace
::isTalk( $page->page_namespace
);
1318 * Dump output filter to include or exclude pages in a given set of namespaces.
1321 class DumpNamespaceFilter
extends DumpFilter
{
1322 var $invert = false;
1323 var $namespaces = array();
1326 * @param $sink DumpOutput
1329 function __construct( &$sink, $param ) {
1330 parent
::__construct( $sink );
1333 "NS_MAIN" => NS_MAIN
,
1334 "NS_TALK" => NS_TALK
,
1335 "NS_USER" => NS_USER
,
1336 "NS_USER_TALK" => NS_USER_TALK
,
1337 "NS_PROJECT" => NS_PROJECT
,
1338 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1339 "NS_FILE" => NS_FILE
,
1340 "NS_FILE_TALK" => NS_FILE_TALK
,
1341 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1342 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1343 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1344 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1345 "NS_TEMPLATE" => NS_TEMPLATE
,
1346 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1347 "NS_HELP" => NS_HELP
,
1348 "NS_HELP_TALK" => NS_HELP_TALK
,
1349 "NS_CATEGORY" => NS_CATEGORY
,
1350 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1352 if ( $param { 0 } == '!' ) {
1353 $this->invert
= true;
1354 $param = substr( $param, 1 );
1357 foreach ( explode( ',', $param ) as $key ) {
1358 $key = trim( $key );
1359 if ( isset( $constants[$key] ) ) {
1360 $ns = $constants[$key];
1361 $this->namespaces
[$ns] = true;
1362 } elseif ( is_numeric( $key ) ) {
1363 $ns = intval( $key );
1364 $this->namespaces
[$ns] = true;
1366 throw new MWException( "Unrecognized namespace key '$key'\n" );
1375 function pass( $page ) {
1376 $match = isset( $this->namespaces
[$page->page_namespace
] );
1377 return $this->invert
xor $match;
1383 * Dump output filter to include only the last revision in each page sequence.
1386 class DumpLatestFilter
extends DumpFilter
{
1387 var $page, $pageString, $rev, $revString;
1391 * @param $string string
1393 function writeOpenPage( $page, $string ) {
1394 $this->page
= $page;
1395 $this->pageString
= $string;
1399 * @param $string string
1401 function writeClosePage( $string ) {
1403 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1404 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1405 $this->sink
->writeClosePage( $string );
1408 $this->revString
= null;
1410 $this->pageString
= null;
1415 * @param $string string
1417 function writeRevision( $rev, $string ) {
1418 if ( $rev->rev_id
== $this->page
->page_latest
) {
1420 $this->revString
= $string;
1426 * Base class for output stream; prints to stdout or buffer or whereever.
1429 class DumpMultiWriter
{
1434 function __construct( $sinks ) {
1435 $this->sinks
= $sinks;
1436 $this->count
= count( $sinks );
1440 * @param $string string
1442 function writeOpenStream( $string ) {
1443 for ( $i = 0; $i < $this->count
; $i++
) {
1444 $this->sinks
[$i]->writeOpenStream( $string );
1449 * @param $string string
1451 function writeCloseStream( $string ) {
1452 for ( $i = 0; $i < $this->count
; $i++
) {
1453 $this->sinks
[$i]->writeCloseStream( $string );
1459 * @param $string string
1461 function writeOpenPage( $page, $string ) {
1462 for ( $i = 0; $i < $this->count
; $i++
) {
1463 $this->sinks
[$i]->writeOpenPage( $page, $string );
1470 function writeClosePage( $string ) {
1471 for ( $i = 0; $i < $this->count
; $i++
) {
1472 $this->sinks
[$i]->writeClosePage( $string );
1480 function writeRevision( $rev, $string ) {
1481 for ( $i = 0; $i < $this->count
; $i++
) {
1482 $this->sinks
[$i]->writeRevision( $rev, $string );
1489 function closeRenameAndReopen( $newnames ) {
1490 $this->closeAndRename( $newnames, true );
1494 * @param $newnames array
1497 function closeAndRename( $newnames, $open = false ) {
1498 for ( $i = 0; $i < $this->count
; $i++
) {
1499 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1506 function getFilenames() {
1507 $filenames = array();
1508 for ( $i = 0; $i < $this->count
; $i++
) {
1509 $filenames[] = $this->sinks
[$i]->getFilenames();
1517 * @param $string string
1520 function xmlsafe( $string ) {
1521 wfProfileIn( __FUNCTION__
);
1524 * The page may contain old data which has not been properly normalized.
1525 * Invalid UTF-8 sequences or forbidden control characters will make our
1526 * XML output invalid, so be sure to strip them out.
1528 $string = UtfNormal
::cleanUp( $string );
1530 $string = htmlspecialchars( $string );
1531 wfProfileOut( __FUNCTION__
);