3 * Base classes for dumps and export
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * https://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 bool Return distinct author list (when not returning full history) */
35 public $list_authors = false;
38 public $dumpUploads = false;
41 public $dumpUploadFileContents = false;
44 protected $author_list = "";
48 const STABLE
= 4; // extension defined
64 /** @var DumpOutput */
68 * Returns the export schema version.
71 public static function schemaVersion() {
76 * If using WikiExporter::STREAM to stream a large amount of data,
77 * provide a database connection which is not managed by
78 * LoadBalancer to read from: some history blob types will
79 * make additional queries to pull source data while the
80 * main query is still running.
82 * @param DatabaseBase $db
83 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
84 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
85 * - offset: non-inclusive offset at which to start the query
86 * - limit: maximum number of rows to return
87 * - dir: "asc" or "desc" timestamp order
88 * @param int $buffer One of WikiExporter::BUFFER or WikiExporter::STREAM
89 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
91 function __construct( $db, $history = WikiExporter
::CURRENT
,
92 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
94 $this->history
= $history;
95 $this->buffer
= $buffer;
96 $this->writer
= new XmlDumpWriter();
97 $this->sink
= new DumpOutput();
102 * Set the DumpOutput or DumpFilter object which will receive
103 * various row objects and XML output for filtering. Filters
104 * can be chained or used as callbacks.
106 * @param DumpOutput $sink
108 public function setOutputSink( &$sink ) {
109 $this->sink
=& $sink;
112 public function openStream() {
113 $output = $this->writer
->openStream();
114 $this->sink
->writeOpenStream( $output );
117 public function closeStream() {
118 $output = $this->writer
->closeStream();
119 $this->sink
->writeCloseStream( $output );
123 * Dumps a series of page and revision records for all pages
124 * in the database, either including complete history or only
125 * the most recent version.
127 public function allPages() {
128 $this->dumpFrom( '' );
132 * Dumps a series of page and revision records for those pages
133 * in the database falling within the page_id range given.
134 * @param int $start Inclusive lower limit (this id is included)
135 * @param int $end Exclusive upper limit (this id is not included)
136 * If 0, no upper limit.
138 public function pagesByRange( $start, $end ) {
139 $condition = 'page_id >= ' . intval( $start );
141 $condition .= ' AND page_id < ' . intval( $end );
143 $this->dumpFrom( $condition );
147 * Dumps a series of page and revision records for those pages
148 * in the database with revisions falling within the rev_id range given.
149 * @param int $start Inclusive lower limit (this id is included)
150 * @param int $end Exclusive upper limit (this id is not included)
151 * If 0, no upper limit.
153 public function revsByRange( $start, $end ) {
154 $condition = 'rev_id >= ' . intval( $start );
156 $condition .= ' AND rev_id < ' . intval( $end );
158 $this->dumpFrom( $condition );
162 * @param Title $title
164 public function pageByTitle( $title ) {
166 'page_namespace=' . $title->getNamespace() .
167 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
171 * @param string $name
172 * @throws MWException
174 public function pageByName( $name ) {
175 $title = Title
::newFromText( $name );
176 if ( is_null( $title ) ) {
177 throw new MWException( "Can't export invalid title" );
179 $this->pageByTitle( $title );
184 * @param array $names
186 public function pagesByName( $names ) {
187 foreach ( $names as $name ) {
188 $this->pageByName( $name );
192 public function allLogs() {
193 $this->dumpFrom( '' );
200 public function logsByRange( $start, $end ) {
201 $condition = 'log_id >= ' . intval( $start );
203 $condition .= ' AND log_id < ' . intval( $end );
205 $this->dumpFrom( $condition );
209 * Generates the distinct list of authors of an article
210 * Not called by default (depends on $this->list_authors)
211 * Can be set by Special:Export when not exporting whole history
215 protected function do_list_authors( $cond ) {
216 wfProfileIn( __METHOD__
);
217 $this->author_list
= "<contributors>";
220 $res = $this->db
->select(
221 array( 'page', 'revision' ),
222 array( 'DISTINCT rev_user_text', 'rev_user' ),
224 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
231 foreach ( $res as $row ) {
232 $this->author_list
.= "<contributor>" .
234 htmlentities( $row->rev_user_text
) .
241 $this->author_list
.= "</contributors>";
242 wfProfileOut( __METHOD__
);
246 * @param string $cond
247 * @throws MWException
250 protected function dumpFrom( $cond = '' ) {
251 wfProfileIn( __METHOD__
);
252 # For logging dumps...
253 if ( $this->history
& self
::LOGS
) {
254 $where = array( 'user_id = log_user' );
256 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
258 $where[] = $hideLogs;
260 # Add on any caller specified conditions
264 # Get logging table name for logging.* clause
265 $logging = $this->db
->tableName( 'logging' );
267 if ( $this->buffer
== WikiExporter
::STREAM
) {
268 $prev = $this->db
->bufferResults( false );
270 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
272 $result = $this->db
->select( array( 'logging', 'user' ),
273 array( "{$logging}.*", 'user_name' ), // grab the user name
276 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
278 $wrapper = $this->db
->resultObject( $result );
279 $this->outputLogStream( $wrapper );
280 if ( $this->buffer
== WikiExporter
::STREAM
) {
281 $this->db
->bufferResults( $prev );
283 } catch ( Exception
$e ) {
284 // Throwing the exception does not reliably free the resultset, and
285 // would also leave the connection in unbuffered mode.
292 } catch ( Exception
$e2 ) {
293 // Already in panic mode -> ignoring $e2 as $e has
297 // Putting database back in previous buffer mode
299 if ( $this->buffer
== WikiExporter
::STREAM
) {
300 $this->db
->bufferResults( $prev );
302 } catch ( Exception
$e2 ) {
303 // Already in panic mode -> ignoring $e2 as $e has
307 // Inform caller about problem
308 wfProfileOut( __METHOD__
);
313 $tables = array( 'page', 'revision' );
314 $opts = array( 'ORDER BY' => 'page_id ASC' );
315 $opts['USE INDEX'] = array();
317 if ( is_array( $this->history
) ) {
318 # Time offset/limit for all pages/history...
319 $revJoin = 'page_id=rev_page';
321 if ( $this->history
['dir'] == 'asc' ) {
323 $opts['ORDER BY'] = 'rev_timestamp ASC';
326 $opts['ORDER BY'] = 'rev_timestamp DESC';
329 if ( !empty( $this->history
['offset'] ) ) {
330 $revJoin .= " AND rev_timestamp $op " .
331 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
333 $join['revision'] = array( 'INNER JOIN', $revJoin );
335 if ( !empty( $this->history
['limit'] ) ) {
336 $opts['LIMIT'] = intval( $this->history
['limit'] );
338 } elseif ( $this->history
& WikiExporter
::FULL
) {
339 # Full history dumps...
340 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
341 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
342 # Latest revision dumps...
343 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
344 $this->do_list_authors( $cond );
346 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
347 } elseif ( $this->history
& WikiExporter
::STABLE
) {
348 # "Stable" revision dumps...
349 # Default JOIN, to be overridden...
350 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
351 # One, and only one hook should set this, and return false
352 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
353 wfProfileOut( __METHOD__
);
354 throw new MWException( __METHOD__
. " given invalid history dump type." );
356 } elseif ( $this->history
& WikiExporter
::RANGE
) {
357 # Dump of revisions within a specified range
358 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
359 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
361 # Unknown history specification parameter?
362 wfProfileOut( __METHOD__
);
363 throw new MWException( __METHOD__
. " given invalid history dump type." );
365 # Query optimization hacks
367 $opts[] = 'STRAIGHT_JOIN';
368 $opts['USE INDEX']['page'] = 'PRIMARY';
370 # Build text join options
371 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
373 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
376 if ( $this->buffer
== WikiExporter
::STREAM
) {
377 $prev = $this->db
->bufferResults( false );
380 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
382 wfRunHooks( 'ModifyExportQuery',
383 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
386 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
387 $wrapper = $this->db
->resultObject( $result );
388 # Output dump results
389 $this->outputPageStream( $wrapper );
391 if ( $this->buffer
== WikiExporter
::STREAM
) {
392 $this->db
->bufferResults( $prev );
394 } catch ( Exception
$e ) {
395 // Throwing the exception does not reliably free the resultset, and
396 // would also leave the connection in unbuffered mode.
403 } catch ( Exception
$e2 ) {
404 // Already in panic mode -> ignoring $e2 as $e has
408 // Putting database back in previous buffer mode
410 if ( $this->buffer
== WikiExporter
::STREAM
) {
411 $this->db
->bufferResults( $prev );
413 } catch ( Exception
$e2 ) {
414 // Already in panic mode -> ignoring $e2 as $e has
418 // Inform caller about problem
422 wfProfileOut( __METHOD__
);
426 * Runs through a query result set dumping page and revision records.
427 * The result set should be sorted/grouped by page to avoid duplicate
428 * page records in the output.
431 * streaming (non-buffered) queries, as long as it was made on a
432 * separate database connection not managed by LoadBalancer; some
433 * blob storage types will make queries to pull source data.
435 * @param ResultWrapper $resultset
437 protected function outputPageStream( $resultset ) {
439 foreach ( $resultset as $row ) {
440 if ( $last === null ||
441 $last->page_namespace
!= $row->page_namespace ||
442 $last->page_title
!= $row->page_title
) {
443 if ( $last !== null ) {
445 if ( $this->dumpUploads
) {
446 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
448 $output .= $this->writer
->closePage();
449 $this->sink
->writeClosePage( $output );
451 $output = $this->writer
->openPage( $row );
452 $this->sink
->writeOpenPage( $row, $output );
455 $output = $this->writer
->writeRevision( $row );
456 $this->sink
->writeRevision( $row, $output );
458 if ( $last !== null ) {
460 if ( $this->dumpUploads
) {
461 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
463 $output .= $this->author_list
;
464 $output .= $this->writer
->closePage();
465 $this->sink
->writeClosePage( $output );
470 * @param array $resultset
472 protected function outputLogStream( $resultset ) {
473 foreach ( $resultset as $row ) {
474 $output = $this->writer
->writeLogItem( $row );
475 $this->sink
->writeLogItem( $row, $output );
483 class XmlDumpWriter
{
485 * Returns the export schema version.
486 * @deprecated since 1.20; use WikiExporter::schemaVersion() instead
489 function schemaVersion() {
490 wfDeprecated( __METHOD__
, '1.20' );
491 return WikiExporter
::schemaVersion();
495 * Opens the XML output stream's root "<mediawiki>" element.
496 * This does not include an xml directive, so is safe to include
497 * as a subelement in a larger XML stream. Namespace and XML Schema
498 * references are included.
500 * Output will be encoded in UTF-8.
504 function openStream() {
505 global $wgLanguageCode;
506 $ver = WikiExporter
::schemaVersion();
507 return Xml
::element( 'mediawiki', array(
508 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
509 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
510 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
511 #TODO: how do we get a new version up there?
512 "http://www.mediawiki.org/xml/export-$ver.xsd",
514 'xml:lang' => $wgLanguageCode ),
523 function siteInfo() {
528 $this->caseSetting(),
529 $this->namespaces() );
530 return " <siteinfo>\n " .
531 implode( "\n ", $info ) .
538 function sitename() {
540 return Xml
::element( 'sitename', array(), $wgSitename );
546 function generator() {
548 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
554 function homelink() {
555 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalURL() );
561 function caseSetting() {
562 global $wgCapitalLinks;
563 // "case-insensitive" option is reserved for future
564 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
565 return Xml
::element( 'case', array(), $sensitivity );
571 function namespaces() {
573 $spaces = "<namespaces>\n";
574 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
576 Xml
::element( 'namespace',
579 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
582 $spaces .= " </namespaces>";
587 * Closes the output stream with the closing root element.
588 * Call when finished dumping things.
592 function closeStream() {
593 return "</mediawiki>\n";
597 * Opens a "<page>" section on the output stream, with data
598 * from the given database row.
603 public function openPage( $row ) {
605 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
606 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
607 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
608 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
609 if ( $row->page_is_redirect
) {
610 $page = WikiPage
::factory( $title );
611 $redirect = $page->getRedirectTarget();
612 if ( $redirect instanceof Title
&& $redirect->isValidRedirectTarget() ) {
614 $out .= Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) );
619 if ( $row->page_restrictions
!= '' ) {
620 $out .= ' ' . Xml
::element( 'restrictions', array(),
621 strval( $row->page_restrictions
) ) . "\n";
624 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
630 * Closes a "<page>" section on the output stream.
635 function closePage() {
640 * Dumps a "<revision>" section on the output stream, with
641 * data filled in from the given database row.
647 function writeRevision( $row ) {
648 wfProfileIn( __METHOD__
);
650 $out = " <revision>\n";
651 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
652 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
653 $out .= " " . Xml
::element( 'parentid', null, strval( $row->rev_parent_id
) ) . "\n";
656 $out .= $this->writeTimestamp( $row->rev_timestamp
);
658 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_USER
) ) {
659 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
661 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
664 if ( isset( $row->rev_minor_edit
) && $row->rev_minor_edit
) {
665 $out .= " <minor/>\n";
667 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) ) {
668 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
669 } elseif ( $row->rev_comment
!= '' ) {
670 $out .= " " . Xml
::elementClean( 'comment', array(), strval( $row->rev_comment
) ) . "\n";
673 if ( isset( $row->rev_content_model
) && !is_null( $row->rev_content_model
) ) {
674 $content_model = strval( $row->rev_content_model
);
676 // probably using $wgContentHandlerUseDB = false;
677 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
678 $content_model = ContentHandler
::getDefaultModelFor( $title );
681 $content_handler = ContentHandler
::getForModelID( $content_model );
683 if ( isset( $row->rev_content_format
) && !is_null( $row->rev_content_format
) ) {
684 $content_format = strval( $row->rev_content_format
);
686 // probably using $wgContentHandlerUseDB = false;
687 $content_format = $content_handler->getDefaultFormat();
691 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
692 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
693 } elseif ( isset( $row->old_text
) ) {
694 // Raw text from the database may have invalid chars
695 $text = strval( Revision
::getRevisionText( $row ) );
696 $text = $content_handler->exportTransform( $text, $content_format );
697 $out .= " " . Xml
::elementClean( 'text',
698 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
699 strval( $text ) ) . "\n";
702 $out .= " " . Xml
::element( 'text',
703 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
707 if ( isset( $row->rev_sha1
)
709 && !( $row->rev_deleted
& Revision
::DELETED_TEXT
)
711 $out .= " " . Xml
::element( 'sha1', null, strval( $row->rev_sha1
) ) . "\n";
713 $out .= " <sha1/>\n";
716 $out .= " " . Xml
::element( 'model', null, strval( $content_model ) ) . "\n";
717 $out .= " " . Xml
::element( 'format', null, strval( $content_format ) ) . "\n";
719 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
721 $out .= " </revision>\n";
723 wfProfileOut( __METHOD__
);
728 * Dumps a "<logitem>" section on the output stream, with
729 * data filled in from the given database row.
735 function writeLogItem( $row ) {
736 wfProfileIn( __METHOD__
);
738 $out = " <logitem>\n";
739 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
741 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
743 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
744 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
746 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
749 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
750 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
751 } elseif ( $row->log_comment
!= '' ) {
752 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
755 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
756 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
758 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
759 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
761 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
762 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
763 $out .= " " . Xml
::elementClean( 'params',
764 array( 'xml:space' => 'preserve' ),
765 strval( $row->log_params
) ) . "\n";
768 $out .= " </logitem>\n";
770 wfProfileOut( __METHOD__
);
775 * @param string $timestamp
776 * @param string $indent Default to six spaces
779 function writeTimestamp( $timestamp, $indent = " " ) {
780 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
781 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
786 * @param string $text
787 * @param string $indent Default to six spaces
790 function writeContributor( $id, $text, $indent = " " ) {
791 $out = $indent . "<contributor>\n";
792 if ( $id ||
!IP
::isValid( $text ) ) {
793 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
794 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
796 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
798 $out .= $indent . "</contributor>\n";
803 * Warning! This data is potentially inconsistent. :(
805 * @param bool $dumpContents
808 function writeUploads( $row, $dumpContents = false ) {
809 if ( $row->page_namespace
== NS_FILE
) {
810 $img = wfLocalFile( $row->page_title
);
811 if ( $img && $img->exists() ) {
813 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
814 $out .= $this->writeUpload( $ver, $dumpContents );
816 $out .= $this->writeUpload( $img, $dumpContents );
825 * @param bool $dumpContents
828 function writeUpload( $file, $dumpContents = false ) {
829 if ( $file->isOld() ) {
831 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
835 if ( $dumpContents ) {
836 $be = $file->getRepo()->getBackend();
837 # Dump file as base64
838 # Uses only XML-safe characters, so does not need escaping
839 # @todo Too bad this loads the contents into memory (script might swap)
840 $contents = ' <contents encoding="base64">' .
841 chunk_split( base64_encode(
842 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
847 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
848 $comment = Xml
::element( 'comment', array( 'deleted' => 'deleted' ) );
850 $comment = Xml
::elementClean( 'comment', null, $file->getDescription() );
852 return " <upload>\n" .
853 $this->writeTimestamp( $file->getTimestamp() ) .
854 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
855 " " . $comment . "\n" .
856 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
858 " " . Xml
::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
859 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
860 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
861 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
867 * Return prefixed text form of title, but using the content language's
868 * canonical namespace. This skips any special-casing such as gendered
869 * user namespaces -- which while useful, are not yet listed in the
870 * XML "<siteinfo>" data so are unsafe in export.
872 * @param Title $title
876 public static function canonicalTitle( Title
$title ) {
877 if ( $title->isExternal() ) {
878 return $title->getPrefixedText();
882 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
884 if ( $prefix !== '' ) {
888 return $prefix . $title->getText();
893 * Base class for output stream; prints to stdout or buffer or wherever.
899 * @param string $string
901 function writeOpenStream( $string ) {
902 $this->write( $string );
906 * @param string $string
908 function writeCloseStream( $string ) {
909 $this->write( $string );
913 * @param object $page
914 * @param string $string
916 function writeOpenPage( $page, $string ) {
917 $this->write( $string );
921 * @param string $string
923 function writeClosePage( $string ) {
924 $this->write( $string );
929 * @param string $string
931 function writeRevision( $rev, $string ) {
932 $this->write( $string );
937 * @param string $string
939 function writeLogItem( $rev, $string ) {
940 $this->write( $string );
944 * Override to write to a different stream type.
945 * @param string $string
948 function write( $string ) {
953 * Close the old file, move it to a specified name,
954 * and reopen new file with the old name. Use this
955 * for writing out a file in multiple pieces
956 * at specified checkpoints (e.g. every n hours).
957 * @param string|array $newname File name. May be a string or an array with one element
959 function closeRenameAndReopen( $newname ) {
963 * Close the old file, and move it to a specified name.
964 * Use this for the last piece of a file written out
965 * at specified checkpoints (e.g. every n hours).
966 * @param string|array $newname File name. May be a string or an array with one element
967 * @param bool $open If true, a new file with the old filename will be opened
968 * again for writing (default: false)
970 function closeAndRename( $newname, $open = false ) {
974 * Returns the name of the file or files which are
975 * being written to, if there are any.
978 function getFilenames() {
984 * Stream outputter to send data to a file.
987 class DumpFileOutput
extends DumpOutput
{
988 protected $handle = false, $filename;
991 * @param string $file
993 function __construct( $file ) {
994 $this->handle
= fopen( $file, "wt" );
995 $this->filename
= $file;
999 * @param string $string
1001 function writeCloseStream( $string ) {
1002 parent
::writeCloseStream( $string );
1003 if ( $this->handle
) {
1004 fclose( $this->handle
);
1005 $this->handle
= false;
1010 * @param string $string
1012 function write( $string ) {
1013 fputs( $this->handle
, $string );
1017 * @param string $newname
1019 function closeRenameAndReopen( $newname ) {
1020 $this->closeAndRename( $newname, true );
1024 * @param string $newname
1025 * @throws MWException
1027 function renameOrException( $newname ) {
1028 if ( !rename( $this->filename
, $newname ) ) {
1029 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
1034 * @param array $newname
1036 * @throws MWException
1038 function checkRenameArgCount( $newname ) {
1039 if ( is_array( $newname ) ) {
1040 if ( count( $newname ) > 1 ) {
1041 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
1043 $newname = $newname[0];
1050 * @param string $newname
1053 function closeAndRename( $newname, $open = false ) {
1054 $newname = $this->checkRenameArgCount( $newname );
1056 if ( $this->handle
) {
1057 fclose( $this->handle
);
1058 $this->handle
= false;
1060 $this->renameOrException( $newname );
1062 $this->handle
= fopen( $this->filename
, "wt" );
1068 * @return string|null
1070 function getFilenames() {
1071 return $this->filename
;
1076 * Stream outputter to send data to a file via some filter program.
1077 * Even if compression is available in a library, using a separate
1078 * program can allow us to make use of a multi-processor system.
1081 class DumpPipeOutput
extends DumpFileOutput
{
1082 protected $command, $filename;
1083 protected $procOpenResource = false;
1086 * @param string $command
1087 * @param string $file
1089 function __construct( $command, $file = null ) {
1090 if ( !is_null( $file ) ) {
1091 $command .= " > " . wfEscapeShellArg( $file );
1094 $this->startCommand( $command );
1095 $this->command
= $command;
1096 $this->filename
= $file;
1100 * @param string $string
1102 function writeCloseStream( $string ) {
1103 parent
::writeCloseStream( $string );
1104 if ( $this->procOpenResource
) {
1105 proc_close( $this->procOpenResource
);
1106 $this->procOpenResource
= false;
1111 * @param string $command
1113 function startCommand( $command ) {
1115 0 => array( "pipe", "r" ),
1118 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
1119 $this->handle
= $pipes[0];
1123 * @param string $newname
1125 function closeRenameAndReopen( $newname ) {
1126 $this->closeAndRename( $newname, true );
1130 * @param string $newname
1133 function closeAndRename( $newname, $open = false ) {
1134 $newname = $this->checkRenameArgCount( $newname );
1136 if ( $this->handle
) {
1137 fclose( $this->handle
);
1138 $this->handle
= false;
1140 if ( $this->procOpenResource
) {
1141 proc_close( $this->procOpenResource
);
1142 $this->procOpenResource
= false;
1144 $this->renameOrException( $newname );
1146 $command = $this->command
;
1147 $command .= " > " . wfEscapeShellArg( $this->filename
);
1148 $this->startCommand( $command );
1155 * Sends dump output via the gzip compressor.
1158 class DumpGZipOutput
extends DumpPipeOutput
{
1160 * @param string $file
1162 function __construct( $file ) {
1163 parent
::__construct( "gzip", $file );
1168 * Sends dump output via the bgzip2 compressor.
1171 class DumpBZip2Output
extends DumpPipeOutput
{
1173 * @param string $file
1175 function __construct( $file ) {
1176 parent
::__construct( "bzip2", $file );
1181 * Sends dump output via the p7zip compressor.
1184 class Dump7ZipOutput
extends DumpPipeOutput
{
1186 * @param string $file
1188 function __construct( $file ) {
1189 $command = $this->setup7zCommand( $file );
1190 parent
::__construct( $command );
1191 $this->filename
= $file;
1195 * @param string $file
1198 function setup7zCommand( $file ) {
1199 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1200 // Suppress annoying useless crap from p7zip
1201 // Unfortunately this could suppress real error messages too
1202 $command .= ' >' . wfGetNull() . ' 2>&1';
1207 * @param string $newname
1210 function closeAndRename( $newname, $open = false ) {
1211 $newname = $this->checkRenameArgCount( $newname );
1213 fclose( $this->handle
);
1214 proc_close( $this->procOpenResource
);
1215 $this->renameOrException( $newname );
1217 $command = $this->setup7zCommand( $this->filename
);
1218 $this->startCommand( $command );
1225 * Dump output filter class.
1226 * This just does output filtering and streaming; XML formatting is done
1227 * higher up, so be careful in what you do.
1233 * FIXME will need to be made protected whenever legacy code
1241 protected $sendingThisPage;
1244 * @param DumpOutput $sink
1246 function __construct( &$sink ) {
1247 $this->sink
=& $sink;
1251 * @param string $string
1253 function writeOpenStream( $string ) {
1254 $this->sink
->writeOpenStream( $string );
1258 * @param string $string
1260 function writeCloseStream( $string ) {
1261 $this->sink
->writeCloseStream( $string );
1265 * @param object $page
1266 * @param string $string
1268 function writeOpenPage( $page, $string ) {
1269 $this->sendingThisPage
= $this->pass( $page, $string );
1270 if ( $this->sendingThisPage
) {
1271 $this->sink
->writeOpenPage( $page, $string );
1276 * @param string $string
1278 function writeClosePage( $string ) {
1279 if ( $this->sendingThisPage
) {
1280 $this->sink
->writeClosePage( $string );
1281 $this->sendingThisPage
= false;
1286 * @param object $rev
1287 * @param string $string
1289 function writeRevision( $rev, $string ) {
1290 if ( $this->sendingThisPage
) {
1291 $this->sink
->writeRevision( $rev, $string );
1296 * @param object $rev
1297 * @param string $string
1299 function writeLogItem( $rev, $string ) {
1300 $this->sink
->writeRevision( $rev, $string );
1304 * @param string $newname
1306 function closeRenameAndReopen( $newname ) {
1307 $this->sink
->closeRenameAndReopen( $newname );
1311 * @param string $newname
1314 function closeAndRename( $newname, $open = false ) {
1315 $this->sink
->closeAndRename( $newname, $open );
1321 function getFilenames() {
1322 return $this->sink
->getFilenames();
1326 * Override for page-based filter types.
1327 * @param object $page
1330 function pass( $page ) {
1336 * Simple dump output filter to exclude all talk pages.
1339 class DumpNotalkFilter
extends DumpFilter
{
1341 * @param object $page
1344 function pass( $page ) {
1345 return !MWNamespace
::isTalk( $page->page_namespace
);
1350 * Dump output filter to include or exclude pages in a given set of namespaces.
1353 class DumpNamespaceFilter
extends DumpFilter
{
1355 protected $invert = false;
1358 protected $namespaces = array();
1361 * @param DumpOutput $sink
1362 * @param array $param
1363 * @throws MWException
1365 function __construct( &$sink, $param ) {
1366 parent
::__construct( $sink );
1369 "NS_MAIN" => NS_MAIN
,
1370 "NS_TALK" => NS_TALK
,
1371 "NS_USER" => NS_USER
,
1372 "NS_USER_TALK" => NS_USER_TALK
,
1373 "NS_PROJECT" => NS_PROJECT
,
1374 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1375 "NS_FILE" => NS_FILE
,
1376 "NS_FILE_TALK" => NS_FILE_TALK
,
1377 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1378 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1379 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1380 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1381 "NS_TEMPLATE" => NS_TEMPLATE
,
1382 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1383 "NS_HELP" => NS_HELP
,
1384 "NS_HELP_TALK" => NS_HELP_TALK
,
1385 "NS_CATEGORY" => NS_CATEGORY
,
1386 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1388 if ( $param { 0 } == '!' ) {
1389 $this->invert
= true;
1390 $param = substr( $param, 1 );
1393 foreach ( explode( ',', $param ) as $key ) {
1394 $key = trim( $key );
1395 if ( isset( $constants[$key] ) ) {
1396 $ns = $constants[$key];
1397 $this->namespaces
[$ns] = true;
1398 } elseif ( is_numeric( $key ) ) {
1399 $ns = intval( $key );
1400 $this->namespaces
[$ns] = true;
1402 throw new MWException( "Unrecognized namespace key '$key'\n" );
1408 * @param object $page
1411 function pass( $page ) {
1412 $match = isset( $this->namespaces
[$page->page_namespace
] );
1413 return $this->invert
xor $match;
1418 * Dump output filter to include only the last revision in each page sequence.
1421 class DumpLatestFilter
extends DumpFilter
{
1424 protected $pageString;
1428 protected $revString;
1431 * @param object $page
1432 * @param string $string
1434 function writeOpenPage( $page, $string ) {
1435 $this->page
= $page;
1436 $this->pageString
= $string;
1440 * @param string $string
1442 function writeClosePage( $string ) {
1444 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1445 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1446 $this->sink
->writeClosePage( $string );
1449 $this->revString
= null;
1451 $this->pageString
= null;
1455 * @param object $rev
1456 * @param string $string
1458 function writeRevision( $rev, $string ) {
1459 if ( $rev->rev_id
== $this->page
->page_latest
) {
1461 $this->revString
= $string;
1467 * Base class for output stream; prints to stdout or buffer or wherever.
1470 class DumpMultiWriter
{
1473 * @param array $sinks
1475 function __construct( $sinks ) {
1476 $this->sinks
= $sinks;
1477 $this->count
= count( $sinks );
1481 * @param string $string
1483 function writeOpenStream( $string ) {
1484 for ( $i = 0; $i < $this->count
; $i++
) {
1485 $this->sinks
[$i]->writeOpenStream( $string );
1490 * @param string $string
1492 function writeCloseStream( $string ) {
1493 for ( $i = 0; $i < $this->count
; $i++
) {
1494 $this->sinks
[$i]->writeCloseStream( $string );
1499 * @param object $page
1500 * @param string $string
1502 function writeOpenPage( $page, $string ) {
1503 for ( $i = 0; $i < $this->count
; $i++
) {
1504 $this->sinks
[$i]->writeOpenPage( $page, $string );
1509 * @param string $string
1511 function writeClosePage( $string ) {
1512 for ( $i = 0; $i < $this->count
; $i++
) {
1513 $this->sinks
[$i]->writeClosePage( $string );
1518 * @param object $rev
1519 * @param string $string
1521 function writeRevision( $rev, $string ) {
1522 for ( $i = 0; $i < $this->count
; $i++
) {
1523 $this->sinks
[$i]->writeRevision( $rev, $string );
1528 * @param array $newnames
1530 function closeRenameAndReopen( $newnames ) {
1531 $this->closeAndRename( $newnames, true );
1535 * @param array $newnames
1538 function closeAndRename( $newnames, $open = false ) {
1539 for ( $i = 0; $i < $this->count
; $i++
) {
1540 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1547 function getFilenames() {
1548 $filenames = array();
1549 for ( $i = 0; $i < $this->count
; $i++
) {
1550 $filenames[] = $this->sinks
[$i]->getFilenames();
1557 * @param string $string
1559 * @todo FIXME: Only used in OAI extension. Move over there.
1561 function xmlsafe( $string ) {
1562 wfProfileIn( __FUNCTION__
);
1565 * The page may contain old data which has not been properly normalized.
1566 * Invalid UTF-8 sequences or forbidden control characters will make our
1567 * XML output invalid, so be sure to strip them out.
1569 $string = UtfNormal
::cleanUp( $string );
1571 $string = htmlspecialchars( $string );
1572 wfProfileOut( __FUNCTION__
);