Make XmlDumpwriter resilient to blob store corruption.
[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\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;
32
33 /**
34 * @ingroup Dump
35 */
36 class XmlDumpWriter {
37
38 /** Output serialized revision content. */
39 const WRITE_CONTENT = 0;
40
41 /** Only output subs for revision content. */
42 const WRITE_STUB = 1;
43
44 /**
45 * Only output subs for revision content, indicating that the content has been
46 * deleted/suppressed. For internal use only.
47 */
48 const WRITE_STUB_DELETED = 2;
49
50 /**
51 * @var string[] the schema versions supported for output
52 * @final
53 */
54 public static $supportedSchemas = [
55 XML_DUMP_SCHEMA_VERSION_10,
56 XML_DUMP_SCHEMA_VERSION_11
57 ];
58
59 /**
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
62 * constants.
63 */
64 private $schemaVersion;
65
66 /**
67 * Title of the currently processed page
68 *
69 * @var Title|null
70 */
71 private $currentTitle = null;
72
73 /**
74 * @var int Whether to output revision content or just stubs. WRITE_CONTENT or WRITE_STUB.
75 */
76 private $contentMode;
77
78 /**
79 * XmlDumpWriter constructor.
80 *
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
84 * constants.
85 */
86 public function __construct(
87 $contentMode = self::WRITE_CONTENT,
88 $schemaVersion = XML_DUMP_SCHEMA_VERSION_11
89 ) {
90 Assert::parameter(
91 in_array( $contentMode, [ self::WRITE_CONTENT, self::WRITE_STUB ] ),
92 '$contentMode',
93 'must be one of the following constants: WRITE_CONTENT or WRITE_STUB.'
94 );
95
96 Assert::parameter(
97 in_array( $schemaVersion, self::$supportedSchemas ),
98 '$schemaVersion',
99 'must be one of the following schema versions: '
100 . implode( ',', self::$supportedSchemas )
101 );
102
103 $this->contentMode = $contentMode;
104 $this->schemaVersion = $schemaVersion;
105 }
106
107 /**
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.
112 *
113 * Output will be encoded in UTF-8.
114 *
115 * @return string
116 */
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",
122 /*
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.
125 *
126 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
127 * you copy in the new xsd file.
128 *
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
131 */
132 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
133 "http://www.mediawiki.org/xml/export-$ver.xsd",
134 'version' => $ver,
135 'xml:lang' => MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() ],
136 null ) .
137 "\n" .
138 $this->siteInfo();
139 }
140
141 /**
142 * @return string
143 */
144 function siteInfo() {
145 $info = [
146 $this->sitename(),
147 $this->dbname(),
148 $this->homelink(),
149 $this->generator(),
150 $this->caseSetting(),
151 $this->namespaces() ];
152 return " <siteinfo>\n " .
153 implode( "\n ", $info ) .
154 "\n </siteinfo>\n";
155 }
156
157 /**
158 * @return string
159 */
160 function sitename() {
161 global $wgSitename;
162 return Xml::element( 'sitename', [], $wgSitename );
163 }
164
165 /**
166 * @return string
167 */
168 function dbname() {
169 global $wgDBname;
170 return Xml::element( 'dbname', [], $wgDBname );
171 }
172
173 /**
174 * @return string
175 */
176 function generator() {
177 global $wgVersion;
178 return Xml::element( 'generator', [], "MediaWiki $wgVersion" );
179 }
180
181 /**
182 * @return string
183 */
184 function homelink() {
185 return Xml::element( 'base', [], Title::newMainPage()->getCanonicalURL() );
186 }
187
188 /**
189 * @return string
190 */
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 );
196 }
197
198 /**
199 * @return string
200 */
201 function namespaces() {
202 $spaces = "<namespaces>\n";
203 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
204 foreach (
205 MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces()
206 as $ns => $title
207 ) {
208 $spaces .= ' ' .
209 Xml::element( 'namespace',
210 [
211 'key' => $ns,
212 'case' => $nsInfo->isCapitalized( $ns )
213 ? 'first-letter' : 'case-sensitive',
214 ], $title ) . "\n";
215 }
216 $spaces .= " </namespaces>";
217 return $spaces;
218 }
219
220 /**
221 * Closes the output stream with the closing root element.
222 * Call when finished dumping things.
223 *
224 * @return string
225 */
226 function closeStream() {
227 return "</mediawiki>\n";
228 }
229
230 /**
231 * Opens a "<page>" section on the output stream, with data
232 * from the given database row.
233 *
234 * @param object $row
235 * @return string
236 */
237 public function openPage( $row ) {
238 $out = " <page>\n";
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() ) {
248 $out .= ' ';
249 $out .= Xml::element( 'redirect', [ 'title' => self::canonicalTitle( $redirect ) ] );
250 $out .= "\n";
251 }
252 }
253
254 if ( $row->page_restrictions != '' ) {
255 $out .= ' ' . Xml::element( 'restrictions', [],
256 strval( $row->page_restrictions ) ) . "\n";
257 }
258
259 Hooks::run( 'XmlDumpWriterOpenPage', [ $this, &$out, $row, $this->currentTitle ] );
260
261 return $out;
262 }
263
264 /**
265 * Closes a "<page>" section on the output stream.
266 *
267 * @private
268 * @return string
269 */
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 );
276 }
277 return " </page>\n";
278 }
279
280 /**
281 * @return RevisionStore
282 */
283 private function getRevisionStore() {
284 return MediaWikiServices::getInstance()->getRevisionStore();
285 }
286
287 /**
288 * @return SqlBlobStore
289 */
290 private function getBlobStore() {
291 return MediaWikiServices::getInstance()->getBlobStore();
292 }
293
294 /**
295 * Invokes the given method on the given object, catching and logging any storage related
296 * exceptions.
297 *
298 * @param object $obj
299 * @param string $method
300 * @param array $args
301 * @param string $warning The warning to output in case of a storage related exception.
302 *
303 * @return mixed Returns the method's return value,
304 * or null in case of a storage related exception.
305 * @throws Exception
306 */
307 private function invokeLenient( $obj, $method, $args = [], $warning ) {
308 try {
309 return call_user_func_array( [ $obj, $method ], $args );
310 } catch ( SuppressedDataException $ex ) {
311 return null;
312 } catch ( Exception $ex ) {
313 if ( $ex instanceof MWException || $ex instanceof RuntimeException ) {
314 MWDebug::warning( $warning . ': ' . $ex->getMessage() );
315 return null;
316 } else {
317 throw $ex;
318 }
319 }
320 }
321
322 /**
323 * Dumps a "<revision>" section on the output stream, with
324 * data filled in from the given database row.
325 *
326 * @param object $row
327 * @param null|object[] $slotRows
328 *
329 * @return string
330 * @throws FatalError
331 * @throws MWException
332 * @private
333 */
334 function writeRevision( $row, $slotRows = null ) {
335 $rev = $this->getRevisionStore()->newRevisionFromRowAndSlots(
336 $row,
337 $slotRows,
338 0,
339 $this->currentTitle
340 );
341
342 $out = " <revision>\n";
343 $out .= " " . Xml::element( 'id', null, strval( $rev->getId() ) ) . "\n";
344
345 if ( $rev->getParentId() ) {
346 $out .= " " . Xml::element( 'parentid', null, strval( $rev->getParentId() ) ) . "\n";
347 }
348
349 $out .= $this->writeTimestamp( $rev->getTimestamp() );
350
351 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
352 $out .= " " . Xml::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
353 } else {
354 // empty values get written out as uid 0, see T224221
355 $user = $rev->getUser();
356 $out .= $this->writeContributor(
357 $user ? $user->getId() : 0,
358 $user ? $user->getName() : ''
359 );
360 }
361
362 if ( $rev->isMinor() ) {
363 $out .= " <minor/>\n";
364 }
365 if ( $rev->isDeleted( RevisionRecord::DELETED_COMMENT ) ) {
366 $out .= " " . Xml::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
367 } else {
368 if ( $rev->getComment()->text != '' ) {
369 $out .= " "
370 . Xml::elementClean( 'comment', [], strval( $rev->getComment()->text ) )
371 . "\n";
372 }
373 }
374
375 $contentMode = $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ? self::WRITE_STUB_DELETED
376 : $this->contentMode;
377
378 foreach ( $rev->getSlots()->getSlots() as $slot ) {
379 $out .= $this->writeSlot( $slot, $contentMode );
380 }
381
382 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
383 $out .= " <sha1/>\n";
384 } else {
385 $sha1 = $this->invokeLenient(
386 $rev,
387 'getSha1',
388 [],
389 'failed to determine sha1 for revision ' . $rev->getId()
390 );
391 $out .= " " . Xml::element( 'sha1', null, strval( $sha1 ) ) . "\n";
392 }
393
394 // Avoid PHP 7.1 warning from passing $this by reference
395 $writer = $this;
396 $text = '';
397 if ( $contentMode === self::WRITE_CONTENT ) {
398 /** @var Content $content */
399 $content = $this->invokeLenient(
400 $rev,
401 'getContent',
402 [ SlotRecord::MAIN, RevisionRecord::RAW ],
403 'Failed to load main slot content of revision ' . $rev->getId()
404 );
405
406 $text = $content ? $content->serialize() : '';
407 }
408 Hooks::run( 'XmlDumpWriterWriteRevision', [ &$writer, &$out, $row, $text, $rev ] );
409
410 $out .= " </revision>\n";
411
412 return $out;
413 }
414
415 /**
416 * @param SlotRecord $slot
417 * @param int $contentMode see the WRITE_XXX constants
418 *
419 * @return string
420 */
421 private function writeSlot( SlotRecord $slot, $contentMode ) {
422 $isMain = $slot->getRole() === SlotRecord::MAIN;
423 $isV11 = $this->schemaVersion >= XML_DUMP_SCHEMA_VERSION_11;
424
425 if ( !$isV11 && !$isMain ) {
426 // ignore extra slots
427 return '';
428 }
429
430 $out = '';
431 $indent = ' ';
432
433 if ( !$isMain ) {
434 // non-main slots are wrapped into an additional element.
435 $out .= ' ' . Xml::openElement( 'content' ) . "\n";
436 $indent .= ' ';
437 $out .= $indent . Xml::element( 'role', null, strval( $slot->getRole() ) ) . "\n";
438 }
439
440 if ( $isV11 ) {
441 $out .= $indent . Xml::element( 'origin', null, strval( $slot->getOrigin() ) ) . "\n";
442 }
443
444 $contentModel = $slot->getModel();
445 $contentHandler = ContentHandler::getForModelID( $contentModel );
446 $contentFormat = $contentHandler->getDefaultFormat();
447
448 // XXX: The content format is only relevant when actually outputting serialized content.
449 // It should probably be an attribute on the text tag.
450 $out .= $indent . Xml::element( 'model', null, strval( $contentModel ) ) . "\n";
451 $out .= $indent . Xml::element( 'format', null, strval( $contentFormat ) ) . "\n";
452
453 $textAttributes = [
454 'xml:space' => 'preserve',
455 'bytes' => $this->invokeLenient(
456 $slot,
457 'getSize',
458 [],
459 'failed to determine size for slot ' . $slot->getRole() . ' of revision '
460 . $slot->getRevision()
461 ) ?: '0'
462 ];
463
464 if ( $isV11 ) {
465 $textAttributes['sha1'] = $this->invokeLenient(
466 $slot,
467 'getSha1',
468 [],
469 'failed to determine sha1 for slot ' . $slot->getRole() . ' of revision '
470 . $slot->getRevision()
471 ) ?: '';
472 }
473
474 if ( $contentMode === self::WRITE_CONTENT ) {
475 $content = $this->invokeLenient(
476 $slot,
477 'getContent',
478 [],
479 'failed to load content for slot ' . $slot->getRole() . ' of revision '
480 . $slot->getRevision()
481 );
482
483 if ( $content === null ) {
484 $out .= $indent . Xml::element( 'text', $textAttributes ) . "\n";
485 } else {
486 $out .= $this->writeText( $content, $textAttributes, $indent );
487 }
488 } elseif ( $contentMode === self::WRITE_STUB_DELETED ) {
489 // write <text> placeholder tag
490 $textAttributes['deleted'] = 'deleted';
491 $out .= $indent . Xml::element( 'text', $textAttributes ) . "\n";
492 } else {
493 // write <text> stub tag
494 if ( $isV11 ) {
495 $textAttributes['location'] = $slot->getAddress();
496 }
497
498 // Output the numerical text ID if possible, for backwards compatibility.
499 // Note that this is currently the ONLY reason we have a BlobStore here at all.
500 // When removing this line, check whether the BlobStore has become unused.
501 try {
502 // NOTE: this will only work for addresses of the form "tt:12345".
503 // If we want to support other kinds of addresses in the future,
504 // we will have to silently ignore failures here.
505 // For now, this fails for "tt:0", which is present in the WMF production
506 // database of of Juli 2019, due to data corruption.
507 $textId = $this->getBlobStore()->getTextIdFromAddress( $slot->getAddress() );
508 } catch ( InvalidArgumentException $ex ) {
509 MWDebug::warning( 'Bad content address for slot ' . $slot->getRole()
510 . ' of revision ' . $slot->getRevision() . ': ' . $ex->getMessage() );
511 $textId = 0;
512 }
513
514 if ( $textId ) {
515 $textAttributes['id'] = $textId;
516 }
517
518 $out .= $indent . Xml::element( 'text', $textAttributes ) . "\n";
519 }
520
521 if ( !$isMain ) {
522 $out .= ' ' . Xml::closeElement( 'content' ) . "\n";
523 }
524
525 return $out;
526 }
527
528 /**
529 * @param Content $content
530 * @param string[] $textAttributes
531 * @param string $indent
532 *
533 * @return string
534 */
535 private function writeText( Content $content, $textAttributes, $indent ) {
536 $out = '';
537
538 $contentHandler = $content->getContentHandler();
539 $contentFormat = $contentHandler->getDefaultFormat();
540
541 if ( $content instanceof TextContent ) {
542 // HACK: For text based models, bypass the serialization step. This allows extensions (like Flow)
543 // that use incompatible combinations of serialization format and content model.
544 $data = $content->getNativeData();
545 } else {
546 $data = $content->serialize( $contentFormat );
547 }
548
549 $data = $contentHandler->exportTransform( $data, $contentFormat );
550 $textAttributes['bytes'] = $size = strlen( $data ); // make sure to use the actual size
551 $out .= $indent . Xml::elementClean( 'text', $textAttributes, strval( $data ) ) . "\n";
552
553 return $out;
554 }
555
556 /**
557 * Dumps a "<logitem>" section on the output stream, with
558 * data filled in from the given database row.
559 *
560 * @param object $row
561 * @return string
562 * @private
563 */
564 function writeLogItem( $row ) {
565 $out = " <logitem>\n";
566 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
567
568 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
569
570 if ( $row->log_deleted & LogPage::DELETED_USER ) {
571 $out .= " " . Xml::element( 'contributor', [ 'deleted' => 'deleted' ] ) . "\n";
572 } else {
573 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
574 }
575
576 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
577 $out .= " " . Xml::element( 'comment', [ 'deleted' => 'deleted' ] ) . "\n";
578 } else {
579 $comment = CommentStore::getStore()->getComment( 'log_comment', $row )->text;
580 if ( $comment != '' ) {
581 $out .= " " . Xml::elementClean( 'comment', null, strval( $comment ) ) . "\n";
582 }
583 }
584
585 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
586 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
587
588 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
589 $out .= " " . Xml::element( 'text', [ 'deleted' => 'deleted' ] ) . "\n";
590 } else {
591 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
592 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
593 $out .= " " . Xml::elementClean( 'params',
594 [ 'xml:space' => 'preserve' ],
595 strval( $row->log_params ) ) . "\n";
596 }
597
598 $out .= " </logitem>\n";
599
600 return $out;
601 }
602
603 /**
604 * @param string $timestamp
605 * @param string $indent Default to six spaces
606 * @return string
607 */
608 function writeTimestamp( $timestamp, $indent = " " ) {
609 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
610 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
611 }
612
613 /**
614 * @param int $id
615 * @param string $text
616 * @param string $indent Default to six spaces
617 * @return string
618 */
619 function writeContributor( $id, $text, $indent = " " ) {
620 $out = $indent . "<contributor>\n";
621 if ( $id || !IP::isValid( $text ) ) {
622 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
623 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
624 } else {
625 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
626 }
627 $out .= $indent . "</contributor>\n";
628 return $out;
629 }
630
631 /**
632 * Warning! This data is potentially inconsistent. :(
633 * @param object $row
634 * @param bool $dumpContents
635 * @return string
636 */
637 function writeUploads( $row, $dumpContents = false ) {
638 if ( $row->page_namespace == NS_FILE ) {
639 $img = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
640 ->newFile( $row->page_title );
641 if ( $img && $img->exists() ) {
642 $out = '';
643 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
644 $out .= $this->writeUpload( $ver, $dumpContents );
645 }
646 $out .= $this->writeUpload( $img, $dumpContents );
647 return $out;
648 }
649 }
650 return '';
651 }
652
653 /**
654 * @param File $file
655 * @param bool $dumpContents
656 * @return string
657 */
658 function writeUpload( $file, $dumpContents = false ) {
659 if ( $file->isOld() ) {
660 $archiveName = " " .
661 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
662 } else {
663 $archiveName = '';
664 }
665 if ( $dumpContents ) {
666 $be = $file->getRepo()->getBackend();
667 # Dump file as base64
668 # Uses only XML-safe characters, so does not need escaping
669 # @todo Too bad this loads the contents into memory (script might swap)
670 $contents = ' <contents encoding="base64">' .
671 chunk_split( base64_encode(
672 $be->getFileContents( [ 'src' => $file->getPath() ] ) ) ) .
673 " </contents>\n";
674 } else {
675 $contents = '';
676 }
677 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
678 $comment = Xml::element( 'comment', [ 'deleted' => 'deleted' ] );
679 } else {
680 $comment = Xml::elementClean( 'comment', null, strval( $file->getDescription() ) );
681 }
682 return " <upload>\n" .
683 $this->writeTimestamp( $file->getTimestamp() ) .
684 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
685 " " . $comment . "\n" .
686 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
687 $archiveName .
688 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
689 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
690 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
691 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
692 $contents .
693 " </upload>\n";
694 }
695
696 /**
697 * Return prefixed text form of title, but using the content language's
698 * canonical namespace. This skips any special-casing such as gendered
699 * user namespaces -- which while useful, are not yet listed in the
700 * XML "<siteinfo>" data so are unsafe in export.
701 *
702 * @param Title $title
703 * @return string
704 * @since 1.18
705 */
706 public static function canonicalTitle( Title $title ) {
707 if ( $title->isExternal() ) {
708 return $title->getPrefixedText();
709 }
710
711 $prefix = MediaWikiServices::getInstance()->getContentLanguage()->
712 getFormattedNsText( $title->getNamespace() );
713
714 // @todo Emit some kind of warning to the user if $title->getNamespace() !==
715 // NS_MAIN and $prefix === '' (viz. pages in an unregistered namespace)
716
717 if ( $prefix !== '' ) {
718 $prefix .= ':';
719 }
720
721 return $prefix . $title->getText();
722 }
723 }