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
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\RevisionStore
;
28 use MediaWiki\Revision\SlotRecord
;
29 use MediaWiki\Revision\SuppressedDataException
;
30 use MediaWiki\Storage\SqlBlobStore
;
31 use Wikimedia\Assert\Assert
;
38 /** Output serialized revision content. */
39 const WRITE_CONTENT
= 0;
41 /** Only output subs for revision content. */
45 * Only output subs for revision content, indicating that the content has been
46 * deleted/suppressed. For internal use only.
48 const WRITE_STUB_DELETED
= 2;
51 * @var string[] the schema versions supported for output
54 public static $supportedSchemas = [
55 XML_DUMP_SCHEMA_VERSION_10
,
56 XML_DUMP_SCHEMA_VERSION_11
60 * @var string which schema version the generated XML should comply to.
61 * One of the values from self::$supportedSchemas, using the SCHEMA_VERSION_XX
64 private $schemaVersion;
67 * Title of the currently processed page
71 private $currentTitle = null;
74 * @var int Whether to output revision content or just stubs. WRITE_CONTENT or WRITE_STUB.
79 * XmlDumpWriter constructor.
81 * @param int $contentMode WRITE_CONTENT or WRITE_STUB.
82 * @param string $schemaVersion which schema version the generated XML should comply to.
83 * One of the values from self::$supportedSchemas, using the XML_DUMP_SCHEMA_VERSION_XX
86 public function __construct(
87 $contentMode = self
::WRITE_CONTENT
,
88 $schemaVersion = XML_DUMP_SCHEMA_VERSION_11
91 in_array( $contentMode, [ self
::WRITE_CONTENT
, self
::WRITE_STUB
] ),
93 'must be one of the following constants: WRITE_CONTENT or WRITE_STUB.'
97 in_array( $schemaVersion, self
::$supportedSchemas ),
99 'must be one of the following schema versions: '
100 . implode( ',', self
::$supportedSchemas )
103 $this->contentMode
= $contentMode;
104 $this->schemaVersion
= $schemaVersion;
108 * Opens the XML output stream's root "<mediawiki>" element.
109 * This does not include an xml directive, so is safe to include
110 * as a subelement in a larger XML stream. Namespace and XML Schema
111 * references are included.
113 * Output will be encoded in UTF-8.
117 function openStream() {
118 $ver = $this->schemaVersion
;
119 return Xml
::element( 'mediawiki', [
120 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
121 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
123 * When a new version of the schema is created, it needs staging on mediawiki.org.
124 * This requires a change in the operations/mediawiki-config git repo.
126 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
127 * you copy in the new xsd file.
129 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
130 * echo "https://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
132 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
133 "http://www.mediawiki.org/xml/export-$ver.xsd",
135 'xml:lang' => MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() ],
144 function siteInfo() {
150 $this->caseSetting(),
151 $this->namespaces() ];
152 return " <siteinfo>\n " .
153 implode( "\n ", $info ) .
160 function sitename() {
162 return Xml
::element( 'sitename', [], $wgSitename );
170 return Xml
::element( 'dbname', [], $wgDBname );
176 function generator() {
178 return Xml
::element( 'generator', [], "MediaWiki $wgVersion" );
184 function homelink() {
185 return Xml
::element( 'base', [], Title
::newMainPage()->getCanonicalURL() );
191 function caseSetting() {
192 global $wgCapitalLinks;
193 // "case-insensitive" option is reserved for future
194 $sensitivity = $wgCapitalLinks ?
'first-letter' : 'case-sensitive';
195 return Xml
::element( 'case', [], $sensitivity );
201 function namespaces() {
202 $spaces = "<namespaces>\n";
203 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
205 MediaWikiServices
::getInstance()->getContentLanguage()->getFormattedNamespaces()
209 Xml
::element( 'namespace',
212 'case' => $nsInfo->isCapitalized( $ns )
213 ?
'first-letter' : 'case-sensitive',
216 $spaces .= " </namespaces>";
221 * Closes the output stream with the closing root element.
222 * Call when finished dumping things.
226 function closeStream() {
227 return "</mediawiki>\n";
231 * Opens a "<page>" section on the output stream, with data
232 * from the given database row.
237 public function openPage( $row ) {
239 $this->currentTitle
= Title
::newFromRow( $row );
240 $canonicalTitle = self
::canonicalTitle( $this->currentTitle
);
241 $out .= ' ' . Xml
::elementClean( 'title', [], $canonicalTitle ) . "\n";
242 $out .= ' ' . Xml
::element( 'ns', [], strval( $row->page_namespace
) ) . "\n";
243 $out .= ' ' . Xml
::element( 'id', [], strval( $row->page_id
) ) . "\n";
244 if ( $row->page_is_redirect
) {
245 $page = WikiPage
::factory( $this->currentTitle
);
246 $redirect = $page->getRedirectTarget();
247 if ( $redirect instanceof Title
&& $redirect->isValidRedirectTarget() ) {
249 $out .= Xml
::element( 'redirect', [ 'title' => self
::canonicalTitle( $redirect ) ] );
254 if ( $row->page_restrictions
!= '' ) {
255 $out .= ' ' . Xml
::element( 'restrictions', [],
256 strval( $row->page_restrictions
) ) . "\n";
259 Hooks
::run( 'XmlDumpWriterOpenPage', [ $this, &$out, $row, $this->currentTitle
] );
265 * Closes a "<page>" section on the output stream.
270 function closePage() {
271 if ( $this->currentTitle
!== null ) {
272 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
273 // In rare cases, link cache has the same key for some pages which
274 // might be read as part of the same batch. T220424 and T220316
275 $linkCache->clearLink( $this->currentTitle
);
281 * @return RevisionStore
283 private function getRevisionStore() {
284 return MediaWikiServices
::getInstance()->getRevisionStore();
288 * @return SqlBlobStore
290 private function getBlobStore() {
291 return MediaWikiServices
::getInstance()->getBlobStore();
295 * Dumps a "<revision>" section on the output stream, with
296 * data filled in from the given database row.
299 * @param null|object[] $slotRows
303 * @throws MWException
306 function writeRevision( $row, $slotRows = null ) {
307 $rev = $this->getRevisionStore()->newRevisionFromRowAndSlots(
314 $out = " <revision>\n";
315 $out .= " " . Xml
::element( 'id', null, strval( $rev->getId() ) ) . "\n";
317 if ( $rev->getParentId() ) {
318 $out .= " " . Xml
::element( 'parentid', null, strval( $rev->getParentId() ) ) . "\n";
321 $out .= $this->writeTimestamp( $rev->getTimestamp() );
323 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
324 $out .= " " . Xml
::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
326 // empty values get written out as uid 0, see T224221
327 $user = $rev->getUser();
328 $out .= $this->writeContributor(
329 $user ?
$user->getId() : 0,
330 $user ?
$user->getName() : ''
334 if ( $rev->isMinor() ) {
335 $out .= " <minor/>\n";
337 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
338 $out .= " " . Xml
::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
340 if ( $rev->getComment()->text
!= '' ) {
342 . Xml
::elementClean( 'comment', [], strval( $rev->getComment()->text
) )
347 $contentMode = $rev->isDeleted( Revision
::DELETED_TEXT
) ? self
::WRITE_STUB_DELETED
348 : $this->contentMode
;
350 foreach ( $rev->getSlots()->getSlots() as $slot ) {
351 $out .= $this->writeSlot( $slot, $contentMode );
354 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
355 $out .= " <sha1/>\n";
357 $out .= " " . Xml
::element( 'sha1', null, strval( $rev->getSha1() ) ) . "\n";
360 // Avoid PHP 7.1 warning from passing $this by reference
362 $text = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::RAW
);
363 Hooks
::run( 'XmlDumpWriterWriteRevision', [ &$writer, &$out, $row, $text, $rev ] );
365 $out .= " </revision>\n";
371 * @param SlotRecord $slot
372 * @param int $contentMode see the WRITE_XXX constants
376 private function writeSlot( SlotRecord
$slot, $contentMode ) {
377 $isMain = $slot->getRole() === SlotRecord
::MAIN
;
378 $isV11 = $this->schemaVersion
>= XML_DUMP_SCHEMA_VERSION_11
;
380 if ( !$isV11 && !$isMain ) {
381 // ignore extra slots
389 // non-main slots are wrapped into an additional element.
390 $out .= ' ' . Xml
::openElement( 'content' ) . "\n";
392 $out .= $indent . Xml
::element( 'role', null, strval( $slot->getRole() ) ) . "\n";
396 $out .= $indent . Xml
::element( 'origin', null, strval( $slot->getOrigin() ) ) . "\n";
399 $contentModel = $slot->getModel();
400 $contentHandler = ContentHandler
::getForModelID( $contentModel );
401 $contentFormat = $contentHandler->getDefaultFormat();
403 // XXX: The content format is only relevant when actually outputting serialized content.
404 // It should probably be an attribute on the text tag.
405 $out .= $indent . Xml
::element( 'model', null, strval( $contentModel ) ) . "\n";
406 $out .= $indent . Xml
::element( 'format', null, strval( $contentFormat ) ) . "\n";
409 'xml:space' => 'preserve',
410 'bytes' => $slot->getSize(),
414 $textAttributes['sha1'] = $slot->getSha1();
417 if ( $contentMode === self
::WRITE_CONTENT
) {
420 $out .= $this->writeText( $slot->getContent(), $textAttributes, $indent );
421 } catch ( SuppressedDataException
$ex ) {
422 // NOTE: this shouldn't happen, since the caller is supposed to have checked
423 // for suppressed content!
424 // write <text> placeholder tag
425 $textAttributes['deleted'] = 'deleted';
426 $out .= $indent . Xml
::element( 'text', $textAttributes ) . "\n";
428 catch ( Exception
$ex ) {
429 if ( $ex instanceof MWException ||
$ex instanceof RuntimeException
) {
430 // there's no provision in the schema for an attribute that will let
431 // the user know this element was unavailable due to error; an empty
432 // tag is the best we can do
433 $out .= $indent . Xml
::element( 'text' ) . "\n";
435 'failed to load content slot ' . $slot->getRole() . ' for revision '
436 . $slot->getRevision() . "\n"
442 } elseif ( $contentMode === self
::WRITE_STUB_DELETED
) {
443 // write <text> placeholder tag
444 $textAttributes['deleted'] = 'deleted';
445 $out .= $indent . Xml
::element( 'text', $textAttributes ) . "\n";
447 // write <text> stub tag
449 $textAttributes['location'] = $slot->getAddress();
452 // Output the numerical text ID if possible, for backwards compatibility.
453 // Note that this is currently the ONLY reason we have a BlobStore here at all.
454 // When removing this line, check whether the BlobStore has become unused.
455 $textId = $this->getBlobStore()->getTextIdFromAddress( $slot->getAddress() );
457 $textAttributes['id'] = $textId;
458 } elseif ( !$isV11 ) {
459 throw new InvalidArgumentException(
460 'Cannot produce stubs for non-text-table content blobs with schema version '
461 . $this->schemaVersion
465 $out .= $indent . Xml
::element( 'text', $textAttributes ) . "\n";
469 $out .= ' ' . Xml
::closeElement( 'content' ) . "\n";
476 * @param Content $content
477 * @param string[] $textAttributes
478 * @param string $indent
482 private function writeText( Content
$content, $textAttributes, $indent ) {
485 $contentHandler = $content->getContentHandler();
486 $contentFormat = $contentHandler->getDefaultFormat();
488 if ( $content instanceof TextContent
) {
489 // HACK: For text based models, bypass the serialization step. This allows extensions (like Flow)
490 // that use incompatible combinations of serialization format and content model.
491 $data = $content->getNativeData();
493 $data = $content->serialize( $contentFormat );
496 $data = $contentHandler->exportTransform( $data, $contentFormat );
497 $textAttributes['bytes'] = $size = strlen( $data ); // make sure to use the actual size
498 $out .= $indent . Xml
::elementClean( 'text', $textAttributes, strval( $data ) ) . "\n";
504 * Dumps a "<logitem>" section on the output stream, with
505 * data filled in from the given database row.
511 function writeLogItem( $row ) {
512 $out = " <logitem>\n";
513 $out .= " " . Xml
::element( 'id', null, strval( $row->log_id
) ) . "\n";
515 $out .= $this->writeTimestamp( $row->log_timestamp
, " " );
517 if ( $row->log_deleted
& LogPage
::DELETED_USER
) {
518 $out .= " " . Xml
::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
520 $out .= $this->writeContributor( $row->log_user
, $row->user_name
, " " );
523 if ( $row->log_deleted
& LogPage
::DELETED_COMMENT
) {
524 $out .= " " . Xml
::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
526 $comment = CommentStore
::getStore()->getComment( 'log_comment', $row )->text
;
527 if ( $comment != '' ) {
528 $out .= " " . Xml
::elementClean( 'comment', null, strval( $comment ) ) . "\n";
532 $out .= " " . Xml
::element( 'type', null, strval( $row->log_type
) ) . "\n";
533 $out .= " " . Xml
::element( 'action', null, strval( $row->log_action
) ) . "\n";
535 if ( $row->log_deleted
& LogPage
::DELETED_ACTION
) {
536 $out .= " " . Xml
::element( 'text', [ 'deleted' => 'deleted' ] ) . "\n";
538 $title = Title
::makeTitle( $row->log_namespace
, $row->log_title
);
539 $out .= " " . Xml
::elementClean( 'logtitle', null, self
::canonicalTitle( $title ) ) . "\n";
540 $out .= " " . Xml
::elementClean( 'params',
541 [ 'xml:space' => 'preserve' ],
542 strval( $row->log_params
) ) . "\n";
545 $out .= " </logitem>\n";
551 * @param string $timestamp
552 * @param string $indent Default to six spaces
555 function writeTimestamp( $timestamp, $indent = " " ) {
556 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
557 return $indent . Xml
::element( 'timestamp', null, $ts ) . "\n";
562 * @param string $text
563 * @param string $indent Default to six spaces
566 function writeContributor( $id, $text, $indent = " " ) {
567 $out = $indent . "<contributor>\n";
568 if ( $id ||
!IP
::isValid( $text ) ) {
569 $out .= $indent . " " . Xml
::elementClean( 'username', null, strval( $text ) ) . "\n";
570 $out .= $indent . " " . Xml
::element( 'id', null, strval( $id ) ) . "\n";
572 $out .= $indent . " " . Xml
::elementClean( 'ip', null, strval( $text ) ) . "\n";
574 $out .= $indent . "</contributor>\n";
579 * Warning! This data is potentially inconsistent. :(
581 * @param bool $dumpContents
584 function writeUploads( $row, $dumpContents = false ) {
585 if ( $row->page_namespace
== NS_FILE
) {
586 $img = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
587 ->newFile( $row->page_title
);
588 if ( $img && $img->exists() ) {
590 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
591 $out .= $this->writeUpload( $ver, $dumpContents );
593 $out .= $this->writeUpload( $img, $dumpContents );
602 * @param bool $dumpContents
605 function writeUpload( $file, $dumpContents = false ) {
606 if ( $file->isOld() ) {
608 Xml
::element( 'archivename', null, $file->getArchiveName() ) . "\n";
612 if ( $dumpContents ) {
613 $be = $file->getRepo()->getBackend();
614 # Dump file as base64
615 # Uses only XML-safe characters, so does not need escaping
616 # @todo Too bad this loads the contents into memory (script might swap)
617 $contents = ' <contents encoding="base64">' .
618 chunk_split( base64_encode(
619 $be->getFileContents( [ 'src' => $file->getPath() ] ) ) ) .
624 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
625 $comment = Xml
::element( 'comment', [ 'deleted' => 'deleted' ] );
627 $comment = Xml
::elementClean( 'comment', null, strval( $file->getDescription() ) );
629 return " <upload>\n" .
630 $this->writeTimestamp( $file->getTimestamp() ) .
631 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
632 " " . $comment . "\n" .
633 " " . Xml
::element( 'filename', null, $file->getName() ) . "\n" .
635 " " . Xml
::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
636 " " . Xml
::element( 'size', null, $file->getSize() ) . "\n" .
637 " " . Xml
::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
638 " " . Xml
::element( 'rel', null, $file->getRel() ) . "\n" .
644 * Return prefixed text form of title, but using the content language's
645 * canonical namespace. This skips any special-casing such as gendered
646 * user namespaces -- which while useful, are not yet listed in the
647 * XML "<siteinfo>" data so are unsafe in export.
649 * @param Title $title
653 public static function canonicalTitle( Title
$title ) {
654 if ( $title->isExternal() ) {
655 return $title->getPrefixedText();
658 $prefix = MediaWikiServices
::getInstance()->getContentLanguage()->
659 getFormattedNsText( $title->getNamespace() );
661 // @todo Emit some kind of warning to the user if $title->getNamespace() !==
662 // NS_MAIN and $prefix === '' (viz. pages in an unregistered namespace)
664 if ( $prefix !== '' ) {
668 return $prefix . $title->getText();