Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / title / Title.php
blob15b60f7e8b3051c3bf44b838acc424ef7b8d2189
1 <?php
2 /**
3 * Representation of a title within MediaWiki.
5 * See Title.md
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @file
25 namespace MediaWiki\Title;
27 use HTMLCacheUpdateJob;
28 use InvalidArgumentException;
29 use MapCacheLRU;
30 use MediaWiki\Cache\LinkCache;
31 use MediaWiki\Context\RequestContext;
32 use MediaWiki\DAO\WikiAwareEntityTrait;
33 use MediaWiki\Deferred\AutoCommitUpdate;
34 use MediaWiki\Deferred\DeferredUpdates;
35 use MediaWiki\HookContainer\HookRunner;
36 use MediaWiki\Html\Html;
37 use MediaWiki\Interwiki\InterwikiLookup;
38 use MediaWiki\Language\ILanguageConverter;
39 use MediaWiki\Language\Language;
40 use MediaWiki\Linker\LinkTarget;
41 use MediaWiki\MainConfigNames;
42 use MediaWiki\MediaWikiServices;
43 use MediaWiki\Message\Message;
44 use MediaWiki\Page\ExistingPageRecord;
45 use MediaWiki\Page\PageIdentity;
46 use MediaWiki\Page\PageIdentityValue;
47 use MediaWiki\Page\PageReference;
48 use MediaWiki\Page\PageStoreRecord;
49 use MediaWiki\Page\ProperPageIdentity;
50 use MediaWiki\Parser\Sanitizer;
51 use MediaWiki\Request\PathRouter;
52 use MediaWiki\ResourceLoader\WikiModule;
53 use MediaWiki\SpecialPage\SpecialPage;
54 use MediaWiki\Utils\MWTimestamp;
55 use MessageLocalizer;
56 use MWException;
57 use RuntimeException;
58 use stdClass;
59 use Stringable;
60 use Wikimedia\Assert\Assert;
61 use Wikimedia\Assert\PreconditionException;
62 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
63 use Wikimedia\Parsoid\Core\LinkTargetTrait;
64 use Wikimedia\Rdbms\DBAccessObjectUtils;
65 use Wikimedia\Rdbms\IConnectionProvider;
66 use Wikimedia\Rdbms\IDatabase;
67 use Wikimedia\Rdbms\IDBAccessObject;
68 use WikiPage;
70 /**
71 * Represents a title within MediaWiki.
72 * Optionally may contain an interwiki designation or namespace.
73 * @note This class can fetch various kinds of data from the database;
74 * however, it does so inefficiently.
75 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
76 * and does not rely on global state or the database.
78 class Title implements Stringable, LinkTarget, PageIdentity {
79 use WikiAwareEntityTrait;
80 use LinkTargetTrait;
82 /** @var MapCacheLRU|null */
83 private static $titleCache = null;
85 /**
86 * Title::newFromText maintains a cache to avoid expensive re-normalization of
87 * commonly used titles. On a batch operation this can become a memory leak
88 * if not bounded.
90 private const CACHE_MAX = 1000;
92 /**
93 * Flag for use with factory methods like newFromLinkTarget() that have
94 * a $forceClone parameter. If set, the method must return a new instance.
95 * Without this flag, some factory methods may return existing instances.as
97 * @since 1.33
99 public const NEW_CLONE = 'clone';
101 /** @var string Text form (spaces not underscores) of the main part */
102 private $mTextform = '';
104 /** @var string URL-encoded form of the main part */
105 private $mUrlform = '';
107 /** @var string Main part with underscores */
108 private $mDbkeyform = '';
110 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
111 private $mNamespace = NS_MAIN;
113 /** @var string Interwiki prefix */
114 private $mInterwiki = '';
116 /** @var bool Was this Title created from a string with a local interwiki prefix? */
117 private $mLocalInterwiki = false;
119 /** @var string Title fragment (i.e. the bit after the #) */
120 private $mFragment = '';
122 /***************************************************************************/
123 // region Private member variables
124 /** @name Private member variables
125 * Please use the accessor functions instead.
126 * @internal
127 * @{
130 /** @var int Article ID, fetched from the link cache on demand */
131 public $mArticleID = -1;
133 /** @var int|false ID of most recent revision */
134 protected $mLatestID = false;
137 * @var string|false ID of the page's content model, i.e. one of the
138 * CONTENT_MODEL_XXX constants
140 private $mContentModel = false;
143 * @var bool If a content model was forced via setContentModel()
144 * this will be true to avoid having other code paths reset it
146 private $mForcedContentModel = false;
148 /** @var int|null Estimated number of revisions; null of not loaded */
149 private $mEstimateRevisions;
152 * Text form including namespace/interwiki, initialised on demand
154 * Only public to share cache with TitleFormatter
156 * @internal
157 * @var string|null
159 public $prefixedText = null;
162 * Namespace to assume when no namespace was passed to factory methods.
163 * This must be NS_MAIN, as it's hardcoded in several places. See T2696.
164 * Used primarily for {{transclusion}} tags.
166 private const DEFAULT_NAMESPACE = NS_MAIN;
168 /** @var int The page length, 0 for special pages */
169 protected $mLength = -1;
171 /** @var null|bool Is the article at this title a redirect? */
172 public $mRedirect = null;
174 /** @var bool Whether a page has any subpages */
175 private $mHasSubpages;
177 /** @var array|null The (string) language code of the page's language and content code. */
178 private $mPageLanguage;
180 /** @var string|false|null The page language code from the database, null if not saved in
181 * the database or false if not loaded, yet.
183 private $mDbPageLanguage = false;
185 /** @var TitleValue|null */
186 private $mTitleValue = null;
188 /** @var bool|null Would deleting this page be a big deletion? */
189 private $mIsBigDeletion = null;
191 /** @var bool|null Is the title known to be valid? */
192 private $mIsValid = null;
194 /** @var string|null The key of this instance in the internal Title instance cache */
195 private $mInstanceCacheKey = null;
197 // endregion -- end of private member variables
198 /** @} */
199 /***************************************************************************/
202 * Shorthand for getting a Language Converter for specific language
203 * @param Language $language Language of converter
204 * @return ILanguageConverter
206 private function getLanguageConverter( $language ): ILanguageConverter {
207 return MediaWikiServices::getInstance()->getLanguageConverterFactory()
208 ->getLanguageConverter( $language );
212 * Shorthand for getting a Language Converter for page's language
213 * @return ILanguageConverter
215 private function getPageLanguageConverter(): ILanguageConverter {
216 return $this->getLanguageConverter( $this->getPageLanguage() );
220 * Shorthand for getting a database connection provider
221 * @return IConnectionProvider
223 private function getDbProvider(): IConnectionProvider {
224 return MediaWikiServices::getInstance()->getConnectionProvider();
228 * B/C kludge: provide a TitleParser for use by Title.
229 * Ideally, Title would have no methods that need this.
230 * Avoid usage of this singleton by using TitleValue
231 * and the associated services when possible.
233 * @return TitleFormatter
235 private static function getTitleFormatter() {
236 return MediaWikiServices::getInstance()->getTitleFormatter();
240 * B/C kludge: provide an InterwikiLookup for use by Title.
241 * Ideally, Title would have no methods that need this.
242 * Avoid usage of this singleton by using TitleValue
243 * and the associated services when possible.
245 * @return InterwikiLookup
247 private static function getInterwikiLookup() {
248 return MediaWikiServices::getInstance()->getInterwikiLookup();
251 private function __construct() {
255 * Create a new Title from a prefixed DB key
257 * @param string $key The database key, which has underscores
258 * instead of spaces, possibly including namespace and
259 * interwiki prefixes
260 * @return Title|null Title, or null on an error
262 public static function newFromDBkey( $key ) {
263 $t = new self();
265 try {
266 $t->secureAndSplit( $key );
267 return $t;
268 } catch ( MalformedTitleException $ex ) {
269 return null;
274 * Returns a Title given a LinkTarget.
275 * If the given LinkTarget is already a Title instance, that instance is returned,
276 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
277 * is already a Title instance, that instance is copied using the clone operator.
279 * @since 1.27
280 * @param ParsoidLinkTarget $linkTarget Assumed to be safe.
281 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
282 * @return Title
284 public static function newFromLinkTarget( ParsoidLinkTarget $linkTarget, $forceClone = '' ) {
285 if ( $linkTarget instanceof Title ) {
286 // Special case if it's already a Title object
287 if ( $forceClone === self::NEW_CLONE ) {
288 return clone $linkTarget;
289 } else {
290 return $linkTarget;
293 return self::makeTitle(
294 $linkTarget->getNamespace(),
295 $linkTarget->getText(),
296 $linkTarget->getFragment(),
297 $linkTarget->getInterwiki()
302 * Same as newFromLinkTarget(), but if passed null, returns null.
304 * @since 1.34
305 * @param ParsoidLinkTarget|null $linkTarget Assumed to be safe (if not null).
306 * @return Title|null
308 public static function castFromLinkTarget( ?ParsoidLinkTarget $linkTarget ) {
309 if ( !$linkTarget ) {
310 return null;
312 return self::newFromLinkTarget( $linkTarget );
316 * Return a Title for a given PageIdentity. If $pageIdentity is a Title,
317 * that Title is returned unchanged.
319 * @since 1.41
320 * @param PageIdentity $pageIdentity
321 * @return Title
323 public static function newFromPageIdentity( PageIdentity $pageIdentity ): Title {
324 return self::newFromPageReference( $pageIdentity );
328 * Same as newFromPageIdentity(), but if passed null, returns null.
330 * @since 1.36
331 * @param PageIdentity|null $pageIdentity
332 * @return Title|null
334 public static function castFromPageIdentity( ?PageIdentity $pageIdentity ): ?Title {
335 return self::castFromPageReference( $pageIdentity );
339 * Return a Title for a given Reference. If $pageReference is a Title,
340 * that Title is returned unchanged.
342 * @since 1.41
343 * @param PageReference $pageReference
344 * @return Title
346 public static function newFromPageReference( PageReference $pageReference ): Title {
347 if ( $pageReference instanceof Title ) {
348 return $pageReference;
351 $pageReference->assertWiki( self::LOCAL );
352 $title = self::makeTitle( $pageReference->getNamespace(), $pageReference->getDBkey() );
354 if ( $pageReference instanceof PageIdentity ) {
355 $title->mArticleID = $pageReference->getId();
357 return $title;
361 * Same as newFromPageReference(), but if passed null, returns null.
363 * @since 1.37
364 * @param PageReference|null $pageReference
365 * @return Title|null
367 public static function castFromPageReference( ?PageReference $pageReference ): ?Title {
368 if ( !$pageReference ) {
369 return null;
371 return self::newFromPageReference( $pageReference );
375 * Create a new Title from text, such as what one would find in a link.
376 * Decodes any HTML entities in the text.
377 * Titles returned by this method are guaranteed to be valid.
378 * Call canExist() to check if the Title represents an editable page.
380 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
381 * It may instead be a cached instance created previously, with references to it remaining
382 * elsewhere.
384 * @param string|int|null $text The link text; spaces, prefixes, and an
385 * initial ':' indicating the main namespace are accepted.
386 * @param int $defaultNamespace The namespace to use if none is specified
387 * by a prefix. If you want to force a specific namespace even if
388 * $text might begin with a namespace prefix, use makeTitle() or
389 * makeTitleSafe().
390 * @return Title|null Title or null if the Title could not be parsed because
391 * it is invalid.
393 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
394 // DWIM: Integers can be passed in here when page titles are used as array keys.
395 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
396 throw new InvalidArgumentException( '$text must be a string.' );
398 if ( $text === null || $text === '' ) {
399 return null;
402 try {
403 return self::newFromTextThrow( (string)$text, (int)$defaultNamespace );
404 } catch ( MalformedTitleException $ex ) {
405 return null;
410 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
411 * rather than returning null.
413 * Titles returned by this method are guaranteed to be valid.
414 * Call canExist() to check if the Title represents an editable page.
416 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
417 * It may instead be a cached instance created previously, with references to it remaining
418 * elsewhere.
420 * @see Title::newFromText
422 * @since 1.25
423 * @param string $text Title text to check
424 * @param int $defaultNamespace
425 * @throws MalformedTitleException If the title is invalid.
426 * @return Title
428 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
429 if ( is_object( $text ) ) {
430 throw new InvalidArgumentException( '$text must be a string, given an object' );
431 } elseif ( $text === null ) {
432 // Legacy code relies on MalformedTitleException being thrown in this case
433 // TODO: fix(happens when URL with no title in it is parsed).
434 throw new MalformedTitleException( 'title-invalid-empty' );
437 $titleCache = self::getTitleCache();
439 // Wiki pages often contain multiple links to the same page.
440 // Title normalization and parsing can become expensive on pages with many
441 // links, so we can save a little time by caching them.
442 if ( $defaultNamespace === NS_MAIN ) {
443 $t = $titleCache->get( $text );
444 if ( $t ) {
445 return $t;
449 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
450 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
452 $t = new Title();
453 $dbKeyForm = strtr( $filteredText, ' ', '_' );
455 $t->secureAndSplit( $dbKeyForm, (int)$defaultNamespace );
456 if ( $defaultNamespace === NS_MAIN ) {
457 $t->mInstanceCacheKey = $text;
458 $titleCache->set( $text, $t );
460 return $t;
464 * Removes this instance from the internal title cache, so it can be modified in-place
465 * without polluting the cache (see T281337).
467 private function uncache() {
468 if ( $this->mInstanceCacheKey !== null ) {
469 $titleCache = self::getTitleCache();
470 $titleCache->clear( $this->mInstanceCacheKey );
471 $this->mInstanceCacheKey = null;
476 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
478 * Example of wrong and broken code:
479 * $title = Title::newFromURL( $request->getText( 'title' ) );
481 * Example of right code:
482 * $title = Title::newFromText( $request->getText( 'title' ) );
484 * Create a new Title from URL-encoded text. Ensures that
485 * the given title's length does not exceed the maximum.
487 * @param string $url The title, as might be taken from a URL
488 * @return Title|null The new object, or null on an error
490 public static function newFromURL( $url ) {
491 $t = new Title();
493 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
494 # but some URLs used it as a space replacement and they still come
495 # from some external search tools.
496 if ( !str_contains( self::legalChars(), '+' ) ) {
497 $url = strtr( $url, '+', ' ' );
500 $dbKeyForm = strtr( $url, ' ', '_' );
502 try {
503 $t->secureAndSplit( $dbKeyForm );
504 return $t;
505 } catch ( MalformedTitleException $ex ) {
506 return null;
511 * @return MapCacheLRU
513 private static function getTitleCache() {
514 if ( self::$titleCache === null ) {
515 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
517 return self::$titleCache;
521 * Create a new Title from an article ID
523 * @param int $id The page_id corresponding to the Title to create
524 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
525 * @return Title|null The new object, or null on an error
527 public static function newFromID( $id, $flags = 0 ) {
528 $pageStore = MediaWikiServices::getInstance()->getPageStore();
529 $dbr = DBAccessObjectUtils::getDBFromRecency(
530 MediaWikiServices::getInstance()->getConnectionProvider(),
531 $flags
533 $row = $dbr->newSelectQueryBuilder()
534 ->select( $pageStore->getSelectFields() )
535 ->from( 'page' )
536 ->where( [ 'page_id' => $id ] )
537 ->recency( $flags )
538 ->caller( __METHOD__ )->fetchRow();
539 if ( $row !== false ) {
540 $title = self::newFromRow( $row );
541 } else {
542 $title = null;
545 return $title;
549 * Make a Title object from a DB row
551 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
552 * @return Title
554 public static function newFromRow( $row ) {
555 $t = self::makeTitle( $row->page_namespace, $row->page_title );
556 $t->loadFromRow( $row );
557 return $t;
561 * Load Title object fields from a DB row.
562 * If false is given, the title will be treated as non-existing.
564 * @param stdClass|false $row Database row
566 public function loadFromRow( $row ) {
567 if ( $row ) { // page found
568 if ( isset( $row->page_id ) ) {
569 $this->mArticleID = (int)$row->page_id;
571 if ( isset( $row->page_len ) ) {
572 $this->mLength = (int)$row->page_len;
574 if ( isset( $row->page_is_redirect ) ) {
575 $this->mRedirect = (bool)$row->page_is_redirect;
577 if ( isset( $row->page_latest ) ) {
578 $this->mLatestID = (int)$row->page_latest;
580 if ( isset( $row->page_content_model ) ) {
581 $this->lazyFillContentModel( $row->page_content_model );
582 } else {
583 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
585 if ( isset( $row->page_lang ) ) {
586 $this->mDbPageLanguage = (string)$row->page_lang;
588 } else { // page not found
589 $this->mArticleID = 0;
590 $this->mLength = 0;
591 $this->mRedirect = false;
592 $this->mLatestID = 0;
593 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
598 * Create a new Title from a namespace index and a DB key.
600 * It's assumed that $ns and $title are safe, for instance when
601 * they came directly from the database or a special page name,
602 * not from user input.
604 * No validation is applied. For convenience, spaces are normalized
605 * to underscores, so that e.g. user_text fields can be used directly.
607 * @note This method may return Title objects that are "invalid"
608 * according to the isValid() method. This is usually caused by
609 * configuration changes: e.g. a namespace that was once defined is
610 * no longer configured, or a character that was once allowed in
611 * titles is now forbidden.
613 * @param int $ns The namespace of the article
614 * @param string $title The unprefixed database key form
615 * @param string $fragment The link fragment (after the "#")
616 * @param string $interwiki The interwiki prefix
617 * @return Title The new object
619 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
620 $t = new Title();
621 $t->mInterwiki = $interwiki;
622 $t->mFragment = self::normalizeFragment( $fragment );
623 $t->mNamespace = $ns = (int)$ns;
624 $t->mDbkeyform = strtr( $title, ' ', '_' );
625 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
626 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
627 $t->mTextform = strtr( $title, '_', ' ' );
628 return $t;
632 * Create a new Title from a namespace index and a DB key.
633 * The parameters will be checked for validity, which is a bit slower
634 * than makeTitle() but safer for user-provided data.
636 * The Title object returned by this method is guaranteed to be valid.
637 * Call canExist() to check if the Title represents an editable page.
639 * @param int $ns The namespace of the article
640 * @param string $title Database key form
641 * @param string $fragment The link fragment (after the "#")
642 * @param string $interwiki Interwiki prefix
643 * @return Title|null The new object, or null on an error
645 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
646 // NOTE: ideally, this would just call makeTitle() and then isValid(),
647 // but presently, that means more overhead on a potential performance hotspot.
649 if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
650 return null;
653 $t = new Title();
654 $dbKeyForm = self::makeName( $ns, $title, $fragment, $interwiki, true );
656 try {
657 $t->secureAndSplit( $dbKeyForm );
658 return $t;
659 } catch ( MalformedTitleException $ex ) {
660 return null;
665 * Create a new Title for the Main Page
667 * This uses the 'mainpage' interface message, which could be specified in
668 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
669 * will use the user language, which would involve initialising the session
670 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
671 * be sure to pass in a MessageLocalizer (such as your own RequestContext or
672 * ResourceLoader Context) to prevent an error.
674 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
675 * It may instead be a cached instance created previously, with references to it remaining
676 * elsewhere.
678 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
679 * @return Title
681 public static function newMainPage( ?MessageLocalizer $localizer = null ) {
682 static $recursionGuard = false;
684 $title = null;
686 if ( !$recursionGuard ) {
687 $msg = $localizer ? $localizer->msg( 'mainpage' ) : wfMessage( 'mainpage' );
689 $recursionGuard = true;
690 $title = self::newFromText( $msg->inContentLanguage()->text() );
691 $recursionGuard = false;
694 // Every page renders at least one link to the Main Page (e.g. sidebar).
695 // Don't produce fatal errors that would make the wiki inaccessible, and hard to fix the
696 // invalid message.
698 // Fallback scenarios:
699 // * Recursion guard
700 // If the message contains a bare local interwiki (T297571), then
701 // Title::newFromText via MediaWikiTitleCodec::splitTitleString can get back here.
702 // * Invalid title
703 // If the 'mainpage' message contains something that is invalid, Title::newFromText
704 // will return null.
706 return $title ?? self::makeTitle( NS_MAIN, 'Main Page' );
710 * Get a regex character class describing the legal characters in a link
712 * @return string The list of characters, not delimited
714 public static function legalChars() {
715 global $wgLegalTitleChars;
716 return $wgLegalTitleChars;
720 * Utility method for converting a character sequence from bytes to Unicode.
722 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
723 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
725 * @param string $byteClass
726 * @return string
728 public static function convertByteClassToUnicodeClass( $byteClass ) {
729 $length = strlen( $byteClass );
730 // Input token queue
731 $x0 = $x1 = $x2 = '';
732 // Decoded queue
733 $d0 = $d1 = '';
734 // Decoded integer codepoints
735 $ord0 = $ord1 = $ord2 = 0;
736 // Re-encoded queue
737 $r0 = $r1 = $r2 = '';
738 // Output
739 $out = '';
740 // Flags
741 $allowUnicode = false;
742 for ( $pos = 0; $pos < $length; $pos++ ) {
743 // Shift the queues down
744 $x2 = $x1;
745 $x1 = $x0;
746 $d1 = $d0;
747 $ord2 = $ord1;
748 $ord1 = $ord0;
749 $r2 = $r1;
750 $r1 = $r0;
751 // Load the current input token and decoded values
752 $inChar = $byteClass[$pos];
753 if ( $inChar === '\\' ) {
754 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
755 $x0 = $inChar . $m[0];
756 $d0 = chr( hexdec( $m[1] ) );
757 $pos += strlen( $m[0] );
758 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
759 $x0 = $inChar . $m[0];
760 $d0 = chr( octdec( $m[0] ) );
761 $pos += strlen( $m[0] );
762 } elseif ( $pos + 1 >= $length ) {
763 $x0 = $d0 = '\\';
764 } else {
765 $d0 = $byteClass[$pos + 1];
766 $x0 = $inChar . $d0;
767 $pos++;
769 } else {
770 $x0 = $d0 = $inChar;
772 $ord0 = ord( $d0 );
773 // Load the current re-encoded value
774 if ( $ord0 < 32 || $ord0 == 0x7f ) {
775 $r0 = sprintf( '\x%02x', $ord0 );
776 } elseif ( $ord0 >= 0x80 ) {
777 // Allow unicode if a single high-bit character appears
778 $r0 = sprintf( '\x%02x', $ord0 );
779 $allowUnicode = true;
780 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
781 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
782 $r0 = '\\' . $d0;
783 } else {
784 $r0 = $d0;
786 // Do the output
787 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
788 // Range
789 if ( $ord2 > $ord0 ) {
790 // Empty range
791 } elseif ( $ord0 >= 0x80 ) {
792 // Unicode range
793 $allowUnicode = true;
794 if ( $ord2 < 0x80 ) {
795 // Keep the non-unicode section of the range
796 $out .= "$r2-\\x7F";
798 } else {
799 // Normal range
800 $out .= "$r2-$r0";
802 // Reset state to the initial value
803 // @phan-suppress-next-line PhanPluginRedundantAssignmentInLoop
804 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
805 } elseif ( $ord2 < 0x80 ) {
806 // ASCII character
807 $out .= $r2;
810 // @phan-suppress-next-line PhanSuspiciousValueComparison
811 if ( $ord1 < 0x80 ) {
812 $out .= $r1;
814 if ( $ord0 < 0x80 ) {
815 $out .= $r0;
817 if ( $allowUnicode ) {
818 $out .= '\u0080-\uFFFF';
820 return $out;
824 * Make a prefixed DB key from a DB key and a namespace index
826 * @param int $ns Numerical representation of the namespace
827 * @param string $title The DB key form the title
828 * @param string $fragment The link fragment (after the "#")
829 * @param string $interwiki The interwiki prefix
830 * @param bool $canonicalNamespace If true, use the canonical name for
831 * $ns instead of the localized version.
832 * @return string The prefixed form of the title
834 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
835 $canonicalNamespace = false
837 if ( $canonicalNamespace ) {
838 $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
839 getCanonicalName( $ns );
840 } else {
841 $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
843 if ( $namespace === false ) {
844 // See T165149. Awkward, but better than erroneously linking to the main namespace.
845 $namespace = self::makeName( NS_SPECIAL, "Badtitle/NS$ns", '', '', $canonicalNamespace );
847 $name = $namespace === '' ? $title : "$namespace:$title";
848 if ( strval( $interwiki ) != '' ) {
849 $name = "$interwiki:$name";
851 if ( strval( $fragment ) != '' ) {
852 $name .= '#' . $fragment;
854 return $name;
858 * Callback for usort() to do title sorts by (namespace, title)
860 * @param LinkTarget|PageReference $a
861 * @param LinkTarget|PageReference $b
863 * @return int Result of string comparison, or namespace comparison
865 public static function compare( $a, $b ) {
866 return $a->getNamespace() <=> $b->getNamespace()
867 ?: strcmp( $a->getDBkey(), $b->getDBkey() );
871 * Returns true if the title is a valid link target, and that it has been
872 * properly normalized. This method checks that the title is syntactically valid,
873 * and that the namespace it refers to exists.
875 * Titles constructed using newFromText() or makeTitleSafe() are always valid.
877 * @note Code that wants to check whether the title can represent a page that can
878 * be created and edited should use canExist() instead. Examples of valid titles
879 * that cannot "exist" are Special pages, interwiki links, and on-page section links
880 * that only have the fragment part set.
882 * @see canExist()
884 * @return bool
886 public function isValid() {
887 if ( $this->mIsValid !== null ) {
888 return $this->mIsValid;
891 try {
892 // Optimization: Avoid Title::getFullText because that involves GenderCache
893 // and (unbatched) database queries. For validation, canonical namespace suffices.
894 $text = self::makeName( $this->mNamespace, $this->mDbkeyform, $this->mFragment, $this->mInterwiki, true );
895 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
897 '@phan-var MediaWikiTitleCodec $titleCodec';
898 $parts = $titleCodec->splitTitleString( $text, $this->mNamespace );
900 // Check that nothing changed!
901 // This ensures that $text was already properly normalized.
902 if ( $parts['fragment'] !== $this->mFragment
903 || $parts['interwiki'] !== $this->mInterwiki
904 || $parts['local_interwiki'] !== $this->mLocalInterwiki
905 || $parts['namespace'] !== $this->mNamespace
906 || $parts['dbkey'] !== $this->mDbkeyform
908 $this->mIsValid = false;
909 return $this->mIsValid;
911 } catch ( MalformedTitleException $ex ) {
912 $this->mIsValid = false;
913 return $this->mIsValid;
916 $this->mIsValid = true;
917 return $this->mIsValid;
921 * Determine whether the object refers to a page within
922 * this project (either this wiki or a wiki with a local
923 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
925 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
927 public function isLocal() {
928 if ( $this->isExternal() ) {
929 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
930 if ( $iw ) {
931 return $iw->isLocal();
934 return true;
938 * Get the interwiki prefix
940 * Use Title::isExternal to check if a interwiki is set
942 * @return string Interwiki prefix
944 public function getInterwiki(): string {
945 return $this->mInterwiki;
949 * Was this a local interwiki link?
951 * @return bool
953 public function wasLocalInterwiki() {
954 return $this->mLocalInterwiki;
958 * Determine whether the object refers to a page within
959 * this project and is transcludable.
961 * @return bool True if this is transcludable
963 public function isTrans() {
964 if ( !$this->isExternal() ) {
965 return false;
968 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
972 * Returns the DB name of the distant wiki which owns the object.
974 * @return string|false The DB name
976 public function getTransWikiID() {
977 if ( !$this->isExternal() ) {
978 return false;
981 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
985 * Get a TitleValue object representing this Title.
987 * @note Not all valid Titles have a corresponding valid TitleValue
988 * (e.g. TitleValues cannot represent page-local links that have a
989 * fragment but no title text).
991 * @return TitleValue|null
993 public function getTitleValue() {
994 if ( $this->mTitleValue === null ) {
995 try {
996 $this->mTitleValue = new TitleValue(
997 $this->mNamespace,
998 $this->mDbkeyform,
999 $this->mFragment,
1000 $this->mInterwiki
1002 } catch ( InvalidArgumentException $ex ) {
1003 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
1004 $this->getPrefixedText() . ']]: ' . $ex->getMessage() );
1008 return $this->mTitleValue;
1012 * Get the text form (spaces not underscores) of the main part
1014 * @return string Main part of the title
1016 public function getText(): string {
1017 return $this->mTextform;
1021 * Get the URL-encoded form of the main part
1023 * @return string Main part of the title, URL-encoded
1025 public function getPartialURL() {
1026 return $this->mUrlform;
1030 * Get the main part with underscores
1032 * @return string Main part of the title, with underscores
1034 public function getDBkey(): string {
1035 return $this->mDbkeyform;
1039 * Get the namespace index, i.e. one of the NS_xxxx constants.
1041 * @return int Namespace index
1043 public function getNamespace(): int {
1044 return $this->mNamespace;
1048 * @param int $flags
1050 * @return bool Whether $flags indicates that the latest information should be
1051 * read from the primary database, bypassing caches.
1053 private function shouldReadLatest( int $flags ) {
1054 return ( $flags & ( IDBAccessObject::READ_LATEST ) ) > 0;
1058 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1060 * @todo Deprecate this in favor of SlotRecord::getModel()
1062 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
1063 * @return string Content model id
1065 public function getContentModel( $flags = 0 ) {
1066 if ( $this->mForcedContentModel ) {
1067 if ( !$this->mContentModel ) {
1068 throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
1070 // Content model is locked to the currently loaded one
1071 return $this->mContentModel;
1074 if ( $this->shouldReadLatest( $flags ) || !$this->mContentModel ) {
1075 $this->lazyFillContentModel( $this->getFieldFromPageStore( 'page_content_model', $flags ) );
1078 if ( !$this->mContentModel ) {
1079 $slotRoleregistry = MediaWikiServices::getInstance()->getSlotRoleRegistry();
1080 $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
1081 $this->lazyFillContentModel( $mainSlotHandler->getDefaultModel( $this ) );
1084 return $this->mContentModel;
1088 * Convenience method for checking a title's content model name
1090 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1091 * @return bool True if $this->getContentModel() == $id
1093 public function hasContentModel( $id ) {
1094 return $this->getContentModel() == $id;
1098 * Set a proposed content model for the page for permissions checking
1100 * This does not actually change the content model of a title in the DB.
1101 * It only affects this particular Title instance. The content model is
1102 * forced to remain this value until another setContentModel() call.
1104 * ContentHandler::canBeUsedOn() should be checked before calling this
1105 * if there is any doubt regarding the applicability of the content model
1107 * @warning This must only be used if the caller controls the further use of
1108 * this Title object, to avoid other code unexpectedly using the new value.
1110 * @since 1.28
1111 * @param string $model CONTENT_MODEL_XXX constant
1113 public function setContentModel( $model ) {
1114 if ( (string)$model === '' ) {
1115 throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
1118 $this->uncache();
1119 $this->mContentModel = $model;
1120 $this->mForcedContentModel = true;
1124 * If the content model field is not frozen then update it with a retrieved value
1126 * @param string|bool $model CONTENT_MODEL_XXX constant or false
1128 private function lazyFillContentModel( $model ) {
1129 if ( !$this->mForcedContentModel ) {
1130 $this->mContentModel = ( $model === false ) ? false : (string)$model;
1135 * Get the namespace text
1137 * @return string|false Namespace name with underscores (not spaces), e.g. 'User_talk'
1139 public function getNsText() {
1140 if ( $this->isExternal() ) {
1141 // This probably shouldn't even happen, except for interwiki transclusion.
1142 // If possible, use the canonical name for the foreign namespace.
1143 if ( $this->mNamespace === NS_MAIN ) {
1144 // Optimisation
1145 return '';
1146 } else {
1147 $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
1148 getCanonicalName( $this->mNamespace );
1149 if ( $nsText !== false ) {
1150 return $nsText;
1155 try {
1156 $formatter = self::getTitleFormatter();
1157 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1158 } catch ( InvalidArgumentException $ex ) {
1159 wfDebug( __METHOD__ . ': ' . $ex->getMessage() );
1160 return false;
1165 * Get the namespace text of the subject (rather than talk) page
1167 * @return string Namespace name with underscores (not spaces)
1169 public function getSubjectNsText() {
1170 $services = MediaWikiServices::getInstance();
1171 return $services->getContentLanguage()->
1172 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
1176 * Get the namespace text of the talk page
1178 * @return string Namespace name with underscores (not spaces)
1180 public function getTalkNsText() {
1181 $services = MediaWikiServices::getInstance();
1182 return $services->getContentLanguage()->
1183 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
1187 * Can this title have a corresponding talk page?
1189 * False for relative section links (with getText() === ''),
1190 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1192 * @see NamespaceInfo::canHaveTalkPage
1193 * @since 1.30
1195 * @return bool True if this title either is a talk page or can have a talk page associated.
1197 public function canHaveTalkPage() {
1198 return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1202 * Can this title represent a page in the wiki's database?
1204 * Titles can exist as pages in the database if they are valid, and they
1205 * are not Special pages, interwiki links, or fragment-only links.
1207 * @see isValid()
1209 * @return bool true if and only if this title can be used to perform an edit.
1211 public function canExist(): bool {
1212 // NOTE: Don't use getArticleID(), we don't want to
1213 // trigger a database query here. This check is supposed to
1214 // act as an optimization, not add extra cost.
1215 if ( $this->mArticleID > 0 ) {
1216 // It exists, so it can exist.
1217 return true;
1220 // NOTE: we call the relatively expensive isValid() method further down,
1221 // but we can bail out early if we already know the title is invalid.
1222 if ( $this->mIsValid === false ) {
1223 // It's invalid, so it can't exist.
1224 return false;
1227 if ( $this->getNamespace() < NS_MAIN ) {
1228 // It's a special page, so it can't exist in the database.
1229 return false;
1232 if ( $this->isExternal() ) {
1233 // If it's external, it's not local, so it can't exist.
1234 return false;
1237 if ( $this->getText() === '' ) {
1238 // The title has no text, so it can't exist in the database.
1239 // It's probably an on-page section link, like "#something".
1240 return false;
1243 // Double check that the title is valid.
1244 return $this->isValid();
1248 * Returns true if this is a special page.
1250 * @return bool
1252 public function isSpecialPage() {
1253 return $this->mNamespace === NS_SPECIAL;
1257 * Returns true if this title resolves to the named special page
1259 * @param string $name The special page name
1260 * @return bool
1262 public function isSpecial( $name ) {
1263 if ( $this->isSpecialPage() ) {
1264 [ $thisName, /* $subpage */ ] =
1265 MediaWikiServices::getInstance()->getSpecialPageFactory()->
1266 resolveAlias( $this->mDbkeyform );
1267 if ( $name == $thisName ) {
1268 return true;
1271 return false;
1275 * If the Title refers to a special page alias which is not the local default, resolve
1276 * the alias, and localise the name as necessary. Otherwise, return $this
1278 * @return Title
1280 public function fixSpecialName() {
1281 if ( $this->isSpecialPage() ) {
1282 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1283 [ $canonicalName, $par ] = $spFactory->resolveAlias( $this->mDbkeyform );
1284 if ( $canonicalName ) {
1285 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1286 if ( $localName != $this->mDbkeyform ) {
1287 return self::makeTitle( NS_SPECIAL, $localName );
1291 return $this;
1295 * Returns true if the title is inside the specified namespace.
1297 * @param int $ns The namespace
1298 * @return bool
1299 * @since 1.19
1301 public function inNamespace( int $ns ): bool {
1302 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1303 equals( $this->mNamespace, $ns );
1307 * Returns true if the title is inside one of the specified namespaces.
1309 * @param int|int[] ...$namespaces The namespaces to check for
1310 * @return bool
1311 * @since 1.19
1313 public function inNamespaces( ...$namespaces ) {
1314 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1315 $namespaces = $namespaces[0];
1318 foreach ( $namespaces as $ns ) {
1319 if ( $this->inNamespace( $ns ) ) {
1320 return true;
1324 return false;
1328 * Returns true if the title has the same subject namespace as the
1329 * namespace specified.
1330 * For example this method will take NS_USER and return true if namespace
1331 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1332 * as their subject namespace.
1334 * This is MUCH simpler than individually testing for equivalence
1335 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1336 * @since 1.19
1337 * @param int $ns
1338 * @return bool
1340 public function hasSubjectNamespace( $ns ) {
1341 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1342 subjectEquals( $this->mNamespace, $ns );
1346 * Is this Title in a namespace which contains content?
1347 * In other words, is this a content page, for the purposes of calculating
1348 * statistics, etc?
1350 * @return bool
1352 public function isContentPage() {
1353 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1354 isContent( $this->mNamespace );
1358 * Would anybody with sufficient privileges be able to move this page?
1359 * Some pages just aren't movable.
1361 * @return bool
1363 public function isMovable() {
1364 $services = MediaWikiServices::getInstance();
1365 if (
1366 !$services->getNamespaceInfo()->
1367 isMovable( $this->mNamespace ) || $this->isExternal()
1369 // Interwiki title or immovable namespace. Hooks don't get to override here
1370 return false;
1373 $result = true;
1374 ( new HookRunner( $services->getHookContainer() ) )->onTitleIsMovable( $this, $result );
1375 return $result;
1379 * Is this the mainpage?
1380 * @see T302186
1382 * @since 1.18
1383 * @return bool
1385 public function isMainPage() {
1386 /** @var Title|null */
1387 static $cachedMainPage;
1388 $cachedMainPage ??= self::newMainPage();
1389 return $this->equals( $cachedMainPage );
1393 * Is this a subpage?
1395 * @return bool
1397 public function isSubpage() {
1398 return MediaWikiServices::getInstance()
1399 ->getNamespaceInfo()
1400 ->hasSubpages( $this->mNamespace )
1401 && str_contains( $this->getText(), '/' );
1405 * Is this a conversion table for the LanguageConverter?
1407 * @return bool
1409 public function isConversionTable() {
1410 // @todo ConversionTable should become a separate content model.
1411 // @todo And the prefix should be localized, too!
1413 return $this->mNamespace === NS_MEDIAWIKI &&
1414 str_starts_with( $this->getText(), 'Conversiontable/' );
1418 * Does that page contain wikitext, or it is JS, CSS or whatever?
1420 * @return bool
1422 public function isWikitextPage() {
1423 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1427 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1428 * global UI. This is generally true for pages in the MediaWiki namespace having
1429 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1431 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1432 * for that!
1434 * Note that this method should not return true for pages that contain and show
1435 * "inactive" CSS, JSON, or JS.
1437 * @return bool
1438 * @since 1.31
1440 public function isSiteConfigPage() {
1441 return (
1442 $this->isSiteCssConfigPage()
1443 || $this->isSiteJsonConfigPage()
1444 || $this->isSiteJsConfigPage()
1449 * Is this a "config" (.css, .json, or .js) subpage of a user page?
1451 * @return bool
1452 * @since 1.31
1454 public function isUserConfigPage() {
1455 return (
1456 $this->isUserCssConfigPage()
1457 || $this->isUserJsonConfigPage()
1458 || $this->isUserJsConfigPage()
1463 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1465 * @return string Containing skin name from .css, .json, or .js subpage title
1466 * @since 1.31
1468 public function getSkinFromConfigSubpage() {
1469 $text = $this->getText();
1470 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
1471 if ( $lastSlashPos === false ) {
1472 return '';
1475 $lastDot = strrpos( $text, '.', $lastSlashPos );
1476 if ( $lastDot === false ) {
1477 return '';
1480 return substr( $text, $lastSlashPos + 1, $lastDot - $lastSlashPos - 1 );
1484 * Is this a CSS "config" subpage of a user page?
1486 * @return bool
1487 * @since 1.31
1489 public function isUserCssConfigPage() {
1490 return (
1491 $this->mNamespace === NS_USER
1492 && $this->isSubpage()
1493 && $this->hasContentModel( CONTENT_MODEL_CSS )
1498 * Is this a JSON "config" subpage of a user page?
1500 * @return bool
1501 * @since 1.31
1503 public function isUserJsonConfigPage() {
1504 return (
1505 $this->mNamespace === NS_USER
1506 && $this->isSubpage()
1507 && $this->hasContentModel( CONTENT_MODEL_JSON )
1512 * Is this a JS "config" subpage of a user page?
1514 * @return bool
1515 * @since 1.31
1517 public function isUserJsConfigPage() {
1518 return (
1519 $this->mNamespace === NS_USER
1520 && $this->isSubpage()
1521 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1526 * Is this a sitewide CSS "config" page?
1528 * @return bool
1529 * @since 1.32
1531 public function isSiteCssConfigPage() {
1532 return (
1533 $this->mNamespace === NS_MEDIAWIKI
1534 && (
1535 $this->hasContentModel( CONTENT_MODEL_CSS )
1536 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1537 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1538 || str_ends_with( $this->mDbkeyform, '.css' )
1544 * Is this a sitewide JSON "config" page?
1546 * @return bool
1547 * @since 1.32
1549 public function isSiteJsonConfigPage() {
1550 return (
1551 $this->mNamespace === NS_MEDIAWIKI
1552 && (
1553 $this->hasContentModel( CONTENT_MODEL_JSON )
1554 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1555 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1556 || str_ends_with( $this->mDbkeyform, '.json' )
1562 * Is this a sitewide JS "config" page?
1564 * @return bool
1565 * @since 1.31
1567 public function isSiteJsConfigPage() {
1568 return (
1569 $this->mNamespace === NS_MEDIAWIKI
1570 && (
1571 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1572 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1573 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1574 || str_ends_with( $this->mDbkeyform, '.js' )
1580 * Is this a message which can contain raw HTML?
1582 * @return bool
1583 * @since 1.32
1585 public function isRawHtmlMessage() {
1586 global $wgRawHtmlMessages;
1588 if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1589 return false;
1591 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1592 return in_array( $message, $wgRawHtmlMessages, true );
1596 * Is this a talk page of some sort?
1598 * @return bool
1600 public function isTalkPage() {
1601 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1602 isTalk( $this->mNamespace );
1606 * Get a Title object associated with the talk page of this article
1608 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1609 * with NamespaceInfo::canHaveTalkPage(). Note that the new method will
1610 * throw if asked for the talk page of a section-only link, or of an interwiki
1611 * link.
1612 * @return Title The object for the talk page
1613 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1614 * or because it's a relative link, or an interwiki link.
1616 public function getTalkPage() {
1617 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1618 // Instead of failing on invalid titles, let's just log the issue for now.
1619 // See the discussion on T227817.
1621 // Is this the same title?
1622 $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
1623 if ( $this->mNamespace == $talkNS ) {
1624 return $this;
1627 $title = self::makeTitle( $talkNS, $this->mDbkeyform );
1629 $this->warnIfPageCannotExist( $title, __METHOD__ );
1631 return $title;
1632 // TODO: replace the above with the code below:
1633 // return self::castFromLinkTarget(
1634 // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1638 * Get a Title object associated with the talk page of this article,
1639 * if such a talk page can exist.
1641 * @since 1.30
1643 * @return Title|null The object for the talk page,
1644 * or null if no associated talk page can exist, according to canHaveTalkPage().
1646 public function getTalkPageIfDefined() {
1647 if ( !$this->canHaveTalkPage() ) {
1648 return null;
1651 return $this->getTalkPage();
1655 * Get a title object associated with the subject page of this
1656 * talk page
1658 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1659 * @return Title The object for the subject page
1661 public function getSubjectPage() {
1662 // Is this the same title?
1663 $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
1664 ->getSubject( $this->mNamespace );
1665 if ( $this->mNamespace == $subjectNS ) {
1666 return $this;
1668 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1669 // Instead of failing on invalid titles, let's just log the issue for now.
1670 // See the discussion on T227817.
1671 $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
1673 $this->warnIfPageCannotExist( $title, __METHOD__ );
1675 return $title;
1676 // TODO: replace the above with the code below:
1677 // return self::castFromLinkTarget(
1678 // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1682 * @param Title $title
1683 * @param string $method
1685 * @return bool whether a warning was issued
1687 private function warnIfPageCannotExist( Title $title, $method ) {
1688 if ( $this->getText() == '' ) {
1689 wfLogWarning(
1690 $method . ': called on empty title ' . $this->getFullText() . ', returning '
1691 . $title->getFullText()
1694 return true;
1697 if ( $this->getInterwiki() !== '' ) {
1698 wfLogWarning(
1699 $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1700 . $title->getFullText()
1703 return true;
1706 return false;
1710 * Get the other title for this page, if this is a subject page
1711 * get the talk page, if it is a subject page get the talk page
1713 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1714 * @since 1.25
1715 * @throws MWException If the page doesn't have an other page
1716 * @return Title
1718 public function getOtherPage() {
1719 // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1720 // until their semantics has become exactly the same.
1721 // See the discussion on T227817.
1722 if ( $this->isSpecialPage() ) {
1723 throw new MWException( 'Special pages cannot have other pages' );
1725 if ( $this->isTalkPage() ) {
1726 return $this->getSubjectPage();
1727 } else {
1728 if ( !$this->canHaveTalkPage() ) {
1729 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1731 return $this->getTalkPage();
1733 // TODO: replace the above with the code below:
1734 // return self::castFromLinkTarget(
1735 // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1739 * Get the Title fragment (i.e.\ the bit after the #) in text form
1741 * Use Title::hasFragment to check for a fragment
1743 * @return string Title fragment
1745 public function getFragment(): string {
1746 return $this->mFragment;
1750 * Get the fragment in URL form, including the "#" character if there is one
1752 * @return string Fragment in URL form
1754 public function getFragmentForURL() {
1755 if ( !$this->hasFragment() ) {
1756 return '';
1757 } elseif ( $this->isExternal() ) {
1758 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1759 // so we treat it like a local interwiki.
1760 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1761 if ( $interwiki && !$interwiki->isLocal() ) {
1762 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1766 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1770 * Set the fragment for this title. Removes the first character from the
1771 * specified fragment before setting, so it assumes you're passing it with
1772 * an initial "#".
1774 * @warning This must only be used if the caller controls the further use of
1775 * this Title object, to avoid other code unexpectedly using the new value.
1777 * @param string $fragment Text
1779 public function setFragment( $fragment ) {
1780 $this->uncache();
1781 $this->mFragment = self::normalizeFragment( $fragment );
1785 * Creates a new Title for a different fragment of the same page.
1787 * @since 1.27
1788 * @param string $fragment
1789 * @return Title
1791 public function createFragmentTarget( string $fragment ): self {
1792 return self::makeTitle(
1793 $this->mNamespace,
1794 $this->getText(),
1795 $fragment,
1796 $this->mInterwiki
1801 * Normalizes fragment part of the title.
1803 * @param string $fragment
1804 * @return string
1806 private static function normalizeFragment( $fragment ) {
1807 if ( str_starts_with( $fragment, '#' ) ) {
1808 $fragment = substr( $fragment, 1 );
1810 return strtr( $fragment, '_', ' ' );
1814 * Prefix some arbitrary text with the namespace or interwiki prefix
1815 * of this object
1817 * @param string $name The text
1818 * @return string The prefixed text
1820 private function prefix( $name ) {
1821 $p = '';
1822 if ( $this->isExternal() ) {
1823 $p = $this->mInterwiki . ':';
1826 if ( $this->mNamespace != 0 ) {
1827 $nsText = $this->getNsText();
1829 if ( $nsText === false ) {
1830 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1831 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1832 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1835 $p .= $nsText . ':';
1837 return $p . $name;
1841 * Get the prefixed database key form
1843 * @return string The prefixed title, with underscores and
1844 * any interwiki and namespace prefixes
1846 public function getPrefixedDBkey() {
1847 $s = $this->prefix( $this->mDbkeyform );
1848 $s = strtr( $s, ' ', '_' );
1849 return $s;
1853 * Get the prefixed title with spaces.
1854 * This is the form usually used for display
1856 * @return string The prefixed title, with spaces
1858 public function getPrefixedText() {
1859 if ( $this->prefixedText === null ) {
1860 $s = $this->prefix( $this->mTextform );
1861 $s = strtr( $s, '_', ' ' );
1862 $this->prefixedText = $s;
1864 return $this->prefixedText;
1868 * Return a string representation of this title
1870 * @return string Representation of this title
1872 public function __toString(): string {
1873 return $this->getPrefixedText();
1877 * Get the prefixed title with spaces, plus any fragment
1878 * (part beginning with '#')
1880 * @return string The prefixed title, with spaces and the fragment, including '#'
1882 public function getFullText() {
1883 $text = $this->getPrefixedText();
1884 if ( $this->hasFragment() ) {
1885 $text .= '#' . $this->mFragment;
1887 return $text;
1891 * Finds the first or last subpage divider (slash) in the string.
1892 * Any leading sequence of slashes is ignored, since it does not divide
1893 * two parts of the string. Considering leading slashes dividers would
1894 * result in empty root title or base title (T229443).
1896 * Note that trailing slashes are considered dividers, and empty subpage
1897 * names are allowed.
1899 * @param string $text
1900 * @param int $dir -1 for the last or +1 for the first divider.
1902 * @return false|int
1904 private function findSubpageDivider( $text, $dir ) {
1905 if ( $dir > 0 ) {
1906 // Skip leading slashes, but keep the last one when there is nothing but slashes
1907 $bottom = strspn( $text, '/', 0, -1 );
1908 $idx = strpos( $text, '/', $bottom );
1909 } else {
1910 // Any slash from the end can be a divider, as subpage names can be empty
1911 $idx = strrpos( $text, '/' );
1914 // The first character can never be a divider, as that would result in an empty base
1915 return $idx === 0 ? false : $idx;
1919 * Whether this Title's namespace has subpages enabled.
1920 * @return bool
1922 private function hasSubpagesEnabled() {
1923 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1924 hasSubpages( $this->mNamespace );
1928 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1930 * @note the return value may contain trailing whitespace and is thus
1931 * not safe for use with makeTitle or TitleValue.
1933 * @par Example:
1934 * @code
1935 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1936 * # returns: 'Foo'
1937 * @endcode
1939 * @return string Root name
1940 * @since 1.20
1942 public function getRootText() {
1943 $text = $this->getText();
1944 if ( !$this->hasSubpagesEnabled() ) {
1945 return $text;
1948 $firstSlashPos = $this->findSubpageDivider( $text, +1 );
1949 // Don't discard the real title if there's no subpage involved
1950 if ( $firstSlashPos === false ) {
1951 return $text;
1954 return substr( $text, 0, $firstSlashPos );
1958 * Get the root page name title, i.e. the leftmost part before any slashes
1960 * @par Example:
1961 * @code
1962 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1963 * # returns: Title{User:Foo}
1964 * @endcode
1966 * @return Title
1967 * @since 1.20
1969 public function getRootTitle() {
1970 $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1972 if ( !$title ) {
1973 if ( !$this->isValid() ) {
1974 // If the title wasn't valid in the first place, we can't expect
1975 // to successfully parse it. T290194
1976 return $this;
1979 Assert::postcondition(
1980 $title !== null,
1981 'makeTitleSafe() should always return a Title for the text ' .
1982 'returned by getRootText().'
1986 return $title;
1990 * Get the base page name without a namespace, i.e. the part before the subpage name
1992 * @note the return value may contain trailing whitespace and is thus
1993 * not safe for use with makeTitle or TitleValue.
1995 * @par Example:
1996 * @code
1997 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1998 * # returns: 'Foo/Bar'
1999 * @endcode
2001 * @return string Base name
2003 public function getBaseText() {
2004 $text = $this->getText();
2005 if ( !$this->hasSubpagesEnabled() ) {
2006 return $text;
2009 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2010 // Don't discard the real title if there's no subpage involved
2011 if ( $lastSlashPos === false ) {
2012 return $text;
2015 return substr( $text, 0, $lastSlashPos );
2019 * Get the base page name title, i.e. the part before the subpage name.
2021 * @par Example:
2022 * @code
2023 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
2024 * # returns: Title{User:Foo/Bar}
2025 * @endcode
2027 * @return Title
2028 * @since 1.20
2030 public function getBaseTitle() {
2031 $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
2033 if ( !$title ) {
2034 if ( !$this->isValid() ) {
2035 // If the title wasn't valid in the first place, we can't expect
2036 // to successfully parse it. T290194
2037 return $this;
2040 Assert::postcondition(
2041 $title !== null,
2042 'makeTitleSafe() should always return a Title for the text ' .
2043 'returned by getBaseText().'
2047 return $title;
2051 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
2053 * @par Example:
2054 * @code
2055 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
2056 * # returns: "Baz"
2057 * @endcode
2059 * @return string Subpage name
2061 public function getSubpageText() {
2062 $text = $this->getText();
2063 if ( !$this->hasSubpagesEnabled() ) {
2064 return $text;
2067 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2068 if ( $lastSlashPos === false ) {
2069 // T256922 - Return the title text if no subpages
2070 return $text;
2072 return substr( $text, $lastSlashPos + 1 );
2076 * Get the title for a subpage of the current page
2078 * @par Example:
2079 * @code
2080 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
2081 * # returns: Title{User:Foo/Bar/Baz/Asdf}
2082 * @endcode
2084 * @param string $text The subpage name to add to the title
2085 * @return Title|null Subpage title, or null on an error
2086 * @since 1.20
2088 public function getSubpage( $text ) {
2089 return self::makeTitleSafe(
2090 $this->mNamespace,
2091 $this->getText() . '/' . $text,
2093 $this->mInterwiki
2098 * Get a URL-encoded form of the subpage text
2100 * @return string URL-encoded subpage name
2102 public function getSubpageUrlForm() {
2103 $text = $this->getSubpageText();
2104 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
2105 return $text;
2109 * Get a URL-encoded title (not an actual URL) including interwiki
2111 * @return string The URL-encoded form
2113 public function getPrefixedURL() {
2114 $s = $this->prefix( $this->mDbkeyform );
2115 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2116 return $s;
2120 * Get a real URL referring to this title, with interwiki link and
2121 * fragment
2123 * @see self::getLocalURL for the arguments.
2124 * @see \MediaWiki\Utils\UrlUtils::expand()
2125 * @param string|array $query
2126 * @param false $query2 deprecated since MW 1.19; ignored since MW 1.41
2127 * @param string|int|null $proto Protocol type to use in URL
2128 * @return string The URL
2130 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
2131 $services = MediaWikiServices::getInstance();
2133 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2135 # Hand off all the decisions on urls to getLocalURL
2136 $url = $this->getLocalURL( $query );
2138 # Expand the url to make it a full url. Note that getLocalURL has the
2139 # potential to output full urls for a variety of reasons, so we use
2140 # UrlUtils::expand() instead of simply prepending $wgServer
2141 $url = (string)$services->getUrlUtils()->expand( $url, $proto );
2143 # Finally, add the fragment.
2144 $url .= $this->getFragmentForURL();
2145 ( new HookRunner( $services->getHookContainer() ) )->onGetFullURL( $this, $url, $query );
2146 return $url;
2150 * Get a url appropriate for making redirects based on an untrusted url arg
2152 * This is basically the same as getFullUrl(), but in the case of external
2153 * interwikis, we send the user to a landing page, to prevent possible
2154 * phishing attacks and the like.
2156 * @note Uses current protocol by default, since technically relative urls
2157 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2158 * places where the url gets cached, as might pollute between
2159 * https and non-https users.
2160 * @see self::getLocalURL for the arguments.
2161 * @param array|string $query
2162 * @param string $proto Protocol type to use in URL
2163 * @return string A url suitable to use in an HTTP location header.
2165 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2166 $target = $this;
2167 if ( $this->isExternal() ) {
2168 $target = SpecialPage::getTitleFor(
2169 'GoToInterwiki',
2170 $this->getPrefixedDBkey()
2173 return $target->getFullURL( $query, false, $proto );
2177 * Get a URL with no fragment or server name (relative URL) from a Title object.
2178 * If this page is generated with action=render, however,
2179 * $wgServer is prepended to make an absolute URL.
2181 * @see self::getFullURL to always get an absolute URL.
2182 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2183 * valid to link, locally, to the current Title.
2184 * @see self::newFromText to produce a Title object.
2186 * @param string|array $query An optional query string,
2187 * not used for interwiki links. Can be specified as an associative array as well,
2188 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2189 * Some query patterns will trigger various shorturl path replacements.
2191 * @return string
2193 public function getLocalURL( $query = '' ) {
2194 global $wgArticlePath, $wgScript, $wgMainPageIsDomainRoot;
2196 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2198 $services = MediaWikiServices::getInstance();
2199 $hookRunner = new HookRunner( $services->getHookContainer() );
2200 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2201 if ( $interwiki ) {
2202 $namespace = $this->getNsText();
2203 if ( $namespace != '' ) {
2204 # Can this actually happen? Interwikis shouldn't be parsed.
2205 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2206 $namespace .= ':';
2208 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2209 $url = wfAppendQuery( $url, $query );
2210 } else {
2211 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2212 if ( $query == '' ) {
2213 if ( $wgMainPageIsDomainRoot && $this->isMainPage() ) {
2214 $url = '/';
2215 } else {
2216 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2218 $hookRunner->onGetLocalURL__Article( $this, $url );
2219 } else {
2220 global $wgVariantArticlePath, $wgActionPaths;
2221 $url = false;
2222 $matches = [];
2224 $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
2226 if ( $articlePaths
2227 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2229 $action = urldecode( $matches[2] );
2230 if ( isset( $articlePaths[$action] ) ) {
2231 $query = $matches[1];
2232 if ( isset( $matches[4] ) ) {
2233 $query .= $matches[4];
2235 $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2236 if ( $query != '' ) {
2237 $url = wfAppendQuery( $url, $query );
2242 if ( $url === false
2243 && $wgVariantArticlePath
2244 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2245 && $this->getPageLanguage()->equals( $services->getContentLanguage() )
2246 && $this->getPageLanguageConverter()->hasVariants()
2248 $variant = urldecode( $matches[1] );
2249 if ( $this->getPageLanguageConverter()->hasVariant( $variant ) ) {
2250 // Only do the variant replacement if the given variant is a valid
2251 // variant for the page's language.
2252 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2253 $url = str_replace( '$1', $dbkey, $url );
2257 if ( $url === false ) {
2258 if ( $query == '-' ) {
2259 $query = '';
2261 $url = "{$wgScript}?title={$dbkey}&{$query}";
2264 $hookRunner->onGetLocalURL__Internal( $this, $url, $query );
2267 $hookRunner->onGetLocalURL( $this, $url, $query );
2268 return $url;
2272 * Get a URL that's the simplest URL that will be valid to link, locally,
2273 * to the current Title. It includes the fragment, but does not include
2274 * the server unless action=render is used (or the link is external). If
2275 * there's a fragment but the prefixed text is empty, we just return a link
2276 * to the fragment.
2278 * The result obviously should not be URL-escaped, but does need to be
2279 * HTML-escaped if it's being output in HTML.
2281 * @param string|array $query
2282 * @param string|string[]|false $query2 deprecated since MW 1.19; ignored since MW 1.41
2283 * @param string|int|false $proto A PROTO_* constant on how the URL should be expanded,
2284 * or false (default) for no expansion
2285 * @see self::getLocalURL for the arguments.
2286 * @return string The URL
2288 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2289 if ( $this->isExternal() || $proto !== false ) {
2290 $ret = $this->getFullURL( $query, false, $proto );
2291 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2292 $ret = $this->getFragmentForURL();
2293 } else {
2294 $ret = $this->getLocalURL( $query ) . $this->getFragmentForURL();
2296 return $ret;
2300 * Get the URL form for an internal link.
2301 * - Used in various CDN-related code, in case we have a different
2302 * internal hostname for the server from the exposed one.
2304 * This uses $wgInternalServer to qualify the path, or $wgServer
2305 * if $wgInternalServer is not set. If the server variable used is
2306 * protocol-relative, the URL will be expanded to http://
2308 * @see self::getLocalURL for the arguments.
2309 * @param string|array $query
2310 * @return string The URL
2312 public function getInternalURL( $query = '' ) {
2313 global $wgInternalServer, $wgServer;
2314 $services = MediaWikiServices::getInstance();
2316 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2318 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2319 $url = (string)$services->getUrlUtils()->expand( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2320 ( new HookRunner( $services->getHookContainer() ) )
2321 ->onGetInternalURL( $this, $url, $query );
2322 return $url;
2326 * Get the URL for a canonical link, for use in things like IRC and
2327 * e-mail notifications. Uses $wgCanonicalServer and the
2328 * GetCanonicalURL hook.
2330 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2332 * @see self::getLocalURL for the arguments.
2333 * @param string|array $query
2334 * @return string The URL
2335 * @since 1.18
2337 public function getCanonicalURL( $query = '' ) {
2338 $services = MediaWikiServices::getInstance();
2340 $query = is_array( $query ) ? wfArrayToCgi( $query ) : $query;
2342 $url = (string)$services->getUrlUtils()->expand(
2343 $this->getLocalURL( $query ) . $this->getFragmentForURL(),
2344 PROTO_CANONICAL
2346 ( new HookRunner( $services->getHookContainer() ) )
2347 ->onGetCanonicalURL( $this, $url, $query );
2348 return $url;
2352 * Get the edit URL for this Title
2354 * @return string The URL, or a null string if this is an interwiki link
2356 public function getEditURL() {
2357 if ( $this->isExternal() ) {
2358 return '';
2360 $s = $this->getLocalURL( 'action=edit' );
2362 return $s;
2366 * Is this title subject to title protection?
2367 * Title protection is the one applied against creation of such title.
2369 * @deprecated since 1.37, use RestrictionStore::getCreateProtection() instead;
2370 * hard-deprecated since 1.43
2372 * @return array|bool An associative array representing any existent title
2373 * protection, or false if there's none.
2375 public function getTitleProtection() {
2376 wfDeprecated( __METHOD__, '1.37' );
2377 return MediaWikiServices::getInstance()->getRestrictionStore()->getCreateProtection( $this )
2378 ?: false;
2382 * Remove any title protection due to page existing
2384 * @deprecated since 1.37, do not use (this is only for WikiPage::onArticleCreate)
2386 public function deleteTitleProtection() {
2387 MediaWikiServices::getInstance()->getRestrictionStore()->deleteCreateProtection( $this );
2391 * Load restrictions from the page_restrictions table
2393 * @deprecated since 1.37, no public replacement; hard-deprecated since 1.43
2395 * @param int $flags A bit field. If IDBAccessObject::READ_LATEST is set, skip replicas and read
2396 * from the primary DB.
2398 public function loadRestrictions( $flags = 0 ) {
2399 wfDeprecated( __METHOD__, '1.37' );
2400 MediaWikiServices::getInstance()->getRestrictionStore()->loadRestrictions( $this, $flags );
2404 * Flush the protection cache in this object and force reload from the database.
2405 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2407 * @deprecated since 1.37, now internal; hard-deprecated since 1.43
2409 public function flushRestrictions() {
2410 wfDeprecated( __METHOD__, '1.37' );
2411 MediaWikiServices::getInstance()->getRestrictionStore()->flushRestrictions( $this );
2415 * Purge expired restrictions from the page_restrictions table
2417 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2419 public static function purgeExpiredRestrictions() {
2420 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2421 return;
2424 DeferredUpdates::addUpdate( new AutoCommitUpdate(
2425 MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase(),
2426 __METHOD__,
2427 static function ( IDatabase $dbw, $fname ) {
2428 $config = MediaWikiServices::getInstance()->getMainConfig();
2429 $ids = $dbw->newSelectQueryBuilder()
2430 ->select( 'pr_id' )
2431 ->from( 'page_restrictions' )
2432 ->where( $dbw->expr( 'pr_expiry', '<', $dbw->timestamp() ) )
2433 ->limit( $config->get( MainConfigNames::UpdateRowsPerQuery ) ) // T135470
2434 ->caller( $fname )->fetchFieldValues();
2435 if ( $ids ) {
2436 $dbw->newDeleteQueryBuilder()
2437 ->deleteFrom( 'page_restrictions' )
2438 ->where( [ 'pr_id' => $ids ] )
2439 ->caller( $fname )->execute();
2442 $dbw->newDeleteQueryBuilder()
2443 ->deleteFrom( 'protected_titles' )
2444 ->where( $dbw->expr( 'pt_expiry', '<', $dbw->timestamp() ) )
2445 ->caller( $fname )->execute();
2447 ) );
2451 * Does this have subpages? (Warning, usually requires an extra DB query.)
2453 * @return bool
2455 public function hasSubpages() {
2456 if (
2457 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2458 hasSubpages( $this->mNamespace )
2460 # Duh
2461 return false;
2464 # We dynamically add a member variable for the purpose of this method
2465 # alone to cache the result. There's no point in having it hanging
2466 # around uninitialized in every Title object; therefore we only add it
2467 # if needed and don't declare it statically.
2468 if ( $this->mHasSubpages === null ) {
2469 $subpages = $this->getSubpages( 1 );
2470 $this->mHasSubpages = $subpages instanceof TitleArrayFromResult && $subpages->count();
2473 return $this->mHasSubpages;
2477 * Get all subpages of this page.
2479 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2480 * @return TitleArrayFromResult|array TitleArrayFromResult, or empty array if this page's namespace
2481 * doesn't allow subpages
2483 public function getSubpages( $limit = -1 ) {
2484 if (
2485 !MediaWikiServices::getInstance()->getNamespaceInfo()->
2486 hasSubpages( $this->mNamespace )
2488 return [];
2491 $services = MediaWikiServices::getInstance();
2492 $pageStore = $services->getPageStore();
2493 $titleFactory = $services->getTitleFactory();
2494 $query = $pageStore->newSelectQueryBuilder()
2495 ->fields( $pageStore->getSelectFields() )
2496 ->whereTitlePrefix( $this->getNamespace(), $this->getDBkey() . '/' )
2497 ->caller( __METHOD__ );
2498 if ( $limit > -1 ) {
2499 $query->limit( $limit );
2502 return $titleFactory->newTitleArrayFromResult( $query->fetchResultSet() );
2506 * Is there a version of this page in the deletion archive?
2508 * @deprecated since 1.36. Use self::getDeletedEditsCount()
2509 * @return int The number of archived revisions
2511 public function isDeleted() {
2512 return $this->getDeletedEditsCount();
2516 * Is there a version of this page in the deletion archive?
2518 * @since 1.36
2519 * @return int The number of archived revisions
2521 public function getDeletedEditsCount() {
2522 if ( $this->mNamespace < 0 ) {
2523 return 0;
2526 $dbr = $this->getDbProvider()->getReplicaDatabase();
2527 $n = (int)$dbr->newSelectQueryBuilder()
2528 ->select( 'COUNT(*)' )
2529 ->from( 'archive' )
2530 ->where( [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ] )
2531 ->caller( __METHOD__ )->fetchField();
2532 if ( $this->mNamespace === NS_FILE ) {
2533 $n += $dbr->newSelectQueryBuilder()
2534 ->select( 'COUNT(*)' )
2535 ->from( 'filearchive' )
2536 ->where( [ 'fa_name' => $this->mDbkeyform ] )
2537 ->caller( __METHOD__ )->fetchField();
2539 return $n;
2543 * Is there a version of this page in the deletion archive?
2545 * @deprecated since 1.36, Use self::hasDeletedEdits()
2546 * @return bool
2548 public function isDeletedQuick() {
2549 return $this->hasDeletedEdits();
2553 * Is there a version of this page in the deletion archive?
2555 * @since 1.36
2556 * @return bool
2558 public function hasDeletedEdits() {
2559 if ( $this->mNamespace < 0 ) {
2560 return false;
2562 $dbr = $this->getDbProvider()->getReplicaDatabase();
2563 $deleted = (bool)$dbr->newSelectQueryBuilder()
2564 ->select( '1' )
2565 ->from( 'archive' )
2566 ->where( [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ] )
2567 ->caller( __METHOD__ )->fetchField();
2568 if ( !$deleted && $this->mNamespace === NS_FILE ) {
2569 $deleted = (bool)$dbr->newSelectQueryBuilder()
2570 ->select( '1' )
2571 ->from( 'filearchive' )
2572 ->where( [ 'fa_name' => $this->mDbkeyform ] )
2573 ->caller( __METHOD__ )->fetchField();
2575 return $deleted;
2579 * Get the article ID for this Title from the link cache,
2580 * adding it if necessary
2582 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2583 * @return int The ID
2585 public function getArticleID( $flags = 0 ) {
2586 if ( $this->mArticleID === -1 && !$this->canExist() ) {
2587 $this->mArticleID = 0;
2589 return $this->mArticleID;
2592 if ( $this->mArticleID === -1 || $this->shouldReadLatest( $flags ) ) {
2593 $this->mArticleID = (int)$this->getFieldFromPageStore( 'page_id', $flags );
2596 return $this->mArticleID;
2600 * Is this an article that is a redirect page?
2601 * Uses link cache, adding it if necessary.
2603 * This is intended to provide fast access to page_is_redirect for linking.
2604 * In rare cases, there might not be a valid target in the redirect table
2605 * even though this function returns true.
2607 * To find a redirect target, just call WikiPage::getRedirectTarget() and
2608 * check if it returns null, there's no need to call this first.
2610 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2611 * @return bool
2613 public function isRedirect( $flags = 0 ) {
2614 if ( $this->shouldReadLatest( $flags ) || $this->mRedirect === null ) {
2615 $this->mRedirect = (bool)$this->getFieldFromPageStore( 'page_is_redirect', $flags );
2618 return $this->mRedirect;
2622 * What is the length of this page?
2623 * Uses link cache, adding it if necessary
2625 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2626 * @return int
2628 public function getLength( $flags = 0 ) {
2629 if ( $this->shouldReadLatest( $flags ) || $this->mLength < 0 ) {
2630 $this->mLength = (int)$this->getFieldFromPageStore( 'page_len', $flags );
2633 if ( $this->mLength < 0 ) {
2634 $this->mLength = 0;
2637 return $this->mLength;
2641 * What is the page_latest field for this page?
2643 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
2644 * @return int Int or 0 if the page doesn't exist
2646 public function getLatestRevID( $flags = 0 ) {
2647 if ( $this->shouldReadLatest( $flags ) || $this->mLatestID === false ) {
2648 $this->mLatestID = (int)$this->getFieldFromPageStore( 'page_latest', $flags );
2651 if ( !$this->mLatestID ) {
2652 $this->mLatestID = 0;
2655 return $this->mLatestID;
2659 * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
2661 * This can be called on page insertion to allow loading of the new page_id without
2662 * having to create a new Title instance. Likewise with deletion.
2664 * This is also used during page moves, to reflect the change in the relationship
2665 * between article ID and title text.
2667 * @note This overrides Title::setContentModel()
2669 * @param int|bool $id Page ID, 0 for non-existent, or false for "unknown" (lazy-load)
2671 public function resetArticleID( $id ) {
2672 if ( $id === false ) {
2673 $this->mArticleID = -1;
2674 } else {
2675 $this->mArticleID = (int)$id;
2677 $this->mRedirect = null;
2678 $this->mLength = -1;
2679 $this->mLatestID = false;
2680 $this->mContentModel = false;
2681 $this->mForcedContentModel = false;
2682 $this->mEstimateRevisions = null;
2683 $this->mPageLanguage = null;
2684 $this->mDbPageLanguage = false;
2685 $this->mIsBigDeletion = null;
2687 $this->uncache();
2688 MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
2689 MediaWikiServices::getInstance()->getRestrictionStore()->flushRestrictions( $this );
2692 public static function clearCaches() {
2693 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2694 $linkCache->clear();
2696 $titleCache = self::getTitleCache();
2697 $titleCache->clear();
2701 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2703 * @param string $text Containing title to capitalize
2704 * @param int $ns Namespace index, defaults to NS_MAIN
2705 * @return string Containing capitalized title
2707 public static function capitalize( $text, $ns = NS_MAIN ) {
2708 $services = MediaWikiServices::getInstance();
2709 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
2710 return $services->getContentLanguage()->ucfirst( $text );
2711 } else {
2712 return $text;
2717 * Secure and split - main initialisation function for this object
2719 * Assumes that $text is urldecoded
2720 * and uses underscores, but not otherwise munged. This function
2721 * removes illegal characters, splits off the interwiki and
2722 * namespace prefixes, sets the other forms, and canonicalizes
2723 * everything.
2725 * If this method returns normally, the Title is valid.
2727 * @param string $text
2728 * @param int|null $defaultNamespace
2730 * @throws MalformedTitleException On malformed titles
2732 private function secureAndSplit( $text, $defaultNamespace = null ) {
2733 $defaultNamespace ??= self::DEFAULT_NAMESPACE;
2735 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
2736 // the parsing code with Title, while avoiding massive refactoring.
2737 // @todo: get rid of secureAndSplit, refactor parsing code.
2738 // @note: getTitleParser() returns a TitleParser implementation which does not have a
2739 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
2740 /** @var MediaWikiTitleCodec $titleCodec */
2741 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
2742 '@phan-var MediaWikiTitleCodec $titleCodec';
2743 // MalformedTitleException can be thrown here
2744 $parts = $titleCodec->splitTitleString( $text, $defaultNamespace );
2746 # Fill fields
2747 $this->setFragment( '#' . $parts['fragment'] );
2748 $this->mInterwiki = $parts['interwiki'];
2749 $this->mLocalInterwiki = $parts['local_interwiki'];
2750 $this->mNamespace = $parts['namespace'];
2752 $this->mDbkeyform = $parts['dbkey'];
2753 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
2754 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
2756 // splitTitleString() guarantees that this title is valid.
2757 $this->mIsValid = true;
2759 # We already know that some pages won't be in the database!
2760 if ( $this->isExternal() || $this->isSpecialPage() || $this->mTextform === '' ) {
2761 $this->mArticleID = 0;
2766 * Get an array of Title objects linking to this Title
2767 * Also stores the IDs in the link cache.
2769 * WARNING: do not use this function on arbitrary user-supplied titles!
2770 * On heavily-used templates it will max out the memory.
2772 * @param array $options May be FOR UPDATE
2773 * @param string $table Table name
2774 * @param string $prefix Fields prefix
2775 * @return Title[]
2777 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
2778 if ( count( $options ) > 0 ) {
2779 $db = $this->getDbProvider()->getPrimaryDatabase();
2780 } else {
2781 $db = $this->getDbProvider()->getReplicaDatabase();
2784 $linksMigration = MediaWikiServices::getInstance()->getLinksMigration();
2785 if ( isset( $linksMigration::$mapping[$table] ) ) {
2786 $titleConds = $linksMigration->getLinksConditions( $table, $this );
2787 } else {
2788 $titleConds = [
2789 "{$prefix}_namespace" => $this->mNamespace,
2790 "{$prefix}_title" => $this->mDbkeyform
2794 $res = $db->newSelectQueryBuilder()
2795 ->select( LinkCache::getSelectFields() )
2796 ->from( $table )
2797 ->join( 'page', null, "{$prefix}_from=page_id" )
2798 ->where( $titleConds )
2799 ->options( $options )
2800 ->caller( __METHOD__ )
2801 ->fetchResultSet();
2803 $retVal = [];
2804 if ( $res->numRows() ) {
2805 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2806 foreach ( $res as $row ) {
2807 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
2808 if ( $titleObj ) {
2809 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2810 $retVal[] = $titleObj;
2814 return $retVal;
2818 * Get an array of Title objects using this Title as a template
2819 * Also stores the IDs in the link cache.
2821 * WARNING: do not use this function on arbitrary user-supplied titles!
2822 * On heavily-used templates it will max out the memory.
2824 * @param array $options Query option to Database::select()
2825 * @return Title[]
2827 public function getTemplateLinksTo( $options = [] ) {
2828 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2832 * Get an array of Title objects linked from this Title
2833 * Also stores the IDs in the link cache.
2835 * WARNING: do not use this function on arbitrary user-supplied titles!
2836 * On heavily-used templates it will max out the memory.
2838 * @param array $options Query option to Database::select()
2839 * @param string $table Table name
2840 * @param string $prefix Fields prefix
2841 * @return Title[] List of Titles linking here
2843 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
2844 $id = $this->getArticleID();
2846 # If the page doesn't exist; there can't be any link from this page
2847 if ( !$id ) {
2848 return [];
2851 $db = $this->getDbProvider()->getReplicaDatabase();
2852 $linksMigration = MediaWikiServices::getInstance()->getLinksMigration();
2854 $queryBuilder = $db->newSelectQueryBuilder();
2855 if ( isset( $linksMigration::$mapping[$table] ) ) {
2856 [ $blNamespace, $blTitle ] = $linksMigration->getTitleFields( $table );
2857 $linktargetQueryInfo = $linksMigration->getQueryInfo( $table );
2858 $queryBuilder->queryInfo( $linktargetQueryInfo );
2859 } else {
2860 $blNamespace = "{$prefix}_namespace";
2861 $blTitle = "{$prefix}_title";
2862 $queryBuilder->select( [ $blNamespace, $blTitle ] )
2863 ->from( $table );
2866 $pageQuery = WikiPage::getQueryInfo();
2867 $res = $queryBuilder
2868 ->where( [ "{$prefix}_from" => $id ] )
2869 ->leftJoin( 'page', null, [ "page_namespace=$blNamespace", "page_title=$blTitle" ] )
2870 ->fields( $pageQuery['fields'] )
2871 ->options( $options )
2872 ->caller( __METHOD__ )
2873 ->fetchResultSet();
2875 $retVal = [];
2876 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2877 foreach ( $res as $row ) {
2878 if ( $row->page_id ) {
2879 $titleObj = self::newFromRow( $row );
2880 } else {
2881 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
2882 $linkCache->addBadLinkObj( $titleObj );
2884 $retVal[] = $titleObj;
2887 return $retVal;
2891 * Get an array of Title objects used on this Title as a template
2892 * Also stores the IDs in the link cache.
2894 * WARNING: do not use this function on arbitrary user-supplied titles!
2895 * On heavily-used templates it will max out the memory.
2897 * @param array $options May be FOR UPDATE
2898 * @return Title[]
2900 public function getTemplateLinksFrom( $options = [] ) {
2901 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
2905 * Locks the page row and check if this page is single revision redirect
2907 * This updates the cached fields of this instance via Title::loadFromRow()
2909 * @return bool
2911 public function isSingleRevRedirect() {
2912 $dbw = $this->getDbProvider()->getPrimaryDatabase();
2913 $dbw->startAtomic( __METHOD__ );
2914 $pageStore = MediaWikiServices::getInstance()->getPageStore();
2916 $row = $dbw->newSelectQueryBuilder()
2917 ->select( $pageStore->getSelectFields() )
2918 ->from( 'page' )
2919 ->where( $this->pageCond() )
2920 ->caller( __METHOD__ )->fetchRow();
2921 // Update the cached fields
2922 $this->loadFromRow( $row );
2924 if ( $this->mRedirect && $this->mLatestID ) {
2925 $isSingleRevRedirect = !$dbw->newSelectQueryBuilder()
2926 ->select( '1' )
2927 ->forUpdate()
2928 ->from( 'revision' )
2929 ->where( [ 'rev_page' => $this->mArticleID, $dbw->expr( 'rev_id', '!=', (int)$this->mLatestID ) ] )
2930 ->caller( __METHOD__ )->fetchField();
2931 } else {
2932 $isSingleRevRedirect = false;
2935 $dbw->endAtomic( __METHOD__ );
2937 return $isSingleRevRedirect;
2941 * Get categories to which this Title belongs and return an array of
2942 * categories' names.
2944 * @return string[] Array of parents in the form:
2945 * $parent => $currentarticle
2947 public function getParentCategories() {
2948 $data = [];
2950 $titleKey = $this->getArticleID();
2952 if ( $titleKey === 0 ) {
2953 return $data;
2956 $dbr = $this->getDbProvider()->getReplicaDatabase();
2958 $res = $dbr->newSelectQueryBuilder()
2959 ->select( 'cl_to' )
2960 ->from( 'categorylinks' )
2961 ->where( [ 'cl_from' => $titleKey ] )
2962 ->caller( __METHOD__ )->fetchResultSet();
2964 if ( $res->numRows() > 0 ) {
2965 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2966 foreach ( $res as $row ) {
2967 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
2968 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
2969 $this->getFullText();
2972 return $data;
2976 * Get a tree of parent categories
2978 * @param array $children Array with the children in the keys, to check for circular refs
2979 * @return array Tree of parent categories
2981 public function getParentCategoryTree( $children = [] ) {
2982 $stack = [];
2983 $parents = $this->getParentCategories();
2985 if ( $parents ) {
2986 foreach ( $parents as $parent => $current ) {
2987 if ( array_key_exists( $parent, $children ) ) {
2988 # Circular reference
2989 $stack[$parent] = [];
2990 } else {
2991 $nt = self::newFromText( $parent );
2992 if ( $nt ) {
2993 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
2999 return $stack;
3003 * Get an associative array for selecting this title from
3004 * the "page" table
3006 * @return array Array suitable for the $where parameter of DB::select()
3008 public function pageCond() {
3009 if ( $this->mArticleID > 0 ) {
3010 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3011 return [ 'page_id' => $this->mArticleID ];
3012 } else {
3013 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3018 * Check if this is a new page.
3020 * @note This returns false if the page does not exist.
3021 * @param int $flags one of the READ_XXX constants.
3023 * @return bool
3025 public function isNewPage( $flags = IDBAccessObject::READ_NORMAL ) {
3026 // NOTE: we rely on PHP casting "0" to false here.
3027 return (bool)$this->getFieldFromPageStore( 'page_is_new', $flags );
3031 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3032 * @deprecated since 1.37 External callers shouldn't need to know about this.
3034 * @return bool
3036 public function isBigDeletion() {
3037 global $wgDeleteRevisionsLimit;
3039 if ( !$wgDeleteRevisionsLimit ) {
3040 return false;
3043 if ( $this->mIsBigDeletion === null ) {
3044 $dbr = $this->getDbProvider()->getReplicaDatabase();
3045 $revCount = $dbr->newSelectQueryBuilder()
3046 ->select( '1' )
3047 ->from( 'revision' )
3048 ->where( [ 'rev_page' => $this->getArticleID() ] )
3049 ->limit( $wgDeleteRevisionsLimit + 1 )
3050 ->caller( __METHOD__ )->fetchRowCount();
3052 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
3055 return $this->mIsBigDeletion;
3059 * Get the approximate revision count of this page.
3061 * @return int
3063 public function estimateRevisionCount() {
3064 if ( !$this->exists() ) {
3065 return 0;
3068 if ( $this->mEstimateRevisions === null ) {
3069 $dbr = $this->getDbProvider()->getReplicaDatabase();
3070 $this->mEstimateRevisions = $dbr->newSelectQueryBuilder()
3071 ->select( '*' )
3072 ->from( 'revision' )
3073 ->where( [ 'rev_page' => $this->getArticleID() ] )
3074 ->caller( __METHOD__ )
3075 ->estimateRowCount();
3078 return $this->mEstimateRevisions;
3082 * Compares with another Title.
3084 * A Title object is considered equal to another Title if it has the same text,
3085 * the same interwiki prefix, and the same namespace.
3087 * @note This is different from isSameLinkAs(), which also compares the fragment part,
3088 * and from isSamePageAs(), which takes into account the page ID.
3090 * @phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
3091 * @param Title|object $other
3093 * @return bool true if $other is a Title and refers to the same page.
3095 public function equals( object $other ) {
3096 // NOTE: In contrast to isSameLinkAs(), this ignores the fragment part!
3097 // NOTE: In contrast to isSamePageAs(), this ignores the page ID!
3098 // NOTE: === is necessary for proper matching of number-like titles
3099 return $other instanceof Title
3100 && $this->getInterwiki() === $other->getInterwiki()
3101 && $this->getNamespace() === $other->getNamespace()
3102 && $this->getDBkey() === $other->getDBkey();
3106 * @inheritDoc
3107 * @since 1.36
3109 public function isSamePageAs( PageReference $other ): bool {
3110 // NOTE: keep in sync with PageReferenceValue::isSamePageAs()!
3111 return $this->getWikiId() === $other->getWikiId()
3112 && $this->getNamespace() === $other->getNamespace()
3113 && $this->getDBkey() === $other->getDBkey();
3117 * Check if this title is a subpage of another title
3119 * @param Title $title
3120 * @return bool
3122 public function isSubpageOf( Title $title ) {
3123 return $this->mInterwiki === $title->mInterwiki
3124 && $this->mNamespace == $title->mNamespace
3125 && str_starts_with( $this->mDbkeyform, $title->mDbkeyform . '/' );
3129 * Check if page exists. For historical reasons, this function simply
3130 * checks for the existence of the title in the page table, and will
3131 * thus return false for interwiki links, special pages and the like.
3132 * If you want to know if a title can be meaningfully viewed, you should
3133 * probably call the isKnown() method instead.
3135 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
3136 * @return bool
3138 public function exists( $flags = 0 ): bool {
3139 $exists = $this->getArticleID( $flags ) != 0;
3140 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onTitleExists( $this, $exists );
3141 return $exists;
3145 * Should links to this title be shown as potentially viewable (i.e. as
3146 * "bluelinks"), even if there's no record by this title in the page
3147 * table?
3149 * This function is semi-deprecated for public use, as well as somewhat
3150 * misleadingly named. You probably just want to call isKnown(), which
3151 * calls this function internally.
3153 * (ISSUE: Most of these checks are cheap, but the file existence check
3154 * can potentially be quite expensive. Including it here fixes a lot of
3155 * existing code, but we might want to add an optional parameter to skip
3156 * it and any other expensive checks.)
3158 * @return bool
3160 public function isAlwaysKnown() {
3161 $isKnown = null;
3163 $services = MediaWikiServices::getInstance();
3164 ( new HookRunner( $services->getHookContainer() ) )->onTitleIsAlwaysKnown( $this, $isKnown );
3166 if ( $isKnown !== null ) {
3167 return $isKnown;
3170 if ( $this->isExternal() ) {
3171 return true; // any interwiki link might be viewable, for all we know
3174 switch ( $this->mNamespace ) {
3175 case NS_MEDIA:
3176 case NS_FILE:
3177 // file exists, possibly in a foreign repo
3178 return (bool)$services->getRepoGroup()->findFile( $this );
3179 case NS_SPECIAL:
3180 // valid special page
3181 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
3182 case NS_MAIN:
3183 // selflink, possibly with fragment
3184 return $this->mDbkeyform == '';
3185 case NS_MEDIAWIKI:
3186 // known system message
3187 return $this->hasSourceText() !== false;
3188 default:
3189 return false;
3194 * Does this title refer to a page that can (or might) be meaningfully
3195 * viewed? In particular, this function may be used to determine if
3196 * links to the title should be rendered as "bluelinks" (as opposed to
3197 * "redlinks" to non-existent pages).
3198 * Adding something else to this function will cause inconsistency
3199 * since LinkHolderArray calls isAlwaysKnown() and does its own
3200 * page existence check.
3202 * @return bool
3204 public function isKnown() {
3205 return $this->isAlwaysKnown() || $this->exists();
3209 * Does this page have source text?
3211 * @return bool
3213 public function hasSourceText() {
3214 if ( $this->exists() ) {
3215 return true;
3218 if ( $this->mNamespace === NS_MEDIAWIKI ) {
3219 $services = MediaWikiServices::getInstance();
3220 // If the page doesn't exist but is a known system message, default
3221 // message content will be displayed, same for language subpages-
3222 // Use always content language to avoid loading hundreds of languages
3223 // to get the link color.
3224 $contLang = $services->getContentLanguage();
3225 [ $name, ] = $services->getMessageCache()->figureMessage(
3226 $contLang->lcfirst( $this->getText() )
3228 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
3229 return $message->exists();
3232 return false;
3236 * Get the default (plain) message contents for a page that overrides an
3237 * interface message key.
3239 * Primary use cases:
3241 * - Article:
3242 * - Show default when viewing the page. The Article::getSubstituteContent
3243 * method displays the default message content, instead of the
3244 * 'noarticletext' placeholder message normally used.
3246 * - EditPage:
3247 * - Title of edit page. When creating an interface message override,
3248 * the editor is told they are "Editing the page", instead of
3249 * "Creating the page". (EditPage::setHeaders)
3250 * - Edit notice. The 'translateinterface' edit notice is shown when creating
3251 * or editing an interface message override. (EditPage::showIntro)
3252 * - Opening the editor. The contents of the localisation message are used
3253 * as contents of the editor when creating a new page in the MediaWiki
3254 * namespace. This simplifies the process for editors when "changing"
3255 * an interface message by creating an override. (EditPage::getContentObject)
3256 * - Showing a diff. The left-hand side of a diff when an editor is
3257 * previewing their changes before saving the creation of a page in the
3258 * MediaWiki namespace. (EditPage::showDiff)
3259 * - Disallowing a save. When attempting to create a MediaWiki-namespace
3260 * page with the proposed content matching the interface message default,
3261 * the save is rejected, the same way we disallow blank pages from being
3262 * created. (EditPage using DefaultTextConstraint)
3264 * - ApiEditPage:
3265 * - Default content, when using the 'prepend' or 'append' feature.
3267 * - SkinTemplate:
3268 * - Label the create action as "Edit", if the page can be an override.
3270 * @return string|false
3272 public function getDefaultMessageText() {
3273 $message = $this->getDefaultSystemMessage();
3275 return $message ? $message->plain() : false;
3279 * Same as getDefaultMessageText, but returns a Message object.
3281 * @see ::getDefaultMessageText
3283 * @return ?Message
3285 public function getDefaultSystemMessage(): ?Message {
3286 if ( $this->mNamespace !== NS_MEDIAWIKI ) { // Just in case
3287 return null;
3290 [ $name, $lang ] = MediaWikiServices::getInstance()->getMessageCache()->figureMessage(
3291 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
3294 if ( wfMessage( $name )->inLanguage( $lang )->useDatabase( false )->exists() ) {
3295 return wfMessage( $name )->inLanguage( $lang );
3296 } else {
3297 return null;
3302 * Updates page_touched for this page; called from LinksUpdate.php
3304 * @param string|null $purgeTime [optional] TS_MW timestamp
3305 * @return bool True if the update succeeded
3307 public function invalidateCache( $purgeTime = null ) {
3308 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
3309 return false;
3311 if ( $this->mArticleID === 0 ) {
3312 // avoid gap locking if we know it's not there
3313 return true;
3316 $conds = $this->pageCond();
3318 // Periodically recompute page_random (T309477). This mitigates bias on
3319 // Special:Random due deleted pages leaving "gaps" in the distribution.
3321 // Optimization: Update page_random only for 10% of updates.
3322 // Optimization: Do this outside the main transaction to avoid locking for too long.
3323 // Optimization: Update page_random alongside page_touched to avoid extra database writes.
3324 DeferredUpdates::addUpdate(
3325 new AutoCommitUpdate(
3326 $this->getDbProvider()->getPrimaryDatabase(),
3327 __METHOD__,
3328 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
3329 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
3330 $update = $dbw->newUpdateQueryBuilder()
3331 ->update( 'page' )
3332 ->set( [ 'page_touched' => $dbTimestamp ] )
3333 ->where( $conds )
3334 ->andWhere( $dbw->expr( 'page_touched', '<', $dbTimestamp ) );
3336 if ( mt_rand( 1, 10 ) === 1 ) {
3337 $update->andSet( [ 'page_random' => wfRandom() ] );
3340 $update->caller( $fname )->execute();
3342 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
3344 WikiModule::invalidateModuleCache(
3345 $this, null, null, $dbw->getDomainID() );
3348 DeferredUpdates::PRESEND
3351 return true;
3355 * Update page_touched timestamps and send CDN purge messages for
3356 * pages linking to this title. May be sent to the job queue depending
3357 * on the number of links. Typically called on create and delete.
3359 public function touchLinks() {
3360 $jobs = [];
3361 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
3362 $this,
3363 'pagelinks',
3364 [ 'causeAction' => 'page-touch' ]
3366 if ( $this->mNamespace === NS_CATEGORY ) {
3367 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
3368 $this,
3369 'categorylinks',
3370 [ 'causeAction' => 'category-touch' ]
3374 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
3378 * Get the last touched timestamp
3380 * @param int $flags one of the READ_XXX constants.
3381 * @return string|false Last-touched timestamp
3383 public function getTouched( int $flags = IDBAccessObject::READ_NORMAL ) {
3384 $touched = $this->getFieldFromPageStore( 'page_touched', $flags );
3385 return $touched ? MWTimestamp::convert( TS_MW, $touched ) : false;
3389 * Generate strings used for xml 'id' names in monobook tabs
3391 * @param string $prepend Defaults to 'nstab-'
3392 * @return string XML 'id' name
3394 public function getNamespaceKey( $prepend = 'nstab-' ) {
3395 // Gets the subject namespace of this title
3396 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
3397 $subjectNS = $nsInfo->getSubject( $this->mNamespace );
3398 // Prefer canonical namespace name for HTML IDs
3399 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
3400 if ( $namespaceKey === false ) {
3401 // Fallback to localised text
3402 $namespaceKey = $this->getSubjectNsText();
3404 // Makes namespace key lowercase
3405 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
3406 // Uses main
3407 if ( $namespaceKey == '' ) {
3408 $namespaceKey = 'main';
3410 // Changes file to image for backwards compatibility
3411 if ( $namespaceKey == 'file' ) {
3412 $namespaceKey = 'image';
3414 return $prepend . $namespaceKey;
3418 * Get all extant redirects to this Title
3420 * @param int|null $ns Single namespace to consider; null to consider all namespaces
3421 * @return Title[]
3423 public function getRedirectsHere( $ns = null ) {
3424 $redirs = [];
3426 $queryBuilder = $this->getDbProvider()->getReplicaDatabase()->newSelectQueryBuilder()
3427 ->select( [ 'page_namespace', 'page_title' ] )
3428 ->from( 'redirect' )
3429 ->join( 'page', null, 'rd_from = page_id' )
3430 ->where( [
3431 'rd_namespace' => $this->mNamespace,
3432 'rd_title' => $this->mDbkeyform,
3433 'rd_interwiki' => $this->isExternal() ? $this->mInterwiki : '',
3434 ] );
3436 if ( $ns !== null ) {
3437 $queryBuilder->andWhere( [ 'page_namespace' => $ns ] );
3440 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
3442 foreach ( $res as $row ) {
3443 $redirs[] = self::newFromRow( $row );
3445 return $redirs;
3449 * Check if this Title is a valid redirect target
3451 * @return bool
3453 public function isValidRedirectTarget() {
3454 global $wgInvalidRedirectTargets;
3456 if ( $this->isSpecialPage() ) {
3457 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
3458 foreach ( [ 'Userlogout', ...$wgInvalidRedirectTargets ] as $target ) {
3459 if ( $this->isSpecial( $target ) ) {
3460 return false;
3463 return true;
3466 // relative section links are not valid redirect targets (T278367)
3467 return $this->getDBkey() !== '' && $this->isValid();
3471 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
3473 * @return bool
3475 public function canUseNoindex() {
3476 global $wgExemptFromUserRobotsControl;
3478 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
3479 MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
3481 return !in_array( $this->mNamespace, $bannedNamespaces );
3485 * Returns the raw sort key to be used for categories, with the specified
3486 * prefix. This will be fed to Collation::getSortKey() to get a
3487 * binary sortkey that can be used for actual sorting.
3489 * @param string $prefix The prefix to be used, specified using
3490 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
3491 * prefix.
3492 * @return string
3494 public function getCategorySortkey( $prefix = '' ) {
3495 $unprefixed = $this->getText();
3497 // Anything that uses this hook should only depend
3498 // on the Title object passed in, and should probably
3499 // tell the users to run updateCollations.php --force
3500 // in order to re-sort existing category relations.
3501 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
3502 ->onGetDefaultSortkey( $this, $unprefixed );
3503 if ( $prefix !== '' ) {
3504 # Separate with a line feed, so the unprefixed part is only used as
3505 # a tiebreaker when two pages have the exact same prefix.
3506 # In UCA, tab is the only character that can sort above LF
3507 # so we strip both of them from the original prefix.
3508 $prefix = strtr( $prefix, "\n\t", ' ' );
3509 return "$prefix\n$unprefixed";
3511 return $unprefixed;
3515 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
3516 * to true in LocalSettings.php, otherwise returns null. If there is no language saved in
3517 * the database, it will return null.
3519 * @param int $flags
3521 * @return ?string
3523 private function getDbPageLanguageCode( int $flags = 0 ): ?string {
3524 global $wgPageLanguageUseDB;
3526 // check, if the page language could be saved in the database, and if so and
3527 // the value is not requested already, lookup the page language using PageStore
3528 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
3529 $this->mDbPageLanguage = $this->getFieldFromPageStore( 'page_lang', $flags ) ?: null;
3532 return $this->mDbPageLanguage ?: null;
3536 * Returns the Language object from the page language code saved in the database.
3537 * If $wgPageLanguageUseDB is set to false or there is no language saved in the database
3538 * or the language code in the database is invalid or unsupported, it will return null.
3540 * @return Language|null
3542 private function getDbPageLanguage(): ?Language {
3543 $languageCode = $this->getDbPageLanguageCode();
3544 if ( $languageCode === null ) {
3545 return null;
3547 $services = MediaWikiServices::getInstance();
3548 if ( !$services->getLanguageNameUtils()->isKnownLanguageTag( $languageCode ) ) {
3549 return null;
3551 return $services->getLanguageFactory()->getLanguage( $languageCode );
3555 * Get the language in which the content of this page is written in
3556 * wikitext. Defaults to content language, but in certain cases it can be
3557 * e.g. $wgLang (such as special pages, which are in the user language).
3559 * @since 1.18
3560 * @return Language
3562 public function getPageLanguage() {
3563 global $wgLanguageCode;
3564 if ( $this->isSpecialPage() ) {
3565 // special pages are in the user language
3566 return RequestContext::getMain()->getLanguage();
3569 // Checking if DB language is set
3570 $dbPageLanguage = $this->getDbPageLanguage();
3571 if ( $dbPageLanguage ) {
3572 return $dbPageLanguage;
3575 $services = MediaWikiServices::getInstance();
3576 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
3577 // Note that this may depend on user settings, so the cache should
3578 // be only per-request.
3579 // NOTE: ContentHandler::getPageLanguage() may need to load the
3580 // content to determine the page language!
3581 // Checking $wgLanguageCode hasn't changed for the benefit of unit
3582 // tests.
3583 $contentHandler = $services->getContentHandlerFactory()
3584 ->getContentHandler( $this->getContentModel() );
3585 $langObj = $contentHandler->getPageLanguage( $this );
3586 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
3587 } else {
3588 $langObj = $services->getLanguageFactory()
3589 ->getLanguage( $this->mPageLanguage[0] );
3592 return $langObj;
3596 * Get the language in which the content of this page is written when
3597 * viewed by user. Defaults to content language, but in certain cases it can be
3598 * e.g. the user language (such as special pages).
3600 * @deprecated since 1.42 Use ParserOutput::getLanguage instead. See also OutputPage::getContLangForJS.
3601 * Hard-deprecated since 1.43.
3602 * @since 1.20
3603 * @return Language
3605 public function getPageViewLanguage() {
3606 wfDeprecated( __METHOD__, '1.42' );
3607 $services = MediaWikiServices::getInstance();
3609 if ( $this->isSpecialPage() ) {
3610 // If the user chooses a variant, the content is actually
3611 // in a language whose code is the variant code.
3612 $userLang = RequestContext::getMain()->getLanguage();
3613 $variant = $this->getLanguageConverter( $userLang )->getPreferredVariant();
3614 if ( $userLang->getCode() !== $variant ) {
3615 return $services->getLanguageFactory()
3616 ->getLanguage( $variant );
3619 return $userLang;
3622 // Checking if DB language is set
3623 $pageLang = $this->getDbPageLanguage();
3624 if ( $pageLang ) {
3625 $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
3626 if ( $pageLang->getCode() !== $variant ) {
3627 return $services->getLanguageFactory()
3628 ->getLanguage( $variant );
3631 return $pageLang;
3634 // @note Can't be cached persistently, depends on user settings.
3635 // @note ContentHandler::getPageViewLanguage() may need to load the
3636 // content to determine the page language!
3637 $contentHandler = $services->getContentHandlerFactory()
3638 ->getContentHandler( $this->getContentModel() );
3639 $pageLang = $contentHandler->getPageViewLanguage( $this );
3640 return $pageLang;
3644 * Get a list of rendered edit notices for this page.
3646 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
3647 * they will already be wrapped in paragraphs.
3649 * @since 1.21
3650 * @param int $oldid Revision ID that's being edited
3651 * @return string[]
3653 public function getEditNotices( $oldid = 0 ) {
3654 $notices = [];
3656 $editnotice_base = 'editnotice-' . $this->mNamespace;
3657 // Optional notice for the entire namespace
3658 $messages = [ $editnotice_base => 'namespace' ];
3660 if (
3661 MediaWikiServices::getInstance()->getNamespaceInfo()->
3662 hasSubpages( $this->mNamespace )
3664 // Optional notice for page itself and any parent page
3665 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
3666 $editnotice_base .= '-' . $part;
3667 $messages[$editnotice_base] = 'base';
3669 } else {
3670 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
3671 $messages[$editnotice_base . '-' . strtr( $this->mDbkeyform, '/', '-' )] = 'page';
3674 foreach ( $messages as $editnoticeText => $class ) {
3675 // The following messages are used here:
3676 // * editnotice-0
3677 // * editnotice-0-Title
3678 // * editnotice-0-Title-Subpage
3679 // * editnotice-…
3680 $msg = wfMessage( $editnoticeText )->page( $this );
3681 if ( $msg->exists() ) {
3682 $html = $msg->parseAsBlock();
3683 // Edit notices may have complex logic, but output nothing (T91715)
3684 if ( trim( $html ) !== '' ) {
3685 $notices[$editnoticeText] = Html::rawElement(
3686 'div',
3687 [ 'class' => [
3688 'mw-editnotice',
3689 // The following classes are used here:
3690 // * mw-editnotice-namespace
3691 // * mw-editnotice-base
3692 // * mw-editnotice-page
3693 "mw-editnotice-$class",
3694 // The following classes are used here:
3695 // * mw-editnotice-0
3696 // * mw-editnotice-…
3697 Sanitizer::escapeClass( "mw-$editnoticeText" )
3698 ] ],
3699 $html
3705 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
3706 ->onTitleGetEditNotices( $this, $oldid, $notices );
3707 return $notices;
3711 * @param string $field
3712 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
3713 * @return string|false
3715 private function getFieldFromPageStore( $field, $flags ) {
3716 $pageStore = MediaWikiServices::getInstance()->getPageStore();
3718 if ( !in_array( $field, $pageStore->getSelectFields(), true ) ) {
3719 throw new InvalidArgumentException( "Unknown field: $field" );
3722 if ( $flags === IDBAccessObject::READ_NORMAL && $this->mArticleID === 0 ) {
3723 // page does not exist
3724 return false;
3727 if ( !$this->canExist() ) {
3728 return false;
3731 $page = $pageStore->getPageByReference( $this, $flags );
3733 if ( $page instanceof PageStoreRecord ) {
3734 return $page->getField( $field );
3735 } else {
3736 // The page record failed to load, remember the page as non-existing.
3737 // Note that this can happen even if a page ID was known before under some
3738 // rare circumstances, if this method is called with the READ_LATEST bit set
3739 // and the page has been deleted since the ID had initially been determined.
3740 $this->mArticleID = 0;
3741 return false;
3746 * @return array
3748 public function __sleep() {
3749 return [
3750 'mNamespace',
3751 'mDbkeyform',
3752 'mFragment',
3753 'mInterwiki',
3754 'mLocalInterwiki',
3758 public function __wakeup() {
3759 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
3760 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3761 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3764 public function __clone() {
3765 $this->mInstanceCacheKey = null;
3769 * Returns false to indicate that this Title belongs to the local wiki.
3771 * @note The behavior of this method is considered undefined for interwiki links.
3772 * At the moment, this method always returns false. But this may change in the future.
3774 * @since 1.36
3775 * @return string|false Always self::LOCAL
3777 public function getWikiId() {
3778 return self::LOCAL;
3782 * Returns the page ID.
3784 * If this ID is 0, this means the page does not exist.
3786 * @see getArticleID()
3787 * @since 1.36, since 1.35.6 as an alias of getArticleID()
3789 * @param string|false $wikiId The wiki ID expected by the caller.
3791 * @throws PreconditionException if this Title instance does not represent a proper page,
3792 * that is, if it is a section link, interwiki link, link to a special page, or such.
3793 * @throws PreconditionException if $wikiId is not false.
3795 * @return int
3797 public function getId( $wikiId = self::LOCAL ): int {
3798 $this->assertWiki( $wikiId );
3799 $this->assertProperPage();
3800 return $this->getArticleID();
3804 * Code that requires this Title to be a "proper page" in the sense
3805 * defined by PageIdentity should call this method.
3807 * For the purpose of the Title class, a proper page is one that can
3808 * exist in the page table. That is, a Title represents a proper page
3809 * if canExist() returns true.
3811 * @see canExist()
3813 * @throws PreconditionException
3815 private function assertProperPage() {
3816 Assert::precondition(
3817 $this->canExist(),
3818 'This Title instance does not represent a proper page, but merely a link target.'
3823 * Returns the page represented by this Title as a ProperPageIdentity.
3824 * The ProperPageIdentity returned by this method is guaranteed to be immutable.
3825 * If this Title does not represent a proper page, an exception is thrown.
3827 * It is preferred to use this method rather than using the Title as a PageIdentity directly.
3829 * @return ProperPageIdentity
3830 * @throws PreconditionException if the page is not a proper page, that is, if it is a section
3831 * link, interwiki link, link to a special page, or such.
3832 * @since 1.36
3834 public function toPageIdentity(): ProperPageIdentity {
3835 // TODO: replace individual member fields with a PageIdentityValue that is always present
3837 $this->assertProperPage();
3839 return new PageIdentityValue(
3840 $this->getId(),
3841 $this->getNamespace(),
3842 $this->getDBkey(),
3843 $this->getWikiId()
3848 * Returns the page represented by this Title as a ProperPageRecord.
3849 * The PageRecord returned by this method is guaranteed to be immutable,
3850 * the page is guaranteed to exist.
3852 * @note For now, this method queries the database on every call.
3853 * @since 1.36
3855 * @param int $flags A bitfield of IDBAccessObject::READ_* constants
3857 * @return ExistingPageRecord
3858 * @throws PreconditionException if the page does not exist, or is not a proper page,
3859 * that is, if it is a section link, interwiki link, link to a special page, or such.
3861 public function toPageRecord( $flags = 0 ): ExistingPageRecord {
3862 // TODO: Cache this? Construct is more efficiently?
3864 $this->assertProperPage();
3866 Assert::precondition(
3867 $this->exists( $flags ),
3868 'This Title instance does not represent an existing page: ' . $this
3871 return new PageStoreRecord(
3872 (object)[
3873 'page_id' => $this->getArticleID( $flags ),
3874 'page_namespace' => $this->getNamespace(),
3875 'page_title' => $this->getDBkey(),
3876 'page_wiki_id' => $this->getWikiId(),
3877 'page_latest' => $this->getLatestRevID( $flags ),
3878 'page_is_new' => $this->isNewPage( $flags ),
3879 'page_is_redirect' => $this->isRedirect( $flags ),
3880 'page_touched' => $this->getTouched( $flags ),
3881 'page_lang' => $this->getDbPageLanguageCode( $flags ),
3883 PageIdentity::LOCAL
3889 /** @deprecated class alias since 1.40 */
3890 class_alias( Title::class, 'Title' );