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
53 * If using WikiExporter::STREAM to stream a large amount of data,
54 * provide a database connection which is not managed by
55 * LoadBalancer to read from: some history blob types will
56 * make additional queries to pull source data while the
57 * main query is still running.
59 * @param $db DatabaseBase
60 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
61 * WikiExporter::RANGE or WikiExporter::STABLE,
62 * or an associative array:
63 * offset: non-inclusive offset at which to start the query
64 * limit: maximum number of rows to return
65 * dir: "asc" or "desc" timestamp order
66 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
67 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
69 function __construct( &$db, $history = WikiExporter
::CURRENT
,
70 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
72 $this->history
= $history;
73 $this->buffer
= $buffer;
74 $this->writer
= new XmlDumpWriter();
75 $this->sink
= new DumpOutput();
80 * Set the DumpOutput or DumpFilter object which will receive
81 * various row objects and XML output for filtering. Filters
82 * can be chained or used as callbacks.
86 public function setOutputSink( &$sink ) {
90 public function openStream() {
91 $output = $this->writer
->openStream();
92 $this->sink
->writeOpenStream( $output );
95 public function closeStream() {
96 $output = $this->writer
->closeStream();
97 $this->sink
->writeCloseStream( $output );
101 * Dumps a series of page and revision records for all pages
102 * in the database, either including complete history or only
103 * the most recent version.
105 public function allPages() {
106 $this->dumpFrom( '' );
110 * Dumps a series of page and revision records for those pages
111 * in the database falling within the page_id range given.
112 * @param $start Int: inclusive lower limit (this id is included)
113 * @param $end Int: Exclusive upper limit (this id is not included)
114 * If 0, no upper limit.
116 public function pagesByRange( $start, $end ) {
117 $condition = 'page_id >= ' . intval( $start );
119 $condition .= ' AND page_id < ' . intval( $end );
121 $this->dumpFrom( $condition );
125 * Dumps a series of page and revision records for those pages
126 * in the database with revisions falling within the rev_id range given.
127 * @param $start Int: inclusive lower limit (this id is included)
128 * @param $end Int: Exclusive upper limit (this id is not included)
129 * If 0, no upper limit.
131 public function revsByRange( $start, $end ) {
132 $condition = 'rev_id >= ' . intval( $start );
134 $condition .= ' AND rev_id < ' . intval( $end );
136 $this->dumpFrom( $condition );
140 * @param $title Title
142 public function pageByTitle( $title ) {
144 'page_namespace=' . $title->getNamespace() .
145 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
148 public function pageByName( $name ) {
149 $title = Title
::newFromText( $name );
150 if ( is_null( $title ) ) {
151 throw new MWException( "Can't export invalid title" );
153 $this->pageByTitle( $title );
157 public function pagesByName( $names ) {
158 foreach ( $names as $name ) {
159 $this->pageByName( $name );
163 public function allLogs() {
164 $this->dumpFrom( '' );
167 public function logsByRange( $start, $end ) {
168 $condition = 'log_id >= ' . intval( $start );
170 $condition .= ' AND log_id < ' . intval( $end );
172 $this->dumpFrom( $condition );
175 # Generates the distinct list of authors of an article
176 # Not called by default (depends on $this->list_authors)
177 # Can be set by Special:Export when not exporting whole history
178 protected function do_list_authors( $cond ) {
179 wfProfileIn( __METHOD__
);
180 $this->author_list
= "<contributors>";
183 $res = $this->db
->select(
184 array( 'page', 'revision' ),
185 array( 'DISTINCT rev_user_text', 'rev_user' ),
187 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
194 foreach ( $res as $row ) {
195 $this->author_list
.= "<contributor>" .
197 htmlentities( $row->rev_user_text
) .
204 $this->author_list
.= "</contributors>";
205 wfProfileOut( __METHOD__
);
208 protected function dumpFrom( $cond = '' ) {
209 wfProfileIn( __METHOD__
);
210 # For logging dumps...
211 if ( $this->history
& self
::LOGS
) {
212 $where = array( 'user_id = log_user' );
214 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
215 if ( $hideLogs ) $where[] = $hideLogs;
216 # Add on any caller specified conditions
217 if ( $cond ) $where[] = $cond;
218 # Get logging table name for logging.* clause
219 $logging = $this->db
->tableName( 'logging' );
221 if ( $this->buffer
== WikiExporter
::STREAM
) {
222 $prev = $this->db
->bufferResults( false );
224 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
226 $result = $this->db
->select( array( 'logging', 'user' ),
227 array( "{$logging}.*", 'user_name' ), // grab the user name
230 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
232 $wrapper = $this->db
->resultObject( $result );
233 $this->outputLogStream( $wrapper );
234 if ( $this->buffer
== WikiExporter
::STREAM
) {
235 $this->db
->bufferResults( $prev );
237 } catch ( Exception
$e ) {
238 // Throwing the exception does not reliably free the resultset, and
239 // would also leave the connection in unbuffered mode.
246 } catch ( Exception
$e2 ) {
247 // Already in panic mode -> ignoring $e2 as $e has
251 // Putting database back in previous buffer mode
253 if ( $this->buffer
== WikiExporter
::STREAM
) {
254 $this->db
->bufferResults( $prev );
256 } catch ( Exception
$e2 ) {
257 // Already in panic mode -> ignoring $e2 as $e has
261 // Inform caller about problem
266 $tables = array( 'page', 'revision' );
267 $opts = array( 'ORDER BY' => 'page_id ASC' );
268 $opts['USE INDEX'] = array();
270 if ( is_array( $this->history
) ) {
271 # Time offset/limit for all pages/history...
272 $revJoin = 'page_id=rev_page';
274 if ( $this->history
['dir'] == 'asc' ) {
276 $opts['ORDER BY'] = 'rev_timestamp ASC';
279 $opts['ORDER BY'] = 'rev_timestamp DESC';
282 if ( !empty( $this->history
['offset'] ) ) {
283 $revJoin .= " AND rev_timestamp $op " .
284 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
286 $join['revision'] = array( 'INNER JOIN', $revJoin );
288 if ( !empty( $this->history
['limit'] ) ) {
289 $opts['LIMIT'] = intval( $this->history
['limit'] );
291 } elseif ( $this->history
& WikiExporter
::FULL
) {
292 # Full history dumps...
293 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
294 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
295 # Latest revision dumps...
296 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
297 $this->do_list_authors( $cond );
299 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
300 } elseif ( $this->history
& WikiExporter
::STABLE
) {
301 # "Stable" revision dumps...
302 # Default JOIN, to be overridden...
303 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
304 # One, and only one hook should set this, and return false
305 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
306 wfProfileOut( __METHOD__
);
307 throw new MWException( __METHOD__
. " given invalid history dump type." );
309 } elseif ( $this->history
& WikiExporter
::RANGE
) {
310 # Dump of revisions within a specified range
311 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
312 $opts['ORDER BY'] = 'rev_page ASC, rev_id ASC';
314 # Uknown history specification parameter?
315 wfProfileOut( __METHOD__
);
316 throw new MWException( __METHOD__
. " given invalid history dump type." );
318 # Query optimization hacks
320 $opts[] = 'STRAIGHT_JOIN';
321 $opts['USE INDEX']['page'] = 'PRIMARY';
323 # Build text join options
324 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
326 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
329 if ( $this->buffer
== WikiExporter
::STREAM
) {
330 $prev = $this->db
->bufferResults( false );
333 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
335 wfRunHooks( 'ModifyExportQuery',
336 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
339 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
340 $wrapper = $this->db
->resultObject( $result );
341 # Output dump results
342 $this->outputPageStream( $wrapper );
344 if ( $this->buffer
== WikiExporter
::STREAM
) {
345 $this->db
->bufferResults( $prev );
347 } catch ( Exception
$e ) {
348 // Throwing the exception does not reliably free the resultset, and
349 // would also leave the connection in unbuffered mode.
356 } catch ( Exception
$e2 ) {
357 // Already in panic mode -> ignoring $e2 as $e has
361 // Putting database back in previous buffer mode
363 if ( $this->buffer
== WikiExporter
::STREAM
) {
364 $this->db
->bufferResults( $prev );
366 } catch ( Exception
$e2 ) {
367 // Already in panic mode -> ignoring $e2 as $e has
371 // Inform caller about problem
375 wfProfileOut( __METHOD__
);
379 * Runs through a query result set dumping page and revision records.
380 * The result set should be sorted/grouped by page to avoid duplicate
381 * page records in the output.
384 * streaming (non-buffered) queries, as long as it was made on a
385 * separate database connection not managed by LoadBalancer; some
386 * blob storage types will make queries to pull source data.
388 * @param $resultset ResultWrapper
390 protected function outputPageStream( $resultset ) {
392 foreach ( $resultset as $row ) {
393 if ( is_null( $last ) ||
394 $last->page_namespace
!= $row->page_namespace ||
395 $last->page_title
!= $row->page_title
) {
396 if ( isset( $last ) ) {
398 if ( $this->dumpUploads
) {
399 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
401 $output .= $this->writer
->closePage();
402 $this->sink
->writeClosePage( $output );
404 $output = $this->writer
->openPage( $row );
405 $this->sink
->writeOpenPage( $row, $output );
408 $output = $this->writer
->writeRevision( $row );
409 $this->sink
->writeRevision( $row, $output );
411 if ( isset( $last ) ) {
413 if ( $this->dumpUploads
) {
414 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
416 $output .= $this->author_list
;
417 $output .= $this->writer
->closePage();
418 $this->sink
->writeClosePage( $output );
422 protected function outputLogStream( $resultset ) {
423 foreach ( $resultset as $row ) {
424 $output = $this->writer
->writeLogItem( $row );
425 $this->sink
->writeLogItem( $row, $output );
433 class XmlDumpWriter
{
435 * Returns the export schema version.
438 function schemaVersion() {
443 * Opens the XML output stream's root <mediawiki> element.
444 * This does not include an xml directive, so is safe to include
445 * as a subelement in a larger XML stream. Namespace and XML Schema
446 * references are included.
448 * Output will be encoded in UTF-8.
452 function openStream() {
453 global $wgLanguageCode;
454 $ver = $this->schemaVersion();
455 return Xml
::element( 'mediawiki', array(
456 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
457 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
458 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
459 "http://www.mediawiki.org/xml/export-$ver.xsd",
461 'xml:lang' => $wgLanguageCode ),
467 function siteInfo() {
472 $this->caseSetting(),
473 $this->namespaces() );
474 return " <siteinfo>\n " .
475 implode( "\n ", $info ) .
479 function sitename() {
481 return Xml
::element( 'sitename', array(), $wgSitename );
484 function generator() {
486 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
489 function homelink() {
490 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalUrl() );
493 function caseSetting() {
494 global $wgCapitalLinks;
495 // "case-insensitive" option is reserved for future
496 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
497 return Xml
::element( 'case', array(), $sensitivity );
500 function namespaces() {
502 $spaces = "<namespaces>\n";
503 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
505 Xml
::element( 'namespace',
507 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
510 $spaces .= " </namespaces>";
515 * Closes the output stream with the closing root element.
516 * Call when finished dumping things.
520 function closeStream() {
521 return "</mediawiki>\n";
525 * Opens a <page> section on the output stream, with data
526 * from the given database row.
532 function openPage( $row ) {
534 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
535 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
536 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
537 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
538 if ( $row->page_is_redirect
) {
539 $page = WikiPage
::factory( $title );
540 $redirect = $page->getRedirectTarget();
541 if ( $redirect instanceOf Title
&& $redirect->isValidRedirectTarget() ) {
542 $out .= ' ' . Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) ) . "\n";
546 if ( $row->page_restrictions
!= '' ) {
547 $out .= ' ' . Xml
::element( 'restrictions', array(),
548 strval( $row->page_restrictions
) ) . "\n";
551 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
557 * Closes a <page> section on the output stream.
562 function closePage() {
567 * Dumps a <revision> section on the output stream, with
568 * data filled in from the given database row.
574 function writeRevision( $row ) {
575 wfProfileIn( __METHOD__
);
577 $out = " <revision>\n";
578 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
580 $out .= $this->writeTimestamp( $row->rev_timestamp
);
582 if ( $row->rev_deleted
& Revision
::DELETED_USER
) {
583 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
585 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
588 if ( $row->rev_minor_edit
) {
589 $out .= " <minor/>\n";
591 if ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) {
592 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
593 } elseif ( $row->rev_comment
!= '' ) {
594 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->rev_comment
) ) . "\n";
598 if ( $row->rev_deleted
& Revision
::DELETED_TEXT
) {
599 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
600 } elseif ( isset( $row->old_text
) ) {
601 // Raw text from the database may have invalid chars
602 $text = strval( Revision
::getRevisionText( $row ) );
603 $out .= " " . Xml
::elementClean( 'text',
604 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
605 strval( $text ) ) . "\n";
608 $out .= " " . Xml
::element( 'text',
609 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
613 if ( $row->rev_sha1
&& !( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
614 $out .= " " . Xml
::element('sha1', null, strval( $row->rev_sha1
) ) . "\n";
616 $out .= " <sha1/>\n";
619 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
621 $out .= " </revision>\n";
623 wfProfileOut( __METHOD__
);
628 * Dumps a <logitem> section on the output stream, with
629 * data filled in from the given database row.
635 function writeLogItem( $row ) {
636 wfProfileIn( __METHOD__
);
638 $out = " <logitem>\n";
639 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
641 $out .= $this->writeTimestamp( $row->log_timestamp
);
643 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
644 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
646 $out .= $this->writeContributor( $row->log_user
, $row->user_name
);
649 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
650 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
651 } elseif ( $row->log_comment
!= '' ) {
652 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
655 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
656 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
658 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
659 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
661 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
662 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
663 $out .= " " . Xml
::elementClean( 'params',
664 array( 'xml:space' => 'preserve' ),
665 strval( $row->log_params
) ) . "\n";
668 $out .= " </logitem>\n";
670 wfProfileOut( __METHOD__
);
674 function writeTimestamp( $timestamp ) {
675 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
676 return " " . Xml
::element( 'timestamp', null, $ts ) . "\n";
679 function writeContributor( $id, $text ) {
680 $out = " <contributor>\n";
681 if ( $id ||
!IP
::isValid( $text ) ) {
682 $out .= " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
683 $out .= " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
685 $out .= " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
687 $out .= " </contributor>\n";
692 * Warning! This data is potentially inconsistent. :(
695 function writeUploads( $row, $dumpContents = false ) {
696 if ( $row->page_namespace
== NS_IMAGE
) {
697 $img = wfLocalFile( $row->page_title
);
698 if ( $img && $img->exists() ) {
700 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
701 $out .= $this->writeUpload( $ver, $dumpContents );
703 $out .= $this->writeUpload( $img, $dumpContents );
712 * @param $dumpContents bool
715 function writeUpload( $file, $dumpContents = false ) {
716 if ( $file->isOld() ) {
718 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
722 if ( $dumpContents ) {
723 # Dump file as base64
724 # Uses only XML-safe characters, so does not need escaping
725 $contents = ' <contents encoding="base64">' .
726 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
731 return " <upload>\n" .
732 $this->writeTimestamp( $file->getTimestamp() ) .
733 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
734 " " . Xml
::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
735 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
737 " " . Xml
::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
738 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
739 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
740 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
746 * Return prefixed text form of title, but using the content language's
747 * canonical namespace. This skips any special-casing such as gendered
748 * user namespaces -- which while useful, are not yet listed in the
749 * XML <siteinfo> data so are unsafe in export.
751 * @param Title $title
755 public static function canonicalTitle( Title
$title ) {
756 if ( $title->getInterwiki() ) {
757 return $title->getPrefixedText();
761 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
763 if ( $prefix !== '' ) {
767 return $prefix . $title->getText();
773 * Base class for output stream; prints to stdout or buffer or whereever.
777 function writeOpenStream( $string ) {
778 $this->write( $string );
781 function writeCloseStream( $string ) {
782 $this->write( $string );
785 function writeOpenPage( $page, $string ) {
786 $this->write( $string );
789 function writeClosePage( $string ) {
790 $this->write( $string );
793 function writeRevision( $rev, $string ) {
794 $this->write( $string );
797 function writeLogItem( $rev, $string ) {
798 $this->write( $string );
802 * Override to write to a different stream type.
805 function write( $string ) {
810 * Close the old file, move it to a specified name,
811 * and reopen new file with the old name. Use this
812 * for writing out a file in multiple pieces
813 * at specified checkpoints (e.g. every n hours).
814 * @param $newname mixed File name. May be a string or an array with one element
816 function closeRenameAndReopen( $newname ) {
821 * Close the old file, and move it to a specified name.
822 * Use this for the last piece of a file written out
823 * at specified checkpoints (e.g. every n hours).
824 * @param $newname mixed File name. May be a string or an array with one element
825 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
827 function closeAndRename( $newname, $open = false ) {
832 * Returns the name of the file or files which are
833 * being written to, if there are any.
836 function getFilenames() {
842 * Stream outputter to send data to a file.
845 class DumpFileOutput
extends DumpOutput
{
846 protected $handle = false, $filename;
848 function __construct( $file ) {
849 $this->handle
= fopen( $file, "wt" );
850 $this->filename
= $file;
853 function writeCloseStream( $string ) {
854 parent
::writeCloseStream( $string );
855 if ( $this->handle
) {
856 fclose( $this->handle
);
857 $this->handle
= false;
861 function write( $string ) {
862 fputs( $this->handle
, $string );
865 function closeRenameAndReopen( $newname ) {
866 $this->closeAndRename( $newname, true );
869 function renameOrException( $newname ) {
870 if (! rename( $this->filename
, $newname ) ) {
871 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
875 function checkRenameArgCount( $newname ) {
876 if ( is_array( $newname ) ) {
877 if ( count( $newname ) > 1 ) {
878 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
880 $newname = $newname[0];
886 function closeAndRename( $newname, $open = false ) {
887 $newname = $this->checkRenameArgCount( $newname );
889 if ( $this->handle
) {
890 fclose( $this->handle
);
891 $this->handle
= false;
893 $this->renameOrException( $newname );
895 $this->handle
= fopen( $this->filename
, "wt" );
900 function getFilenames() {
901 return $this->filename
;
906 * Stream outputter to send data to a file via some filter program.
907 * Even if compression is available in a library, using a separate
908 * program can allow us to make use of a multi-processor system.
911 class DumpPipeOutput
extends DumpFileOutput
{
912 protected $command, $filename;
913 protected $procOpenResource = false;
915 function __construct( $command, $file = null ) {
916 if ( !is_null( $file ) ) {
917 $command .= " > " . wfEscapeShellArg( $file );
920 $this->startCommand( $command );
921 $this->command
= $command;
922 $this->filename
= $file;
925 function writeCloseStream( $string ) {
926 parent
::writeCloseStream( $string );
927 if ( $this->procOpenResource
) {
928 proc_close( $this->procOpenResource
);
929 $this->procOpenResource
= false;
933 function startCommand( $command ) {
935 0 => array( "pipe", "r" ),
938 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
939 $this->handle
= $pipes[0];
942 function closeRenameAndReopen( $newname ) {
943 $this->closeAndRename( $newname, true );
946 function closeAndRename( $newname, $open = false ) {
947 $newname = $this->checkRenameArgCount( $newname );
949 if ( $this->handle
) {
950 fclose( $this->handle
);
951 $this->handle
= false;
953 if ( $this->procOpenResource
) {
954 proc_close( $this->procOpenResource
);
955 $this->procOpenResource
= false;
957 $this->renameOrException( $newname );
959 $command = $this->command
;
960 $command .= " > " . wfEscapeShellArg( $this->filename
);
961 $this->startCommand( $command );
969 * Sends dump output via the gzip compressor.
972 class DumpGZipOutput
extends DumpPipeOutput
{
973 function __construct( $file ) {
974 parent
::__construct( "gzip", $file );
979 * Sends dump output via the bgzip2 compressor.
982 class DumpBZip2Output
extends DumpPipeOutput
{
983 function __construct( $file ) {
984 parent
::__construct( "bzip2", $file );
989 * Sends dump output via the p7zip compressor.
992 class Dump7ZipOutput
extends DumpPipeOutput
{
993 function __construct( $file ) {
994 $command = $this->setup7zCommand( $file );
995 parent
::__construct( $command );
996 $this->filename
= $file;
999 function setup7zCommand( $file ) {
1000 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1001 // Suppress annoying useless crap from p7zip
1002 // Unfortunately this could suppress real error messages too
1003 $command .= ' >' . wfGetNull() . ' 2>&1';
1007 function closeAndRename( $newname, $open = false ) {
1008 $newname = $this->checkRenameArgCount( $newname );
1010 fclose( $this->handle
);
1011 proc_close( $this->procOpenResource
);
1012 $this->renameOrException( $newname );
1014 $command = $this->setup7zCommand( $this->filename
);
1015 $this->startCommand( $command );
1024 * Dump output filter class.
1025 * This just does output filtering and streaming; XML formatting is done
1026 * higher up, so be careful in what you do.
1030 function __construct( &$sink ) {
1031 $this->sink
=& $sink;
1034 function writeOpenStream( $string ) {
1035 $this->sink
->writeOpenStream( $string );
1038 function writeCloseStream( $string ) {
1039 $this->sink
->writeCloseStream( $string );
1042 function writeOpenPage( $page, $string ) {
1043 $this->sendingThisPage
= $this->pass( $page, $string );
1044 if ( $this->sendingThisPage
) {
1045 $this->sink
->writeOpenPage( $page, $string );
1049 function writeClosePage( $string ) {
1050 if ( $this->sendingThisPage
) {
1051 $this->sink
->writeClosePage( $string );
1052 $this->sendingThisPage
= false;
1056 function writeRevision( $rev, $string ) {
1057 if ( $this->sendingThisPage
) {
1058 $this->sink
->writeRevision( $rev, $string );
1062 function writeLogItem( $rev, $string ) {
1063 $this->sink
->writeRevision( $rev, $string );
1066 function closeRenameAndReopen( $newname ) {
1067 $this->sink
->closeRenameAndReopen( $newname );
1070 function closeAndRename( $newname, $open = false ) {
1071 $this->sink
->closeAndRename( $newname, $open );
1074 function getFilenames() {
1075 return $this->sink
->getFilenames();
1079 * Override for page-based filter types.
1082 function pass( $page ) {
1088 * Simple dump output filter to exclude all talk pages.
1091 class DumpNotalkFilter
extends DumpFilter
{
1092 function pass( $page ) {
1093 return !MWNamespace
::isTalk( $page->page_namespace
);
1098 * Dump output filter to include or exclude pages in a given set of namespaces.
1101 class DumpNamespaceFilter
extends DumpFilter
{
1102 var $invert = false;
1103 var $namespaces = array();
1105 function __construct( &$sink, $param ) {
1106 parent
::__construct( $sink );
1109 "NS_MAIN" => NS_MAIN
,
1110 "NS_TALK" => NS_TALK
,
1111 "NS_USER" => NS_USER
,
1112 "NS_USER_TALK" => NS_USER_TALK
,
1113 "NS_PROJECT" => NS_PROJECT
,
1114 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1115 "NS_FILE" => NS_FILE
,
1116 "NS_FILE_TALK" => NS_FILE_TALK
,
1117 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1118 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1119 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1120 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1121 "NS_TEMPLATE" => NS_TEMPLATE
,
1122 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1123 "NS_HELP" => NS_HELP
,
1124 "NS_HELP_TALK" => NS_HELP_TALK
,
1125 "NS_CATEGORY" => NS_CATEGORY
,
1126 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1128 if ( $param { 0 } == '!' ) {
1129 $this->invert
= true;
1130 $param = substr( $param, 1 );
1133 foreach ( explode( ',', $param ) as $key ) {
1134 $key = trim( $key );
1135 if ( isset( $constants[$key] ) ) {
1136 $ns = $constants[$key];
1137 $this->namespaces
[$ns] = true;
1138 } elseif ( is_numeric( $key ) ) {
1139 $ns = intval( $key );
1140 $this->namespaces
[$ns] = true;
1142 throw new MWException( "Unrecognized namespace key '$key'\n" );
1147 function pass( $page ) {
1148 $match = isset( $this->namespaces
[$page->page_namespace
] );
1149 return $this->invert
xor $match;
1155 * Dump output filter to include only the last revision in each page sequence.
1158 class DumpLatestFilter
extends DumpFilter
{
1159 var $page, $pageString, $rev, $revString;
1161 function writeOpenPage( $page, $string ) {
1162 $this->page
= $page;
1163 $this->pageString
= $string;
1166 function writeClosePage( $string ) {
1168 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1169 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1170 $this->sink
->writeClosePage( $string );
1173 $this->revString
= null;
1175 $this->pageString
= null;
1178 function writeRevision( $rev, $string ) {
1179 if ( $rev->rev_id
== $this->page
->page_latest
) {
1181 $this->revString
= $string;
1187 * Base class for output stream; prints to stdout or buffer or whereever.
1190 class DumpMultiWriter
{
1191 function __construct( $sinks ) {
1192 $this->sinks
= $sinks;
1193 $this->count
= count( $sinks );
1196 function writeOpenStream( $string ) {
1197 for ( $i = 0; $i < $this->count
; $i++
) {
1198 $this->sinks
[$i]->writeOpenStream( $string );
1202 function writeCloseStream( $string ) {
1203 for ( $i = 0; $i < $this->count
; $i++
) {
1204 $this->sinks
[$i]->writeCloseStream( $string );
1208 function writeOpenPage( $page, $string ) {
1209 for ( $i = 0; $i < $this->count
; $i++
) {
1210 $this->sinks
[$i]->writeOpenPage( $page, $string );
1214 function writeClosePage( $string ) {
1215 for ( $i = 0; $i < $this->count
; $i++
) {
1216 $this->sinks
[$i]->writeClosePage( $string );
1220 function writeRevision( $rev, $string ) {
1221 for ( $i = 0; $i < $this->count
; $i++
) {
1222 $this->sinks
[$i]->writeRevision( $rev, $string );
1226 function closeRenameAndReopen( $newnames ) {
1227 $this->closeAndRename( $newnames, true );
1230 function closeAndRename( $newnames, $open = false ) {
1231 for ( $i = 0; $i < $this->count
; $i++
) {
1232 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1236 function getFilenames() {
1237 $filenames = array();
1238 for ( $i = 0; $i < $this->count
; $i++
) {
1239 $filenames[] = $this->sinks
[$i]->getFilenames();
1246 function xmlsafe( $string ) {
1247 wfProfileIn( __FUNCTION__
);
1250 * The page may contain old data which has not been properly normalized.
1251 * Invalid UTF-8 sequences or forbidden control characters will make our
1252 * XML output invalid, so be sure to strip them out.
1254 $string = UtfNormal
::cleanUp( $string );
1256 $string = htmlspecialchars( $string );
1257 wfProfileOut( __FUNCTION__
);