Title::convertByteClassToUnicodeClass(): Cleanup
[mediawiki.git] / includes / Title.php
blob7fd775f82d851da13e1426cfb94ca4d318a5365b
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 use MediaWiki\Interwiki\InterwikiLookup;
26 use MediaWiki\Linker\LinkTarget;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\User\UserIdentity;
29 use Wikimedia\Assert\Assert;
30 use Wikimedia\Rdbms\Database;
31 use Wikimedia\Rdbms\IDatabase;
33 /**
34 * Represents a title within MediaWiki.
35 * Optionally may contain an interwiki designation or namespace.
36 * @note This class can fetch various kinds of data from the database;
37 * however, it does so inefficiently.
38 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
39 * and does not rely on global state or the database.
41 class Title implements LinkTarget, IDBAccessObject {
42 /** @var MapCacheLRU|null */
43 private static $titleCache = null;
45 /**
46 * Title::newFromText maintains a cache to avoid expensive re-normalization of
47 * commonly used titles. On a batch operation this can become a memory leak
48 * if not bounded. After hitting this many titles reset the cache.
50 private const CACHE_MAX = 1000;
52 /**
53 * Used to be GAID_FOR_UPDATE define(). Used with getArticleID() and friends
54 * to use the master DB and inject it into link cache.
55 * @deprecated since 1.34, use Title::READ_LATEST instead.
57 public const GAID_FOR_UPDATE = 512;
59 /**
60 * Flag for use with factory methods like newFromLinkTarget() that have
61 * a $forceClone parameter. If set, the method must return a new instance.
62 * Without this flag, some factory methods may return existing instances.
64 * @since 1.33
66 public const NEW_CLONE = 'clone';
68 /***************************************************************************/
69 // region Private member variables
70 /** @name Private member variables
71 * Please use the accessor functions instead.
72 * @internal
73 * @{
76 /** @var string Text form (spaces not underscores) of the main part */
77 public $mTextform = '';
78 /** @var string URL-encoded form of the main part */
79 public $mUrlform = '';
80 /** @var string Main part with underscores */
81 public $mDbkeyform = '';
82 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
83 public $mNamespace = NS_MAIN;
84 /** @var string Interwiki prefix */
85 public $mInterwiki = '';
86 /** @var bool Was this Title created from a string with a local interwiki prefix? */
87 private $mLocalInterwiki = false;
88 /** @var string Title fragment (i.e. the bit after the #) */
89 public $mFragment = '';
91 /** @var int Article ID, fetched from the link cache on demand */
92 public $mArticleID = -1;
94 /** @var bool|int ID of most recent revision */
95 protected $mLatestID = false;
97 /**
98 * @var bool|string ID of the page's content model, i.e. one of the
99 * CONTENT_MODEL_XXX constants
101 private $mContentModel = false;
104 * @var bool If a content model was forced via setContentModel()
105 * this will be true to avoid having other code paths reset it
107 private $mForcedContentModel = false;
109 /** @var int Estimated number of revisions; null of not loaded */
110 private $mEstimateRevisions;
112 /** @var array Array of groups allowed to edit this article */
113 public $mRestrictions = [];
116 * @var string|bool Comma-separated set of permission keys
117 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
118 * Edit and move sections are separated by a colon
119 * Example: "edit=autoconfirmed,sysop:move=sysop"
121 protected $mOldRestrictions = false;
123 /** @var bool Cascade restrictions on this page to included templates and images? */
124 public $mCascadeRestriction;
126 /** Caching the results of getCascadeProtectionSources */
127 public $mCascadingRestrictions;
129 /** @var array When do the restrictions on this page expire? */
130 protected $mRestrictionsExpiry = [];
132 /** @var bool Are cascading restrictions in effect on this page? */
133 protected $mHasCascadingRestrictions;
135 /** @var array Where are the cascading restrictions coming from on this page? */
136 public $mCascadeSources;
138 /** @var bool Boolean for initialisation on demand */
139 public $mRestrictionsLoaded = false;
142 * Text form including namespace/interwiki, initialised on demand
144 * Only public to share cache with TitleFormatter
146 * @internal
147 * @var string|null
149 public $prefixedText = null;
151 /** @var mixed Cached value for getTitleProtection (create protection) */
152 public $mTitleProtection;
155 * @var int Namespace index when there is no namespace. Don't change the
156 * following default, NS_MAIN is hardcoded in several places. See T2696.
157 * Used primarily for {{transclusion}} tags.
158 * @see newFromText()
160 public $mDefaultNamespace = NS_MAIN;
162 /** @var int The page length, 0 for special pages */
163 protected $mLength = -1;
165 /** @var null|bool Is the article at this title a redirect? */
166 public $mRedirect = null;
168 /** @var bool Whether a page has any subpages */
169 private $mHasSubpages;
171 /** @var array|null The (string) language code of the page's language and content code. */
172 private $mPageLanguage;
174 /** @var string|bool|null The page language code from the database, null if not saved in
175 * the database or false if not loaded, yet.
177 private $mDbPageLanguage = false;
179 /** @var TitleValue|null A corresponding TitleValue object */
180 private $mTitleValue = null;
182 /** @var bool|null Would deleting this page be a big deletion? */
183 private $mIsBigDeletion = null;
185 /** @var bool|null Is the title known to be valid? */
186 private $mIsValid = null;
188 // endregion -- end of private member variables
189 /** @} */
190 /***************************************************************************/
193 * Shorthand for getting a Language Converter for specific language
194 * @param Language $language Language of converter
195 * @return ILanguageConverter
197 private function getLanguageConverter( $language ) : ILanguageConverter {
198 return MediaWikiServices::getInstance()->getLanguageConverterFactory()
199 ->getLanguageConverter( $language );
203 * Shorthand for getting a Language Converter for page's language
204 * @return ILanguageConverter
206 private function getPageLanguageConverter() : ILanguageConverter {
207 return $this->getLanguageConverter( $this->getPageLanguage() );
211 * B/C kludge: provide a TitleParser for use by Title.
212 * Ideally, Title would have no methods that need this.
213 * Avoid usage of this singleton by using TitleValue
214 * and the associated services when possible.
216 * @return TitleFormatter
218 private static function getTitleFormatter() {
219 return MediaWikiServices::getInstance()->getTitleFormatter();
223 * B/C kludge: provide an InterwikiLookup for use by Title.
224 * Ideally, Title would have no methods that need this.
225 * Avoid usage of this singleton by using TitleValue
226 * and the associated services when possible.
228 * @return InterwikiLookup
230 private static function getInterwikiLookup() {
231 return MediaWikiServices::getInstance()->getInterwikiLookup();
234 private function __construct() {
238 * Create a new Title from a prefixed DB key
240 * @param string $key The database key, which has underscores
241 * instead of spaces, possibly including namespace and
242 * interwiki prefixes
243 * @return Title|null Title, or null on an error
245 public static function newFromDBkey( $key ) {
246 $t = new self();
248 try {
249 $t->secureAndSplit( $key );
250 return $t;
251 } catch ( MalformedTitleException $ex ) {
252 return null;
257 * Returns a Title given a TitleValue.
258 * If the given TitleValue is already a Title instance, that instance is returned,
259 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
260 * is already a Title instance, that instance is copied using the clone operator.
262 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
264 * @param TitleValue $titleValue Assumed to be safe.
265 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
267 * @return Title
269 public static function newFromTitleValue( TitleValue $titleValue, $forceClone = '' ) {
270 return self::newFromLinkTarget( $titleValue, $forceClone );
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 * @param LinkTarget $linkTarget Assumed to be safe.
280 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
282 * @return Title
284 public static function newFromLinkTarget( LinkTarget $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 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
306 * @return Title|null
308 public static function castFromLinkTarget( $linkTarget ) {
309 return $linkTarget ? self::newFromLinkTarget( $linkTarget ) : null;
313 * Create a new Title from text, such as what one would find in a link.
314 * Decodes any HTML entities in the text.
315 * Titles returned by this method are guaranteed to be valid.
316 * Call canExist() to check if the Title represents an editable page.
318 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
319 * It may instead be a cached instance created previously, with references to it remaining
320 * elsewhere.
322 * @param string|int|null $text The link text; spaces, prefixes, and an
323 * initial ':' indicating the main namespace are accepted.
324 * @param int $defaultNamespace The namespace to use if none is specified
325 * by a prefix. If you want to force a specific namespace even if
326 * $text might begin with a namespace prefix, use makeTitle() or
327 * makeTitleSafe().
328 * @throws InvalidArgumentException
329 * @return Title|null Title or null if the Title could not be parsed because
330 * it is invalid.
332 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
333 // DWIM: Integers can be passed in here when page titles are used as array keys.
334 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
335 throw new InvalidArgumentException( '$text must be a string.' );
337 if ( $text === null ) {
338 return null;
341 try {
342 return self::newFromTextThrow( (string)$text, (int)$defaultNamespace );
343 } catch ( MalformedTitleException $ex ) {
344 return null;
349 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
350 * rather than returning null.
352 * Titles returned by this method are guaranteed to be valid.
353 * Call canExist() to check if the Title represents an editable page.
355 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
356 * It may instead be a cached instance created previously, with references to it remaining
357 * elsewhere.
359 * @see Title::newFromText
361 * @since 1.25
362 * @param string $text Title text to check
363 * @param int $defaultNamespace
364 * @throws MalformedTitleException If the title is invalid.
365 * @return Title
367 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
368 if ( is_object( $text ) ) {
369 throw new MWException( '$text must be a string, given an object' );
370 } elseif ( $text === null ) {
371 // Legacy code relies on MalformedTitleException being thrown in this case
372 // (happens when URL with no title in it is parsed). TODO fix
373 throw new MalformedTitleException( 'title-invalid-empty' );
376 $titleCache = self::getTitleCache();
378 // Wiki pages often contain multiple links to the same page.
379 // Title normalization and parsing can become expensive on pages with many
380 // links, so we can save a little time by caching them.
381 // In theory these are value objects and won't get changed...
382 if ( $defaultNamespace === NS_MAIN ) {
383 $t = $titleCache->get( $text );
384 if ( $t ) {
385 return $t;
389 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
390 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
392 $t = new Title();
393 $dbKeyForm = strtr( $filteredText, ' ', '_' );
395 $t->secureAndSplit( $dbKeyForm, (int)$defaultNamespace );
396 if ( $defaultNamespace === NS_MAIN ) {
397 $titleCache->set( $text, $t );
399 return $t;
403 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
405 * Example of wrong and broken code:
406 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
408 * Example of right code:
409 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
411 * Create a new Title from URL-encoded text. Ensures that
412 * the given title's length does not exceed the maximum.
414 * @param string $url The title, as might be taken from a URL
415 * @return Title|null The new object, or null on an error
417 public static function newFromURL( $url ) {
418 $t = new Title();
420 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
421 # but some URLs used it as a space replacement and they still come
422 # from some external search tools.
423 if ( strpos( self::legalChars(), '+' ) === false ) {
424 $url = strtr( $url, '+', ' ' );
427 $dbKeyForm = strtr( $url, ' ', '_' );
429 try {
430 $t->secureAndSplit( $dbKeyForm );
431 return $t;
432 } catch ( MalformedTitleException $ex ) {
433 return null;
438 * @return MapCacheLRU
440 private static function getTitleCache() {
441 if ( self::$titleCache === null ) {
442 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
444 return self::$titleCache;
448 * Returns a list of fields that are to be selected for initializing Title
449 * objects or LinkCache entries.
451 * @return array
453 protected static function getSelectFields() {
454 global $wgPageLanguageUseDB;
456 $fields = [
457 'page_namespace', 'page_title', 'page_id',
458 'page_len', 'page_is_redirect', 'page_latest',
459 'page_content_model',
462 if ( $wgPageLanguageUseDB ) {
463 $fields[] = 'page_lang';
466 return $fields;
470 * Create a new Title from an article ID
472 * @param int $id The page_id corresponding to the Title to create
473 * @param int $flags Bitfield of class READ_* constants
474 * @return Title|null The new object, or null on an error
476 public static function newFromID( $id, $flags = 0 ) {
477 $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
478 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
479 $row = wfGetDB( $index )->selectRow(
480 'page',
481 self::getSelectFields(),
482 [ 'page_id' => $id ],
483 __METHOD__,
484 $options
486 if ( $row !== false ) {
487 $title = self::newFromRow( $row );
488 } else {
489 $title = null;
492 return $title;
496 * Make an array of titles from an array of IDs
498 * @param int[] $ids Array of IDs
499 * @return Title[] Array of Titles
501 public static function newFromIDs( $ids ) {
502 if ( !count( $ids ) ) {
503 return [];
505 $dbr = wfGetDB( DB_REPLICA );
507 $res = $dbr->select(
508 'page',
509 self::getSelectFields(),
510 [ 'page_id' => $ids ],
511 __METHOD__
514 $titles = [];
515 foreach ( $res as $row ) {
516 $titles[] = self::newFromRow( $row );
518 return $titles;
522 * Make a Title object from a DB row
524 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
525 * @return Title Corresponding Title
527 public static function newFromRow( $row ) {
528 $t = self::makeTitle( $row->page_namespace, $row->page_title );
529 $t->loadFromRow( $row );
530 return $t;
534 * Load Title object fields from a DB row.
535 * If false is given, the title will be treated as non-existing.
537 * @param stdClass|bool $row Database row
539 public function loadFromRow( $row ) {
540 if ( $row ) { // page found
541 if ( isset( $row->page_id ) ) {
542 $this->mArticleID = (int)$row->page_id;
544 if ( isset( $row->page_len ) ) {
545 $this->mLength = (int)$row->page_len;
547 if ( isset( $row->page_is_redirect ) ) {
548 $this->mRedirect = (bool)$row->page_is_redirect;
550 if ( isset( $row->page_latest ) ) {
551 $this->mLatestID = (int)$row->page_latest;
553 if ( isset( $row->page_content_model ) ) {
554 $this->lazyFillContentModel( $row->page_content_model );
555 } else {
556 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
558 if ( isset( $row->page_lang ) ) {
559 $this->mDbPageLanguage = (string)$row->page_lang;
561 if ( isset( $row->page_restrictions ) ) {
562 $this->mOldRestrictions = $row->page_restrictions;
564 } else { // page not found
565 $this->mArticleID = 0;
566 $this->mLength = 0;
567 $this->mRedirect = false;
568 $this->mLatestID = 0;
569 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
574 * Create a new Title from a namespace index and a DB key.
576 * It's assumed that $ns and $title are safe, for instance when
577 * they came directly from the database or a special page name,
578 * not from user input.
580 * No validation is applied. For convenience, spaces are normalized
581 * to underscores, so that e.g. user_text fields can be used directly.
583 * @note This method may return Title objects that are "invalid"
584 * according to the isValid() method. This is usually caused by
585 * configuration changes: e.g. a namespace that was once defined is
586 * no longer configured, or a character that was once allowed in
587 * titles is now forbidden.
589 * @param int $ns The namespace of the article
590 * @param string $title The unprefixed database key form
591 * @param string $fragment The link fragment (after the "#")
592 * @param string $interwiki The interwiki prefix
593 * @return Title The new object
595 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
596 $t = new Title();
597 $t->mInterwiki = $interwiki;
598 $t->mFragment = $fragment;
599 $t->mNamespace = $ns = (int)$ns;
600 $t->mDbkeyform = strtr( $title, ' ', '_' );
601 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
602 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
603 $t->mTextform = strtr( $title, '_', ' ' );
604 return $t;
608 * Create a new Title from a namespace index and a DB key.
609 * The parameters will be checked for validity, which is a bit slower
610 * than makeTitle() but safer for user-provided data.
612 * The Title object returned by this method is guaranteed to be valid.
613 * Call canExist() to check if the Title represents an editable page.
615 * @param int $ns The namespace of the article
616 * @param string $title Database key form
617 * @param string $fragment The link fragment (after the "#")
618 * @param string $interwiki Interwiki prefix
619 * @return Title|null The new object, or null on an error
621 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
622 // NOTE: ideally, this would just call makeTitle() and then isValid(),
623 // but presently, that means more overhead on a potential performance hotspot.
625 if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
626 return null;
629 $t = new Title();
630 $dbKeyForm = self::makeName( $ns, $title, $fragment, $interwiki, true );
632 try {
633 $t->secureAndSplit( $dbKeyForm );
634 return $t;
635 } catch ( MalformedTitleException $ex ) {
636 return null;
641 * Create a new Title for the Main Page
643 * This uses the 'mainpage' interface message, which could be specified in
644 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
645 * will use the user language, which would involve initialising the session
646 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
647 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
648 * or ResourceloaderContext) to prevent an error.
650 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
651 * It may instead be a cached instance created previously, with references to it remaining
652 * elsewhere.
654 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
655 * @return Title
657 public static function newMainPage( MessageLocalizer $localizer = null ) {
658 if ( $localizer ) {
659 $msg = $localizer->msg( 'mainpage' );
660 } else {
661 $msg = wfMessage( 'mainpage' );
664 $title = self::newFromText( $msg->inContentLanguage()->text() );
666 // Every page renders at least one link to the Main Page (e.g. sidebar).
667 // If the localised value is invalid, don't produce fatal errors that
668 // would make the wiki inaccessible (and hard to fix the invalid message).
669 // Gracefully fallback...
670 if ( !$title ) {
671 $title = self::newFromText( 'Main Page' );
673 return $title;
677 * Get the prefixed DB key associated with an ID
679 * @param int $id The page_id of the article
680 * @return string|null An object representing the article, or null if no such article was found
681 * @deprecated since 1.36, use Title::newFromID( $id )->getPrefixedDBkey() instead.
683 public static function nameOf( $id ) {
684 wfDeprecated( __METHOD__, '1.36' );
686 $dbr = wfGetDB( DB_REPLICA );
688 $s = $dbr->selectRow(
689 'page',
690 [ 'page_namespace', 'page_title' ],
691 [ 'page_id' => $id ],
692 __METHOD__
694 if ( $s === false ) {
695 return null;
698 return self::makeName( $s->page_namespace, $s->page_title );
702 * Get a regex character class describing the legal characters in a link
704 * @return string The list of characters, not delimited
706 public static function legalChars() {
707 global $wgLegalTitleChars;
708 return $wgLegalTitleChars;
712 * Utility method for converting a character sequence from bytes to Unicode.
714 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
715 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
717 * @param string $byteClass
718 * @return string
720 public static function convertByteClassToUnicodeClass( $byteClass ) {
721 $length = strlen( $byteClass );
722 // Input token queue
723 $x0 = $x1 = $x2 = '';
724 // Decoded queue
725 $d0 = $d1 = '';
726 // Decoded integer codepoints
727 $ord0 = $ord1 = $ord2 = 0;
728 // Re-encoded queue
729 $r0 = $r1 = $r2 = '';
730 // Output
731 $out = '';
732 // Flags
733 $allowUnicode = false;
734 for ( $pos = 0; $pos < $length; $pos++ ) {
735 // Shift the queues down
736 $x2 = $x1;
737 $x1 = $x0;
738 $d1 = $d0;
739 $ord2 = $ord1;
740 $ord1 = $ord0;
741 $r2 = $r1;
742 $r1 = $r0;
743 // Load the current input token and decoded values
744 $inChar = $byteClass[$pos];
745 if ( $inChar === '\\' ) {
746 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
747 $x0 = $inChar . $m[0];
748 $d0 = chr( hexdec( $m[1] ) );
749 $pos += strlen( $m[0] );
750 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
751 $x0 = $inChar . $m[0];
752 $d0 = chr( octdec( $m[0] ) );
753 $pos += strlen( $m[0] );
754 } elseif ( $pos + 1 >= $length ) {
755 $x0 = $d0 = '\\';
756 } else {
757 $d0 = $byteClass[$pos + 1];
758 $x0 = $inChar . $d0;
759 $pos++;
761 } else {
762 $x0 = $d0 = $inChar;
764 $ord0 = ord( $d0 );
765 // Load the current re-encoded value
766 if ( $ord0 < 32 || $ord0 == 0x7f ) {
767 $r0 = sprintf( '\x%02x', $ord0 );
768 } elseif ( $ord0 >= 0x80 ) {
769 // Allow unicode if a single high-bit character appears
770 $r0 = sprintf( '\x%02x', $ord0 );
771 $allowUnicode = true;
772 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
773 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
774 $r0 = '\\' . $d0;
775 } else {
776 $r0 = $d0;
778 // Do the output
779 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
780 // Range
781 if ( $ord2 > $ord0 ) {
782 // Empty range
783 } elseif ( $ord0 >= 0x80 ) {
784 // Unicode range
785 $allowUnicode = true;
786 if ( $ord2 < 0x80 ) {
787 // Keep the non-unicode section of the range
788 $out .= "$r2-\\x7F";
790 } else {
791 // Normal range
792 $out .= "$r2-$r0";
794 // Reset state to the initial value
795 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
796 } elseif ( $ord2 < 0x80 ) {
797 // ASCII character
798 $out .= $r2;
801 // @phan-suppress-next-line PhanSuspiciousValueComparison
802 if ( $ord1 < 0x80 ) {
803 $out .= $r1;
805 if ( $ord0 < 0x80 ) {
806 $out .= $r0;
808 if ( $allowUnicode ) {
809 $out .= '\u0080-\uFFFF';
811 return $out;
815 * Make a prefixed DB key from a DB key and a namespace index
817 * @param int $ns Numerical representation of the namespace
818 * @param string $title The DB key form the title
819 * @param string $fragment The link fragment (after the "#")
820 * @param string $interwiki The interwiki prefix
821 * @param bool $canonicalNamespace If true, use the canonical name for
822 * $ns instead of the localized version.
823 * @return string The prefixed form of the title
825 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
826 $canonicalNamespace = false
828 if ( $canonicalNamespace ) {
829 $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
830 getCanonicalName( $ns );
831 } else {
832 $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
834 $name = $namespace == '' ? $title : "$namespace:$title";
835 if ( strval( $interwiki ) != '' ) {
836 $name = "$interwiki:$name";
838 if ( strval( $fragment ) != '' ) {
839 $name .= '#' . $fragment;
841 return $name;
845 * Callback for usort() to do title sorts by (namespace, title)
847 * @param LinkTarget $a
848 * @param LinkTarget $b
850 * @return int Result of string comparison, or namespace comparison
852 public static function compare( LinkTarget $a, LinkTarget $b ) {
853 return $a->getNamespace() <=> $b->getNamespace()
854 ?: strcmp( $a->getText(), $b->getText() );
858 * Returns true if the title is a valid link target, and that it has been
859 * properly normalized. This method checks that the title is syntactically valid,
860 * and that the namespace it refers to exists.
862 * Titles constructed using newFromText() or makeTitleSafe() are always valid.
864 * @note Code that wants to check whether the title can represent a page that can
865 * be created and edited should use canExist() instead. Examples of valid titles
866 * that cannot "exist" are Special pages, interwiki links, and on-page section links
867 * that only have the fragment part set.
869 * @see canExist()
871 * @return bool
873 public function isValid() {
874 if ( $this->mIsValid !== null ) {
875 return $this->mIsValid;
878 try {
879 $text = $this->getFullText();
880 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
882 '@phan-var MediaWikiTitleCodec $titleCodec';
883 $parts = $titleCodec->splitTitleString( $text, $this->mNamespace );
885 // Check that nothing changed!
886 // This ensures that $text was already perperly normalized.
887 if ( $parts['fragment'] !== $this->mFragment
888 || $parts['interwiki'] !== $this->mInterwiki
889 || $parts['local_interwiki'] !== $this->mLocalInterwiki
890 || $parts['namespace'] !== $this->mNamespace
891 || $parts['dbkey'] !== $this->mDbkeyform
893 $this->mIsValid = false;
894 return $this->mIsValid;
896 } catch ( MalformedTitleException $ex ) {
897 $this->mIsValid = false;
898 return $this->mIsValid;
901 $this->mIsValid = true;
902 return $this->mIsValid;
906 * Determine whether the object refers to a page within
907 * this project (either this wiki or a wiki with a local
908 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
910 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
912 public function isLocal() {
913 if ( $this->isExternal() ) {
914 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
915 if ( $iw ) {
916 return $iw->isLocal();
919 return true;
923 * Is this Title interwiki?
925 * @return bool
927 public function isExternal() {
928 return $this->mInterwiki !== '';
932 * Get the interwiki prefix
934 * Use Title::isExternal to check if a interwiki is set
936 * @return string Interwiki prefix
938 public function getInterwiki() {
939 return $this->mInterwiki;
943 * Was this a local interwiki link?
945 * @return bool
947 public function wasLocalInterwiki() {
948 return $this->mLocalInterwiki;
952 * Determine whether the object refers to a page within
953 * this project and is transcludable.
955 * @return bool True if this is transcludable
957 public function isTrans() {
958 if ( !$this->isExternal() ) {
959 return false;
962 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
966 * Returns the DB name of the distant wiki which owns the object.
968 * @return string|false The DB name
970 public function getTransWikiID() {
971 if ( !$this->isExternal() ) {
972 return false;
975 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
979 * Get a TitleValue object representing this Title.
981 * @note Not all valid Titles have a corresponding valid TitleValue
982 * (e.g. TitleValues cannot represent page-local links that have a
983 * fragment but no title text).
985 * @return TitleValue|null
987 public function getTitleValue() {
988 if ( $this->mTitleValue === null ) {
989 try {
990 $this->mTitleValue = new TitleValue(
991 $this->mNamespace,
992 $this->mDbkeyform,
993 $this->mFragment,
994 $this->mInterwiki
996 } catch ( InvalidArgumentException $ex ) {
997 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
998 $this->getPrefixedText() . ']]: ' . $ex->getMessage() );
1002 return $this->mTitleValue;
1006 * Get the text form (spaces not underscores) of the main part
1008 * @return string Main part of the title
1010 public function getText() {
1011 return $this->mTextform;
1015 * Get the URL-encoded form of the main part
1017 * @return string Main part of the title, URL-encoded
1019 public function getPartialURL() {
1020 return $this->mUrlform;
1024 * Get the main part with underscores
1026 * @return string Main part of the title, with underscores
1028 public function getDBkey() {
1029 return $this->mDbkeyform;
1033 * Get the namespace index, i.e. one of the NS_xxxx constants.
1035 * @return int Namespace index
1037 public function getNamespace() {
1038 return $this->mNamespace;
1042 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1044 * @todo Deprecate this in favor of SlotRecord::getModel()
1046 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
1047 * @return string Content model id
1049 public function getContentModel( $flags = 0 ) {
1050 if ( $this->mForcedContentModel ) {
1051 if ( !$this->mContentModel ) {
1052 throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
1054 // Content model is locked to the currently loaded one
1055 return $this->mContentModel;
1058 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
1059 $this->lazyFillContentModel( $this->loadFieldFromDB( 'page_content_model', $flags ) );
1060 } elseif (
1061 ( !$this->mContentModel || $flags & self::GAID_FOR_UPDATE ) &&
1062 $this->getArticleID( $flags )
1064 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1065 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1066 $this->lazyFillContentModel( $linkCache->getGoodLinkFieldObj( $this, 'model' ) );
1069 if ( !$this->mContentModel ) {
1070 $this->lazyFillContentModel( ContentHandler::getDefaultModelFor( $this ) );
1073 return $this->mContentModel;
1077 * Convenience method for checking a title's content model name
1079 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1080 * @return bool True if $this->getContentModel() == $id
1082 public function hasContentModel( $id ) {
1083 return $this->getContentModel() == $id;
1087 * Set a proposed content model for the page for permissions checking
1089 * This does not actually change the content model of a title in the DB.
1090 * It only affects this particular Title instance. The content model is
1091 * forced to remain this value until another setContentModel() call.
1093 * ContentHandler::canBeUsedOn() should be checked before calling this
1094 * if there is any doubt regarding the applicability of the content model
1096 * @since 1.28
1097 * @param string $model CONTENT_MODEL_XXX constant
1099 public function setContentModel( $model ) {
1100 if ( (string)$model === '' ) {
1101 throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
1104 $this->mContentModel = $model;
1105 $this->mForcedContentModel = true;
1109 * If the content model field is not frozen then update it with a retreived value
1111 * @param string|bool $model CONTENT_MODEL_XXX constant or false
1113 private function lazyFillContentModel( $model ) {
1114 if ( !$this->mForcedContentModel ) {
1115 $this->mContentModel = ( $model === false ) ? false : (string)$model;
1120 * Get the namespace text
1122 * @return string|false Namespace text
1124 public function getNsText() {
1125 if ( $this->isExternal() ) {
1126 // This probably shouldn't even happen, except for interwiki transclusion.
1127 // If possible, use the canonical name for the foreign namespace.
1128 $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
1129 getCanonicalName( $this->mNamespace );
1130 if ( $nsText !== false ) {
1131 return $nsText;
1135 try {
1136 $formatter = self::getTitleFormatter();
1137 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1138 } catch ( InvalidArgumentException $ex ) {
1139 wfDebug( __METHOD__ . ': ' . $ex->getMessage() );
1140 return false;
1145 * Get the namespace text of the subject (rather than talk) page
1147 * @return string Namespace text
1149 public function getSubjectNsText() {
1150 $services = MediaWikiServices::getInstance();
1151 return $services->getContentLanguage()->
1152 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
1156 * Get the namespace text of the talk page
1158 * @return string Namespace text
1160 public function getTalkNsText() {
1161 $services = MediaWikiServices::getInstance();
1162 return $services->getContentLanguage()->
1163 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
1167 * Can this title have a corresponding talk page?
1169 * False for relative section links (with getText() === ''),
1170 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1172 * @see NamespaceInfo::canHaveTalkPage
1173 * @since 1.30
1175 * @return bool True if this title either is a talk page or can have a talk page associated.
1177 public function canHaveTalkPage() {
1178 return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1182 * Can this title represent a page in the wiki's database?
1184 * Titles can exist as pages in the database if they are valid, and they
1185 * are not Special pages, interwiki links, or fragment-only links.
1187 * @see isValid()
1189 * @return bool true if and only if this title can be used to perform an edit.
1191 public function canExist() {
1192 // NOTE: Don't use getArticleID(), we don't want to
1193 // trigger a database query here. This check is supposed to
1194 // act as an optimization, not add extra cost.
1195 if ( $this->mArticleID > 0 ) {
1196 // It exists, so it can exist.
1197 return true;
1200 // NOTE: we call the relatively expensive isValid() method further down,
1201 // but we can bail out early if we already know the title is invalid.
1202 if ( $this->mIsValid === false ) {
1203 // It's invalid, so it can't exist.
1204 return false;
1207 if ( $this->getNamespace() < NS_MAIN ) {
1208 // It's a special page, so it can't exist in the database.
1209 return false;
1212 if ( $this->isExternal() ) {
1213 // If it's external, it's not local, so it can't exist.
1214 return false;
1217 if ( $this->getText() === '' ) {
1218 // The title has no text, so it can't exist in the database.
1219 // It's probably an on-page section link, like "#something".
1220 return false;
1223 // Double check that the title is valid.
1224 return $this->isValid();
1228 * Can this title be added to a user's watchlist?
1230 * False for relative section links (with getText() === ''),
1231 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1233 * @return bool
1235 public function isWatchable() {
1236 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
1237 return $this->getText() !== '' && !$this->isExternal() &&
1238 $nsInfo->isWatchable( $this->mNamespace );
1242 * Returns true if this is a special page.
1244 * @return bool
1246 public function isSpecialPage() {
1247 return $this->mNamespace === NS_SPECIAL;
1251 * Returns true if this title resolves to the named special page
1253 * @param string $name The special page name
1254 * @return bool
1256 public function isSpecial( $name ) {
1257 if ( $this->isSpecialPage() ) {
1258 list( $thisName, /* $subpage */ ) =
1259 MediaWikiServices::getInstance()->getSpecialPageFactory()->
1260 resolveAlias( $this->mDbkeyform );
1261 if ( $name == $thisName ) {
1262 return true;
1265 return false;
1269 * If the Title refers to a special page alias which is not the local default, resolve
1270 * the alias, and localise the name as necessary. Otherwise, return $this
1272 * @return Title
1274 public function fixSpecialName() {
1275 if ( $this->isSpecialPage() ) {
1276 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1277 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform );
1278 if ( $canonicalName ) {
1279 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1280 if ( $localName != $this->mDbkeyform ) {
1281 return self::makeTitle( NS_SPECIAL, $localName );
1285 return $this;
1289 * Returns true if the title is inside the specified namespace.
1291 * Please make use of this instead of comparing to getNamespace()
1292 * This function is much more resistant to changes we may make
1293 * to namespaces than code that makes direct comparisons.
1294 * @param int $ns The namespace
1295 * @return bool
1296 * @since 1.19
1298 public function inNamespace( $ns ) {
1299 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1300 equals( $this->mNamespace, $ns );
1304 * Returns true if the title is inside one of the specified namespaces.
1306 * @param int|int[] ...$namespaces The namespaces to check for
1307 * @return bool
1308 * @since 1.19
1310 public function inNamespaces( ...$namespaces ) {
1311 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1312 $namespaces = $namespaces[0];
1315 foreach ( $namespaces as $ns ) {
1316 if ( $this->inNamespace( $ns ) ) {
1317 return true;
1321 return false;
1325 * Returns true if the title has the same subject namespace as the
1326 * namespace specified.
1327 * For example this method will take NS_USER and return true if namespace
1328 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1329 * as their subject namespace.
1331 * This is MUCH simpler than individually testing for equivalence
1332 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1333 * @since 1.19
1334 * @param int $ns
1335 * @return bool
1337 public function hasSubjectNamespace( $ns ) {
1338 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1339 subjectEquals( $this->mNamespace, $ns );
1343 * Is this Title in a namespace which contains content?
1344 * In other words, is this a content page, for the purposes of calculating
1345 * statistics, etc?
1347 * @return bool
1349 public function isContentPage() {
1350 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1351 isContent( $this->mNamespace );
1355 * Would anybody with sufficient privileges be able to move this page?
1356 * Some pages just aren't movable.
1358 * @return bool
1360 public function isMovable() {
1361 if (
1362 !MediaWikiServices::getInstance()->getNamespaceInfo()->
1363 isMovable( $this->mNamespace ) || $this->isExternal()
1365 // Interwiki title or immovable namespace. Hooks don't get to override here
1366 return false;
1369 $result = true;
1370 Hooks::runner()->onTitleIsMovable( $this, $result );
1371 return $result;
1375 * Is this the mainpage?
1376 * @note Title::newFromText seems to be sufficiently optimized by the title
1377 * cache that we don't need to over-optimize by doing direct comparisons and
1378 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1379 * ends up reporting something differently than $title->isMainPage();
1381 * @since 1.18
1382 * @return bool
1384 public function isMainPage() {
1385 return $this->equals( self::newMainPage() );
1389 * Is this a subpage?
1391 * @return bool
1393 public function isSubpage() {
1394 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1395 hasSubpages( $this->mNamespace )
1396 ? strpos( $this->getText(), '/' ) !== false
1397 : false;
1401 * Is this a conversion table for the LanguageConverter?
1403 * @return bool
1405 public function isConversionTable() {
1406 // @todo ConversionTable should become a separate content model.
1408 return $this->mNamespace === NS_MEDIAWIKI &&
1409 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1413 * Does that page contain wikitext, or it is JS, CSS or whatever?
1415 * @return bool
1417 public function isWikitextPage() {
1418 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1422 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1423 * global UI. This is generally true for pages in the MediaWiki namespace having
1424 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1426 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1427 * for that!
1429 * Note that this method should not return true for pages that contain and show
1430 * "inactive" CSS, JSON, or JS.
1432 * @return bool
1433 * @since 1.31
1435 public function isSiteConfigPage() {
1436 return (
1437 $this->isSiteCssConfigPage()
1438 || $this->isSiteJsonConfigPage()
1439 || $this->isSiteJsConfigPage()
1444 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1446 * @return bool
1447 * @since 1.31
1449 public function isUserConfigPage() {
1450 return (
1451 $this->isUserCssConfigPage()
1452 || $this->isUserJsonConfigPage()
1453 || $this->isUserJsConfigPage()
1458 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1460 * @return string Containing skin name from .css, .json, or .js subpage title
1461 * @since 1.31
1463 public function getSkinFromConfigSubpage() {
1464 $subpage = explode( '/', $this->mTextform );
1465 $subpage = $subpage[count( $subpage ) - 1];
1466 $lastdot = strrpos( $subpage, '.' );
1467 if ( $lastdot === false ) {
1468 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1470 return substr( $subpage, 0, $lastdot );
1474 * Is this a CSS "config" sub-page of a user page?
1476 * @return bool
1477 * @since 1.31
1479 public function isUserCssConfigPage() {
1480 return (
1481 $this->mNamespace === NS_USER
1482 && $this->isSubpage()
1483 && $this->hasContentModel( CONTENT_MODEL_CSS )
1488 * Is this a JSON "config" sub-page of a user page?
1490 * @return bool
1491 * @since 1.31
1493 public function isUserJsonConfigPage() {
1494 return (
1495 $this->mNamespace === NS_USER
1496 && $this->isSubpage()
1497 && $this->hasContentModel( CONTENT_MODEL_JSON )
1502 * Is this a JS "config" sub-page of a user page?
1504 * @return bool
1505 * @since 1.31
1507 public function isUserJsConfigPage() {
1508 return (
1509 $this->mNamespace === NS_USER
1510 && $this->isSubpage()
1511 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1516 * Is this a sitewide CSS "config" page?
1518 * @return bool
1519 * @since 1.32
1521 public function isSiteCssConfigPage() {
1522 return (
1523 $this->mNamespace === NS_MEDIAWIKI
1524 && (
1525 $this->hasContentModel( CONTENT_MODEL_CSS )
1526 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1527 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1528 || substr( $this->mDbkeyform, -4 ) === '.css'
1534 * Is this a sitewide JSON "config" page?
1536 * @return bool
1537 * @since 1.32
1539 public function isSiteJsonConfigPage() {
1540 return (
1541 $this->mNamespace === NS_MEDIAWIKI
1542 && (
1543 $this->hasContentModel( CONTENT_MODEL_JSON )
1544 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1545 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1546 || substr( $this->mDbkeyform, -5 ) === '.json'
1552 * Is this a sitewide JS "config" page?
1554 * @return bool
1555 * @since 1.31
1557 public function isSiteJsConfigPage() {
1558 return (
1559 $this->mNamespace === NS_MEDIAWIKI
1560 && (
1561 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1562 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1563 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1564 || substr( $this->mDbkeyform, -3 ) === '.js'
1570 * Is this a message which can contain raw HTML?
1572 * @return bool
1573 * @since 1.32
1575 public function isRawHtmlMessage() {
1576 global $wgRawHtmlMessages;
1578 if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1579 return false;
1581 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1582 return in_array( $message, $wgRawHtmlMessages, true );
1586 * Is this a talk page of some sort?
1588 * @return bool
1590 public function isTalkPage() {
1591 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1592 isTalk( $this->mNamespace );
1596 * Get a Title object associated with the talk page of this article
1598 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1599 * with NamespaceInfo::canHaveTalkPage(). Note that the new method will
1600 * throw if asked for the talk page of a section-only link, or of an interwiki
1601 * link.
1602 * @return Title The object for the talk page
1603 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1604 * or because it's a relative link, or an interwiki link.
1606 public function getTalkPage() {
1607 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1608 // Instead of failing on invalid titles, let's just log the issue for now.
1609 // See the discussion on T227817.
1611 // Is this the same title?
1612 $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
1613 if ( $this->mNamespace == $talkNS ) {
1614 return $this;
1617 $title = self::makeTitle( $talkNS, $this->mDbkeyform );
1619 $this->warnIfPageCannotExist( $title, __METHOD__ );
1621 return $title;
1622 // TODO: replace the above with the code below:
1623 // return self::castFromLinkTarget(
1624 // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1628 * Get a Title object associated with the talk page of this article,
1629 * if such a talk page can exist.
1631 * @since 1.30
1633 * @return Title|null The object for the talk page,
1634 * or null if no associated talk page can exist, according to canHaveTalkPage().
1636 public function getTalkPageIfDefined() {
1637 if ( !$this->canHaveTalkPage() ) {
1638 return null;
1641 return $this->getTalkPage();
1645 * Get a title object associated with the subject page of this
1646 * talk page
1648 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1649 * @return Title The object for the subject page
1651 public function getSubjectPage() {
1652 // Is this the same title?
1653 $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
1654 ->getSubject( $this->mNamespace );
1655 if ( $this->mNamespace == $subjectNS ) {
1656 return $this;
1658 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1659 // Instead of failing on invalid titles, let's just log the issue for now.
1660 // See the discussion on T227817.
1661 $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
1663 $this->warnIfPageCannotExist( $title, __METHOD__ );
1665 return $title;
1666 // TODO: replace the above with the code below:
1667 // return self::castFromLinkTarget(
1668 // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1672 * @param Title $title
1673 * @param string $method
1675 * @return bool whether a warning was issued
1677 private function warnIfPageCannotExist( Title $title, $method ) {
1678 if ( $this->getText() == '' ) {
1679 wfLogWarning(
1680 $method . ': called on empty title ' . $this->getFullText() . ', returning '
1681 . $title->getFullText()
1684 return true;
1687 if ( $this->getInterwiki() !== '' ) {
1688 wfLogWarning(
1689 $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1690 . $title->getFullText()
1693 return true;
1696 return false;
1700 * Get the other title for this page, if this is a subject page
1701 * get the talk page, if it is a subject page get the talk page
1703 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1704 * @since 1.25
1705 * @throws MWException If the page doesn't have an other page
1706 * @return Title
1708 public function getOtherPage() {
1709 // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1710 // until their semantics has become exactly the same.
1711 // See the discussion on T227817.
1712 if ( $this->isSpecialPage() ) {
1713 throw new MWException( 'Special pages cannot have other pages' );
1715 if ( $this->isTalkPage() ) {
1716 return $this->getSubjectPage();
1717 } else {
1718 if ( !$this->canHaveTalkPage() ) {
1719 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1721 return $this->getTalkPage();
1723 // TODO: replace the above with the code below:
1724 // return self::castFromLinkTarget(
1725 // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1729 * Get the default namespace index, for when there is no namespace
1731 * @return int Default namespace index
1733 public function getDefaultNamespace() {
1734 return $this->mDefaultNamespace;
1738 * Get the Title fragment (i.e.\ the bit after the #) in text form
1740 * Use Title::hasFragment to check for a fragment
1742 * @return string Title fragment
1744 public function getFragment() {
1745 return $this->mFragment;
1749 * Check if a Title fragment is set
1751 * @return bool
1752 * @since 1.23
1754 public function hasFragment() {
1755 return $this->mFragment !== '';
1759 * Get the fragment in URL form, including the "#" character if there is one
1761 * @return string Fragment in URL form
1763 public function getFragmentForURL() {
1764 if ( !$this->hasFragment() ) {
1765 return '';
1766 } elseif ( $this->isExternal() ) {
1767 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1768 // so we treat it like a local interwiki.
1769 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1770 if ( $interwiki && !$interwiki->isLocal() ) {
1771 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1775 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1779 * Set the fragment for this title. Removes the first character from the
1780 * specified fragment before setting, so it assumes you're passing it with
1781 * an initial "#".
1783 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1784 * or Title::createFragmentTarget().
1785 * Still in active use privately.
1787 * @internal
1788 * @param string $fragment Text
1790 public function setFragment( $fragment ) {
1791 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1795 * Creates a new Title for a different fragment of the same page.
1797 * @since 1.27
1798 * @param string $fragment
1799 * @return Title
1801 public function createFragmentTarget( $fragment ) {
1802 return self::makeTitle(
1803 $this->mNamespace,
1804 $this->getText(),
1805 $fragment,
1806 $this->mInterwiki
1811 * Prefix some arbitrary text with the namespace or interwiki prefix
1812 * of this object
1814 * @param string $name The text
1815 * @return string The prefixed text
1817 private function prefix( $name ) {
1818 $p = '';
1819 if ( $this->isExternal() ) {
1820 $p = $this->mInterwiki . ':';
1823 if ( $this->mNamespace != 0 ) {
1824 $nsText = $this->getNsText();
1826 if ( $nsText === false ) {
1827 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1828 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1829 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1832 $p .= $nsText . ':';
1834 return $p . $name;
1838 * Get the prefixed database key form
1840 * @return string The prefixed title, with underscores and
1841 * any interwiki and namespace prefixes
1843 public function getPrefixedDBkey() {
1844 $s = $this->prefix( $this->mDbkeyform );
1845 $s = strtr( $s, ' ', '_' );
1846 return $s;
1850 * Get the prefixed title with spaces.
1851 * This is the form usually used for display
1853 * @return string The prefixed title, with spaces
1855 public function getPrefixedText() {
1856 if ( $this->prefixedText === null ) {
1857 $s = $this->prefix( $this->mTextform );
1858 $s = strtr( $s, '_', ' ' );
1859 $this->prefixedText = $s;
1861 return $this->prefixedText;
1865 * Return a string representation of this title
1867 * @return string Representation of this title
1869 public function __toString() {
1870 return $this->getPrefixedText();
1874 * Get the prefixed title with spaces, plus any fragment
1875 * (part beginning with '#')
1877 * @return string The prefixed title, with spaces and the fragment, including '#'
1879 public function getFullText() {
1880 $text = $this->getPrefixedText();
1881 if ( $this->hasFragment() ) {
1882 $text .= '#' . $this->mFragment;
1884 return $text;
1888 * Finds the first or last subpage divider (slash) in the string.
1889 * Any leading sequence of slashes is ignored, since it does not divide
1890 * two parts of the string. Considering leading slashes dividers would
1891 * result in empty root title or base title (T229443).
1893 * Note that trailing slashes are considered dividers, and empty subpage
1894 * names are allowed.
1896 * @param string $text
1897 * @param int $dir -1 for the last or +1 for the first divider.
1899 * @return false|int
1901 private function findSubpageDivider( $text, $dir ) {
1902 $top = strlen( $text ) - 1;
1903 $bottom = 0;
1905 while ( $bottom < $top && $text[$bottom] === '/' ) {
1906 $bottom++;
1909 if ( $top < $bottom ) {
1910 return false;
1913 if ( $dir > 0 ) {
1914 $idx = $bottom;
1915 while ( $idx <= $top && $text[$idx] !== '/' ) {
1916 $idx++;
1918 } else {
1919 $idx = $top;
1920 while ( $idx > $bottom && $text[$idx] !== '/' ) {
1921 $idx--;
1925 if ( $idx < $bottom || $idx > $top ) {
1926 return false;
1929 if ( $idx < 1 ) {
1930 return false;
1933 return $idx;
1937 * Whether this Title's namespace has subpages enabled.
1938 * @return bool
1940 private function hasSubpagesEnabled() {
1941 return MediaWikiServices::getInstance()->getNamespaceInfo()->
1942 hasSubpages( $this->mNamespace );
1946 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1948 * @note the return value may contain trailing whitespace and is thus
1949 * not safe for use with makeTitle or TitleValue.
1951 * @par Example:
1952 * @code
1953 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1954 * # returns: 'Foo'
1955 * @endcode
1957 * @return string Root name
1958 * @since 1.20
1960 public function getRootText() {
1961 $text = $this->getText();
1962 if ( !$this->hasSubpagesEnabled() ) {
1963 return $text;
1966 $firstSlashPos = $this->findSubpageDivider( $text, +1 );
1967 // Don't discard the real title if there's no subpage involved
1968 if ( $firstSlashPos === false ) {
1969 return $text;
1972 return substr( $text, 0, $firstSlashPos );
1976 * Get the root page name title, i.e. the leftmost part before any slashes
1978 * @par Example:
1979 * @code
1980 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1981 * # returns: Title{User:Foo}
1982 * @endcode
1984 * @return Title Root title
1985 * @since 1.20
1987 public function getRootTitle() {
1988 $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
1989 Assert::postcondition(
1990 $title !== null,
1991 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1993 return $title;
1997 * Get the base page name without a namespace, i.e. the part before the subpage name
1999 * @note the return value may contain trailing whitespace and is thus
2000 * not safe for use with makeTitle or TitleValue.
2002 * @par Example:
2003 * @code
2004 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
2005 * # returns: 'Foo/Bar'
2006 * @endcode
2008 * @return string Base name
2010 public function getBaseText() {
2011 $text = $this->getText();
2012 if ( !$this->hasSubpagesEnabled() ) {
2013 return $text;
2016 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2017 // Don't discard the real title if there's no subpage involved
2018 if ( $lastSlashPos === false ) {
2019 return $text;
2022 return substr( $text, 0, $lastSlashPos );
2026 * Get the base page name title, i.e. the part before the subpage name.
2028 * @par Example:
2029 * @code
2030 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
2031 * # returns: Title{User:Foo/Bar}
2032 * @endcode
2034 * @return Title Base title
2035 * @since 1.20
2037 public function getBaseTitle() {
2038 $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
2039 Assert::postcondition(
2040 $title !== null,
2041 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
2043 return $title;
2047 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
2049 * @par Example:
2050 * @code
2051 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
2052 * # returns: "Baz"
2053 * @endcode
2055 * @return string Subpage name
2057 public function getSubpageText() {
2058 $text = $this->getText();
2059 if ( !$this->hasSubpagesEnabled() ) {
2060 return $text;
2063 $lastSlashPos = $this->findSubpageDivider( $text, -1 );
2064 if ( $lastSlashPos === false ) {
2065 // T256922 - Return the title text if no subpages
2066 return $text;
2068 return substr( $text, $lastSlashPos + 1 );
2072 * Get the title for a subpage of the current page
2074 * @par Example:
2075 * @code
2076 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
2077 * # returns: Title{User:Foo/Bar/Baz/Asdf}
2078 * @endcode
2080 * @param string $text The subpage name to add to the title
2081 * @return Title|null Subpage title, or null on an error
2082 * @since 1.20
2084 public function getSubpage( $text ) {
2085 return self::makeTitleSafe(
2086 $this->mNamespace,
2087 $this->getText() . '/' . $text,
2089 $this->mInterwiki
2094 * Get a URL-encoded form of the subpage text
2096 * @return string URL-encoded subpage name
2098 public function getSubpageUrlForm() {
2099 $text = $this->getSubpageText();
2100 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
2101 return $text;
2105 * Get a URL-encoded title (not an actual URL) including interwiki
2107 * @return string The URL-encoded form
2109 public function getPrefixedURL() {
2110 $s = $this->prefix( $this->mDbkeyform );
2111 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2112 return $s;
2116 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
2117 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
2118 * second argument named variant. This was deprecated in favor
2119 * of passing an array of option with a "variant" key
2120 * Once $query2 is removed for good, this helper can be dropped
2121 * and the wfArrayToCgi moved to getLocalURL();
2123 * @since 1.19 (r105919)
2124 * @param array|string $query
2125 * @param string|string[]|bool $query2
2126 * @return string
2128 private static function fixUrlQueryArgs( $query, $query2 = false ) {
2129 if ( $query2 !== false ) {
2130 wfDeprecatedMsg( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
2131 "method called with a second parameter is deprecated since MediaWiki 1.19. " .
2132 "Add your parameter to an array passed as the first parameter.", "1.19" );
2134 if ( is_array( $query ) ) {
2135 $query = wfArrayToCgi( $query );
2137 if ( $query2 ) {
2138 if ( is_string( $query2 ) ) {
2139 // $query2 is a string, we will consider this to be
2140 // a deprecated $variant argument and add it to the query
2141 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
2142 } else {
2143 $query2 = wfArrayToCgi( $query2 );
2145 // If we have $query content add a & to it first
2146 if ( $query ) {
2147 $query .= '&';
2149 // Now append the queries together
2150 $query .= $query2;
2152 return $query;
2156 * Get a real URL referring to this title, with interwiki link and
2157 * fragment
2159 * @see self::getLocalURL for the arguments.
2160 * @see wfExpandUrl
2161 * @param string|array $query
2162 * @param string|string[]|bool $query2
2163 * @param string|int|null $proto Protocol type to use in URL
2164 * @return string The URL
2166 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
2167 $query = self::fixUrlQueryArgs( $query, $query2 );
2169 # Hand off all the decisions on urls to getLocalURL
2170 $url = $this->getLocalURL( $query );
2172 # Expand the url to make it a full url. Note that getLocalURL has the
2173 # potential to output full urls for a variety of reasons, so we use
2174 # wfExpandUrl instead of simply prepending $wgServer
2175 $url = wfExpandUrl( $url, $proto );
2177 # Finally, add the fragment.
2178 $url .= $this->getFragmentForURL();
2179 Hooks::runner()->onGetFullURL( $this, $url, $query );
2180 return $url;
2184 * Get a url appropriate for making redirects based on an untrusted url arg
2186 * This is basically the same as getFullUrl(), but in the case of external
2187 * interwikis, we send the user to a landing page, to prevent possible
2188 * phishing attacks and the like.
2190 * @note Uses current protocol by default, since technically relative urls
2191 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2192 * places where the url gets cached, as might pollute between
2193 * https and non-https users.
2194 * @see self::getLocalURL for the arguments.
2195 * @param array|string $query
2196 * @param string $proto Protocol type to use in URL
2197 * @return string A url suitable to use in an HTTP location header.
2199 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
2200 $target = $this;
2201 if ( $this->isExternal() ) {
2202 $target = SpecialPage::getTitleFor(
2203 'GoToInterwiki',
2204 $this->getPrefixedDBkey()
2207 return $target->getFullURL( $query, false, $proto );
2211 * Get a URL with no fragment or server name (relative URL) from a Title object.
2212 * If this page is generated with action=render, however,
2213 * $wgServer is prepended to make an absolute URL.
2215 * @see self::getFullURL to always get an absolute URL.
2216 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2217 * valid to link, locally, to the current Title.
2218 * @see self::newFromText to produce a Title object.
2220 * @param string|array $query An optional query string,
2221 * not used for interwiki links. Can be specified as an associative array as well,
2222 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2223 * Some query patterns will trigger various shorturl path replacements.
2224 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2225 * be an array. If a string is passed it will be interpreted as a deprecated
2226 * variant argument and urlencoded into a variant= argument.
2227 * This second query argument will be added to the $query
2228 * The second parameter is deprecated since 1.19. Pass it as a key,value
2229 * pair in the first parameter array instead.
2231 * @return string String of the URL.
2233 public function getLocalURL( $query = '', $query2 = false ) {
2234 global $wgArticlePath, $wgScript, $wgServer, $wgRequest, $wgMainPageIsDomainRoot;
2236 $query = self::fixUrlQueryArgs( $query, $query2 );
2238 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
2239 if ( $interwiki ) {
2240 $namespace = $this->getNsText();
2241 if ( $namespace != '' ) {
2242 # Can this actually happen? Interwikis shouldn't be parsed.
2243 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2244 $namespace .= ':';
2246 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
2247 $url = wfAppendQuery( $url, $query );
2248 } else {
2249 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2250 if ( $query == '' ) {
2251 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2252 Hooks::runner()->onGetLocalURL__Article( $this, $url );
2253 } else {
2254 global $wgVariantArticlePath, $wgActionPaths;
2255 $url = false;
2256 $matches = [];
2258 $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
2260 if ( $articlePaths
2261 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2263 $action = urldecode( $matches[2] );
2264 if ( isset( $articlePaths[$action] ) ) {
2265 $query = $matches[1];
2266 if ( isset( $matches[4] ) ) {
2267 $query .= $matches[4];
2269 $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2270 if ( $query != '' ) {
2271 $url = wfAppendQuery( $url, $query );
2276 if ( $url === false
2277 && $wgVariantArticlePath
2278 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2279 && $this->getPageLanguage()->equals(
2280 MediaWikiServices::getInstance()->getContentLanguage() )
2281 && $this->getPageLanguageConverter()->hasVariants()
2283 $variant = urldecode( $matches[1] );
2284 if ( $this->getPageLanguageConverter()->hasVariant( $variant ) ) {
2285 // Only do the variant replacement if the given variant is a valid
2286 // variant for the page's language.
2287 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2288 $url = str_replace( '$1', $dbkey, $url );
2292 if ( $url === false ) {
2293 if ( $query == '-' ) {
2294 $query = '';
2296 $url = "{$wgScript}?title={$dbkey}&{$query}";
2299 Hooks::runner()->onGetLocalURL__Internal( $this, $url, $query );
2301 // @todo FIXME: This causes breakage in various places when we
2302 // actually expected a local URL and end up with dupe prefixes.
2303 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2304 $url = $wgServer . $url;
2308 if ( $wgMainPageIsDomainRoot && $this->isMainPage() && $query === '' ) {
2309 return '/';
2312 Hooks::runner()->onGetLocalURL( $this, $url, $query );
2313 return $url;
2317 * Get a URL that's the simplest URL that will be valid to link, locally,
2318 * to the current Title. It includes the fragment, but does not include
2319 * the server unless action=render is used (or the link is external). If
2320 * there's a fragment but the prefixed text is empty, we just return a link
2321 * to the fragment.
2323 * The result obviously should not be URL-escaped, but does need to be
2324 * HTML-escaped if it's being output in HTML.
2326 * @param string|array $query
2327 * @param bool $query2
2328 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2329 * or false (default) for no expansion
2330 * @see self::getLocalURL for the arguments.
2331 * @return string The URL
2333 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2334 if ( $this->isExternal() || $proto !== false ) {
2335 $ret = $this->getFullURL( $query, $query2, $proto );
2336 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2337 $ret = $this->getFragmentForURL();
2338 } else {
2339 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2341 return $ret;
2345 * Get the URL form for an internal link.
2346 * - Used in various CDN-related code, in case we have a different
2347 * internal hostname for the server from the exposed one.
2349 * This uses $wgInternalServer to qualify the path, or $wgServer
2350 * if $wgInternalServer is not set. If the server variable used is
2351 * protocol-relative, the URL will be expanded to http://
2353 * @see self::getLocalURL for the arguments.
2354 * @param string|array $query
2355 * @param string|bool $query2 Deprecated
2356 * @return string The URL
2358 public function getInternalURL( $query = '', $query2 = false ) {
2359 global $wgInternalServer, $wgServer;
2360 $query = self::fixUrlQueryArgs( $query, $query2 );
2361 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2362 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2363 Hooks::runner()->onGetInternalURL( $this, $url, $query );
2364 return $url;
2368 * Get the URL for a canonical link, for use in things like IRC and
2369 * e-mail notifications. Uses $wgCanonicalServer and the
2370 * GetCanonicalURL hook.
2372 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2374 * @see self::getLocalURL for the arguments.
2375 * @param string|array $query
2376 * @param string|bool $query2 Deprecated
2377 * @return string The URL
2378 * @since 1.18
2380 public function getCanonicalURL( $query = '', $query2 = false ) {
2381 $query = self::fixUrlQueryArgs( $query, $query2 );
2382 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2383 Hooks::runner()->onGetCanonicalURL( $this, $url, $query );
2384 return $url;
2388 * Get the edit URL for this Title
2390 * @return string The URL, or a null string if this is an interwiki link
2392 public function getEditURL() {
2393 if ( $this->isExternal() ) {
2394 return '';
2396 $s = $this->getLocalURL( 'action=edit' );
2398 return $s;
2402 * Get a filtered list of all restriction types supported by this wiki.
2403 * @param bool $exists True to get all restriction types that apply to
2404 * titles that do exist, False for all restriction types that apply to
2405 * titles that do not exist
2406 * @return array
2408 public static function getFilteredRestrictionTypes( $exists = true ) {
2409 global $wgRestrictionTypes;
2410 $types = $wgRestrictionTypes;
2411 if ( $exists ) {
2412 # Remove the create restriction for existing titles
2413 $types = array_diff( $types, [ 'create' ] );
2414 } else {
2415 # Only the create and upload restrictions apply to non-existing titles
2416 $types = array_intersect( $types, [ 'create', 'upload' ] );
2418 return $types;
2422 * Returns restriction types for the current Title
2424 * @return array Applicable restriction types
2426 public function getRestrictionTypes() {
2427 if ( $this->isSpecialPage() ) {
2428 return [];
2431 $types = self::getFilteredRestrictionTypes( $this->exists() );
2433 if ( $this->mNamespace !== NS_FILE ) {
2434 # Remove the upload restriction for non-file titles
2435 $types = array_diff( $types, [ 'upload' ] );
2438 Hooks::runner()->onTitleGetRestrictionTypes( $this, $types );
2440 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2441 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}" );
2443 return $types;
2447 * Is this title subject to title protection?
2448 * Title protection is the one applied against creation of such title.
2450 * @return array|bool An associative array representing any existent title
2451 * protection, or false if there's none.
2453 public function getTitleProtection() {
2454 $protection = $this->getTitleProtectionInternal();
2455 if ( $protection ) {
2456 if ( $protection['permission'] == 'sysop' ) {
2457 $protection['permission'] = 'editprotected'; // B/C
2459 if ( $protection['permission'] == 'autoconfirmed' ) {
2460 $protection['permission'] = 'editsemiprotected'; // B/C
2463 return $protection;
2467 * Fetch title protection settings
2469 * To work correctly, $this->loadRestrictions() needs to have access to the
2470 * actual protections in the database without munging 'sysop' =>
2471 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2472 * callers probably want $this->getTitleProtection() instead.
2474 * @return array|bool
2476 protected function getTitleProtectionInternal() {
2477 // Can't protect pages in special namespaces
2478 if ( $this->mNamespace < 0 ) {
2479 return false;
2482 // Can't protect pages that exist.
2483 if ( $this->exists() ) {
2484 return false;
2487 if ( $this->mTitleProtection === null ) {
2488 $dbr = wfGetDB( DB_REPLICA );
2489 $commentStore = CommentStore::getStore();
2490 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2491 $res = $dbr->select(
2492 [ 'protected_titles' ] + $commentQuery['tables'],
2494 'user' => 'pt_user',
2495 'expiry' => 'pt_expiry',
2496 'permission' => 'pt_create_perm'
2497 ] + $commentQuery['fields'],
2498 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2499 __METHOD__,
2501 $commentQuery['joins']
2504 // fetchRow returns false if there are no rows.
2505 $row = $dbr->fetchRow( $res );
2506 if ( $row ) {
2507 $this->mTitleProtection = [
2508 'user' => $row['user'],
2509 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2510 'permission' => $row['permission'],
2511 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
2513 } else {
2514 $this->mTitleProtection = false;
2517 return $this->mTitleProtection;
2521 * Remove any title protection due to page existing
2523 public function deleteTitleProtection() {
2524 $dbw = wfGetDB( DB_MASTER );
2526 $dbw->delete(
2527 'protected_titles',
2528 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2529 __METHOD__
2531 $this->mTitleProtection = false;
2535 * Is this page "semi-protected" - the *only* protection levels are listed
2536 * in $wgSemiprotectedRestrictionLevels?
2538 * @param string $action Action to check (default: edit)
2539 * @return bool
2541 public function isSemiProtected( $action = 'edit' ) {
2542 global $wgSemiprotectedRestrictionLevels;
2544 $restrictions = $this->getRestrictions( $action );
2545 $semi = $wgSemiprotectedRestrictionLevels;
2546 if ( !$restrictions || !$semi ) {
2547 // Not protected, or all protection is full protection
2548 return false;
2551 // Remap autoconfirmed to editsemiprotected for BC
2552 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2553 $semi[$key] = 'editsemiprotected';
2555 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2556 $restrictions[$key] = 'editsemiprotected';
2559 return !array_diff( $restrictions, $semi );
2563 * Does the title correspond to a protected article?
2565 * @param string $action The action the page is protected from,
2566 * by default checks all actions.
2567 * @return bool
2569 public function isProtected( $action = '' ) {
2570 global $wgRestrictionLevels;
2572 $restrictionTypes = $this->getRestrictionTypes();
2574 # Special pages have inherent protection
2575 if ( $this->isSpecialPage() ) {
2576 return true;
2579 # Check regular protection levels
2580 foreach ( $restrictionTypes as $type ) {
2581 if ( $action == $type || $action == '' ) {
2582 $r = $this->getRestrictions( $type );
2583 foreach ( $wgRestrictionLevels as $level ) {
2584 if ( in_array( $level, $r ) && $level != '' ) {
2585 return true;
2591 return false;
2595 * Determines if $user is unable to edit this page because it has been protected
2596 * by $wgNamespaceProtection.
2598 * @deprecated since 1.34 Don't use this function in new code.
2599 * @param User $user User object to check permissions
2600 * @return bool
2602 public function isNamespaceProtected( User $user ) {
2603 global $wgNamespaceProtection;
2605 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2606 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2607 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2608 if ( !$permissionManager->userHasRight( $user, $right ) ) {
2609 return true;
2613 return false;
2617 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2619 * @return bool If the page is subject to cascading restrictions.
2621 public function isCascadeProtected() {
2622 list( $isCascadeProtected, ) = $this->getCascadeProtectionSources( false );
2623 return $isCascadeProtected;
2627 * Determines whether cascading protection sources have already been loaded from
2628 * the database.
2630 * @param bool $getPages True to check if the pages are loaded, or false to check
2631 * if the status is loaded.
2632 * @return bool Whether or not the specified information has been loaded
2633 * @since 1.23
2635 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2636 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2640 * Cascading protection: Get the source of any cascading restrictions on this page.
2642 * @param bool $getPages Whether or not to retrieve the actual pages
2643 * that the restrictions have come from and the actual restrictions
2644 * themselves.
2645 * @return array Two elements: First is an array of Title objects of the
2646 * pages from which cascading restrictions have come, false for
2647 * none, or true if such restrictions exist but $getPages was not
2648 * set. Second is an array like that returned by
2649 * Title::getAllRestrictions(), or an empty array if $getPages is
2650 * false.
2652 public function getCascadeProtectionSources( $getPages = true ) {
2653 $pagerestrictions = [];
2655 if ( $this->mCascadeSources !== null && $getPages ) {
2656 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2657 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2658 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2661 $dbr = wfGetDB( DB_REPLICA );
2663 if ( $this->mNamespace === NS_FILE ) {
2664 $tables = [ 'imagelinks', 'page_restrictions' ];
2665 $where_clauses = [
2666 'il_to' => $this->mDbkeyform,
2667 'il_from=pr_page',
2668 'pr_cascade' => 1
2670 } else {
2671 $tables = [ 'templatelinks', 'page_restrictions' ];
2672 $where_clauses = [
2673 'tl_namespace' => $this->mNamespace,
2674 'tl_title' => $this->mDbkeyform,
2675 'tl_from=pr_page',
2676 'pr_cascade' => 1
2680 if ( $getPages ) {
2681 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2682 'pr_expiry', 'pr_type', 'pr_level' ];
2683 $where_clauses[] = 'page_id=pr_page';
2684 $tables[] = 'page';
2685 } else {
2686 $cols = [ 'pr_expiry' ];
2689 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2691 $sources = $getPages ? [] : false;
2692 $now = wfTimestampNow();
2694 foreach ( $res as $row ) {
2695 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2696 if ( $expiry > $now ) {
2697 if ( $getPages ) {
2698 $page_id = $row->pr_page;
2699 $page_ns = $row->page_namespace;
2700 $page_title = $row->page_title;
2701 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
2702 # Add groups needed for each restriction type if its not already there
2703 # Make sure this restriction type still exists
2705 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2706 $pagerestrictions[$row->pr_type] = [];
2709 if (
2710 isset( $pagerestrictions[$row->pr_type] )
2711 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2713 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2715 } else {
2716 $sources = true;
2721 if ( $getPages ) {
2722 $this->mCascadeSources = $sources;
2723 $this->mCascadingRestrictions = $pagerestrictions;
2724 } else {
2725 $this->mHasCascadingRestrictions = $sources;
2728 return [ $sources, $pagerestrictions ];
2732 * Accessor for mRestrictionsLoaded
2734 * @return bool Whether or not the page's restrictions have already been
2735 * loaded from the database
2736 * @since 1.23
2738 public function areRestrictionsLoaded() {
2739 return $this->mRestrictionsLoaded;
2743 * Accessor/initialisation for mRestrictions
2745 * @param string $action Action that permission needs to be checked for
2746 * @return array Restriction levels needed to take the action. All levels are
2747 * required. Note that restriction levels are normally user rights, but 'sysop'
2748 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2749 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2751 public function getRestrictions( $action ) {
2752 if ( !$this->mRestrictionsLoaded ) {
2753 $this->loadRestrictions();
2755 return $this->mRestrictions[$action] ?? [];
2759 * Accessor/initialisation for mRestrictions
2761 * @return array Keys are actions, values are arrays as returned by
2762 * Title::getRestrictions()
2763 * @since 1.23
2765 public function getAllRestrictions() {
2766 if ( !$this->mRestrictionsLoaded ) {
2767 $this->loadRestrictions();
2769 return $this->mRestrictions;
2773 * Get the expiry time for the restriction against a given action
2775 * @param string $action
2776 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2777 * or not protected at all, or false if the action is not recognised.
2779 public function getRestrictionExpiry( $action ) {
2780 if ( !$this->mRestrictionsLoaded ) {
2781 $this->loadRestrictions();
2783 return $this->mRestrictionsExpiry[$action] ?? false;
2787 * Returns cascading restrictions for the current article
2789 * @return bool
2791 public function areRestrictionsCascading() {
2792 if ( !$this->mRestrictionsLoaded ) {
2793 $this->loadRestrictions();
2796 return $this->mCascadeRestriction;
2800 * Compiles list of active page restrictions from both page table (pre 1.10)
2801 * and page_restrictions table for this existing page.
2802 * Public for usage by LiquidThreads.
2804 * @param stdClass[] $rows Array of db result objects
2805 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2806 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2807 * Edit and move sections are separated by a colon
2808 * Example: "edit=autoconfirmed,sysop:move=sysop"
2810 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2811 // This function will only read rows from a table that we migrated away
2812 // from before adding READ_LATEST support to loadRestrictions, so we
2813 // don't need to support reading from DB_MASTER here.
2814 $dbr = wfGetDB( DB_REPLICA );
2816 $restrictionTypes = $this->getRestrictionTypes();
2818 foreach ( $restrictionTypes as $type ) {
2819 $this->mRestrictions[$type] = [];
2820 $this->mRestrictionsExpiry[$type] = 'infinity';
2823 $this->mCascadeRestriction = false;
2825 # Backwards-compatibility: also load the restrictions from the page record (old format).
2826 if ( $oldFashionedRestrictions !== null ) {
2827 $this->mOldRestrictions = $oldFashionedRestrictions;
2830 if ( $this->mOldRestrictions === false ) {
2831 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
2832 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2833 $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2836 if ( $this->mOldRestrictions != '' ) {
2837 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2838 $temp = explode( '=', trim( $restrict ) );
2839 if ( count( $temp ) == 1 ) {
2840 // old old format should be treated as edit/move restriction
2841 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2842 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2843 } else {
2844 $restriction = trim( $temp[1] );
2845 if ( $restriction != '' ) { // some old entries are empty
2846 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2852 if ( count( $rows ) ) {
2853 # Current system - load second to make them override.
2854 $now = wfTimestampNow();
2856 # Cycle through all the restrictions.
2857 foreach ( $rows as $row ) {
2858 // Don't take care of restrictions types that aren't allowed
2859 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2860 continue;
2863 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2865 // Only apply the restrictions if they haven't expired!
2866 if ( !$expiry || $expiry > $now ) {
2867 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2868 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2870 $this->mCascadeRestriction = $this->mCascadeRestriction || $row->pr_cascade;
2875 $this->mRestrictionsLoaded = true;
2879 * Load restrictions from the page_restrictions table
2881 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2882 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2883 * Edit and move sections are separated by a colon
2884 * Example: "edit=autoconfirmed,sysop:move=sysop"
2885 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2886 * from the master DB.
2888 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2889 $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
2890 if ( $this->mRestrictionsLoaded && !$readLatest ) {
2891 return;
2894 $id = $this->getArticleID( $flags );
2895 if ( $id ) {
2896 $fname = __METHOD__;
2897 $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
2898 return iterator_to_array(
2899 $dbr->select(
2900 'page_restrictions',
2901 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2902 [ 'pr_page' => $id ],
2903 $fname
2908 if ( $readLatest ) {
2909 $dbr = wfGetDB( DB_MASTER );
2910 $rows = $loadRestrictionsFromDb( $dbr );
2911 } else {
2912 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2913 $rows = $cache->getWithSetCallback(
2914 // Page protections always leave a new null revision
2915 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2916 $cache::TTL_DAY,
2917 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2918 $dbr = wfGetDB( DB_REPLICA );
2920 $setOpts += Database::getCacheSetOptions( $dbr );
2921 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2922 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2923 // @TODO: cleanup Title cache and caller assumption mess in general
2924 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2927 return $loadRestrictionsFromDb( $dbr );
2932 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2933 } else {
2934 $title_protection = $this->getTitleProtectionInternal();
2936 if ( $title_protection ) {
2937 $now = wfTimestampNow();
2938 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
2940 if ( !$expiry || $expiry > $now ) {
2941 // Apply the restrictions
2942 $this->mRestrictionsExpiry['create'] = $expiry;
2943 $this->mRestrictions['create'] =
2944 explode( ',', trim( $title_protection['permission'] ) );
2945 } else { // Get rid of the old restrictions
2946 $this->mTitleProtection = false;
2948 } else {
2949 $this->mRestrictionsExpiry['create'] = 'infinity';
2951 $this->mRestrictionsLoaded = true;
2956 * Flush the protection cache in this object and force reload from the database.
2957 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2959 public function flushRestrictions() {
2960 $this->mRestrictionsLoaded = false;
2961 $this->mTitleProtection = null;
2965 * Purge expired restrictions from the page_restrictions table
2967 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2969 public static function purgeExpiredRestrictions() {
2970 if ( wfReadOnly() ) {
2971 return;
2974 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2975 wfGetDB( DB_MASTER ),
2976 __METHOD__,
2977 function ( IDatabase $dbw, $fname ) {
2978 $config = MediaWikiServices::getInstance()->getMainConfig();
2979 $ids = $dbw->selectFieldValues(
2980 'page_restrictions',
2981 'pr_id',
2982 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2983 $fname,
2984 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2986 if ( $ids ) {
2987 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2990 ) );
2992 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2993 wfGetDB( DB_MASTER ),
2994 __METHOD__,
2995 function ( IDatabase $dbw, $fname ) {
2996 $dbw->delete(
2997 'protected_titles',
2998 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2999 $fname
3002 ) );
3006 * Does this have subpages? (Warning, usually requires an extra DB query.)
3008 * @return bool
3010 public function hasSubpages() {
3011 if (
3012 !MediaWikiServices::getInstance()->getNamespaceInfo()->
3013 hasSubpages( $this->mNamespace )
3015 # Duh
3016 return false;
3019 # We dynamically add a member variable for the purpose of this method
3020 # alone to cache the result. There's no point in having it hanging
3021 # around uninitialized in every Title object; therefore we only add it
3022 # if needed and don't declare it statically.
3023 if ( $this->mHasSubpages === null ) {
3024 $this->mHasSubpages = false;
3025 $subpages = $this->getSubpages( 1 );
3026 if ( $subpages instanceof TitleArray ) {
3027 $this->mHasSubpages = (bool)$subpages->current();
3031 return $this->mHasSubpages;
3035 * Get all subpages of this page.
3037 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3038 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3039 * doesn't allow subpages
3041 public function getSubpages( $limit = -1 ) {
3042 if (
3043 !MediaWikiServices::getInstance()->getNamespaceInfo()->
3044 hasSubpages( $this->mNamespace )
3046 return [];
3049 $dbr = wfGetDB( DB_REPLICA );
3050 $conds = [ 'page_namespace' => $this->mNamespace ];
3051 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3052 $options = [];
3053 if ( $limit > -1 ) {
3054 $options['LIMIT'] = $limit;
3056 return TitleArray::newFromResult(
3057 $dbr->select( 'page',
3058 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3059 $conds,
3060 __METHOD__,
3061 $options
3067 * Is there a version of this page in the deletion archive?
3069 * @deprecated since 1.36. Use self::getDeletedEditsCount()
3070 * @return int The number of archived revisions
3072 public function isDeleted() {
3073 return $this->getDeletedEditsCount();
3077 * Is there a version of this page in the deletion archive?
3079 * @since 1.36
3080 * @return int The number of archived revisions
3082 public function getDeletedEditsCount() {
3083 if ( $this->mNamespace < 0 ) {
3084 $n = 0;
3085 } else {
3086 $dbr = wfGetDB( DB_REPLICA );
3088 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3089 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3090 __METHOD__
3092 if ( $this->mNamespace === NS_FILE ) {
3093 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3094 [ 'fa_name' => $this->mDbkeyform ],
3095 __METHOD__
3099 return (int)$n;
3103 * Is there a version of this page in the deletion archive?
3105 * @deprecated since 1.36, Use self::hasDeletedEdits()
3106 * @return bool
3108 public function isDeletedQuick() {
3109 return $this->hasDeletedEdits();
3113 * Is there a version of this page in the deletion archive?
3115 * @since 1.36
3116 * @return bool
3118 public function hasDeletedEdits() {
3119 if ( $this->mNamespace < 0 ) {
3120 return false;
3122 $dbr = wfGetDB( DB_REPLICA );
3123 $deleted = (bool)$dbr->selectField( 'archive', '1',
3124 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3125 __METHOD__
3127 if ( !$deleted && $this->mNamespace === NS_FILE ) {
3128 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3129 [ 'fa_name' => $this->mDbkeyform ],
3130 __METHOD__
3133 return $deleted;
3137 * Get the article ID for this Title from the link cache,
3138 * adding it if necessary
3140 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3141 * @return int The ID
3143 public function getArticleID( $flags = 0 ) {
3144 if ( $this->mNamespace < 0 ) {
3145 $this->mArticleID = 0;
3147 return $this->mArticleID;
3150 if ( $flags & self::GAID_FOR_UPDATE ) {
3151 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3152 $oldUpdate = $linkCache->forUpdate( true );
3153 $linkCache->clearLink( $this );
3154 $this->mArticleID = $linkCache->addLinkObj( $this );
3155 $linkCache->forUpdate( $oldUpdate );
3156 } elseif ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3157 // If mArticleID is >0, pageCond() will use it, making it impossible
3158 // for the call below to return a different result, e.g. after a
3159 // page move.
3160 $this->mArticleID = -1;
3161 $this->mArticleID = (int)$this->loadFieldFromDB( 'page_id', $flags );
3162 } elseif ( $this->mArticleID == -1 ) {
3163 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3164 $this->mArticleID = $linkCache->addLinkObj( $this );
3167 return $this->mArticleID;
3171 * Is this an article that is a redirect page?
3172 * Uses link cache, adding it if necessary
3174 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3175 * @return bool
3177 public function isRedirect( $flags = 0 ) {
3178 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3179 $this->mRedirect = (bool)$this->loadFieldFromDB( 'page_is_redirect', $flags );
3180 } elseif ( $this->mRedirect === null ) {
3181 if ( $this->getArticleID( $flags ) ) {
3182 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3183 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3184 // Note that LinkCache returns null if it thinks the page does not exist;
3185 // always trust the state of LinkCache over that of this Title instance.
3186 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3187 } else {
3188 $this->mRedirect = false;
3192 return $this->mRedirect;
3196 * What is the length of this page?
3197 * Uses link cache, adding it if necessary
3199 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3200 * @return int
3202 public function getLength( $flags = 0 ) {
3203 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3204 $this->mLength = (int)$this->loadFieldFromDB( 'page_len', $flags );
3205 } else {
3206 if ( $this->mLength != -1 ) {
3207 return $this->mLength;
3208 } elseif ( !$this->getArticleID( $flags ) ) {
3209 $this->mLength = 0;
3210 return $this->mLength;
3213 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3214 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3215 // Note that LinkCache returns null if it thinks the page does not exist;
3216 // always trust the state of LinkCache over that of this Title instance.
3217 $this->mLength = (int)$linkCache->getGoodLinkFieldObj( $this, 'length' );
3220 return $this->mLength;
3224 * What is the page_latest field for this page?
3226 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3227 * @return int Int or 0 if the page doesn't exist
3229 public function getLatestRevID( $flags = 0 ) {
3230 if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
3231 $this->mLatestID = (int)$this->loadFieldFromDB( 'page_latest', $flags );
3232 } else {
3233 if ( $this->mLatestID !== false ) {
3234 return (int)$this->mLatestID;
3235 } elseif ( !$this->getArticleID( $flags ) ) {
3236 $this->mLatestID = 0;
3238 return $this->mLatestID;
3241 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3242 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3243 // Note that LinkCache returns null if it thinks the page does not exist;
3244 // always trust the state of LinkCache over that of this Title instance.
3245 $this->mLatestID = (int)$linkCache->getGoodLinkFieldObj( $this, 'revision' );
3248 return $this->mLatestID;
3252 * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
3254 * This can be called on page insertion to allow loading of the new page_id without
3255 * having to create a new Title instance. Likewise with deletion.
3257 * This is also used during page moves, to reflect the change in the relationship
3258 * between article ID and title text.
3260 * @note This overrides Title::setContentModel()
3262 * @param int|bool $id Page ID, 0 for non-existant, or false for "unknown" (lazy-load)
3264 public function resetArticleID( $id ) {
3265 if ( $id === false ) {
3266 $this->mArticleID = -1;
3267 } else {
3268 $this->mArticleID = (int)$id;
3270 $this->mRestrictionsLoaded = false;
3271 $this->mRestrictions = [];
3272 $this->mOldRestrictions = false;
3273 $this->mRedirect = null;
3274 $this->mLength = -1;
3275 $this->mLatestID = false;
3276 $this->mContentModel = false;
3277 $this->mForcedContentModel = false;
3278 $this->mEstimateRevisions = null;
3279 $this->mPageLanguage = null;
3280 $this->mDbPageLanguage = false;
3281 $this->mIsBigDeletion = null;
3283 MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
3286 public static function clearCaches() {
3287 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3288 $linkCache->clear();
3290 $titleCache = self::getTitleCache();
3291 $titleCache->clear();
3295 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3297 * @param string $text Containing title to capitalize
3298 * @param int $ns Namespace index, defaults to NS_MAIN
3299 * @return string Containing capitalized title
3301 public static function capitalize( $text, $ns = NS_MAIN ) {
3302 $services = MediaWikiServices::getInstance();
3303 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3304 return $services->getContentLanguage()->ucfirst( $text );
3305 } else {
3306 return $text;
3311 * Secure and split - main initialisation function for this object
3313 * Assumes that $text is urldecoded
3314 * and uses underscores, but not otherwise munged. This function
3315 * removes illegal characters, splits off the interwiki and
3316 * namespace prefixes, sets the other forms, and canonicalizes
3317 * everything.
3319 * If this method returns normally, the Title is valid.
3321 * @param string $text
3322 * @param int|null $defaultNamespace
3324 * @throws MalformedTitleException On malformed titles
3326 private function secureAndSplit( $text, $defaultNamespace = null ) {
3327 if ( $defaultNamespace === null ) {
3328 $defaultNamespace = $this->mDefaultNamespace;
3331 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3332 // the parsing code with Title, while avoiding massive refactoring.
3333 // @todo: get rid of secureAndSplit, refactor parsing code.
3334 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3335 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3336 /** @var MediaWikiTitleCodec $titleCodec */
3337 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3338 '@phan-var MediaWikiTitleCodec $titleCodec';
3339 // MalformedTitleException can be thrown here
3340 $parts = $titleCodec->splitTitleString( $text, $defaultNamespace );
3342 # Fill fields
3343 $this->setFragment( '#' . $parts['fragment'] );
3344 $this->mInterwiki = $parts['interwiki'];
3345 $this->mLocalInterwiki = $parts['local_interwiki'];
3346 $this->mNamespace = $parts['namespace'];
3347 $this->mDefaultNamespace = $defaultNamespace;
3349 $this->mDbkeyform = $parts['dbkey'];
3350 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3351 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3353 // splitTitleString() guarantees that this title is valid.
3354 $this->mIsValid = true;
3356 # We already know that some pages won't be in the database!
3357 if ( $this->isExternal() || $this->isSpecialPage() || $this->mTextform === '' ) {
3358 $this->mArticleID = 0;
3363 * Get an array of Title objects linking to this Title
3364 * Also stores the IDs in the link cache.
3366 * WARNING: do not use this function on arbitrary user-supplied titles!
3367 * On heavily-used templates it will max out the memory.
3369 * @param array $options May be FOR UPDATE
3370 * @param string $table Table name
3371 * @param string $prefix Fields prefix
3372 * @return Title[] Array of Title objects linking here
3374 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3375 if ( count( $options ) > 0 ) {
3376 $db = wfGetDB( DB_MASTER );
3377 } else {
3378 $db = wfGetDB( DB_REPLICA );
3381 $res = $db->select(
3382 [ 'page', $table ],
3383 self::getSelectFields(),
3385 "{$prefix}_from=page_id",
3386 "{$prefix}_namespace" => $this->mNamespace,
3387 "{$prefix}_title" => $this->mDbkeyform ],
3388 __METHOD__,
3389 $options
3392 $retVal = [];
3393 if ( $res->numRows() ) {
3394 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3395 foreach ( $res as $row ) {
3396 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3397 if ( $titleObj ) {
3398 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3399 $retVal[] = $titleObj;
3403 return $retVal;
3407 * Get an array of Title objects using this Title as a template
3408 * Also stores the IDs in the link cache.
3410 * WARNING: do not use this function on arbitrary user-supplied titles!
3411 * On heavily-used templates it will max out the memory.
3413 * @param array $options Query option to Database::select()
3414 * @return Title[] Array of Title the Title objects linking here
3416 public function getTemplateLinksTo( $options = [] ) {
3417 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3421 * Get an array of Title objects linked from this Title
3422 * Also stores the IDs in the link cache.
3424 * WARNING: do not use this function on arbitrary user-supplied titles!
3425 * On heavily-used templates it will max out the memory.
3427 * @param array $options Query option to Database::select()
3428 * @param string $table Table name
3429 * @param string $prefix Fields prefix
3430 * @return Title[] List of Titles linking here
3432 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3433 $id = $this->getArticleID();
3435 # If the page doesn't exist; there can't be any link from this page
3436 if ( !$id ) {
3437 return [];
3440 $db = wfGetDB( DB_REPLICA );
3442 $blNamespace = "{$prefix}_namespace";
3443 $blTitle = "{$prefix}_title";
3445 $pageQuery = WikiPage::getQueryInfo();
3446 $res = $db->select(
3447 [ $table, 'nestpage' => $pageQuery['tables'] ],
3448 array_merge(
3449 [ $blNamespace, $blTitle ],
3450 $pageQuery['fields']
3452 [ "{$prefix}_from" => $id ],
3453 __METHOD__,
3454 $options,
3455 [ 'nestpage' => [
3456 'LEFT JOIN',
3457 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3458 ] ] + $pageQuery['joins']
3461 $retVal = [];
3462 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3463 foreach ( $res as $row ) {
3464 if ( $row->page_id ) {
3465 $titleObj = self::newFromRow( $row );
3466 } else {
3467 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3468 $linkCache->addBadLinkObj( $titleObj );
3470 $retVal[] = $titleObj;
3473 return $retVal;
3477 * Get an array of Title objects used on this Title as a template
3478 * Also stores the IDs in the link cache.
3480 * WARNING: do not use this function on arbitrary user-supplied titles!
3481 * On heavily-used templates it will max out the memory.
3483 * @param array $options May be FOR UPDATE
3484 * @return Title[] Array of Title the Title objects used here
3486 public function getTemplateLinksFrom( $options = [] ) {
3487 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3491 * Get an array of Title objects referring to non-existent articles linked
3492 * from this page.
3494 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3495 * should use redirect table in this case).
3496 * @return Title[] Array of Title the Title objects
3498 public function getBrokenLinksFrom() {
3499 if ( $this->getArticleID() == 0 ) {
3500 # All links from article ID 0 are false positives
3501 return [];
3504 $dbr = wfGetDB( DB_REPLICA );
3505 $res = $dbr->select(
3506 [ 'page', 'pagelinks' ],
3507 [ 'pl_namespace', 'pl_title' ],
3509 'pl_from' => $this->getArticleID(),
3510 'page_namespace IS NULL'
3512 __METHOD__, [],
3514 'page' => [
3515 'LEFT JOIN',
3516 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3521 $retVal = [];
3522 foreach ( $res as $row ) {
3523 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3525 return $retVal;
3529 * Get a list of URLs to purge from the CDN cache when this page changes.
3531 * @deprecated 1.35 Use HtmlCacheUpdater
3532 * @return string[] Array of String the URLs
3534 public function getCdnUrls() {
3535 $htmlCache = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
3536 return $htmlCache->getUrls( $this );
3540 * Purge all applicable CDN URLs
3541 * @deprecated 1.35 Use HtmlCacheUpdater
3543 public function purgeSquid() {
3544 $htmlCache = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
3545 $htmlCache->purgeTitleUrls( $this, $htmlCache::PURGE_INTENT_TXROUND_REFLECTED );
3549 * Locks the page row and check if this page is single revision redirect
3551 * This updates the cached fields of this instance via Title::loadFromRow()
3553 * @return bool
3555 public function isSingleRevRedirect() {
3556 $dbw = wfGetDB( DB_MASTER );
3557 $dbw->startAtomic( __METHOD__ );
3559 $row = $dbw->selectRow(
3560 'page',
3561 self::getSelectFields(),
3562 $this->pageCond(),
3563 __METHOD__,
3564 [ 'FOR UPDATE' ]
3566 // Update the cached fields
3567 $this->loadFromRow( $row );
3569 if ( $this->mRedirect && $this->mLatestID ) {
3570 $isSingleRevRedirect = !$dbw->selectField(
3571 'revision',
3572 '1',
3573 [ 'rev_page' => $this->mArticleID, 'rev_id != ' . (int)$this->mLatestID ],
3574 __METHOD__,
3575 [ 'FOR UPDATE' ]
3577 } else {
3578 $isSingleRevRedirect = false;
3581 $dbw->endAtomic( __METHOD__ );
3583 return $isSingleRevRedirect;
3587 * Get categories to which this Title belongs and return an array of
3588 * categories' names.
3590 * @return string[] Array of parents in the form:
3591 * $parent => $currentarticle
3593 public function getParentCategories() {
3594 $data = [];
3596 $titleKey = $this->getArticleID();
3598 if ( $titleKey === 0 ) {
3599 return $data;
3602 $dbr = wfGetDB( DB_REPLICA );
3604 $res = $dbr->select(
3605 'categorylinks',
3606 'cl_to',
3607 [ 'cl_from' => $titleKey ],
3608 __METHOD__
3611 if ( $res->numRows() > 0 ) {
3612 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
3613 foreach ( $res as $row ) {
3614 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3615 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
3616 $this->getFullText();
3619 return $data;
3623 * Get a tree of parent categories
3625 * @param array $children Array with the children in the keys, to check for circular refs
3626 * @return array Tree of parent categories
3628 public function getParentCategoryTree( $children = [] ) {
3629 $stack = [];
3630 $parents = $this->getParentCategories();
3632 if ( $parents ) {
3633 foreach ( $parents as $parent => $current ) {
3634 if ( array_key_exists( $parent, $children ) ) {
3635 # Circular reference
3636 $stack[$parent] = [];
3637 } else {
3638 $nt = self::newFromText( $parent );
3639 if ( $nt ) {
3640 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3646 return $stack;
3650 * Get an associative array for selecting this title from
3651 * the "page" table
3653 * @return array Array suitable for the $where parameter of DB::select()
3655 public function pageCond() {
3656 if ( $this->mArticleID > 0 ) {
3657 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3658 return [ 'page_id' => $this->mArticleID ];
3659 } else {
3660 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3665 * Get next/previous revision ID relative to another revision ID
3666 * @param int $revId Revision ID. Get the revision that was before this one.
3667 * @param int $flags Bitfield of class READ_* constants
3668 * @param string $dir 'next' or 'prev'
3669 * @return int|bool New revision ID, or false if none exists
3671 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3672 $rl = MediaWikiServices::getInstance()->getRevisionLookup();
3673 $rev = $rl->getRevisionById( $revId, $flags );
3674 if ( !$rev ) {
3675 return false;
3678 $oldRev = ( $dir === 'next' )
3679 ? $rl->getNextRevision( $rev, $flags )
3680 : $rl->getPreviousRevision( $rev, $flags );
3682 return $oldRev ? $oldRev->getId() : false;
3686 * Get the revision ID of the previous revision
3688 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3689 * @param int $revId Revision ID. Get the revision that was before this one.
3690 * @param int $flags Bitfield of class READ_* constants
3691 * @return int|bool Old revision ID, or false if none exists
3693 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3694 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3698 * Get the revision ID of the next revision
3700 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3701 * @param int $revId Revision ID. Get the revision that was after this one.
3702 * @param int $flags Bitfield of class READ_* constants
3703 * @return int|bool Next revision ID, or false if none exists
3705 public function getNextRevisionID( $revId, $flags = 0 ) {
3706 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3710 * Get the first revision of the page
3712 * @deprecated since 1.35. Use RevisionLookup::getFirstRevision instead.
3713 * @param int $flags Bitfield of class READ_* constants
3714 * @return Revision|null If page doesn't exist
3716 public function getFirstRevision( $flags = 0 ) {
3717 wfDeprecated( __METHOD__, '1.35' );
3718 $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
3719 $rev = MediaWikiServices::getInstance()
3720 ->getRevisionLookup()
3721 ->getFirstRevision( $this, $flags );
3722 return $rev ? new Revision( $rev ) : null;
3726 * Get the oldest revision timestamp of this page
3728 * @deprecated since 1.35. Use RevisionLookup::getFirstRevision instead.
3729 * @param int $flags Bitfield of class READ_* constants
3730 * @return string|null MW timestamp
3732 public function getEarliestRevTime( $flags = 0 ) {
3733 $rev = MediaWikiServices::getInstance()
3734 ->getRevisionLookup()
3735 ->getFirstRevision( $this, $flags );
3736 return $rev ? $rev->getTimestamp() : null;
3740 * Check if this is a new page
3742 * @return bool
3744 public function isNewPage() {
3745 $dbr = wfGetDB( DB_REPLICA );
3746 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3750 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3752 * @return bool
3754 public function isBigDeletion() {
3755 global $wgDeleteRevisionsLimit;
3757 if ( !$wgDeleteRevisionsLimit ) {
3758 return false;
3761 if ( $this->mIsBigDeletion === null ) {
3762 $dbr = wfGetDB( DB_REPLICA );
3764 $revCount = $dbr->selectRowCount(
3765 'revision',
3766 '1',
3767 [ 'rev_page' => $this->getArticleID() ],
3768 __METHOD__,
3769 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
3772 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
3775 return $this->mIsBigDeletion;
3779 * Get the approximate revision count of this page.
3781 * @return int
3783 public function estimateRevisionCount() {
3784 if ( !$this->exists() ) {
3785 return 0;
3788 if ( $this->mEstimateRevisions === null ) {
3789 $dbr = wfGetDB( DB_REPLICA );
3790 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
3791 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
3794 return $this->mEstimateRevisions;
3798 * Get the number of revisions between the given revision.
3799 * Used for diffs and other things that really need it.
3801 * @deprecated since 1.35 Use RevisionStore::countRevisionsBetween instead.
3803 * @param int|Revision $old Old revision or rev ID (first before range)
3804 * @param int|Revision $new New revision or rev ID (first after range)
3805 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3806 * @return int Number of revisions between these revisions.
3808 public function countRevisionsBetween( $old, $new, $max = null ) {
3809 wfDeprecated( __METHOD__, '1.35' );
3810 if ( !( $old instanceof Revision ) ) {
3811 $old = Revision::newFromTitle( $this, (int)$old );
3813 if ( !( $new instanceof Revision ) ) {
3814 $new = Revision::newFromTitle( $this, (int)$new );
3816 if ( !$old || !$new ) {
3817 return 0; // nothing to compare
3819 return MediaWikiServices::getInstance()
3820 ->getRevisionStore()
3821 ->countRevisionsBetween(
3822 $this->getArticleID(),
3823 $old->getRevisionRecord(),
3824 $new->getRevisionRecord(),
3825 $max
3830 * Get the authors between the given revisions or revision IDs.
3831 * Used for diffs and other things that really need it.
3833 * @since 1.23
3834 * @deprecated since 1.35 Use RevisionStore::getAuthorsBetween instead.
3836 * @param int|Revision $old Old revision or rev ID (first before range by default)
3837 * @param int|Revision $new New revision or rev ID (first after range by default)
3838 * @param int $limit Maximum number of authors
3839 * @param string|array $options (Optional): Single option, or an array of options:
3840 * 'include_old' Include $old in the range; $new is excluded.
3841 * 'include_new' Include $new in the range; $old is excluded.
3842 * 'include_both' Include both $old and $new in the range.
3843 * Unknown option values are ignored.
3844 * @return array|null Names of revision authors in the range; null if not both revisions exist
3846 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3847 wfDeprecated( __METHOD__, '1.35' );
3848 if ( !( $old instanceof Revision ) ) {
3849 $old = Revision::newFromTitle( $this, (int)$old );
3851 if ( !( $new instanceof Revision ) ) {
3852 $new = Revision::newFromTitle( $this, (int)$new );
3854 try {
3855 $users = MediaWikiServices::getInstance()
3856 ->getRevisionStore()
3857 ->getAuthorsBetween(
3858 $this->getArticleID(),
3859 $old->getRevisionRecord(),
3860 $new->getRevisionRecord(),
3861 null,
3862 $limit,
3863 $options
3865 return array_map( function ( UserIdentity $user ) {
3866 return $user->getName();
3867 }, $users );
3868 } catch ( InvalidArgumentException $e ) {
3869 return null; // b/c
3874 * Get the number of authors between the given revisions or revision IDs.
3875 * Used for diffs and other things that really need it.
3877 * @deprecated since 1.35 Use RevisionStore::countAuthorsBetween instead.
3879 * @param int|Revision $old Old revision or rev ID (first before range by default)
3880 * @param int|Revision $new New revision or rev ID (first after range by default)
3881 * @param int $limit Maximum number of authors
3882 * @param string|array $options (Optional): Single option, or an array of options:
3883 * 'include_old' Include $old in the range; $new is excluded.
3884 * 'include_new' Include $new in the range; $old is excluded.
3885 * 'include_both' Include both $old and $new in the range.
3886 * Unknown option values are ignored.
3887 * @return int Number of revision authors in the range; zero if not both revisions exist
3889 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3890 wfDeprecated( __METHOD__, '1.35' );
3891 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3892 return $authors ? count( $authors ) : 0;
3896 * Compare with another title.
3898 * @param LinkTarget $title
3899 * @return bool
3901 public function equals( LinkTarget $title ) {
3902 // Note: === is necessary for proper matching of number-like titles.
3903 return $this->mInterwiki === $title->getInterwiki()
3904 && $this->mNamespace == $title->getNamespace()
3905 && $this->mDbkeyform === $title->getDBkey();
3909 * Check if this title is a subpage of another title
3911 * @param Title $title
3912 * @return bool
3914 public function isSubpageOf( Title $title ) {
3915 return $this->mInterwiki === $title->mInterwiki
3916 && $this->mNamespace == $title->mNamespace
3917 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
3921 * Check if page exists. For historical reasons, this function simply
3922 * checks for the existence of the title in the page table, and will
3923 * thus return false for interwiki links, special pages and the like.
3924 * If you want to know if a title can be meaningfully viewed, you should
3925 * probably call the isKnown() method instead.
3927 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3928 * @return bool
3930 public function exists( $flags = 0 ) {
3931 $exists = $this->getArticleID( $flags ) != 0;
3932 Hooks::runner()->onTitleExists( $this, $exists );
3933 return $exists;
3937 * Should links to this title be shown as potentially viewable (i.e. as
3938 * "bluelinks"), even if there's no record by this title in the page
3939 * table?
3941 * This function is semi-deprecated for public use, as well as somewhat
3942 * misleadingly named. You probably just want to call isKnown(), which
3943 * calls this function internally.
3945 * (ISSUE: Most of these checks are cheap, but the file existence check
3946 * can potentially be quite expensive. Including it here fixes a lot of
3947 * existing code, but we might want to add an optional parameter to skip
3948 * it and any other expensive checks.)
3950 * @return bool
3952 public function isAlwaysKnown() {
3953 $isKnown = null;
3956 * Allows overriding default behavior for determining if a page exists.
3957 * If $isKnown is kept as null, regular checks happen. If it's
3958 * a boolean, this value is returned by the isKnown method.
3960 * @since 1.20
3962 * @param Title $title
3963 * @param bool|null $isKnown
3965 Hooks::runner()->onTitleIsAlwaysKnown( $this, $isKnown );
3967 if ( $isKnown !== null ) {
3968 return $isKnown;
3971 if ( $this->isExternal() ) {
3972 return true; // any interwiki link might be viewable, for all we know
3975 $services = MediaWikiServices::getInstance();
3976 switch ( $this->mNamespace ) {
3977 case NS_MEDIA:
3978 case NS_FILE:
3979 // file exists, possibly in a foreign repo
3980 return (bool)$services->getRepoGroup()->findFile( $this );
3981 case NS_SPECIAL:
3982 // valid special page
3983 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
3984 case NS_MAIN:
3985 // selflink, possibly with fragment
3986 return $this->mDbkeyform == '';
3987 case NS_MEDIAWIKI:
3988 // known system message
3989 return $this->hasSourceText() !== false;
3990 default:
3991 return false;
3996 * Does this title refer to a page that can (or might) be meaningfully
3997 * viewed? In particular, this function may be used to determine if
3998 * links to the title should be rendered as "bluelinks" (as opposed to
3999 * "redlinks" to non-existent pages).
4000 * Adding something else to this function will cause inconsistency
4001 * since LinkHolderArray calls isAlwaysKnown() and does its own
4002 * page existence check.
4004 * @return bool
4006 public function isKnown() {
4007 return $this->isAlwaysKnown() || $this->exists();
4011 * Does this page have source text?
4013 * @return bool
4015 public function hasSourceText() {
4016 if ( $this->exists() ) {
4017 return true;
4020 if ( $this->mNamespace === NS_MEDIAWIKI ) {
4021 $services = MediaWikiServices::getInstance();
4022 // If the page doesn't exist but is a known system message, default
4023 // message content will be displayed, same for language subpages-
4024 // Use always content language to avoid loading hundreds of languages
4025 // to get the link color.
4026 $contLang = $services->getContentLanguage();
4027 list( $name, ) = $services->getMessageCache()->figureMessage(
4028 $contLang->lcfirst( $this->getText() )
4030 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4031 return $message->exists();
4034 return false;
4038 * Get the default (plain) message contents for an page that overrides an
4039 * interface message key.
4041 * Primary use cases:
4043 * - Article:
4044 * - Show default when viewing the page. The Article::getSubstituteContent
4045 * method displays the default message content, instead of the
4046 * 'noarticletext' placeholder message normally used.
4048 * - EditPage:
4049 * - Title of edit page. When creating an interface message override,
4050 * the editor is told they are "Editing the page", instead of
4051 * "Creating the page". (EditPage::setHeaders)
4052 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4053 * or editing an interface message override. (EditPage::showIntro)
4054 * - Opening the editor. The contents of the localisation message are used
4055 * as contents of the editor when creating a new page in the MediaWiki
4056 * namespace. This simplifies the process for editors when "changing"
4057 * an interface message by creating an override. (EditPage::getContentObject)
4058 * - Showing a diff. The left-hand side of a diff when an editor is
4059 * previewing their changes before saving the creation of a page in the
4060 * MediaWiki namespace. (EditPage::showDiff)
4061 * - Disallowing a save. When attempting to create a MediaWiki-namespace
4062 * page with the proposed content matching the interface message default,
4063 * the save is rejected, the same way we disallow blank pages from being
4064 * created. (EditPage::internalAttemptSave)
4066 * - ApiEditPage:
4067 * - Default content, when using the 'prepend' or 'append' feature.
4069 * - SkinTemplate:
4070 * - Label the create action as "Edit", if the page can be an override.
4072 * @return string|bool
4074 public function getDefaultMessageText() {
4075 if ( $this->mNamespace !== NS_MEDIAWIKI ) { // Just in case
4076 return false;
4079 list( $name, $lang ) = MediaWikiServices::getInstance()->getMessageCache()->figureMessage(
4080 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4082 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4084 if ( $message->exists() ) {
4085 return $message->plain();
4086 } else {
4087 return false;
4092 * Updates page_touched for this page; called from LinksUpdate.php
4094 * @param string|null $purgeTime [optional] TS_MW timestamp
4095 * @return bool True if the update succeeded
4097 public function invalidateCache( $purgeTime = null ) {
4098 if ( wfReadOnly() ) {
4099 return false;
4101 if ( $this->mArticleID === 0 ) {
4102 // avoid gap locking if we know it's not there
4103 return true;
4106 $conds = $this->pageCond();
4107 DeferredUpdates::addUpdate(
4108 new AutoCommitUpdate(
4109 wfGetDB( DB_MASTER ),
4110 __METHOD__,
4111 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4112 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4113 $dbw->update(
4114 'page',
4115 [ 'page_touched' => $dbTimestamp ],
4116 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4117 $fname
4120 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4122 ResourceLoaderWikiModule::invalidateModuleCache(
4123 $this, null, null, $dbw->getDomainID() );
4126 DeferredUpdates::PRESEND
4129 return true;
4133 * Update page_touched timestamps and send CDN purge messages for
4134 * pages linking to this title. May be sent to the job queue depending
4135 * on the number of links. Typically called on create and delete.
4137 public function touchLinks() {
4138 $jobs = [];
4139 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
4140 $this,
4141 'pagelinks',
4142 [ 'causeAction' => 'page-touch' ]
4144 if ( $this->mNamespace === NS_CATEGORY ) {
4145 $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
4146 $this,
4147 'categorylinks',
4148 [ 'causeAction' => 'category-touch' ]
4152 JobQueueGroup::singleton()->lazyPush( $jobs );
4156 * Get the last touched timestamp
4158 * @param IDatabase|null $db
4159 * @return string|false Last-touched timestamp
4161 public function getTouched( $db = null ) {
4162 if ( $db === null ) {
4163 $db = wfGetDB( DB_REPLICA );
4165 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4166 return $touched;
4170 * Get the timestamp when this page was updated since the user last saw it.
4172 * @deprecated since 1.35
4174 * @param User $user
4175 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4177 public function getNotificationTimestamp( User $user ) {
4178 return MediaWikiServices::getInstance()
4179 ->getWatchlistNotificationManager()
4180 ->getTitleNotificationTimestamp( $user, $this );
4184 * Generate strings used for xml 'id' names in monobook tabs
4186 * @param string $prepend Defaults to 'nstab-'
4187 * @return string XML 'id' name
4189 public function getNamespaceKey( $prepend = 'nstab-' ) {
4190 // Gets the subject namespace of this title
4191 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
4192 $subjectNS = $nsInfo->getSubject( $this->mNamespace );
4193 // Prefer canonical namespace name for HTML IDs
4194 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4195 if ( $namespaceKey === false ) {
4196 // Fallback to localised text
4197 $namespaceKey = $this->getSubjectNsText();
4199 // Makes namespace key lowercase
4200 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4201 // Uses main
4202 if ( $namespaceKey == '' ) {
4203 $namespaceKey = 'main';
4205 // Changes file to image for backwards compatibility
4206 if ( $namespaceKey == 'file' ) {
4207 $namespaceKey = 'image';
4209 return $prepend . $namespaceKey;
4213 * Get all extant redirects to this Title
4215 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4216 * @return Title[] Array of Title redirects to this title
4218 public function getRedirectsHere( $ns = null ) {
4219 $redirs = [];
4221 $dbr = wfGetDB( DB_REPLICA );
4222 $where = [
4223 'rd_namespace' => $this->mNamespace,
4224 'rd_title' => $this->mDbkeyform,
4225 'rd_from = page_id'
4227 if ( $this->isExternal() ) {
4228 $where['rd_interwiki'] = $this->mInterwiki;
4229 } else {
4230 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4232 if ( $ns !== null ) {
4233 $where['page_namespace'] = $ns;
4236 $res = $dbr->select(
4237 [ 'redirect', 'page' ],
4238 [ 'page_namespace', 'page_title' ],
4239 $where,
4240 __METHOD__
4243 foreach ( $res as $row ) {
4244 $redirs[] = self::newFromRow( $row );
4246 return $redirs;
4250 * Check if this Title is a valid redirect target
4252 * @return bool
4254 public function isValidRedirectTarget() {
4255 global $wgInvalidRedirectTargets;
4257 if ( $this->isSpecialPage() ) {
4258 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4259 if ( $this->isSpecial( 'Userlogout' ) ) {
4260 return false;
4263 foreach ( $wgInvalidRedirectTargets as $target ) {
4264 if ( $this->isSpecial( $target ) ) {
4265 return false;
4270 return true;
4274 * Get a backlink cache object
4276 * @return BacklinkCache
4278 public function getBacklinkCache() {
4279 return BacklinkCache::get( $this );
4283 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4285 * @return bool
4287 public function canUseNoindex() {
4288 global $wgExemptFromUserRobotsControl;
4290 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4291 MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
4293 return !in_array( $this->mNamespace, $bannedNamespaces );
4297 * Returns the raw sort key to be used for categories, with the specified
4298 * prefix. This will be fed to Collation::getSortKey() to get a
4299 * binary sortkey that can be used for actual sorting.
4301 * @param string $prefix The prefix to be used, specified using
4302 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4303 * prefix.
4304 * @return string
4306 public function getCategorySortkey( $prefix = '' ) {
4307 $unprefixed = $this->getText();
4309 // Anything that uses this hook should only depend
4310 // on the Title object passed in, and should probably
4311 // tell the users to run updateCollations.php --force
4312 // in order to re-sort existing category relations.
4313 Hooks::runner()->onGetDefaultSortkey( $this, $unprefixed );
4314 if ( $prefix !== '' ) {
4315 # Separate with a line feed, so the unprefixed part is only used as
4316 # a tiebreaker when two pages have the exact same prefix.
4317 # In UCA, tab is the only character that can sort above LF
4318 # so we strip both of them from the original prefix.
4319 $prefix = strtr( $prefix, "\n\t", ' ' );
4320 return "$prefix\n$unprefixed";
4322 return $unprefixed;
4326 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4327 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4328 * the db, it will return NULL.
4330 * @return string|null|bool
4332 private function getDbPageLanguageCode() {
4333 global $wgPageLanguageUseDB;
4335 // check, if the page language could be saved in the database, and if so and
4336 // the value is not requested already, lookup the page language using LinkCache
4337 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4338 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
4339 $linkCache->addLinkObj( $this );
4340 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4343 return $this->mDbPageLanguage;
4347 * Get the language in which the content of this page is written in
4348 * wikitext. Defaults to content language, but in certain cases it can be
4349 * e.g. $wgLang (such as special pages, which are in the user language).
4351 * @since 1.18
4352 * @return Language
4354 public function getPageLanguage() {
4355 global $wgLang, $wgLanguageCode;
4356 if ( $this->isSpecialPage() ) {
4357 // special pages are in the user language
4358 return $wgLang;
4361 // Checking if DB language is set
4362 $dbPageLanguage = $this->getDbPageLanguageCode();
4363 if ( $dbPageLanguage ) {
4364 return wfGetLangObj( $dbPageLanguage );
4367 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4368 // Note that this may depend on user settings, so the cache should
4369 // be only per-request.
4370 // NOTE: ContentHandler::getPageLanguage() may need to load the
4371 // content to determine the page language!
4372 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4373 // tests.
4374 $contentHandler = MediaWikiServices::getInstance()
4375 ->getContentHandlerFactory()
4376 ->getContentHandler( $this->getContentModel() );
4377 $langObj = $contentHandler->getPageLanguage( $this );
4378 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4379 } else {
4380 $langObj = MediaWikiServices::getInstance()->getLanguageFactory()
4381 ->getLanguage( $this->mPageLanguage[0] );
4384 return $langObj;
4388 * Get the language in which the content of this page is written when
4389 * viewed by user. Defaults to content language, but in certain cases it can be
4390 * e.g. $wgLang (such as special pages, which are in the user language).
4392 * @since 1.20
4393 * @return Language
4395 public function getPageViewLanguage() {
4396 global $wgLang;
4398 if ( $this->isSpecialPage() ) {
4399 // If the user chooses a variant, the content is actually
4400 // in a language whose code is the variant code.
4401 $variant = $this->getLanguageConverter( $wgLang )->getPreferredVariant();
4402 if ( $wgLang->getCode() !== $variant ) {
4403 return MediaWikiServices::getInstance()->getLanguageFactory()
4404 ->getLanguage( $variant );
4407 return $wgLang;
4410 // Checking if DB language is set
4411 $dbPageLanguage = $this->getDbPageLanguageCode();
4412 if ( $dbPageLanguage ) {
4413 $pageLang = wfGetLangObj( $dbPageLanguage );
4414 $variant = $this->getLanguageConverter( $pageLang )->getPreferredVariant();
4415 if ( $pageLang->getCode() !== $variant ) {
4416 $pageLang = MediaWikiServices::getInstance()->getLanguageFactory()
4417 ->getLanguage( $variant );
4420 return $pageLang;
4423 // @note Can't be cached persistently, depends on user settings.
4424 // @note ContentHandler::getPageViewLanguage() may need to load the
4425 // content to determine the page language!
4426 $contentHandler = MediaWikiServices::getInstance()
4427 ->getContentHandlerFactory()
4428 ->getContentHandler( $this->getContentModel() );
4429 $pageLang = $contentHandler->getPageViewLanguage( $this );
4430 return $pageLang;
4434 * Get a list of rendered edit notices for this page.
4436 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4437 * they will already be wrapped in paragraphs.
4439 * @since 1.21
4440 * @param int $oldid Revision ID that's being edited
4441 * @return array
4443 public function getEditNotices( $oldid = 0 ) {
4444 $notices = [];
4446 // Optional notice for the entire namespace
4447 $editnotice_ns = 'editnotice-' . $this->mNamespace;
4448 $msg = wfMessage( $editnotice_ns );
4449 if ( $msg->exists() ) {
4450 $html = $msg->parseAsBlock();
4451 // Edit notices may have complex logic, but output nothing (T91715)
4452 if ( trim( $html ) !== '' ) {
4453 $notices[$editnotice_ns] = Html::rawElement(
4454 'div',
4455 [ 'class' => [
4456 'mw-editnotice',
4457 'mw-editnotice-namespace',
4458 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4459 ] ],
4460 $html
4465 if (
4466 MediaWikiServices::getInstance()->getNamespaceInfo()->
4467 hasSubpages( $this->mNamespace )
4469 // Optional notice for page itself and any parent page
4470 $editnotice_base = $editnotice_ns;
4471 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
4472 $editnotice_base .= '-' . $part;
4473 $msg = wfMessage( $editnotice_base );
4474 if ( $msg->exists() ) {
4475 $html = $msg->parseAsBlock();
4476 if ( trim( $html ) !== '' ) {
4477 $notices[$editnotice_base] = Html::rawElement(
4478 'div',
4479 [ 'class' => [
4480 'mw-editnotice',
4481 'mw-editnotice-base',
4482 Sanitizer::escapeClass( "mw-$editnotice_base" )
4483 ] ],
4484 $html
4489 } else {
4490 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4491 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
4492 $msg = wfMessage( $editnoticeText );
4493 if ( $msg->exists() ) {
4494 $html = $msg->parseAsBlock();
4495 if ( trim( $html ) !== '' ) {
4496 $notices[$editnoticeText] = Html::rawElement(
4497 'div',
4498 [ 'class' => [
4499 'mw-editnotice',
4500 'mw-editnotice-page',
4501 Sanitizer::escapeClass( "mw-$editnoticeText" )
4502 ] ],
4503 $html
4509 Hooks::runner()->onTitleGetEditNotices( $this, $oldid, $notices );
4510 return $notices;
4514 * @param string $field
4515 * @param int $flags Bitfield of class READ_* constants
4516 * @return string|bool
4518 private function loadFieldFromDB( $field, $flags ) {
4519 if ( !in_array( $field, self::getSelectFields(), true ) ) {
4520 return false; // field does not exist
4523 $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
4524 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
4526 return wfGetDB( $index )->selectField(
4527 'page',
4528 $field,
4529 $this->pageCond(),
4530 __METHOD__,
4531 $options
4536 * @return array
4538 public function __sleep() {
4539 return [
4540 'mNamespace',
4541 'mDbkeyform',
4542 'mFragment',
4543 'mInterwiki',
4544 'mLocalInterwiki',
4545 'mDefaultNamespace',
4549 public function __wakeup() {
4550 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4551 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4552 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );