Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / export / XmlDumpWriter.php
1 <?php
2 /**
3 * XmlDumpWriter
4 *
5 * Copyright © 2003, 2005, 2006 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Revision\RevisionStore;
27 use MediaWiki\Storage\SqlBlobStore;
28
29 /**
30 * @ingroup Dump
31 */
32 class XmlDumpWriter {
33 /**
34 * @var string[] the schema versions supported for output
35 * @final
36 */
37 public static $supportedSchemas = [
38 XML_DUMP_SCHEMA_VERSION_10,
39 ];
40
41 /**
42 * Title of the currently processed page
43 *
44 * @var Title|null
45 */
46 private $currentTitle = null;
47
48 /**
49 * Opens the XML output stream's root "<mediawiki>" element.
50 * This does not include an xml directive, so is safe to include
51 * as a subelement in a larger XML stream. Namespace and XML Schema
52 * references are included.
53 *
54 * Output will be encoded in UTF-8.
55 *
56 * @return string
57 */
58 function openStream() {
59 $ver = WikiExporter::schemaVersion();
60 return Xml::element( 'mediawiki', [
61 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
62 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
63 /*
64 * When a new version of the schema is created, it needs staging on mediawiki.org.
65 * This requires a change in the operations/mediawiki-config git repo.
66 *
67 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
68 * you copy in the new xsd file.
69 *
70 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
71 * echo "https://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
72 */
73 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
74 "http://www.mediawiki.org/xml/export-$ver.xsd",
75 'version' => $ver,
76 'xml:lang' => MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() ],
77 null ) .
78 "\n" .
79 $this->siteInfo();
80 }
81
82 /**
83 * @return string
84 */
85 function siteInfo() {
86 $info = [
87 $this->sitename(),
88 $this->dbname(),
89 $this->homelink(),
90 $this->generator(),
91 $this->caseSetting(),
92 $this->namespaces() ];
93 return " <siteinfo>\n " .
94 implode( "\n ", $info ) .
95 "\n </siteinfo>\n";
96 }
97
98 /**
99 * @return string
100 */
101 function sitename() {
102 global $wgSitename;
103 return Xml::element( 'sitename', [], $wgSitename );
104 }
105
106 /**
107 * @return string
108 */
109 function dbname() {
110 global $wgDBname;
111 return Xml::element( 'dbname', [], $wgDBname );
112 }
113
114 /**
115 * @return string
116 */
117 function generator() {
118 global $wgVersion;
119 return Xml::element( 'generator', [], "MediaWiki $wgVersion" );
120 }
121
122 /**
123 * @return string
124 */
125 function homelink() {
126 return Xml::element( 'base', [], Title::newMainPage()->getCanonicalURL() );
127 }
128
129 /**
130 * @return string
131 */
132 function caseSetting() {
133 global $wgCapitalLinks;
134 // "case-insensitive" option is reserved for future
135 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
136 return Xml::element( 'case', [], $sensitivity );
137 }
138
139 /**
140 * @return string
141 */
142 function namespaces() {
143 $spaces = "<namespaces>\n";
144 foreach (
145 MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces()
146 as $ns => $title
147 ) {
148 $spaces .= ' ' .
149 Xml::element( 'namespace',
150 [
151 'key' => $ns,
152 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
153 ], $title ) . "\n";
154 }
155 $spaces .= " </namespaces>";
156 return $spaces;
157 }
158
159 /**
160 * Closes the output stream with the closing root element.
161 * Call when finished dumping things.
162 *
163 * @return string
164 */
165 function closeStream() {
166 return "</mediawiki>\n";
167 }
168
169 /**
170 * Opens a "<page>" section on the output stream, with data
171 * from the given database row.
172 *
173 * @param object $row
174 * @return string
175 */
176 public function openPage( $row ) {
177 $out = " <page>\n";
178 $this->currentTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
179 $canonicalTitle = self::canonicalTitle( $this->currentTitle );
180 $out .= ' ' . Xml::elementClean( 'title', [], $canonicalTitle ) . "\n";
181 $out .= ' ' . Xml::element( 'ns', [], strval( $row->page_namespace ) ) . "\n";
182 $out .= ' ' . Xml::element( 'id', [], strval( $row->page_id ) ) . "\n";
183 if ( $row->page_is_redirect ) {
184 $page = WikiPage::factory( $this->currentTitle );
185 $redirect = $page->getRedirectTarget();
186 if ( $redirect instanceof Title && $redirect->isValidRedirectTarget() ) {
187 $out .= ' ';
188 $out .= Xml::element( 'redirect', [ 'title' => self::canonicalTitle( $redirect ) ] );
189 $out .= "\n";
190 }
191 }
192
193 if ( $row->page_restrictions != '' ) {
194 $out .= ' ' . Xml::element( 'restrictions', [],
195 strval( $row->page_restrictions ) ) . "\n";
196 }
197
198 Hooks::run( 'XmlDumpWriterOpenPage', [ $this, &$out, $row, $this->currentTitle ] );
199
200 return $out;
201 }
202
203 /**
204 * Closes a "<page>" section on the output stream.
205 *
206 * @private
207 * @return string
208 */
209 function closePage() {
210 return " </page>\n";
211 }
212
213 /**
214 * @return RevisionStore
215 */
216 private function getRevisionStore() {
217 return MediaWikiServices::getInstance()->getRevisionStore();
218 }
219
220 /**
221 * @return SqlBlobStore
222 */
223 private function getBlobStore() {
224 return MediaWikiServices::getInstance()->getBlobStore();
225 }
226
227 /**
228 * Dumps a "<revision>" section on the output stream, with
229 * data filled in from the given database row.
230 *
231 * @param object $row
232 * @return string
233 * @private
234 */
235 function writeRevision( $row ) {
236 $out = " <revision>\n";
237 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
238 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
239 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
240 }
241
242 $out .= $this->writeTimestamp( $row->rev_timestamp );
243
244 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
245 $out .= " " . Xml::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
246 } else {
247 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
248 }
249
250 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
251 $out .= " <minor/>\n";
252 }
253 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
254 $out .= " " . Xml::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
255 } else {
256 $comment = CommentStore::getStore()->getComment( 'rev_comment', $row )->text;
257 if ( $comment != '' ) {
258 $out .= " " . Xml::elementClean( 'comment', [], strval( $comment ) ) . "\n";
259 }
260 }
261
262 // TODO: rev_content_model no longer exists with MCR, see T174031
263 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
264 $content_model = strval( $row->rev_content_model );
265 } else {
266 // probably using $wgContentHandlerUseDB = false;
267 $content_model = ContentHandler::getDefaultModelFor( $this->currentTitle );
268 }
269
270 $content_handler = ContentHandler::getForModelID( $content_model );
271
272 // TODO: rev_content_format no longer exists with MCR, see T174031
273 if ( isset( $row->rev_content_format ) && !is_null( $row->rev_content_format ) ) {
274 $content_format = strval( $row->rev_content_format );
275 } else {
276 // probably using $wgContentHandlerUseDB = false;
277 $content_format = $content_handler->getDefaultFormat();
278 }
279
280 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
281 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
282
283 $text = '';
284 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
285 $out .= " " . Xml::element( 'text', [ 'deleted' => 'deleted' ] ) . "\n";
286 } elseif ( isset( $row->old_text ) ) {
287 // Raw text from the database may have invalid chars
288 $text = strval( Revision::getRevisionText( $row ) );
289 try {
290 $text = $content_handler->exportTransform( $text, $content_format );
291 }
292 catch ( MWException $ex ) {
293 // leave text as is; that's the way it goes
294 }
295 $out .= " " . Xml::elementClean( 'text',
296 [ 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ],
297 strval( $text ) ) . "\n";
298 } elseif ( isset( $row->_load_content ) ) {
299 // TODO: make this fully MCR aware, see T174031
300 $rev = $this->getRevisionStore()->newRevisionFromRow( $row, 0, $this->currentTitle );
301 $slot = $rev->getSlot( 'main' );
302 $content = $slot->getContent();
303
304 if ( $content instanceof TextContent ) {
305 // HACK: For text based models, bypass the serialization step.
306 // This allows extensions (like Flow)that use incompatible combinations
307 // of serialization format and content model.
308 $text = $content->getNativeData();
309 } else {
310 $text = $content->serialize( $content_format );
311 }
312
313 $text = $content_handler->exportTransform( $text, $content_format );
314 $out .= " " . Xml::elementClean( 'text',
315 [ 'xml:space' => 'preserve', 'bytes' => intval( $slot->getSize() ) ],
316 strval( $text ) ) . "\n";
317 } elseif ( isset( $row->rev_text_id ) ) {
318 // Stub output for pre-MCR schema
319 // TODO: MCR: rev_text_id only exists in the pre-MCR schema. Remove this when
320 // we drop support for the old schema.
321 $out .= " " . Xml::element( 'text',
322 [ 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ],
323 "" ) . "\n";
324 } else {
325 // Backwards-compatible stub output for MCR aware schema
326 // TODO: MCR: emit content addresses instead of text ids, see T174031, T199121
327 $rev = $this->getRevisionStore()->newRevisionFromRow( $row, 0, $this->currentTitle );
328 $slot = $rev->getSlot( 'main' );
329
330 // Note that this is currently the ONLY reason we have a BlobStore here at all.
331 // When removing this line, check whether the BlobStore has become unused.
332 $textId = $this->getBlobStore()->getTextIdFromAddress( $slot->getAddress() );
333 $out .= " " . Xml::element( 'text',
334 [ 'id' => $textId, 'bytes' => intval( $slot->getSize() ) ],
335 "" ) . "\n";
336 }
337
338 if ( isset( $row->rev_sha1 )
339 && $row->rev_sha1
340 && !( $row->rev_deleted & Revision::DELETED_TEXT )
341 ) {
342 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
343 } else {
344 $out .= " <sha1/>\n";
345 }
346
347 // Avoid PHP 7.1 warning from passing $this by reference
348 $writer = $this;
349 Hooks::run( 'XmlDumpWriterWriteRevision', [ &$writer, &$out, $row, $text ] );
350
351 $out .= " </revision>\n";
352
353 return $out;
354 }
355
356 /**
357 * Dumps a "<logitem>" section on the output stream, with
358 * data filled in from the given database row.
359 *
360 * @param object $row
361 * @return string
362 * @private
363 */
364 function writeLogItem( $row ) {
365 $out = " <logitem>\n";
366 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
367
368 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
369
370 if ( $row->log_deleted & LogPage::DELETED_USER ) {
371 $out .= " " . Xml::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
372 } else {
373 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
374 }
375
376 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
377 $out .= " " . Xml::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
378 } else {
379 $comment = CommentStore::getStore()->getComment( 'log_comment', $row )->text;
380 if ( $comment != '' ) {
381 $out .= " " . Xml::elementClean( 'comment', null, strval( $comment ) ) . "\n";
382 }
383 }
384
385 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
386 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
387
388 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
389 $out .= " " . Xml::element( 'text', [ 'deleted' => 'deleted' ] ) . "\n";
390 } else {
391 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
392 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
393 $out .= " " . Xml::elementClean( 'params',
394 [ 'xml:space' => 'preserve' ],
395 strval( $row->log_params ) ) . "\n";
396 }
397
398 $out .= " </logitem>\n";
399
400 return $out;
401 }
402
403 /**
404 * @param string $timestamp
405 * @param string $indent Default to six spaces
406 * @return string
407 */
408 function writeTimestamp( $timestamp, $indent = " " ) {
409 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
410 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
411 }
412
413 /**
414 * @param int $id
415 * @param string $text
416 * @param string $indent Default to six spaces
417 * @return string
418 */
419 function writeContributor( $id, $text, $indent = " " ) {
420 $out = $indent . "<contributor>\n";
421 if ( $id || !IP::isValid( $text ) ) {
422 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
423 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
424 } else {
425 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
426 }
427 $out .= $indent . "</contributor>\n";
428 return $out;
429 }
430
431 /**
432 * Warning! This data is potentially inconsistent. :(
433 * @param object $row
434 * @param bool $dumpContents
435 * @return string
436 */
437 function writeUploads( $row, $dumpContents = false ) {
438 if ( $row->page_namespace == NS_FILE ) {
439 $img = wfLocalFile( $row->page_title );
440 if ( $img && $img->exists() ) {
441 $out = '';
442 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
443 $out .= $this->writeUpload( $ver, $dumpContents );
444 }
445 $out .= $this->writeUpload( $img, $dumpContents );
446 return $out;
447 }
448 }
449 return '';
450 }
451
452 /**
453 * @param File $file
454 * @param bool $dumpContents
455 * @return string
456 */
457 function writeUpload( $file, $dumpContents = false ) {
458 if ( $file->isOld() ) {
459 $archiveName = " " .
460 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
461 } else {
462 $archiveName = '';
463 }
464 if ( $dumpContents ) {
465 $be = $file->getRepo()->getBackend();
466 # Dump file as base64
467 # Uses only XML-safe characters, so does not need escaping
468 # @todo Too bad this loads the contents into memory (script might swap)
469 $contents = ' <contents encoding="base64">' .
470 chunk_split( base64_encode(
471 $be->getFileContents( [ 'src' => $file->getPath() ] ) ) ) .
472 " </contents>\n";
473 } else {
474 $contents = '';
475 }
476 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
477 $comment = Xml::element( 'comment', [ 'deleted' => 'deleted' ] );
478 } else {
479 $comment = Xml::elementClean( 'comment', null, strval( $file->getDescription() ) );
480 }
481 return " <upload>\n" .
482 $this->writeTimestamp( $file->getTimestamp() ) .
483 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
484 " " . $comment . "\n" .
485 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
486 $archiveName .
487 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
488 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
489 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
490 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
491 $contents .
492 " </upload>\n";
493 }
494
495 /**
496 * Return prefixed text form of title, but using the content language's
497 * canonical namespace. This skips any special-casing such as gendered
498 * user namespaces -- which while useful, are not yet listed in the
499 * XML "<siteinfo>" data so are unsafe in export.
500 *
501 * @param Title $title
502 * @return string
503 * @since 1.18
504 */
505 public static function canonicalTitle( Title $title ) {
506 if ( $title->isExternal() ) {
507 return $title->getPrefixedText();
508 }
509
510 $prefix = MediaWikiServices::getInstance()->getContentLanguage()->
511 getFormattedNsText( $title->getNamespace() );
512
513 // @todo Emit some kind of warning to the user if $title->getNamespace() !==
514 // NS_MAIN and $prefix === '' (viz. pages in an unregistered namespace)
515
516 if ( $prefix !== '' ) {
517 $prefix .= ':';
518 }
519
520 return $prefix . $title->getText();
521 }
522 }