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 * If using WikiExporter::STREAM to stream a large amount of data,
63 * provide a database connection which is not managed by
64 * LoadBalancer to read from: some history blob types will
65 * make additional queries to pull source data while the
66 * main query is still running.
68 * @param $db DatabaseBase
69 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
70 * WikiExporter::RANGE or WikiExporter::STABLE,
71 * or an associative array:
72 * offset: non-inclusive offset at which to start the query
73 * limit: maximum number of rows to return
74 * dir: "asc" or "desc" timestamp order
75 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
76 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
78 function __construct( &$db, $history = WikiExporter
::CURRENT
,
79 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
81 $this->history
= $history;
82 $this->buffer
= $buffer;
83 $this->writer
= new XmlDumpWriter();
84 $this->sink
= new DumpOutput();
89 * Set the DumpOutput or DumpFilter object which will receive
90 * various row objects and XML output for filtering. Filters
91 * can be chained or used as callbacks.
95 public function setOutputSink( &$sink ) {
99 public function openStream() {
100 $output = $this->writer
->openStream();
101 $this->sink
->writeOpenStream( $output );
104 public function closeStream() {
105 $output = $this->writer
->closeStream();
106 $this->sink
->writeCloseStream( $output );
110 * Dumps a series of page and revision records for all pages
111 * in the database, either including complete history or only
112 * the most recent version.
114 public function allPages() {
115 $this->dumpFrom( '' );
119 * Dumps a series of page and revision records for those pages
120 * in the database falling within the page_id range given.
121 * @param $start Int: inclusive lower limit (this id is included)
122 * @param $end Int: Exclusive upper limit (this id is not included)
123 * If 0, no upper limit.
125 public function pagesByRange( $start, $end ) {
126 $condition = 'page_id >= ' . intval( $start );
128 $condition .= ' AND page_id < ' . intval( $end );
130 $this->dumpFrom( $condition );
134 * Dumps a series of page and revision records for those pages
135 * in the database with revisions falling within the rev_id range given.
136 * @param $start Int: inclusive lower limit (this id is included)
137 * @param $end Int: Exclusive upper limit (this id is not included)
138 * If 0, no upper limit.
140 public function revsByRange( $start, $end ) {
141 $condition = 'rev_id >= ' . intval( $start );
143 $condition .= ' AND rev_id < ' . intval( $end );
145 $this->dumpFrom( $condition );
149 * @param $title Title
151 public function pageByTitle( $title ) {
153 'page_namespace=' . $title->getNamespace() .
154 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
158 * @param $name string
159 * @throws MWException
161 public function pageByName( $name ) {
162 $title = Title
::newFromText( $name );
163 if ( is_null( $title ) ) {
164 throw new MWException( "Can't export invalid title" );
166 $this->pageByTitle( $title );
171 * @param $names array
173 public function pagesByName( $names ) {
174 foreach ( $names as $name ) {
175 $this->pageByName( $name );
179 public function allLogs() {
180 $this->dumpFrom( '' );
187 public function logsByRange( $start, $end ) {
188 $condition = 'log_id >= ' . intval( $start );
190 $condition .= ' AND log_id < ' . intval( $end );
192 $this->dumpFrom( $condition );
196 * Generates the distinct list of authors of an article
197 * Not called by default (depends on $this->list_authors)
198 * Can be set by Special:Export when not exporting whole history
202 protected function do_list_authors( $cond ) {
203 wfProfileIn( __METHOD__
);
204 $this->author_list
= "<contributors>";
207 $res = $this->db
->select(
208 array( 'page', 'revision' ),
209 array( 'DISTINCT rev_user_text', 'rev_user' ),
211 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
218 foreach ( $res as $row ) {
219 $this->author_list
.= "<contributor>" .
221 htmlentities( $row->rev_user_text
) .
228 $this->author_list
.= "</contributors>";
229 wfProfileOut( __METHOD__
);
233 * @param $cond string
234 * @throws MWException
237 protected function dumpFrom( $cond = '' ) {
238 wfProfileIn( __METHOD__
);
239 # For logging dumps...
240 if ( $this->history
& self
::LOGS
) {
241 $where = array( 'user_id = log_user' );
243 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
244 if ( $hideLogs ) $where[] = $hideLogs;
245 # Add on any caller specified conditions
246 if ( $cond ) $where[] = $cond;
247 # Get logging table name for logging.* clause
248 $logging = $this->db
->tableName( 'logging' );
250 if ( $this->buffer
== WikiExporter
::STREAM
) {
251 $prev = $this->db
->bufferResults( false );
253 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
255 $result = $this->db
->select( array( 'logging', 'user' ),
256 array( "{$logging}.*", 'user_name' ), // grab the user name
259 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
261 $wrapper = $this->db
->resultObject( $result );
262 $this->outputLogStream( $wrapper );
263 if ( $this->buffer
== WikiExporter
::STREAM
) {
264 $this->db
->bufferResults( $prev );
266 } catch ( Exception
$e ) {
267 // Throwing the exception does not reliably free the resultset, and
268 // would also leave the connection in unbuffered mode.
275 } catch ( Exception
$e2 ) {
276 // Already in panic mode -> ignoring $e2 as $e has
280 // Putting database back in previous buffer mode
282 if ( $this->buffer
== WikiExporter
::STREAM
) {
283 $this->db
->bufferResults( $prev );
285 } catch ( Exception
$e2 ) {
286 // Already in panic mode -> ignoring $e2 as $e has
290 // Inform caller about problem
295 $tables = array( 'page', 'revision' );
296 $opts = array( 'ORDER BY' => 'page_id ASC' );
297 $opts['USE INDEX'] = array();
299 if ( is_array( $this->history
) ) {
300 # Time offset/limit for all pages/history...
301 $revJoin = 'page_id=rev_page';
303 if ( $this->history
['dir'] == 'asc' ) {
305 $opts['ORDER BY'] = 'rev_timestamp ASC';
308 $opts['ORDER BY'] = 'rev_timestamp DESC';
311 if ( !empty( $this->history
['offset'] ) ) {
312 $revJoin .= " AND rev_timestamp $op " .
313 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
315 $join['revision'] = array( 'INNER JOIN', $revJoin );
317 if ( !empty( $this->history
['limit'] ) ) {
318 $opts['LIMIT'] = intval( $this->history
['limit'] );
320 } elseif ( $this->history
& WikiExporter
::FULL
) {
321 # Full history dumps...
322 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
323 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
324 # Latest revision dumps...
325 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
326 $this->do_list_authors( $cond );
328 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
329 } elseif ( $this->history
& WikiExporter
::STABLE
) {
330 # "Stable" revision dumps...
331 # Default JOIN, to be overridden...
332 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
333 # One, and only one hook should set this, and return false
334 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
335 wfProfileOut( __METHOD__
);
336 throw new MWException( __METHOD__
. " given invalid history dump type." );
338 } elseif ( $this->history
& WikiExporter
::RANGE
) {
339 # Dump of revisions within a specified range
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
341 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
343 # Uknown history specification parameter?
344 wfProfileOut( __METHOD__
);
345 throw new MWException( __METHOD__
. " given invalid history dump type." );
347 # Query optimization hacks
349 $opts[] = 'STRAIGHT_JOIN';
350 $opts['USE INDEX']['page'] = 'PRIMARY';
352 # Build text join options
353 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
355 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
358 if ( $this->buffer
== WikiExporter
::STREAM
) {
359 $prev = $this->db
->bufferResults( false );
362 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
364 wfRunHooks( 'ModifyExportQuery',
365 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
368 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
369 $wrapper = $this->db
->resultObject( $result );
370 # Output dump results
371 $this->outputPageStream( $wrapper );
373 if ( $this->buffer
== WikiExporter
::STREAM
) {
374 $this->db
->bufferResults( $prev );
376 } catch ( Exception
$e ) {
377 // Throwing the exception does not reliably free the resultset, and
378 // would also leave the connection in unbuffered mode.
385 } catch ( Exception
$e2 ) {
386 // Already in panic mode -> ignoring $e2 as $e has
390 // Putting database back in previous buffer mode
392 if ( $this->buffer
== WikiExporter
::STREAM
) {
393 $this->db
->bufferResults( $prev );
395 } catch ( Exception
$e2 ) {
396 // Already in panic mode -> ignoring $e2 as $e has
400 // Inform caller about problem
404 wfProfileOut( __METHOD__
);
408 * Runs through a query result set dumping page and revision records.
409 * The result set should be sorted/grouped by page to avoid duplicate
410 * page records in the output.
413 * streaming (non-buffered) queries, as long as it was made on a
414 * separate database connection not managed by LoadBalancer; some
415 * blob storage types will make queries to pull source data.
417 * @param $resultset ResultWrapper
419 protected function outputPageStream( $resultset ) {
421 foreach ( $resultset as $row ) {
422 if ( is_null( $last ) ||
423 $last->page_namespace
!= $row->page_namespace ||
424 $last->page_title
!= $row->page_title
) {
425 if ( isset( $last ) ) {
427 if ( $this->dumpUploads
) {
428 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
430 $output .= $this->writer
->closePage();
431 $this->sink
->writeClosePage( $output );
433 $output = $this->writer
->openPage( $row );
434 $this->sink
->writeOpenPage( $row, $output );
437 $output = $this->writer
->writeRevision( $row );
438 $this->sink
->writeRevision( $row, $output );
440 if ( isset( $last ) ) {
442 if ( $this->dumpUploads
) {
443 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
445 $output .= $this->author_list
;
446 $output .= $this->writer
->closePage();
447 $this->sink
->writeClosePage( $output );
452 * @param $resultset array
454 protected function outputLogStream( $resultset ) {
455 foreach ( $resultset as $row ) {
456 $output = $this->writer
->writeLogItem( $row );
457 $this->sink
->writeLogItem( $row, $output );
465 class XmlDumpWriter
{
467 * Returns the export schema version.
470 function schemaVersion() {
475 * Opens the XML output stream's root <mediawiki> element.
476 * This does not include an xml directive, so is safe to include
477 * as a subelement in a larger XML stream. Namespace and XML Schema
478 * references are included.
480 * Output will be encoded in UTF-8.
484 function openStream() {
485 global $wgLanguageCode;
486 $ver = $this->schemaVersion();
487 return Xml
::element( 'mediawiki', array(
488 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
489 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
490 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
491 "http://www.mediawiki.org/xml/export-$ver.xsd",
493 'xml:lang' => $wgLanguageCode ),
502 function siteInfo() {
507 $this->caseSetting(),
508 $this->namespaces() );
509 return " <siteinfo>\n " .
510 implode( "\n ", $info ) .
517 function sitename() {
519 return Xml
::element( 'sitename', array(), $wgSitename );
525 function generator() {
527 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
533 function homelink() {
534 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalUrl() );
540 function caseSetting() {
541 global $wgCapitalLinks;
542 // "case-insensitive" option is reserved for future
543 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
544 return Xml
::element( 'case', array(), $sensitivity );
550 function namespaces() {
552 $spaces = "<namespaces>\n";
553 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
555 Xml
::element( 'namespace',
557 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
560 $spaces .= " </namespaces>";
565 * Closes the output stream with the closing root element.
566 * Call when finished dumping things.
570 function closeStream() {
571 return "</mediawiki>\n";
575 * Opens a <page> section on the output stream, with data
576 * from the given database row.
582 function openPage( $row ) {
584 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
585 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
586 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
587 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
588 if ( $row->page_is_redirect
) {
589 $page = WikiPage
::factory( $title );
590 $redirect = $page->getRedirectTarget();
591 if ( $redirect instanceOf Title
&& $redirect->isValidRedirectTarget() ) {
592 $out .= ' ' . Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) ) . "\n";
596 if ( $row->page_restrictions
!= '' ) {
597 $out .= ' ' . Xml
::element( 'restrictions', array(),
598 strval( $row->page_restrictions
) ) . "\n";
601 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
607 * Closes a <page> section on the output stream.
612 function closePage() {
617 * Dumps a <revision> section on the output stream, with
618 * data filled in from the given database row.
624 function writeRevision( $row ) {
625 wfProfileIn( __METHOD__
);
627 $out = " <revision>\n";
628 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
630 $out .= $this->writeTimestamp( $row->rev_timestamp
);
632 if ( $row->rev_deleted
& Revision
::DELETED_USER
) {
633 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
635 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
638 if ( $row->rev_minor_edit
) {
639 $out .= " <minor/>\n";
641 if ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
642 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
643 } elseif ( $row->rev_comment
!= '' ) {
644 $out .= " " . Xml
::elementClean( 'comment', array(), strval( $row->rev_comment
) ) . "\n";
648 if ( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
649 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
650 } elseif ( isset( $row->old_text
) ) {
651 // Raw text from the database may have invalid chars
652 $text = strval( Revision
::getRevisionText( $row ) );
653 $out .= " " . Xml
::elementClean( 'text',
654 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
655 strval( $text ) ) . "\n";
658 $out .= " " . Xml
::element( 'text',
659 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
663 if ( $row->rev_sha1
&& !( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
664 $out .= " " . Xml
::element('sha1', null, strval( $row->rev_sha1
) ) . "\n";
666 $out .= " <sha1/>\n";
669 if ( isset( $row->rev_content_model
) && !is_null( $row->rev_content_model
) ) {
670 $content_model = intval( $row->rev_content_model
);
672 // probably using $wgContentHandlerUseDB = false;
674 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
675 $content_model = ContentHandler
::getDefaultModelFor( $title );
678 $name = ContentHandler
::getContentModelName( $content_model );
679 $out .= " " . Xml
::element('model', array( 'name' => $name ), strval( $content_model ) ) . "\n";
681 if ( isset( $row->rev_content_format
) && !is_null( $row->rev_content_format
) ) {
682 $content_format = intval( $row->rev_content_format
);
684 // probably using $wgContentHandlerUseDB = false;
686 $content_handler = ContentHandler
::getForModelID( $content_model );
687 $content_format = $content_handler->getDefaultFormat();
690 $mime = ContentHandler
::getContentFormatMimeType( $content_format );
691 $out .= " " . Xml
::element('format', array( 'mime' => $mime ), strval( $content_format ) ) . "\n";
693 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
695 $out .= " </revision>\n";
697 wfProfileOut( __METHOD__
);
702 * Dumps a <logitem> section on the output stream, with
703 * data filled in from the given database row.
709 function writeLogItem( $row ) {
710 wfProfileIn( __METHOD__
);
712 $out = " <logitem>\n";
713 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
715 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
717 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
718 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
720 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
723 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
724 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
725 } elseif ( $row->log_comment
!= '' ) {
726 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
729 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
730 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
732 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
733 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
735 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
736 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
737 $out .= " " . Xml
::elementClean( 'params',
738 array( 'xml:space' => 'preserve' ),
739 strval( $row->log_params
) ) . "\n";
742 $out .= " </logitem>\n";
744 wfProfileOut( __METHOD__
);
749 * @param $timestamp string
752 function writeTimestamp( $timestamp, $indent = " " ) {
753 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
754 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
759 * @param $text string
762 function writeContributor( $id, $text, $indent = " " ) {
763 $out = $indent . "<contributor>\n";
764 if ( $id ||
!IP
::isValid( $text ) ) {
765 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
766 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
768 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
770 $out .= $indent . "</contributor>\n";
775 * Warning! This data is potentially inconsistent. :(
777 * @param $dumpContents bool
780 function writeUploads( $row, $dumpContents = false ) {
781 if ( $row->page_namespace
== NS_IMAGE
) {
782 $img = wfLocalFile( $row->page_title
);
783 if ( $img && $img->exists() ) {
785 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
786 $out .= $this->writeUpload( $ver, $dumpContents );
788 $out .= $this->writeUpload( $img, $dumpContents );
797 * @param $dumpContents bool
800 function writeUpload( $file, $dumpContents = false ) {
801 if ( $file->isOld() ) {
803 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
807 if ( $dumpContents ) {
808 # Dump file as base64
809 # Uses only XML-safe characters, so does not need escaping
810 $contents = ' <contents encoding="base64">' .
811 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
816 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
817 $comment = Xml
::element( 'comment', array( 'deleted' => 'deleted' ) );
819 $comment = Xml
::elementClean( 'comment', null, $file->getDescription() );
821 return " <upload>\n" .
822 $this->writeTimestamp( $file->getTimestamp() ) .
823 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
824 " " . $comment . "\n" .
825 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
827 " " . Xml
::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
828 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
829 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
830 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
836 * Return prefixed text form of title, but using the content language's
837 * canonical namespace. This skips any special-casing such as gendered
838 * user namespaces -- which while useful, are not yet listed in the
839 * XML <siteinfo> data so are unsafe in export.
841 * @param Title $title
845 public static function canonicalTitle( Title
$title ) {
846 if ( $title->getInterwiki() ) {
847 return $title->getPrefixedText();
851 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
853 if ( $prefix !== '' ) {
857 return $prefix . $title->getText();
863 * Base class for output stream; prints to stdout or buffer or whereever.
869 * @param $string string
871 function writeOpenStream( $string ) {
872 $this->write( $string );
876 * @param $string string
878 function writeCloseStream( $string ) {
879 $this->write( $string );
884 * @param $string string
886 function writeOpenPage( $page, $string ) {
887 $this->write( $string );
891 * @param $string string
893 function writeClosePage( $string ) {
894 $this->write( $string );
899 * @param $string string
901 function writeRevision( $rev, $string ) {
902 $this->write( $string );
907 * @param $string string
909 function writeLogItem( $rev, $string ) {
910 $this->write( $string );
914 * Override to write to a different stream type.
915 * @param $string string
918 function write( $string ) {
923 * Close the old file, move it to a specified name,
924 * and reopen new file with the old name. Use this
925 * for writing out a file in multiple pieces
926 * at specified checkpoints (e.g. every n hours).
927 * @param $newname mixed File name. May be a string or an array with one element
929 function closeRenameAndReopen( $newname ) {
934 * Close the old file, and move it to a specified name.
935 * Use this for the last piece of a file written out
936 * at specified checkpoints (e.g. every n hours).
937 * @param $newname mixed File name. May be a string or an array with one element
938 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
940 function closeAndRename( $newname, $open = false ) {
945 * Returns the name of the file or files which are
946 * being written to, if there are any.
949 function getFilenames() {
955 * Stream outputter to send data to a file.
958 class DumpFileOutput
extends DumpOutput
{
959 protected $handle = false, $filename;
964 function __construct( $file ) {
965 $this->handle
= fopen( $file, "wt" );
966 $this->filename
= $file;
970 * @param $string string
972 function writeCloseStream( $string ) {
973 parent
::writeCloseStream( $string );
974 if ( $this->handle
) {
975 fclose( $this->handle
);
976 $this->handle
= false;
981 * @param $string string
983 function write( $string ) {
984 fputs( $this->handle
, $string );
990 function closeRenameAndReopen( $newname ) {
991 $this->closeAndRename( $newname, true );
996 * @throws MWException
998 function renameOrException( $newname ) {
999 if (! rename( $this->filename
, $newname ) ) {
1000 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
1005 * @param $newname array
1007 * @throws MWException
1009 function checkRenameArgCount( $newname ) {
1010 if ( is_array( $newname ) ) {
1011 if ( count( $newname ) > 1 ) {
1012 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
1014 $newname = $newname[0];
1021 * @param $newname mixed
1024 function closeAndRename( $newname, $open = false ) {
1025 $newname = $this->checkRenameArgCount( $newname );
1027 if ( $this->handle
) {
1028 fclose( $this->handle
);
1029 $this->handle
= false;
1031 $this->renameOrException( $newname );
1033 $this->handle
= fopen( $this->filename
, "wt" );
1039 * @return string|null
1041 function getFilenames() {
1042 return $this->filename
;
1047 * Stream outputter to send data to a file via some filter program.
1048 * Even if compression is available in a library, using a separate
1049 * program can allow us to make use of a multi-processor system.
1052 class DumpPipeOutput
extends DumpFileOutput
{
1053 protected $command, $filename;
1054 protected $procOpenResource = false;
1060 function __construct( $command, $file = null ) {
1061 if ( !is_null( $file ) ) {
1062 $command .= " > " . wfEscapeShellArg( $file );
1065 $this->startCommand( $command );
1066 $this->command
= $command;
1067 $this->filename
= $file;
1071 * @param $string string
1073 function writeCloseStream( $string ) {
1074 parent
::writeCloseStream( $string );
1075 if ( $this->procOpenResource
) {
1076 proc_close( $this->procOpenResource
);
1077 $this->procOpenResource
= false;
1084 function startCommand( $command ) {
1086 0 => array( "pipe", "r" ),
1089 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
1090 $this->handle
= $pipes[0];
1094 * @param mixed $newname
1096 function closeRenameAndReopen( $newname ) {
1097 $this->closeAndRename( $newname, true );
1101 * @param $newname mixed
1104 function closeAndRename( $newname, $open = false ) {
1105 $newname = $this->checkRenameArgCount( $newname );
1107 if ( $this->handle
) {
1108 fclose( $this->handle
);
1109 $this->handle
= false;
1111 if ( $this->procOpenResource
) {
1112 proc_close( $this->procOpenResource
);
1113 $this->procOpenResource
= false;
1115 $this->renameOrException( $newname );
1117 $command = $this->command
;
1118 $command .= " > " . wfEscapeShellArg( $this->filename
);
1119 $this->startCommand( $command );
1127 * Sends dump output via the gzip compressor.
1130 class DumpGZipOutput
extends DumpPipeOutput
{
1133 * @param $file string
1135 function __construct( $file ) {
1136 parent
::__construct( "gzip", $file );
1141 * Sends dump output via the bgzip2 compressor.
1144 class DumpBZip2Output
extends DumpPipeOutput
{
1147 * @param $file string
1149 function __construct( $file ) {
1150 parent
::__construct( "bzip2", $file );
1155 * Sends dump output via the p7zip compressor.
1158 class Dump7ZipOutput
extends DumpPipeOutput
{
1161 * @param $file string
1163 function __construct( $file ) {
1164 $command = $this->setup7zCommand( $file );
1165 parent
::__construct( $command );
1166 $this->filename
= $file;
1170 * @param $file string
1173 function setup7zCommand( $file ) {
1174 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1175 // Suppress annoying useless crap from p7zip
1176 // Unfortunately this could suppress real error messages too
1177 $command .= ' >' . wfGetNull() . ' 2>&1';
1182 * @param $newname string
1185 function closeAndRename( $newname, $open = false ) {
1186 $newname = $this->checkRenameArgCount( $newname );
1188 fclose( $this->handle
);
1189 proc_close( $this->procOpenResource
);
1190 $this->renameOrException( $newname );
1192 $command = $this->setup7zCommand( $this->filename
);
1193 $this->startCommand( $command );
1200 * Dump output filter class.
1201 * This just does output filtering and streaming; XML formatting is done
1202 * higher up, so be careful in what you do.
1209 * FIXME will need to be made protected whenever legacy code
1217 protected $sendingThisPage;
1220 * @param $sink DumpOutput
1222 function __construct( &$sink ) {
1223 $this->sink
=& $sink;
1227 * @param $string string
1229 function writeOpenStream( $string ) {
1230 $this->sink
->writeOpenStream( $string );
1234 * @param $string string
1236 function writeCloseStream( $string ) {
1237 $this->sink
->writeCloseStream( $string );
1242 * @param $string string
1244 function writeOpenPage( $page, $string ) {
1245 $this->sendingThisPage
= $this->pass( $page, $string );
1246 if ( $this->sendingThisPage
) {
1247 $this->sink
->writeOpenPage( $page, $string );
1252 * @param $string string
1254 function writeClosePage( $string ) {
1255 if ( $this->sendingThisPage
) {
1256 $this->sink
->writeClosePage( $string );
1257 $this->sendingThisPage
= false;
1263 * @param $string string
1265 function writeRevision( $rev, $string ) {
1266 if ( $this->sendingThisPage
) {
1267 $this->sink
->writeRevision( $rev, $string );
1273 * @param $string string
1275 function writeLogItem( $rev, $string ) {
1276 $this->sink
->writeRevision( $rev, $string );
1280 * @param $newname string
1282 function closeRenameAndReopen( $newname ) {
1283 $this->sink
->closeRenameAndReopen( $newname );
1287 * @param $newname string
1290 function closeAndRename( $newname, $open = false ) {
1291 $this->sink
->closeAndRename( $newname, $open );
1297 function getFilenames() {
1298 return $this->sink
->getFilenames();
1302 * Override for page-based filter types.
1306 function pass( $page ) {
1312 * Simple dump output filter to exclude all talk pages.
1315 class DumpNotalkFilter
extends DumpFilter
{
1321 function pass( $page ) {
1322 return !MWNamespace
::isTalk( $page->page_namespace
);
1327 * Dump output filter to include or exclude pages in a given set of namespaces.
1330 class DumpNamespaceFilter
extends DumpFilter
{
1331 var $invert = false;
1332 var $namespaces = array();
1335 * @param $sink DumpOutput
1338 function __construct( &$sink, $param ) {
1339 parent
::__construct( $sink );
1342 "NS_MAIN" => NS_MAIN
,
1343 "NS_TALK" => NS_TALK
,
1344 "NS_USER" => NS_USER
,
1345 "NS_USER_TALK" => NS_USER_TALK
,
1346 "NS_PROJECT" => NS_PROJECT
,
1347 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1348 "NS_FILE" => NS_FILE
,
1349 "NS_FILE_TALK" => NS_FILE_TALK
,
1350 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1351 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1352 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1353 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1354 "NS_TEMPLATE" => NS_TEMPLATE
,
1355 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1356 "NS_HELP" => NS_HELP
,
1357 "NS_HELP_TALK" => NS_HELP_TALK
,
1358 "NS_CATEGORY" => NS_CATEGORY
,
1359 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1361 if ( $param { 0 } == '!' ) {
1362 $this->invert
= true;
1363 $param = substr( $param, 1 );
1366 foreach ( explode( ',', $param ) as $key ) {
1367 $key = trim( $key );
1368 if ( isset( $constants[$key] ) ) {
1369 $ns = $constants[$key];
1370 $this->namespaces
[$ns] = true;
1371 } elseif ( is_numeric( $key ) ) {
1372 $ns = intval( $key );
1373 $this->namespaces
[$ns] = true;
1375 throw new MWException( "Unrecognized namespace key '$key'\n" );
1384 function pass( $page ) {
1385 $match = isset( $this->namespaces
[$page->page_namespace
] );
1386 return $this->invert
xor $match;
1392 * Dump output filter to include only the last revision in each page sequence.
1395 class DumpLatestFilter
extends DumpFilter
{
1396 var $page, $pageString, $rev, $revString;
1400 * @param $string string
1402 function writeOpenPage( $page, $string ) {
1403 $this->page
= $page;
1404 $this->pageString
= $string;
1408 * @param $string string
1410 function writeClosePage( $string ) {
1412 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1413 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1414 $this->sink
->writeClosePage( $string );
1417 $this->revString
= null;
1419 $this->pageString
= null;
1424 * @param $string string
1426 function writeRevision( $rev, $string ) {
1427 if ( $rev->rev_id
== $this->page
->page_latest
) {
1429 $this->revString
= $string;
1435 * Base class for output stream; prints to stdout or buffer or whereever.
1438 class DumpMultiWriter
{
1443 function __construct( $sinks ) {
1444 $this->sinks
= $sinks;
1445 $this->count
= count( $sinks );
1449 * @param $string string
1451 function writeOpenStream( $string ) {
1452 for ( $i = 0; $i < $this->count
; $i++
) {
1453 $this->sinks
[$i]->writeOpenStream( $string );
1458 * @param $string string
1460 function writeCloseStream( $string ) {
1461 for ( $i = 0; $i < $this->count
; $i++
) {
1462 $this->sinks
[$i]->writeCloseStream( $string );
1468 * @param $string string
1470 function writeOpenPage( $page, $string ) {
1471 for ( $i = 0; $i < $this->count
; $i++
) {
1472 $this->sinks
[$i]->writeOpenPage( $page, $string );
1479 function writeClosePage( $string ) {
1480 for ( $i = 0; $i < $this->count
; $i++
) {
1481 $this->sinks
[$i]->writeClosePage( $string );
1489 function writeRevision( $rev, $string ) {
1490 for ( $i = 0; $i < $this->count
; $i++
) {
1491 $this->sinks
[$i]->writeRevision( $rev, $string );
1498 function closeRenameAndReopen( $newnames ) {
1499 $this->closeAndRename( $newnames, true );
1503 * @param $newnames array
1506 function closeAndRename( $newnames, $open = false ) {
1507 for ( $i = 0; $i < $this->count
; $i++
) {
1508 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1515 function getFilenames() {
1516 $filenames = array();
1517 for ( $i = 0; $i < $this->count
; $i++
) {
1518 $filenames[] = $this->sinks
[$i]->getFilenames();
1526 * @param $string string
1529 function xmlsafe( $string ) {
1530 wfProfileIn( __FUNCTION__
);
1533 * The page may contain old data which has not been properly normalized.
1534 * Invalid UTF-8 sequences or forbidden control characters will make our
1535 * XML output invalid, so be sure to strip them out.
1537 $string = UtfNormal
::cleanUp( $string );
1539 $string = htmlspecialchars( $string );
1540 wfProfileOut( __FUNCTION__
);