3 * Base classes for dumps and export
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
31 * @ingroup SpecialPage Dump
34 var $list_authors = false; # Return distinct author list (when not returning full history)
35 var $author_list = "";
37 var $dumpUploads = false;
38 var $dumpUploadFileContents = false;
42 const STABLE
= 4; // extension defined
62 * Returns the export schema version.
65 public static function schemaVersion() {
70 * If using WikiExporter::STREAM to stream a large amount of data,
71 * provide a database connection which is not managed by
72 * LoadBalancer to read from: some history blob types will
73 * make additional queries to pull source data while the
74 * main query is still running.
76 * @param $db DatabaseBase
77 * @param $history Mixed: one of WikiExporter::FULL, WikiExporter::CURRENT,
78 * WikiExporter::RANGE or WikiExporter::STABLE,
79 * or an associative array:
80 * offset: non-inclusive offset at which to start the query
81 * limit: maximum number of rows to return
82 * dir: "asc" or "desc" timestamp order
83 * @param int $buffer one of WikiExporter::BUFFER or WikiExporter::STREAM
84 * @param int $text one of WikiExporter::TEXT or WikiExporter::STUB
86 function __construct( $db, $history = WikiExporter
::CURRENT
,
87 $buffer = WikiExporter
::BUFFER
, $text = WikiExporter
::TEXT
) {
89 $this->history
= $history;
90 $this->buffer
= $buffer;
91 $this->writer
= new XmlDumpWriter();
92 $this->sink
= new DumpOutput();
97 * Set the DumpOutput or DumpFilter object which will receive
98 * various row objects and XML output for filtering. Filters
99 * can be chained or used as callbacks.
103 public function setOutputSink( &$sink ) {
104 $this->sink
=& $sink;
107 public function openStream() {
108 $output = $this->writer
->openStream();
109 $this->sink
->writeOpenStream( $output );
112 public function closeStream() {
113 $output = $this->writer
->closeStream();
114 $this->sink
->writeCloseStream( $output );
118 * Dumps a series of page and revision records for all pages
119 * in the database, either including complete history or only
120 * the most recent version.
122 public function allPages() {
123 $this->dumpFrom( '' );
127 * Dumps a series of page and revision records for those pages
128 * in the database falling within the page_id range given.
129 * @param int $start inclusive lower limit (this id is included)
130 * @param $end Int: Exclusive upper limit (this id is not included)
131 * If 0, no upper limit.
133 public function pagesByRange( $start, $end ) {
134 $condition = 'page_id >= ' . intval( $start );
136 $condition .= ' AND page_id < ' . intval( $end );
138 $this->dumpFrom( $condition );
142 * Dumps a series of page and revision records for those pages
143 * in the database with revisions falling within the rev_id range given.
144 * @param int $start inclusive lower limit (this id is included)
145 * @param $end Int: Exclusive upper limit (this id is not included)
146 * If 0, no upper limit.
148 public function revsByRange( $start, $end ) {
149 $condition = 'rev_id >= ' . intval( $start );
151 $condition .= ' AND rev_id < ' . intval( $end );
153 $this->dumpFrom( $condition );
157 * @param $title Title
159 public function pageByTitle( $title ) {
161 'page_namespace=' . $title->getNamespace() .
162 ' AND page_title=' . $this->db
->addQuotes( $title->getDBkey() ) );
166 * @param $name string
167 * @throws MWException
169 public function pageByName( $name ) {
170 $title = Title
::newFromText( $name );
171 if ( is_null( $title ) ) {
172 throw new MWException( "Can't export invalid title" );
174 $this->pageByTitle( $title );
179 * @param $names array
181 public function pagesByName( $names ) {
182 foreach ( $names as $name ) {
183 $this->pageByName( $name );
187 public function allLogs() {
188 $this->dumpFrom( '' );
195 public function logsByRange( $start, $end ) {
196 $condition = 'log_id >= ' . intval( $start );
198 $condition .= ' AND log_id < ' . intval( $end );
200 $this->dumpFrom( $condition );
204 * Generates the distinct list of authors of an article
205 * Not called by default (depends on $this->list_authors)
206 * Can be set by Special:Export when not exporting whole history
210 protected function do_list_authors( $cond ) {
211 wfProfileIn( __METHOD__
);
212 $this->author_list
= "<contributors>";
215 $res = $this->db
->select(
216 array( 'page', 'revision' ),
217 array( 'DISTINCT rev_user_text', 'rev_user' ),
219 $this->db
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0',
226 foreach ( $res as $row ) {
227 $this->author_list
.= "<contributor>" .
229 htmlentities( $row->rev_user_text
) .
236 $this->author_list
.= "</contributors>";
237 wfProfileOut( __METHOD__
);
241 * @param $cond string
242 * @throws MWException
245 protected function dumpFrom( $cond = '' ) {
246 wfProfileIn( __METHOD__
);
247 # For logging dumps...
248 if ( $this->history
& self
::LOGS
) {
249 $where = array( 'user_id = log_user' );
251 $hideLogs = LogEventsList
::getExcludeClause( $this->db
);
253 $where[] = $hideLogs;
255 # Add on any caller specified conditions
259 # Get logging table name for logging.* clause
260 $logging = $this->db
->tableName( 'logging' );
262 if ( $this->buffer
== WikiExporter
::STREAM
) {
263 $prev = $this->db
->bufferResults( false );
265 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
267 $result = $this->db
->select( array( 'logging', 'user' ),
268 array( "{$logging}.*", 'user_name' ), // grab the user name
271 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
273 $wrapper = $this->db
->resultObject( $result );
274 $this->outputLogStream( $wrapper );
275 if ( $this->buffer
== WikiExporter
::STREAM
) {
276 $this->db
->bufferResults( $prev );
278 } catch ( Exception
$e ) {
279 // Throwing the exception does not reliably free the resultset, and
280 // would also leave the connection in unbuffered mode.
287 } catch ( Exception
$e2 ) {
288 // Already in panic mode -> ignoring $e2 as $e has
292 // Putting database back in previous buffer mode
294 if ( $this->buffer
== WikiExporter
::STREAM
) {
295 $this->db
->bufferResults( $prev );
297 } catch ( Exception
$e2 ) {
298 // Already in panic mode -> ignoring $e2 as $e has
302 // Inform caller about problem
303 wfProfileOut( __METHOD__
);
308 $tables = array( 'page', 'revision' );
309 $opts = array( 'ORDER BY' => 'page_id ASC' );
310 $opts['USE INDEX'] = array();
312 if ( is_array( $this->history
) ) {
313 # Time offset/limit for all pages/history...
314 $revJoin = 'page_id=rev_page';
316 if ( $this->history
['dir'] == 'asc' ) {
318 $opts['ORDER BY'] = 'rev_timestamp ASC';
321 $opts['ORDER BY'] = 'rev_timestamp DESC';
324 if ( !empty( $this->history
['offset'] ) ) {
325 $revJoin .= " AND rev_timestamp $op " .
326 $this->db
->addQuotes( $this->db
->timestamp( $this->history
['offset'] ) );
328 $join['revision'] = array( 'INNER JOIN', $revJoin );
330 if ( !empty( $this->history
['limit'] ) ) {
331 $opts['LIMIT'] = intval( $this->history
['limit'] );
333 } elseif ( $this->history
& WikiExporter
::FULL
) {
334 # Full history dumps...
335 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
336 } elseif ( $this->history
& WikiExporter
::CURRENT
) {
337 # Latest revision dumps...
338 if ( $this->list_authors
&& $cond != '' ) { // List authors, if so desired
339 $this->do_list_authors( $cond );
341 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
342 } elseif ( $this->history
& WikiExporter
::STABLE
) {
343 # "Stable" revision dumps...
344 # Default JOIN, to be overridden...
345 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
346 # One, and only one hook should set this, and return false
347 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
348 wfProfileOut( __METHOD__
);
349 throw new MWException( __METHOD__
. " given invalid history dump type." );
351 } elseif ( $this->history
& WikiExporter
::RANGE
) {
352 # Dump of revisions within a specified range
353 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
354 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
356 # Unknown history specification parameter?
357 wfProfileOut( __METHOD__
);
358 throw new MWException( __METHOD__
. " given invalid history dump type." );
360 # Query optimization hacks
362 $opts[] = 'STRAIGHT_JOIN';
363 $opts['USE INDEX']['page'] = 'PRIMARY';
365 # Build text join options
366 if ( $this->text
!= WikiExporter
::STUB
) { // 1-pass
368 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
371 if ( $this->buffer
== WikiExporter
::STREAM
) {
372 $prev = $this->db
->bufferResults( false );
375 $wrapper = null; // Assuring $wrapper is not undefined, if exception occurs early
377 wfRunHooks( 'ModifyExportQuery',
378 array( $this->db
, &$tables, &$cond, &$opts, &$join ) );
381 $result = $this->db
->select( $tables, '*', $cond, __METHOD__
, $opts, $join );
382 $wrapper = $this->db
->resultObject( $result );
383 # Output dump results
384 $this->outputPageStream( $wrapper );
386 if ( $this->buffer
== WikiExporter
::STREAM
) {
387 $this->db
->bufferResults( $prev );
389 } catch ( Exception
$e ) {
390 // Throwing the exception does not reliably free the resultset, and
391 // would also leave the connection in unbuffered mode.
398 } catch ( Exception
$e2 ) {
399 // Already in panic mode -> ignoring $e2 as $e has
403 // Putting database back in previous buffer mode
405 if ( $this->buffer
== WikiExporter
::STREAM
) {
406 $this->db
->bufferResults( $prev );
408 } catch ( Exception
$e2 ) {
409 // Already in panic mode -> ignoring $e2 as $e has
413 // Inform caller about problem
417 wfProfileOut( __METHOD__
);
421 * Runs through a query result set dumping page and revision records.
422 * The result set should be sorted/grouped by page to avoid duplicate
423 * page records in the output.
426 * streaming (non-buffered) queries, as long as it was made on a
427 * separate database connection not managed by LoadBalancer; some
428 * blob storage types will make queries to pull source data.
430 * @param $resultset ResultWrapper
432 protected function outputPageStream( $resultset ) {
434 foreach ( $resultset as $row ) {
435 if ( $last === null ||
436 $last->page_namespace
!= $row->page_namespace ||
437 $last->page_title
!= $row->page_title
) {
438 if ( $last !== null ) {
440 if ( $this->dumpUploads
) {
441 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
443 $output .= $this->writer
->closePage();
444 $this->sink
->writeClosePage( $output );
446 $output = $this->writer
->openPage( $row );
447 $this->sink
->writeOpenPage( $row, $output );
450 $output = $this->writer
->writeRevision( $row );
451 $this->sink
->writeRevision( $row, $output );
453 if ( $last !== null ) {
455 if ( $this->dumpUploads
) {
456 $output .= $this->writer
->writeUploads( $last, $this->dumpUploadFileContents
);
458 $output .= $this->author_list
;
459 $output .= $this->writer
->closePage();
460 $this->sink
->writeClosePage( $output );
465 * @param $resultset array
467 protected function outputLogStream( $resultset ) {
468 foreach ( $resultset as $row ) {
469 $output = $this->writer
->writeLogItem( $row );
470 $this->sink
->writeLogItem( $row, $output );
478 class XmlDumpWriter
{
480 * Returns the export schema version.
481 * @deprecated in 1.20; use WikiExporter::schemaVersion() instead
484 function schemaVersion() {
485 wfDeprecated( __METHOD__
, '1.20' );
486 return WikiExporter
::schemaVersion();
490 * Opens the XML output stream's root "<mediawiki>" element.
491 * This does not include an xml directive, so is safe to include
492 * as a subelement in a larger XML stream. Namespace and XML Schema
493 * references are included.
495 * Output will be encoded in UTF-8.
499 function openStream() {
500 global $wgLanguageCode;
501 $ver = WikiExporter
::schemaVersion();
502 return Xml
::element( 'mediawiki', array(
503 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
504 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
505 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
506 #TODO: how do we get a new version up there?
507 "http://www.mediawiki.org/xml/export-$ver.xsd",
509 'xml:lang' => $wgLanguageCode ),
518 function siteInfo() {
523 $this->caseSetting(),
524 $this->namespaces() );
525 return " <siteinfo>\n " .
526 implode( "\n ", $info ) .
533 function sitename() {
535 return Xml
::element( 'sitename', array(), $wgSitename );
541 function generator() {
543 return Xml
::element( 'generator', array(), "MediaWiki $wgVersion" );
549 function homelink() {
550 return Xml
::element( 'base', array(), Title
::newMainPage()->getCanonicalURL() );
556 function caseSetting() {
557 global $wgCapitalLinks;
558 // "case-insensitive" option is reserved for future
559 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
560 return Xml
::element( 'case', array(), $sensitivity );
566 function namespaces() {
568 $spaces = "<namespaces>\n";
569 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
571 Xml
::element( 'namespace',
574 'case' => MWNamespace
::isCapitalized( $ns ) ?
'first-letter' : 'case-sensitive',
577 $spaces .= " </namespaces>";
582 * Closes the output stream with the closing root element.
583 * Call when finished dumping things.
587 function closeStream() {
588 return "</mediawiki>\n";
592 * Opens a "<page>" section on the output stream, with data
593 * from the given database row.
599 function openPage( $row ) {
601 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
602 $out .= ' ' . Xml
::elementClean( 'title', array(), self
::canonicalTitle( $title ) ) . "\n";
603 $out .= ' ' . Xml
::element( 'ns', array(), strval( $row->page_namespace
) ) . "\n";
604 $out .= ' ' . Xml
::element( 'id', array(), strval( $row->page_id
) ) . "\n";
605 if ( $row->page_is_redirect
) {
606 $page = WikiPage
::factory( $title );
607 $redirect = $page->getRedirectTarget();
608 if ( $redirect instanceof Title
&& $redirect->isValidRedirectTarget() ) {
609 $out .= ' ' . Xml
::element( 'redirect', array( 'title' => self
::canonicalTitle( $redirect ) ) ) . "\n";
613 if ( $row->page_restrictions
!= '' ) {
614 $out .= ' ' . Xml
::element( 'restrictions', array(),
615 strval( $row->page_restrictions
) ) . "\n";
618 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
624 * Closes a "<page>" section on the output stream.
629 function closePage() {
634 * Dumps a "<revision>" section on the output stream, with
635 * data filled in from the given database row.
641 function writeRevision( $row ) {
642 wfProfileIn( __METHOD__
);
644 $out = " <revision>\n";
645 $out .= " " . Xml
::element( 'id', null, strval( $row->rev_id
) ) . "\n";
646 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
647 $out .= " " . Xml
::element( 'parentid', null, strval( $row->rev_parent_id
) ) . "\n";
650 $out .= $this->writeTimestamp( $row->rev_timestamp
);
652 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_USER
) ) {
653 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
655 $out .= $this->writeContributor( $row->rev_user
, $row->rev_user_text
);
658 if ( isset( $row->rev_minor_edit
) && $row->rev_minor_edit
) {
659 $out .= " <minor/>\n";
661 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_COMMENT
) ) {
662 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
663 } elseif ( $row->rev_comment
!= '' ) {
664 $out .= " " . Xml
::elementClean( 'comment', array(), strval( $row->rev_comment
) ) . "\n";
668 if ( isset( $row->rev_deleted
) && ( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
669 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
670 } elseif ( isset( $row->old_text
) ) {
671 // Raw text from the database may have invalid chars
672 $text = strval( Revision
::getRevisionText( $row ) );
673 $out .= " " . Xml
::elementClean( 'text',
674 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len
) ),
675 strval( $text ) ) . "\n";
678 $out .= " " . Xml
::element( 'text',
679 array( 'id' => $row->rev_text_id
, 'bytes' => intval( $row->rev_len
) ),
683 if ( isset( $row->rev_sha1
) && $row->rev_sha1
&& !( $row->rev_deleted
& Revision
::DELETED_TEXT
) ) {
684 $out .= " " . Xml
::element( 'sha1', null, strval( $row->rev_sha1
) ) . "\n";
686 $out .= " <sha1/>\n";
689 if ( isset( $row->rev_content_model
) && !is_null( $row->rev_content_model
) ) {
690 $content_model = strval( $row->rev_content_model
);
692 // probably using $wgContentHandlerUseDB = false;
694 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
695 $content_model = ContentHandler
::getDefaultModelFor( $title );
698 $out .= " " . Xml
::element( 'model', null, strval( $content_model ) ) . "\n";
700 if ( isset( $row->rev_content_format
) && !is_null( $row->rev_content_format
) ) {
701 $content_format = strval( $row->rev_content_format
);
703 // probably using $wgContentHandlerUseDB = false;
705 $content_handler = ContentHandler
::getForModelID( $content_model );
706 $content_format = $content_handler->getDefaultFormat();
709 $out .= " " . Xml
::element( 'format', null, strval( $content_format ) ) . "\n";
711 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
713 $out .= " </revision>\n";
715 wfProfileOut( __METHOD__
);
720 * Dumps a "<logitem>" section on the output stream, with
721 * data filled in from the given database row.
727 function writeLogItem( $row ) {
728 wfProfileIn( __METHOD__
);
730 $out = " <logitem>\n";
731 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
733 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
735 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
736 $out .= " " . Xml
::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
738 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
741 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
742 $out .= " " . Xml
::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
743 } elseif ( $row->log_comment
!= '' ) {
744 $out .= " " . Xml
::elementClean( 'comment', null, strval( $row->log_comment
) ) . "\n";
747 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
748 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
750 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
751 $out .= " " . Xml
::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
753 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
754 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
755 $out .= " " . Xml
::elementClean( 'params',
756 array( 'xml:space' => 'preserve' ),
757 strval( $row->log_params
) ) . "\n";
760 $out .= " </logitem>\n";
762 wfProfileOut( __METHOD__
);
767 * @param $timestamp string
768 * @param string $indent Default to six spaces
771 function writeTimestamp( $timestamp, $indent = " " ) {
772 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
773 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
778 * @param $text string
779 * @param string $indent Default to six spaces
782 function writeContributor( $id, $text, $indent = " " ) {
783 $out = $indent . "<contributor>\n";
784 if ( $id ||
!IP
::isValid( $text ) ) {
785 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
786 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
788 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
790 $out .= $indent . "</contributor>\n";
795 * Warning! This data is potentially inconsistent. :(
797 * @param $dumpContents bool
800 function writeUploads( $row, $dumpContents = false ) {
801 if ( $row->page_namespace
== NS_FILE
) {
802 $img = wfLocalFile( $row->page_title
);
803 if ( $img && $img->exists() ) {
805 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
806 $out .= $this->writeUpload( $ver, $dumpContents );
808 $out .= $this->writeUpload( $img, $dumpContents );
817 * @param $dumpContents bool
820 function writeUpload( $file, $dumpContents = false ) {
821 if ( $file->isOld() ) {
823 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
827 if ( $dumpContents ) {
828 $be = $file->getRepo()->getBackend();
829 # Dump file as base64
830 # Uses only XML-safe characters, so does not need escaping
831 # @TODO: too bad this loads the contents into memory (script might swap)
832 $contents = ' <contents encoding="base64">' .
833 chunk_split( base64_encode(
834 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
839 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
840 $comment = Xml
::element( 'comment', array( 'deleted' => 'deleted' ) );
842 $comment = Xml
::elementClean( 'comment', null, $file->getDescription() );
844 return " <upload>\n" .
845 $this->writeTimestamp( $file->getTimestamp() ) .
846 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
847 " " . $comment . "\n" .
848 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
850 " " . Xml
::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
851 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
852 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
853 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
859 * Return prefixed text form of title, but using the content language's
860 * canonical namespace. This skips any special-casing such as gendered
861 * user namespaces -- which while useful, are not yet listed in the
862 * XML "<siteinfo>" data so are unsafe in export.
864 * @param Title $title
868 public static function canonicalTitle( Title
$title ) {
869 if ( $title->getInterwiki() ) {
870 return $title->getPrefixedText();
874 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
876 if ( $prefix !== '' ) {
880 return $prefix . $title->getText();
885 * Base class for output stream; prints to stdout or buffer or wherever.
891 * @param $string string
893 function writeOpenStream( $string ) {
894 $this->write( $string );
898 * @param $string string
900 function writeCloseStream( $string ) {
901 $this->write( $string );
906 * @param $string string
908 function writeOpenPage( $page, $string ) {
909 $this->write( $string );
913 * @param $string string
915 function writeClosePage( $string ) {
916 $this->write( $string );
921 * @param $string string
923 function writeRevision( $rev, $string ) {
924 $this->write( $string );
929 * @param $string string
931 function writeLogItem( $rev, $string ) {
932 $this->write( $string );
936 * Override to write to a different stream type.
937 * @param $string string
940 function write( $string ) {
945 * Close the old file, move it to a specified name,
946 * and reopen new file with the old name. Use this
947 * for writing out a file in multiple pieces
948 * at specified checkpoints (e.g. every n hours).
949 * @param $newname mixed File name. May be a string or an array with one element
951 function closeRenameAndReopen( $newname ) {
955 * Close the old file, and move it to a specified name.
956 * Use this for the last piece of a file written out
957 * at specified checkpoints (e.g. every n hours).
958 * @param $newname mixed File name. May be a string or an array with one element
959 * @param bool $open If true, a new file with the old filename will be opened again for writing (default: false)
961 function closeAndRename( $newname, $open = false ) {
965 * Returns the name of the file or files which are
966 * being written to, if there are any.
969 function getFilenames() {
975 * Stream outputter to send data to a file.
978 class DumpFileOutput
extends DumpOutput
{
979 protected $handle = false, $filename;
984 function __construct( $file ) {
985 $this->handle
= fopen( $file, "wt" );
986 $this->filename
= $file;
990 * @param $string string
992 function writeCloseStream( $string ) {
993 parent
::writeCloseStream( $string );
994 if ( $this->handle
) {
995 fclose( $this->handle
);
996 $this->handle
= false;
1001 * @param $string string
1003 function write( $string ) {
1004 fputs( $this->handle
, $string );
1010 function closeRenameAndReopen( $newname ) {
1011 $this->closeAndRename( $newname, true );
1016 * @throws MWException
1018 function renameOrException( $newname ) {
1019 if ( !rename( $this->filename
, $newname ) ) {
1020 throw new MWException( __METHOD__
. ": rename of file {$this->filename} to $newname failed\n" );
1025 * @param $newname array
1027 * @throws MWException
1029 function checkRenameArgCount( $newname ) {
1030 if ( is_array( $newname ) ) {
1031 if ( count( $newname ) > 1 ) {
1032 throw new MWException( __METHOD__
. ": passed multiple arguments for rename of single file\n" );
1034 $newname = $newname[0];
1041 * @param $newname mixed
1044 function closeAndRename( $newname, $open = false ) {
1045 $newname = $this->checkRenameArgCount( $newname );
1047 if ( $this->handle
) {
1048 fclose( $this->handle
);
1049 $this->handle
= false;
1051 $this->renameOrException( $newname );
1053 $this->handle
= fopen( $this->filename
, "wt" );
1059 * @return string|null
1061 function getFilenames() {
1062 return $this->filename
;
1067 * Stream outputter to send data to a file via some filter program.
1068 * Even if compression is available in a library, using a separate
1069 * program can allow us to make use of a multi-processor system.
1072 class DumpPipeOutput
extends DumpFileOutput
{
1073 protected $command, $filename;
1074 protected $procOpenResource = false;
1080 function __construct( $command, $file = null ) {
1081 if ( !is_null( $file ) ) {
1082 $command .= " > " . wfEscapeShellArg( $file );
1085 $this->startCommand( $command );
1086 $this->command
= $command;
1087 $this->filename
= $file;
1091 * @param $string string
1093 function writeCloseStream( $string ) {
1094 parent
::writeCloseStream( $string );
1095 if ( $this->procOpenResource
) {
1096 proc_close( $this->procOpenResource
);
1097 $this->procOpenResource
= false;
1104 function startCommand( $command ) {
1106 0 => array( "pipe", "r" ),
1109 $this->procOpenResource
= proc_open( $command, $spec, $pipes );
1110 $this->handle
= $pipes[0];
1114 * @param mixed $newname
1116 function closeRenameAndReopen( $newname ) {
1117 $this->closeAndRename( $newname, true );
1121 * @param $newname mixed
1124 function closeAndRename( $newname, $open = false ) {
1125 $newname = $this->checkRenameArgCount( $newname );
1127 if ( $this->handle
) {
1128 fclose( $this->handle
);
1129 $this->handle
= false;
1131 if ( $this->procOpenResource
) {
1132 proc_close( $this->procOpenResource
);
1133 $this->procOpenResource
= false;
1135 $this->renameOrException( $newname );
1137 $command = $this->command
;
1138 $command .= " > " . wfEscapeShellArg( $this->filename
);
1139 $this->startCommand( $command );
1147 * Sends dump output via the gzip compressor.
1150 class DumpGZipOutput
extends DumpPipeOutput
{
1153 * @param $file string
1155 function __construct( $file ) {
1156 parent
::__construct( "gzip", $file );
1161 * Sends dump output via the bgzip2 compressor.
1164 class DumpBZip2Output
extends DumpPipeOutput
{
1167 * @param $file string
1169 function __construct( $file ) {
1170 parent
::__construct( "bzip2", $file );
1175 * Sends dump output via the p7zip compressor.
1178 class Dump7ZipOutput
extends DumpPipeOutput
{
1181 * @param $file string
1183 function __construct( $file ) {
1184 $command = $this->setup7zCommand( $file );
1185 parent
::__construct( $command );
1186 $this->filename
= $file;
1190 * @param $file string
1193 function setup7zCommand( $file ) {
1194 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1195 // Suppress annoying useless crap from p7zip
1196 // Unfortunately this could suppress real error messages too
1197 $command .= ' >' . wfGetNull() . ' 2>&1';
1202 * @param $newname string
1205 function closeAndRename( $newname, $open = false ) {
1206 $newname = $this->checkRenameArgCount( $newname );
1208 fclose( $this->handle
);
1209 proc_close( $this->procOpenResource
);
1210 $this->renameOrException( $newname );
1212 $command = $this->setup7zCommand( $this->filename
);
1213 $this->startCommand( $command );
1220 * Dump output filter class.
1221 * This just does output filtering and streaming; XML formatting is done
1222 * higher up, so be careful in what you do.
1229 * FIXME will need to be made protected whenever legacy code
1237 protected $sendingThisPage;
1240 * @param $sink DumpOutput
1242 function __construct( &$sink ) {
1243 $this->sink
=& $sink;
1247 * @param $string string
1249 function writeOpenStream( $string ) {
1250 $this->sink
->writeOpenStream( $string );
1254 * @param $string string
1256 function writeCloseStream( $string ) {
1257 $this->sink
->writeCloseStream( $string );
1262 * @param $string string
1264 function writeOpenPage( $page, $string ) {
1265 $this->sendingThisPage
= $this->pass( $page, $string );
1266 if ( $this->sendingThisPage
) {
1267 $this->sink
->writeOpenPage( $page, $string );
1272 * @param $string string
1274 function writeClosePage( $string ) {
1275 if ( $this->sendingThisPage
) {
1276 $this->sink
->writeClosePage( $string );
1277 $this->sendingThisPage
= false;
1283 * @param $string string
1285 function writeRevision( $rev, $string ) {
1286 if ( $this->sendingThisPage
) {
1287 $this->sink
->writeRevision( $rev, $string );
1293 * @param $string string
1295 function writeLogItem( $rev, $string ) {
1296 $this->sink
->writeRevision( $rev, $string );
1300 * @param $newname string
1302 function closeRenameAndReopen( $newname ) {
1303 $this->sink
->closeRenameAndReopen( $newname );
1307 * @param $newname string
1310 function closeAndRename( $newname, $open = false ) {
1311 $this->sink
->closeAndRename( $newname, $open );
1317 function getFilenames() {
1318 return $this->sink
->getFilenames();
1322 * Override for page-based filter types.
1326 function pass( $page ) {
1332 * Simple dump output filter to exclude all talk pages.
1335 class DumpNotalkFilter
extends DumpFilter
{
1341 function pass( $page ) {
1342 return !MWNamespace
::isTalk( $page->page_namespace
);
1347 * Dump output filter to include or exclude pages in a given set of namespaces.
1350 class DumpNamespaceFilter
extends DumpFilter
{
1351 var $invert = false;
1352 var $namespaces = array();
1355 * @param $sink DumpOutput
1357 * @throws MWException
1359 function __construct( &$sink, $param ) {
1360 parent
::__construct( $sink );
1363 "NS_MAIN" => NS_MAIN
,
1364 "NS_TALK" => NS_TALK
,
1365 "NS_USER" => NS_USER
,
1366 "NS_USER_TALK" => NS_USER_TALK
,
1367 "NS_PROJECT" => NS_PROJECT
,
1368 "NS_PROJECT_TALK" => NS_PROJECT_TALK
,
1369 "NS_FILE" => NS_FILE
,
1370 "NS_FILE_TALK" => NS_FILE_TALK
,
1371 "NS_IMAGE" => NS_IMAGE
, // NS_IMAGE is an alias for NS_FILE
1372 "NS_IMAGE_TALK" => NS_IMAGE_TALK
,
1373 "NS_MEDIAWIKI" => NS_MEDIAWIKI
,
1374 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK
,
1375 "NS_TEMPLATE" => NS_TEMPLATE
,
1376 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK
,
1377 "NS_HELP" => NS_HELP
,
1378 "NS_HELP_TALK" => NS_HELP_TALK
,
1379 "NS_CATEGORY" => NS_CATEGORY
,
1380 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK
);
1382 if ( $param { 0 } == '!' ) {
1383 $this->invert
= true;
1384 $param = substr( $param, 1 );
1387 foreach ( explode( ',', $param ) as $key ) {
1388 $key = trim( $key );
1389 if ( isset( $constants[$key] ) ) {
1390 $ns = $constants[$key];
1391 $this->namespaces
[$ns] = true;
1392 } elseif ( is_numeric( $key ) ) {
1393 $ns = intval( $key );
1394 $this->namespaces
[$ns] = true;
1396 throw new MWException( "Unrecognized namespace key '$key'\n" );
1405 function pass( $page ) {
1406 $match = isset( $this->namespaces
[$page->page_namespace
] );
1407 return $this->invert
xor $match;
1412 * Dump output filter to include only the last revision in each page sequence.
1415 class DumpLatestFilter
extends DumpFilter
{
1416 var $page, $pageString, $rev, $revString;
1420 * @param $string string
1422 function writeOpenPage( $page, $string ) {
1423 $this->page
= $page;
1424 $this->pageString
= $string;
1428 * @param $string string
1430 function writeClosePage( $string ) {
1432 $this->sink
->writeOpenPage( $this->page
, $this->pageString
);
1433 $this->sink
->writeRevision( $this->rev
, $this->revString
);
1434 $this->sink
->writeClosePage( $string );
1437 $this->revString
= null;
1439 $this->pageString
= null;
1444 * @param $string string
1446 function writeRevision( $rev, $string ) {
1447 if ( $rev->rev_id
== $this->page
->page_latest
) {
1449 $this->revString
= $string;
1455 * Base class for output stream; prints to stdout or buffer or wherever.
1458 class DumpMultiWriter
{
1463 function __construct( $sinks ) {
1464 $this->sinks
= $sinks;
1465 $this->count
= count( $sinks );
1469 * @param $string string
1471 function writeOpenStream( $string ) {
1472 for ( $i = 0; $i < $this->count
; $i++
) {
1473 $this->sinks
[$i]->writeOpenStream( $string );
1478 * @param $string string
1480 function writeCloseStream( $string ) {
1481 for ( $i = 0; $i < $this->count
; $i++
) {
1482 $this->sinks
[$i]->writeCloseStream( $string );
1488 * @param $string string
1490 function writeOpenPage( $page, $string ) {
1491 for ( $i = 0; $i < $this->count
; $i++
) {
1492 $this->sinks
[$i]->writeOpenPage( $page, $string );
1499 function writeClosePage( $string ) {
1500 for ( $i = 0; $i < $this->count
; $i++
) {
1501 $this->sinks
[$i]->writeClosePage( $string );
1509 function writeRevision( $rev, $string ) {
1510 for ( $i = 0; $i < $this->count
; $i++
) {
1511 $this->sinks
[$i]->writeRevision( $rev, $string );
1518 function closeRenameAndReopen( $newnames ) {
1519 $this->closeAndRename( $newnames, true );
1523 * @param $newnames array
1526 function closeAndRename( $newnames, $open = false ) {
1527 for ( $i = 0; $i < $this->count
; $i++
) {
1528 $this->sinks
[$i]->closeAndRename( $newnames[$i], $open );
1535 function getFilenames() {
1536 $filenames = array();
1537 for ( $i = 0; $i < $this->count
; $i++
) {
1538 $filenames[] = $this->sinks
[$i]->getFilenames();
1546 * @param $string string
1549 function xmlsafe( $string ) {
1550 wfProfileIn( __FUNCTION__
);
1553 * The page may contain old data which has not been properly normalized.
1554 * Invalid UTF-8 sequences or forbidden control characters will make our
1555 * XML output invalid, so be sure to strip them out.
1557 $string = UtfNormal
::cleanUp( $string );
1559 $string = htmlspecialchars( $string );
1560 wfProfileOut( __FUNCTION__
);