3 * Representation of a title within %MediaWiki.
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
25 use MediaWiki\Permissions\PermissionManager
;
26 use Wikimedia\Assert\Assert
;
27 use Wikimedia\Rdbms\Database
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use MediaWiki\Linker\LinkTarget
;
30 use MediaWiki\Interwiki\InterwikiLookup
;
31 use MediaWiki\MediaWikiServices
;
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;
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 const CACHE_MAX
= 1000;
53 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
54 * to use the master DB
56 const GAID_FOR_UPDATE
= 1;
59 * Flag for use with factory methods like newFromLinkTarget() that have
60 * a $forceClone parameter. If set, the method must return a new instance.
61 * Without this flag, some factory methods may return existing instances.
65 const NEW_CLONE
= 'clone';
68 * @name Private member variables
69 * Please use the accessor functions instead.
74 /** @var string Text form (spaces not underscores) of the main part */
75 public $mTextform = '';
77 /** @var string URL-encoded form of the main part */
78 public $mUrlform = '';
80 /** @var string Main part with underscores */
81 public $mDbkeyform = '';
83 /** @var string Database key with the initial letter in the case specified by the user */
84 protected $mUserCaseDBKey;
86 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
87 public $mNamespace = NS_MAIN
;
89 /** @var string Interwiki prefix */
90 public $mInterwiki = '';
92 /** @var bool Was this Title created from a string with a local interwiki prefix? */
93 private $mLocalInterwiki = false;
95 /** @var string Title fragment (i.e. the bit after the #) */
96 public $mFragment = '';
98 /** @var int Article ID, fetched from the link cache on demand */
99 public $mArticleID = -1;
101 /** @var bool|int ID of most recent revision */
102 protected $mLatestID = false;
105 * @var bool|string ID of the page's content model, i.e. one of the
106 * CONTENT_MODEL_XXX constants
108 private $mContentModel = false;
111 * @var bool If a content model was forced via setContentModel()
112 * this will be true to avoid having other code paths reset it
114 private $mForcedContentModel = false;
116 /** @var int Estimated number of revisions; null of not loaded */
117 private $mEstimateRevisions;
119 /** @var array Array of groups allowed to edit this article */
120 public $mRestrictions = [];
123 * @var string|bool Comma-separated set of permission keys
124 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
125 * Edit and move sections are separated by a colon
126 * Example: "edit=autoconfirmed,sysop:move=sysop"
128 protected $mOldRestrictions = false;
130 /** @var bool Cascade restrictions on this page to included templates and images? */
131 public $mCascadeRestriction;
133 /** Caching the results of getCascadeProtectionSources */
134 public $mCascadingRestrictions;
136 /** @var array When do the restrictions on this page expire? */
137 protected $mRestrictionsExpiry = [];
139 /** @var bool Are cascading restrictions in effect on this page? */
140 protected $mHasCascadingRestrictions;
142 /** @var array Where are the cascading restrictions coming from on this page? */
143 public $mCascadeSources;
145 /** @var bool Boolean for initialisation on demand */
146 public $mRestrictionsLoaded = false;
149 * Text form including namespace/interwiki, initialised on demand
151 * Only public to share cache with TitleFormatter
156 public $prefixedText = null;
158 /** @var mixed Cached value for getTitleProtection (create protection) */
159 public $mTitleProtection;
162 * @var int Namespace index when there is no namespace. Don't change the
163 * following default, NS_MAIN is hardcoded in several places. See T2696.
164 * Zero except in {{transclusion}} tags.
166 public $mDefaultNamespace = NS_MAIN
;
168 /** @var int The page length, 0 for special pages */
169 protected $mLength = -1;
171 /** @var null Is the article at this title a redirect? */
172 public $mRedirect = null;
174 /** @var array Associative array of user ID -> timestamp/false */
175 private $mNotificationTimestamp = [];
177 /** @var bool Whether a page has any subpages */
178 private $mHasSubpages;
180 /** @var bool The (string) language code of the page's language and content code. */
181 private $mPageLanguage = false;
183 /** @var string|bool|null The page language code from the database, null if not saved in
184 * the database or false if not loaded, yet. */
185 private $mDbPageLanguage = false;
187 /** @var TitleValue|null A corresponding TitleValue object */
188 private $mTitleValue = null;
190 /** @var bool|null Would deleting this page be a big deletion? */
191 private $mIsBigDeletion = null;
195 * B/C kludge: provide a TitleParser for use by Title.
196 * Ideally, Title would have no methods that need this.
197 * Avoid usage of this singleton by using TitleValue
198 * and the associated services when possible.
200 * @return TitleFormatter
202 private static function getTitleFormatter() {
203 return MediaWikiServices
::getInstance()->getTitleFormatter();
207 * B/C kludge: provide an InterwikiLookup for use by Title.
208 * Ideally, Title would have no methods that need this.
209 * Avoid usage of this singleton by using TitleValue
210 * and the associated services when possible.
212 * @return InterwikiLookup
214 private static function getInterwikiLookup() {
215 return MediaWikiServices
::getInstance()->getInterwikiLookup();
221 function __construct() {
225 * Create a new Title from a prefixed DB key
227 * @param string $key The database key, which has underscores
228 * instead of spaces, possibly including namespace and
230 * @return Title|null Title, or null on an error
232 public static function newFromDBkey( $key ) {
234 $t->mDbkeyform
= $key;
237 $t->secureAndSplit();
239 } catch ( MalformedTitleException
$ex ) {
245 * Returns a Title given a TitleValue.
246 * If the given TitleValue is already a Title instance, that instance is returned,
247 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
248 * is already a Title instance, that instance is copied using the clone operator.
250 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
252 * @param TitleValue $titleValue Assumed to be safe.
253 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
257 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
258 return self
::newFromLinkTarget( $titleValue, $forceClone );
262 * Returns a Title given a LinkTarget.
263 * If the given LinkTarget is already a Title instance, that instance is returned,
264 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
265 * is already a Title instance, that instance is copied using the clone operator.
267 * @param LinkTarget $linkTarget Assumed to be safe.
268 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
272 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
273 if ( $linkTarget instanceof Title
) {
274 // Special case if it's already a Title object
275 if ( $forceClone === self
::NEW_CLONE
) {
276 return clone $linkTarget;
281 return self
::makeTitle(
282 $linkTarget->getNamespace(),
283 $linkTarget->getText(),
284 $linkTarget->getFragment(),
285 $linkTarget->getInterwiki()
290 * Same as newFromLinkTarget, but if passed null, returns null.
292 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
296 public static function castFromLinkTarget( $linkTarget ) {
297 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
301 * Create a new Title from text, such as what one would find in a link. De-
302 * codes any HTML entities in the text.
304 * Title objects returned by this method are guaranteed to be valid, and
305 * thus return true from the isValid() method.
307 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
308 * It may instead be a cached instance created previously, with references to it remaining
311 * @param string|int|null $text The link text; spaces, prefixes, and an
312 * initial ':' indicating the main namespace are accepted.
313 * @param int $defaultNamespace The namespace to use if none is specified
314 * by a prefix. If you want to force a specific namespace even if
315 * $text might begin with a namespace prefix, use makeTitle() or
317 * @throws InvalidArgumentException
318 * @return Title|null Title or null on an error.
320 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
321 // DWIM: Integers can be passed in here when page titles are used as array keys.
322 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
323 throw new InvalidArgumentException( '$text must be a string.' );
325 if ( $text === null ) {
330 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
331 } catch ( MalformedTitleException
$ex ) {
337 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
338 * rather than returning null.
340 * The exception subclasses encode detailed information about why the title is invalid.
342 * Title objects returned by this method are guaranteed to be valid, and
343 * thus return true from the isValid() method.
345 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
346 * It may instead be a cached instance created previously, with references to it remaining
349 * @see Title::newFromText
352 * @param string $text Title text to check
353 * @param int $defaultNamespace
354 * @throws MalformedTitleException If the title is invalid
357 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
358 if ( is_object( $text ) ) {
359 throw new MWException( '$text must be a string, given an object' );
360 } elseif ( $text === null ) {
361 // Legacy code relies on MalformedTitleException being thrown in this case
362 // (happens when URL with no title in it is parsed). TODO fix
363 throw new MalformedTitleException( 'title-invalid-empty' );
366 $titleCache = self
::getTitleCache();
368 // Wiki pages often contain multiple links to the same page.
369 // Title normalization and parsing can become expensive on pages with many
370 // links, so we can save a little time by caching them.
371 // In theory these are value objects and won't get changed...
372 if ( $defaultNamespace == NS_MAIN
) {
373 $t = $titleCache->get( $text );
379 // Convert things like é ā or 〗 into normalized (T16952) text
380 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
383 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
384 $t->mDefaultNamespace
= (int)$defaultNamespace;
386 $t->secureAndSplit();
387 if ( $defaultNamespace == NS_MAIN
) {
388 $titleCache->set( $text, $t );
394 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
396 * Example of wrong and broken code:
397 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
399 * Example of right code:
400 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
402 * Create a new Title from URL-encoded text. Ensures that
403 * the given title's length does not exceed the maximum.
405 * @param string $url The title, as might be taken from a URL
406 * @return Title|null The new object, or null on an error
408 public static function newFromURL( $url ) {
411 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
412 # but some URLs used it as a space replacement and they still come
413 # from some external search tools.
414 if ( strpos( self
::legalChars(), '+' ) === false ) {
415 $url = strtr( $url, '+', ' ' );
418 $t->mDbkeyform
= strtr( $url, ' ', '_' );
421 $t->secureAndSplit();
423 } catch ( MalformedTitleException
$ex ) {
429 * @return MapCacheLRU
431 private static function getTitleCache() {
432 if ( self
::$titleCache === null ) {
433 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
435 return self
::$titleCache;
439 * Returns a list of fields that are to be selected for initializing Title
440 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
441 * whether to include page_content_model.
445 protected static function getSelectFields() {
446 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
449 'page_namespace', 'page_title', 'page_id',
450 'page_len', 'page_is_redirect', 'page_latest',
453 if ( $wgContentHandlerUseDB ) {
454 $fields[] = 'page_content_model';
457 if ( $wgPageLanguageUseDB ) {
458 $fields[] = 'page_lang';
465 * Create a new Title from an article ID
467 * @param int $id The page_id corresponding to the Title to create
468 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
469 * @return Title|null The new object, or null on an error
471 public static function newFromID( $id, $flags = 0 ) {
472 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
473 $row = $db->selectRow(
475 self
::getSelectFields(),
476 [ 'page_id' => $id ],
479 if ( $row !== false ) {
480 $title = self
::newFromRow( $row );
489 * Make an array of titles from an array of IDs
491 * @param int[] $ids Array of IDs
492 * @return Title[] Array of Titles
494 public static function newFromIDs( $ids ) {
495 if ( !count( $ids ) ) {
498 $dbr = wfGetDB( DB_REPLICA
);
502 self
::getSelectFields(),
503 [ 'page_id' => $ids ],
508 foreach ( $res as $row ) {
509 $titles[] = self
::newFromRow( $row );
515 * Make a Title object from a DB row
517 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
518 * @return Title Corresponding Title
520 public static function newFromRow( $row ) {
521 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
522 $t->loadFromRow( $row );
527 * Load Title object fields from a DB row.
528 * If false is given, the title will be treated as non-existing.
530 * @param stdClass|bool $row Database row
532 public function loadFromRow( $row ) {
533 if ( $row ) { // page found
534 if ( isset( $row->page_id
) ) {
535 $this->mArticleID
= (int)$row->page_id
;
537 if ( isset( $row->page_len
) ) {
538 $this->mLength
= (int)$row->page_len
;
540 if ( isset( $row->page_is_redirect
) ) {
541 $this->mRedirect
= (bool)$row->page_is_redirect
;
543 if ( isset( $row->page_latest
) ) {
544 $this->mLatestID
= (int)$row->page_latest
;
546 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
547 $this->mContentModel
= (string)$row->page_content_model
;
548 } elseif ( !$this->mForcedContentModel
) {
549 $this->mContentModel
= false; # initialized lazily in getContentModel()
551 if ( isset( $row->page_lang
) ) {
552 $this->mDbPageLanguage
= (string)$row->page_lang
;
554 if ( isset( $row->page_restrictions
) ) {
555 $this->mOldRestrictions
= $row->page_restrictions
;
557 } else { // page not found
558 $this->mArticleID
= 0;
560 $this->mRedirect
= false;
561 $this->mLatestID
= 0;
562 if ( !$this->mForcedContentModel
) {
563 $this->mContentModel
= false; # initialized lazily in getContentModel()
569 * Create a new Title from a namespace index and a DB key.
571 * It's assumed that $ns and $title are safe, for instance when
572 * they came directly from the database or a special page name,
573 * not from user input.
575 * No validation is applied. For convenience, spaces are normalized
576 * to underscores, so that e.g. user_text fields can be used directly.
578 * @note This method may return Title objects that are "invalid"
579 * according to the isValid() method. This is usually caused by
580 * configuration changes: e.g. a namespace that was once defined is
581 * no longer configured, or a character that was once allowed in
582 * titles is now forbidden.
584 * @param int $ns The namespace of the article
585 * @param string $title The unprefixed database key form
586 * @param string $fragment The link fragment (after the "#")
587 * @param string $interwiki The interwiki prefix
588 * @return Title The new object
590 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
592 $t->mInterwiki
= $interwiki;
593 $t->mFragment
= $fragment;
594 $t->mNamespace
= $ns = (int)$ns;
595 $t->mDbkeyform
= strtr( $title, ' ', '_' );
596 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
597 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
598 $t->mTextform
= strtr( $title, '_', ' ' );
599 $t->mContentModel
= false; # initialized lazily in getContentModel()
604 * Create a new Title from a namespace index and a DB key.
605 * The parameters will be checked for validity, which is a bit slower
606 * than makeTitle() but safer for user-provided data.
608 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
609 * that is, they return true from the isValid() method. If no valid Title
610 * can be constructed from the input, this method returns null.
612 * @param int $ns The namespace of the article
613 * @param string $title Database key form
614 * @param string $fragment The link fragment (after the "#")
615 * @param string $interwiki Interwiki prefix
616 * @return Title|null The new object, or null on an error
618 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
619 // NOTE: ideally, this would just call makeTitle() and then isValid(),
620 // but presently, that means more overhead on a potential performance hotspot.
622 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
627 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
630 $t->secureAndSplit();
632 } catch ( MalformedTitleException
$ex ) {
638 * Create a new Title for the Main Page
640 * This uses the 'mainpage' interface message, which could be specified in
641 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
642 * will use the user language, which would involve initialising the session
643 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
644 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
645 * or ResourceloaderContext) to prevent an error.
647 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
648 * It may instead be a cached instance created previously, with references to it remaining
651 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
654 public static function newMainPage( MessageLocalizer
$localizer = null ) {
656 $msg = $localizer->msg( 'mainpage' );
658 $msg = wfMessage( 'mainpage' );
661 $title = self
::newFromText( $msg->inContentLanguage()->text() );
663 // Every page renders at least one link to the Main Page (e.g. sidebar).
664 // If the localised value is invalid, don't produce fatal errors that
665 // would make the wiki inaccessible (and hard to fix the invalid message).
666 // Gracefully fallback...
668 $title = self
::newFromText( 'Main Page' );
674 * Get the prefixed DB key associated with an ID
676 * @param int $id The page_id of the article
677 * @return Title|null An object representing the article, or null if no such article was found
679 public static function nameOf( $id ) {
680 $dbr = wfGetDB( DB_REPLICA
);
682 $s = $dbr->selectRow(
684 [ 'page_namespace', 'page_title' ],
685 [ 'page_id' => $id ],
688 if ( $s === false ) {
692 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
697 * Get a regex character class describing the legal characters in a link
699 * @return string The list of characters, not delimited
701 public static function legalChars() {
702 global $wgLegalTitleChars;
703 return $wgLegalTitleChars;
707 * Utility method for converting a character sequence from bytes to Unicode.
709 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
710 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
712 * @param string $byteClass
715 public static function convertByteClassToUnicodeClass( $byteClass ) {
716 $length = strlen( $byteClass );
718 $x0 = $x1 = $x2 = '';
720 $d0 = $d1 = $d2 = '';
721 // Decoded integer codepoints
722 $ord0 = $ord1 = $ord2 = 0;
724 $r0 = $r1 = $r2 = '';
728 $allowUnicode = false;
729 for ( $pos = 0; $pos < $length; $pos++
) {
730 // Shift the queues down
739 // Load the current input token and decoded values
740 $inChar = $byteClass[$pos];
741 if ( $inChar == '\\' ) {
742 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
743 $x0 = $inChar . $m[0];
744 $d0 = chr( hexdec( $m[1] ) );
745 $pos +
= strlen( $m[0] );
746 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
747 $x0 = $inChar . $m[0];
748 $d0 = chr( octdec( $m[0] ) );
749 $pos +
= strlen( $m[0] );
750 } elseif ( $pos +
1 >= $length ) {
753 $d0 = $byteClass[$pos +
1];
761 // Load the current re-encoded value
762 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
763 $r0 = sprintf( '\x%02x', $ord0 );
764 } elseif ( $ord0 >= 0x80 ) {
765 // Allow unicode if a single high-bit character appears
766 $r0 = sprintf( '\x%02x', $ord0 );
767 $allowUnicode = true;
768 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
769 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
775 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
777 if ( $ord2 > $ord0 ) {
779 } elseif ( $ord0 >= 0x80 ) {
781 $allowUnicode = true;
782 if ( $ord2 < 0x80 ) {
783 // Keep the non-unicode section of the range
790 // Reset state to the initial value
791 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
792 } elseif ( $ord2 < 0x80 ) {
797 if ( $ord1 < 0x80 ) {
800 if ( $ord0 < 0x80 ) {
803 if ( $allowUnicode ) {
804 $out .= '\u0080-\uFFFF';
810 * Make a prefixed DB key from a DB key and a namespace index
812 * @param int $ns Numerical representation of the namespace
813 * @param string $title The DB key form the title
814 * @param string $fragment The link fragment (after the "#")
815 * @param string $interwiki The interwiki prefix
816 * @param bool $canonicalNamespace If true, use the canonical name for
817 * $ns instead of the localized version.
818 * @return string The prefixed form of the title
820 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
821 $canonicalNamespace = false
823 if ( $canonicalNamespace ) {
824 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
825 getCanonicalName( $ns );
827 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
829 $name = $namespace == '' ?
$title : "$namespace:$title";
830 if ( strval( $interwiki ) != '' ) {
831 $name = "$interwiki:$name";
833 if ( strval( $fragment ) != '' ) {
834 $name .= '#' . $fragment;
840 * Callback for usort() to do title sorts by (namespace, title)
842 * @param LinkTarget $a
843 * @param LinkTarget $b
845 * @return int Result of string comparison, or namespace comparison
847 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
848 return $a->getNamespace() <=> $b->getNamespace()
849 ?
: strcmp( $a->getText(), $b->getText() );
853 * Returns true if the title is valid, false if it is invalid.
855 * Valid titles can be round-tripped via makeTitle() and newFromText().
856 * Their DB key can be used in the database, though it may not have the correct
859 * Invalid titles may get returned from makeTitle(), and it may be useful to
860 * allow them to exist, e.g. in order to process log entries about pages in
861 * namespaces that belong to extensions that are no longer installed.
863 * @note This method is relatively expensive. When constructing Title
864 * objects that need to be valid, use an instantiator method that is guaranteed
865 * to return valid titles, such as makeTitleSafe() or newFromText().
869 public function isValid() {
870 $services = MediaWikiServices
::getInstance();
871 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
876 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
877 } catch ( MalformedTitleException
$ex ) {
882 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
889 } catch ( InvalidArgumentException
$ex ) {
897 * Determine whether the object refers to a page within
898 * this project (either this wiki or a wiki with a local
899 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
901 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
903 public function isLocal() {
904 if ( $this->isExternal() ) {
905 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
907 return $iw->isLocal();
914 * Is this Title interwiki?
918 public function isExternal() {
919 return $this->mInterwiki
!== '';
923 * Get the interwiki prefix
925 * Use Title::isExternal to check if a interwiki is set
927 * @return string Interwiki prefix
929 public function getInterwiki() {
930 return $this->mInterwiki
;
934 * Was this a local interwiki link?
938 public function wasLocalInterwiki() {
939 return $this->mLocalInterwiki
;
943 * Determine whether the object refers to a page within
944 * this project and is transcludable.
946 * @return bool True if this is transcludable
948 public function isTrans() {
949 if ( !$this->isExternal() ) {
953 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
957 * Returns the DB name of the distant wiki which owns the object.
959 * @return string|false The DB name
961 public function getTransWikiID() {
962 if ( !$this->isExternal() ) {
966 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
970 * Get a TitleValue object representing this Title.
972 * @note Not all valid Titles have a corresponding valid TitleValue
973 * (e.g. TitleValues cannot represent page-local links that have a
974 * fragment but no title text).
976 * @return TitleValue|null
978 public function getTitleValue() {
979 if ( $this->mTitleValue
=== null ) {
981 $this->mTitleValue
= new TitleValue(
987 } catch ( InvalidArgumentException
$ex ) {
988 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
989 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
993 return $this->mTitleValue
;
997 * Get the text form (spaces not underscores) of the main part
999 * @return string Main part of the title
1001 public function getText() {
1002 return $this->mTextform
;
1006 * Get the URL-encoded form of the main part
1008 * @return string Main part of the title, URL-encoded
1010 public function getPartialURL() {
1011 return $this->mUrlform
;
1015 * Get the main part with underscores
1017 * @return string Main part of the title, with underscores
1019 public function getDBkey() {
1020 return $this->mDbkeyform
;
1024 * Get the DB key with the initial letter case as specified by the user
1025 * @deprecated since 1.33; please use Title::getDBKey() instead
1027 * @return string DB key
1029 function getUserCaseDBKey() {
1030 if ( !is_null( $this->mUserCaseDBKey
) ) {
1031 return $this->mUserCaseDBKey
;
1033 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1034 return $this->mDbkeyform
;
1039 * Get the namespace index, i.e. one of the NS_xxxx constants.
1041 * @return int Namespace index
1043 public function getNamespace() {
1044 return $this->mNamespace
;
1048 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1050 * @todo Deprecate this in favor of SlotRecord::getModel()
1052 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1053 * @return string Content model id
1055 public function getContentModel( $flags = 0 ) {
1056 if ( !$this->mForcedContentModel
1057 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1058 && $this->getArticleID( $flags )
1060 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1061 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1062 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1065 if ( !$this->mContentModel
) {
1066 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1069 return $this->mContentModel
;
1073 * Convenience method for checking a title's content model name
1075 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1076 * @return bool True if $this->getContentModel() == $id
1078 public function hasContentModel( $id ) {
1079 return $this->getContentModel() == $id;
1083 * Set a proposed content model for the page for permissions
1084 * checking. This does not actually change the content model
1087 * Additionally, you should make sure you've checked
1088 * ContentHandler::canBeUsedOn() first.
1091 * @param string $model CONTENT_MODEL_XXX constant
1093 public function setContentModel( $model ) {
1094 $this->mContentModel
= $model;
1095 $this->mForcedContentModel
= true;
1099 * Get the namespace text
1101 * @return string|false Namespace text
1103 public function getNsText() {
1104 if ( $this->isExternal() ) {
1105 // This probably shouldn't even happen, except for interwiki transclusion.
1106 // If possible, use the canonical name for the foreign namespace.
1107 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1108 getCanonicalName( $this->mNamespace
);
1109 if ( $nsText !== false ) {
1115 $formatter = self
::getTitleFormatter();
1116 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1117 } catch ( InvalidArgumentException
$ex ) {
1118 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1124 * Get the namespace text of the subject (rather than talk) page
1126 * @return string Namespace text
1128 public function getSubjectNsText() {
1129 $services = MediaWikiServices
::getInstance();
1130 return $services->getContentLanguage()->
1131 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1135 * Get the namespace text of the talk page
1137 * @return string Namespace text
1139 public function getTalkNsText() {
1140 $services = MediaWikiServices
::getInstance();
1141 return $services->getContentLanguage()->
1142 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1146 * Can this title have a corresponding talk page?
1148 * False for relative section links (with getText() === ''),
1149 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1151 * @see NamespaceInfo::canHaveTalkPage
1154 * @return bool True if this title either is a talk page or can have a talk page associated.
1156 public function canHaveTalkPage() {
1157 return MediaWikiServices
::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1161 * Is this in a namespace that allows actual pages?
1165 public function canExist() {
1166 return $this->mNamespace
>= NS_MAIN
;
1170 * Can this title be added to a user's watchlist?
1172 * False for relative section links (with getText() === ''),
1173 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1177 public function isWatchable() {
1178 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
1179 return $this->getText() !== '' && !$this->isExternal() &&
1180 $nsInfo->isWatchable( $this->mNamespace
);
1184 * Returns true if this is a special page.
1188 public function isSpecialPage() {
1189 return $this->mNamespace
== NS_SPECIAL
;
1193 * Returns true if this title resolves to the named special page
1195 * @param string $name The special page name
1198 public function isSpecial( $name ) {
1199 if ( $this->isSpecialPage() ) {
1200 list( $thisName, /* $subpage */ ) =
1201 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1202 resolveAlias( $this->mDbkeyform
);
1203 if ( $name == $thisName ) {
1211 * If the Title refers to a special page alias which is not the local default, resolve
1212 * the alias, and localise the name as necessary. Otherwise, return $this
1216 public function fixSpecialName() {
1217 if ( $this->isSpecialPage() ) {
1218 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1219 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1220 if ( $canonicalName ) {
1221 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1222 if ( $localName != $this->mDbkeyform
) {
1223 return self
::makeTitle( NS_SPECIAL
, $localName );
1231 * Returns true if the title is inside the specified namespace.
1233 * Please make use of this instead of comparing to getNamespace()
1234 * This function is much more resistant to changes we may make
1235 * to namespaces than code that makes direct comparisons.
1236 * @param int $ns The namespace
1240 public function inNamespace( $ns ) {
1241 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1242 equals( $this->mNamespace
, $ns );
1246 * Returns true if the title is inside one of the specified namespaces.
1248 * @param int|int[] $namespaces,... The namespaces to check for
1252 public function inNamespaces( /* ... */ ) {
1253 $namespaces = func_get_args();
1254 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1255 $namespaces = $namespaces[0];
1258 foreach ( $namespaces as $ns ) {
1259 if ( $this->inNamespace( $ns ) ) {
1268 * Returns true if the title has the same subject namespace as the
1269 * namespace specified.
1270 * For example this method will take NS_USER and return true if namespace
1271 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1272 * as their subject namespace.
1274 * This is MUCH simpler than individually testing for equivalence
1275 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1280 public function hasSubjectNamespace( $ns ) {
1281 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1282 subjectEquals( $this->mNamespace
, $ns );
1286 * Is this Title in a namespace which contains content?
1287 * In other words, is this a content page, for the purposes of calculating
1292 public function isContentPage() {
1293 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1294 isContent( $this->mNamespace
);
1298 * Would anybody with sufficient privileges be able to move this page?
1299 * Some pages just aren't movable.
1303 public function isMovable() {
1305 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1306 isMovable( $this->mNamespace
) ||
$this->isExternal()
1308 // Interwiki title or immovable namespace. Hooks don't get to override here
1313 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1318 * Is this the mainpage?
1319 * @note Title::newFromText seems to be sufficiently optimized by the title
1320 * cache that we don't need to over-optimize by doing direct comparisons and
1321 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1322 * ends up reporting something differently than $title->isMainPage();
1327 public function isMainPage() {
1328 return $this->equals( self
::newMainPage() );
1332 * Is this a subpage?
1336 public function isSubpage() {
1337 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1338 hasSubpages( $this->mNamespace
)
1339 ?
strpos( $this->getText(), '/' ) !== false
1344 * Is this a conversion table for the LanguageConverter?
1348 public function isConversionTable() {
1349 // @todo ConversionTable should become a separate content model.
1351 return $this->mNamespace
== NS_MEDIAWIKI
&&
1352 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1356 * Does that page contain wikitext, or it is JS, CSS or whatever?
1360 public function isWikitextPage() {
1361 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1365 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1366 * global UI. This is generally true for pages in the MediaWiki namespace having
1367 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1369 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1372 * Note that this method should not return true for pages that contain and show
1373 * "inactive" CSS, JSON, or JS.
1378 public function isSiteConfigPage() {
1380 $this->isSiteCssConfigPage()
1381 ||
$this->isSiteJsonConfigPage()
1382 ||
$this->isSiteJsConfigPage()
1387 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1392 public function isUserConfigPage() {
1394 $this->isUserCssConfigPage()
1395 ||
$this->isUserJsonConfigPage()
1396 ||
$this->isUserJsConfigPage()
1401 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1403 * @return string Containing skin name from .css, .json, or .js subpage title
1406 public function getSkinFromConfigSubpage() {
1407 $subpage = explode( '/', $this->mTextform
);
1408 $subpage = $subpage[count( $subpage ) - 1];
1409 $lastdot = strrpos( $subpage, '.' );
1410 if ( $lastdot === false ) {
1411 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1413 return substr( $subpage, 0, $lastdot );
1417 * Is this a CSS "config" sub-page of a user page?
1422 public function isUserCssConfigPage() {
1424 NS_USER
== $this->mNamespace
1425 && $this->isSubpage()
1426 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1431 * Is this a JSON "config" sub-page of a user page?
1436 public function isUserJsonConfigPage() {
1438 NS_USER
== $this->mNamespace
1439 && $this->isSubpage()
1440 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1445 * Is this a JS "config" sub-page of a user page?
1450 public function isUserJsConfigPage() {
1452 NS_USER
== $this->mNamespace
1453 && $this->isSubpage()
1454 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1459 * Is this a sitewide CSS "config" page?
1464 public function isSiteCssConfigPage() {
1466 NS_MEDIAWIKI
== $this->mNamespace
1468 $this->hasContentModel( CONTENT_MODEL_CSS
)
1469 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1470 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1471 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1477 * Is this a sitewide JSON "config" page?
1482 public function isSiteJsonConfigPage() {
1484 NS_MEDIAWIKI
== $this->mNamespace
1486 $this->hasContentModel( CONTENT_MODEL_JSON
)
1487 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1488 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1489 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1495 * Is this a sitewide JS "config" page?
1500 public function isSiteJsConfigPage() {
1502 NS_MEDIAWIKI
== $this->mNamespace
1504 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1505 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1506 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1507 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1513 * Is this a message which can contain raw HTML?
1518 public function isRawHtmlMessage() {
1519 global $wgRawHtmlMessages;
1521 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1524 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1525 return in_array( $message, $wgRawHtmlMessages, true );
1529 * Is this a talk page of some sort?
1533 public function isTalkPage() {
1534 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1535 isTalk( $this->mNamespace
);
1539 * Get a Title object associated with the talk page of this article
1541 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1542 * with NamespaceInfo::canHaveTalkPage().
1543 * @return Title The object for the talk page
1544 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1545 * or because it's a relative link, or an interwiki link.
1547 public function getTalkPage() {
1548 return self
::castFromLinkTarget(
1549 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1553 * Get a Title object associated with the talk page of this article,
1554 * if such a talk page can exist.
1558 * @return Title|null The object for the talk page,
1559 * or null if no associated talk page can exist, according to canHaveTalkPage().
1561 public function getTalkPageIfDefined() {
1562 if ( !$this->canHaveTalkPage() ) {
1566 return $this->getTalkPage();
1570 * Get a title object associated with the subject page of this
1573 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1574 * @return Title The object for the subject page
1576 public function getSubjectPage() {
1577 return self
::castFromLinkTarget(
1578 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1582 * Get the other title for this page, if this is a subject page
1583 * get the talk page, if it is a subject page get the talk page
1585 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1587 * @throws MWException If the page doesn't have an other page
1590 public function getOtherPage() {
1591 return self
::castFromLinkTarget(
1592 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1596 * Get the default namespace index, for when there is no namespace
1598 * @return int Default namespace index
1600 public function getDefaultNamespace() {
1601 return $this->mDefaultNamespace
;
1605 * Get the Title fragment (i.e.\ the bit after the #) in text form
1607 * Use Title::hasFragment to check for a fragment
1609 * @return string Title fragment
1611 public function getFragment() {
1612 return $this->mFragment
;
1616 * Check if a Title fragment is set
1621 public function hasFragment() {
1622 return $this->mFragment
!== '';
1626 * Get the fragment in URL form, including the "#" character if there is one
1628 * @return string Fragment in URL form
1630 public function getFragmentForURL() {
1631 if ( !$this->hasFragment() ) {
1633 } elseif ( $this->isExternal() ) {
1634 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1635 // so we treat it like a local interwiki.
1636 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1637 if ( $interwiki && !$interwiki->isLocal() ) {
1638 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1642 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1646 * Set the fragment for this title. Removes the first character from the
1647 * specified fragment before setting, so it assumes you're passing it with
1650 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1651 * or Title::createFragmentTarget().
1652 * Still in active use privately.
1655 * @param string $fragment Text
1657 public function setFragment( $fragment ) {
1658 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1662 * Creates a new Title for a different fragment of the same page.
1665 * @param string $fragment
1668 public function createFragmentTarget( $fragment ) {
1669 return self
::makeTitle(
1678 * Prefix some arbitrary text with the namespace or interwiki prefix
1681 * @param string $name The text
1682 * @return string The prefixed text
1684 private function prefix( $name ) {
1686 if ( $this->isExternal() ) {
1687 $p = $this->mInterwiki
. ':';
1690 if ( $this->mNamespace
!= 0 ) {
1691 $nsText = $this->getNsText();
1693 if ( $nsText === false ) {
1694 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1695 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1696 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1699 $p .= $nsText . ':';
1705 * Get the prefixed database key form
1707 * @return string The prefixed title, with underscores and
1708 * any interwiki and namespace prefixes
1710 public function getPrefixedDBkey() {
1711 $s = $this->prefix( $this->mDbkeyform
);
1712 $s = strtr( $s, ' ', '_' );
1717 * Get the prefixed title with spaces.
1718 * This is the form usually used for display
1720 * @return string The prefixed title, with spaces
1722 public function getPrefixedText() {
1723 if ( $this->prefixedText
=== null ) {
1724 $s = $this->prefix( $this->mTextform
);
1725 $s = strtr( $s, '_', ' ' );
1726 $this->prefixedText
= $s;
1728 return $this->prefixedText
;
1732 * Return a string representation of this title
1734 * @return string Representation of this title
1736 public function __toString() {
1737 return $this->getPrefixedText();
1741 * Get the prefixed title with spaces, plus any fragment
1742 * (part beginning with '#')
1744 * @return string The prefixed title, with spaces and the fragment, including '#'
1746 public function getFullText() {
1747 $text = $this->getPrefixedText();
1748 if ( $this->hasFragment() ) {
1749 $text .= '#' . $this->mFragment
;
1755 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1757 * @note the return value may contain trailing whitespace and is thus
1758 * not safe for use with makeTitle or TitleValue.
1762 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1766 * @return string Root name
1769 public function getRootText() {
1771 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1772 hasSubpages( $this->mNamespace
)
1774 return $this->getText();
1777 return strtok( $this->getText(), '/' );
1781 * Get the root page name title, i.e. the leftmost part before any slashes
1785 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1786 * # returns: Title{User:Foo}
1789 * @return Title Root title
1792 public function getRootTitle() {
1793 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getRootText() );
1794 Assert
::postcondition(
1796 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1802 * Get the base page name without a namespace, i.e. the part before the subpage name
1804 * @note the return value may contain trailing whitespace and is thus
1805 * not safe for use with makeTitle or TitleValue.
1809 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1810 * # returns: 'Foo/Bar'
1813 * @return string Base name
1815 public function getBaseText() {
1816 $text = $this->getText();
1818 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1819 hasSubpages( $this->mNamespace
)
1824 $lastSlashPos = strrpos( $text, '/' );
1825 // Don't discard the real title if there's no subpage involved
1826 if ( $lastSlashPos === false ) {
1830 return substr( $text, 0, $lastSlashPos );
1834 * Get the base page name title, i.e. the part before the subpage name.
1838 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1839 * # returns: Title{User:Foo/Bar}
1842 * @return Title Base title
1845 public function getBaseTitle() {
1846 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getBaseText() );
1847 Assert
::postcondition(
1849 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1855 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1859 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1863 * @return string Subpage name
1865 public function getSubpageText() {
1867 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1868 hasSubpages( $this->mNamespace
)
1870 return $this->mTextform
;
1872 $parts = explode( '/', $this->mTextform
);
1873 return $parts[count( $parts ) - 1];
1877 * Get the title for a subpage of the current page
1881 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1882 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1885 * @param string $text The subpage name to add to the title
1886 * @return Title|null Subpage title, or null on an error
1889 public function getSubpage( $text ) {
1890 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1894 * Get a URL-encoded form of the subpage text
1896 * @return string URL-encoded subpage name
1898 public function getSubpageUrlForm() {
1899 $text = $this->getSubpageText();
1900 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1905 * Get a URL-encoded title (not an actual URL) including interwiki
1907 * @return string The URL-encoded form
1909 public function getPrefixedURL() {
1910 $s = $this->prefix( $this->mDbkeyform
);
1911 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1916 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1917 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1918 * second argument named variant. This was deprecated in favor
1919 * of passing an array of option with a "variant" key
1920 * Once $query2 is removed for good, this helper can be dropped
1921 * and the wfArrayToCgi moved to getLocalURL();
1923 * @since 1.19 (r105919)
1924 * @param array|string $query
1925 * @param string|string[]|bool $query2
1928 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1929 if ( $query2 !== false ) {
1930 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1931 "method called with a second parameter is deprecated. Add your " .
1932 "parameter to an array passed as the first parameter.", "1.19" );
1934 if ( is_array( $query ) ) {
1935 $query = wfArrayToCgi( $query );
1938 if ( is_string( $query2 ) ) {
1939 // $query2 is a string, we will consider this to be
1940 // a deprecated $variant argument and add it to the query
1941 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1943 $query2 = wfArrayToCgi( $query2 );
1945 // If we have $query content add a & to it first
1949 // Now append the queries together
1956 * Get a real URL referring to this title, with interwiki link and
1959 * @see self::getLocalURL for the arguments.
1961 * @param string|string[] $query
1962 * @param string|string[]|bool $query2
1963 * @param string|int|null $proto Protocol type to use in URL
1964 * @return string The URL
1966 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1967 $query = self
::fixUrlQueryArgs( $query, $query2 );
1969 # Hand off all the decisions on urls to getLocalURL
1970 $url = $this->getLocalURL( $query );
1972 # Expand the url to make it a full url. Note that getLocalURL has the
1973 # potential to output full urls for a variety of reasons, so we use
1974 # wfExpandUrl instead of simply prepending $wgServer
1975 $url = wfExpandUrl( $url, $proto );
1977 # Finally, add the fragment.
1978 $url .= $this->getFragmentForURL();
1979 // Avoid PHP 7.1 warning from passing $this by reference
1981 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1986 * Get a url appropriate for making redirects based on an untrusted url arg
1988 * This is basically the same as getFullUrl(), but in the case of external
1989 * interwikis, we send the user to a landing page, to prevent possible
1990 * phishing attacks and the like.
1992 * @note Uses current protocol by default, since technically relative urls
1993 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1994 * places where the url gets cached, as might pollute between
1995 * https and non-https users.
1996 * @see self::getLocalURL for the arguments.
1997 * @param array|string $query
1998 * @param string $proto Protocol type to use in URL
1999 * @return string A url suitable to use in an HTTP location header.
2001 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
2003 if ( $this->isExternal() ) {
2004 $target = SpecialPage
::getTitleFor(
2006 $this->getPrefixedDBkey()
2009 return $target->getFullURL( $query, false, $proto );
2013 * Get a URL with no fragment or server name (relative URL) from a Title object.
2014 * If this page is generated with action=render, however,
2015 * $wgServer is prepended to make an absolute URL.
2017 * @see self::getFullURL to always get an absolute URL.
2018 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2019 * valid to link, locally, to the current Title.
2020 * @see self::newFromText to produce a Title object.
2022 * @param string|string[] $query An optional query string,
2023 * not used for interwiki links. Can be specified as an associative array as well,
2024 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2025 * Some query patterns will trigger various shorturl path replacements.
2026 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2027 * be an array. If a string is passed it will be interpreted as a deprecated
2028 * variant argument and urlencoded into a variant= argument.
2029 * This second query argument will be added to the $query
2030 * The second parameter is deprecated since 1.19. Pass it as a key,value
2031 * pair in the first parameter array instead.
2033 * @return string String of the URL.
2035 public function getLocalURL( $query = '', $query2 = false ) {
2036 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
2038 $query = self
::fixUrlQueryArgs( $query, $query2 );
2040 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2042 $namespace = $this->getNsText();
2043 if ( $namespace != '' ) {
2044 # Can this actually happen? Interwikis shouldn't be parsed.
2045 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2048 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2049 $url = wfAppendQuery( $url, $query );
2051 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2052 if ( $query == '' ) {
2053 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2054 // Avoid PHP 7.1 warning from passing $this by reference
2056 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2058 global $wgVariantArticlePath, $wgActionPaths;
2062 if ( !empty( $wgActionPaths )
2063 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2065 $action = urldecode( $matches[2] );
2066 if ( isset( $wgActionPaths[$action] ) ) {
2067 $query = $matches[1];
2068 if ( isset( $matches[4] ) ) {
2069 $query .= $matches[4];
2071 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2072 if ( $query != '' ) {
2073 $url = wfAppendQuery( $url, $query );
2079 && $wgVariantArticlePath
2080 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2081 && $this->getPageLanguage()->equals(
2082 MediaWikiServices
::getInstance()->getContentLanguage() )
2083 && $this->getPageLanguage()->hasVariants()
2085 $variant = urldecode( $matches[1] );
2086 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2087 // Only do the variant replacement if the given variant is a valid
2088 // variant for the page's language.
2089 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2090 $url = str_replace( '$1', $dbkey, $url );
2094 if ( $url === false ) {
2095 if ( $query == '-' ) {
2098 $url = "{$wgScript}?title={$dbkey}&{$query}";
2101 // Avoid PHP 7.1 warning from passing $this by reference
2103 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2105 // @todo FIXME: This causes breakage in various places when we
2106 // actually expected a local URL and end up with dupe prefixes.
2107 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2108 $url = $wgServer . $url;
2111 // Avoid PHP 7.1 warning from passing $this by reference
2113 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2118 * Get a URL that's the simplest URL that will be valid to link, locally,
2119 * to the current Title. It includes the fragment, but does not include
2120 * the server unless action=render is used (or the link is external). If
2121 * there's a fragment but the prefixed text is empty, we just return a link
2124 * The result obviously should not be URL-escaped, but does need to be
2125 * HTML-escaped if it's being output in HTML.
2127 * @param string|string[] $query
2128 * @param bool $query2
2129 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2130 * or false (default) for no expansion
2131 * @see self::getLocalURL for the arguments.
2132 * @return string The URL
2134 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2135 if ( $this->isExternal() ||
$proto !== false ) {
2136 $ret = $this->getFullURL( $query, $query2, $proto );
2137 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2138 $ret = $this->getFragmentForURL();
2140 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2146 * Get the URL form for an internal link.
2147 * - Used in various CDN-related code, in case we have a different
2148 * internal hostname for the server from the exposed one.
2150 * This uses $wgInternalServer to qualify the path, or $wgServer
2151 * if $wgInternalServer is not set. If the server variable used is
2152 * protocol-relative, the URL will be expanded to http://
2154 * @see self::getLocalURL for the arguments.
2155 * @param string|string[] $query
2156 * @param string|bool $query2 Deprecated
2157 * @return string The URL
2159 public function getInternalURL( $query = '', $query2 = false ) {
2160 global $wgInternalServer, $wgServer;
2161 $query = self
::fixUrlQueryArgs( $query, $query2 );
2162 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2163 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2164 // Avoid PHP 7.1 warning from passing $this by reference
2166 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2171 * Get the URL for a canonical link, for use in things like IRC and
2172 * e-mail notifications. Uses $wgCanonicalServer and the
2173 * GetCanonicalURL hook.
2175 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2177 * @see self::getLocalURL for the arguments.
2178 * @param string|string[] $query
2179 * @param string|bool $query2 Deprecated
2180 * @return string The URL
2183 public function getCanonicalURL( $query = '', $query2 = false ) {
2184 $query = self
::fixUrlQueryArgs( $query, $query2 );
2185 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2186 // Avoid PHP 7.1 warning from passing $this by reference
2188 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2193 * Get the edit URL for this Title
2195 * @return string The URL, or a null string if this is an interwiki link
2197 public function getEditURL() {
2198 if ( $this->isExternal() ) {
2201 $s = $this->getLocalURL( 'action=edit' );
2207 * Can $user perform $action on this page?
2208 * This skips potentially expensive cascading permission checks
2209 * as well as avoids expensive error formatting
2211 * Suitable for use for nonessential UI controls in common cases, but
2212 * _not_ for functional access control.
2214 * May provide false positives, but should never provide a false negative.
2216 * @param string $action Action that permission needs to be checked for
2217 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2222 * @deprecated since 1.33,
2223 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2226 public function quickUserCan( $action, $user = null ) {
2227 return $this->userCan( $action, $user, false );
2231 * Can $user perform $action on this page?
2233 * @param string $action Action that permission needs to be checked for
2234 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2236 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2241 * @deprecated since 1.33,
2242 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2245 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2246 if ( !$user instanceof User
) {
2251 // TODO: this is for b/c, eventually will be removed
2252 if ( $rigor === true ) {
2253 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2254 } elseif ( $rigor === false ) {
2255 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2258 return MediaWikiServices
::getInstance()->getPermissionManager()
2259 ->userCan( $action, $user, $this, $rigor );
2263 * Can $user perform $action on this page?
2265 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2267 * @param string $action Action that permission needs to be checked for
2268 * @param User $user User to check
2269 * @param string $rigor One of (quick,full,secure)
2270 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2271 * - full : does cheap and expensive checks possibly from a replica DB
2272 * - secure : does cheap and expensive checks, using the master as needed
2273 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2274 * whose corresponding errors may be ignored.
2276 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2279 * @deprecated since 1.33,
2280 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2283 public function getUserPermissionsErrors(
2284 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2286 // TODO: this is for b/c, eventually will be removed
2287 if ( $rigor === true ) {
2288 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2289 } elseif ( $rigor === false ) {
2290 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2293 return MediaWikiServices
::getInstance()->getPermissionManager()
2294 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2298 * Get a filtered list of all restriction types supported by this wiki.
2299 * @param bool $exists True to get all restriction types that apply to
2300 * titles that do exist, False for all restriction types that apply to
2301 * titles that do not exist
2304 public static function getFilteredRestrictionTypes( $exists = true ) {
2305 global $wgRestrictionTypes;
2306 $types = $wgRestrictionTypes;
2308 # Remove the create restriction for existing titles
2309 $types = array_diff( $types, [ 'create' ] );
2311 # Only the create and upload restrictions apply to non-existing titles
2312 $types = array_intersect( $types, [ 'create', 'upload' ] );
2318 * Returns restriction types for the current Title
2320 * @return array Applicable restriction types
2322 public function getRestrictionTypes() {
2323 if ( $this->isSpecialPage() ) {
2327 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2329 if ( $this->mNamespace
!= NS_FILE
) {
2330 # Remove the upload restriction for non-file titles
2331 $types = array_diff( $types, [ 'upload' ] );
2334 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2336 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2337 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2343 * Is this title subject to title protection?
2344 * Title protection is the one applied against creation of such title.
2346 * @return array|bool An associative array representing any existent title
2347 * protection, or false if there's none.
2349 public function getTitleProtection() {
2350 $protection = $this->getTitleProtectionInternal();
2351 if ( $protection ) {
2352 if ( $protection['permission'] == 'sysop' ) {
2353 $protection['permission'] = 'editprotected'; // B/C
2355 if ( $protection['permission'] == 'autoconfirmed' ) {
2356 $protection['permission'] = 'editsemiprotected'; // B/C
2363 * Fetch title protection settings
2365 * To work correctly, $this->loadRestrictions() needs to have access to the
2366 * actual protections in the database without munging 'sysop' =>
2367 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2368 * callers probably want $this->getTitleProtection() instead.
2370 * @return array|bool
2372 protected function getTitleProtectionInternal() {
2373 // Can't protect pages in special namespaces
2374 if ( $this->mNamespace
< 0 ) {
2378 // Can't protect pages that exist.
2379 if ( $this->exists() ) {
2383 if ( $this->mTitleProtection
=== null ) {
2384 $dbr = wfGetDB( DB_REPLICA
);
2385 $commentStore = CommentStore
::getStore();
2386 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2387 $res = $dbr->select(
2388 [ 'protected_titles' ] +
$commentQuery['tables'],
2390 'user' => 'pt_user',
2391 'expiry' => 'pt_expiry',
2392 'permission' => 'pt_create_perm'
2393 ] +
$commentQuery['fields'],
2394 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2397 $commentQuery['joins']
2400 // fetchRow returns false if there are no rows.
2401 $row = $dbr->fetchRow( $res );
2403 $this->mTitleProtection
= [
2404 'user' => $row['user'],
2405 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2406 'permission' => $row['permission'],
2407 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2410 $this->mTitleProtection
= false;
2413 return $this->mTitleProtection
;
2417 * Remove any title protection due to page existing
2419 public function deleteTitleProtection() {
2420 $dbw = wfGetDB( DB_MASTER
);
2424 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2427 $this->mTitleProtection
= false;
2431 * Is this page "semi-protected" - the *only* protection levels are listed
2432 * in $wgSemiprotectedRestrictionLevels?
2434 * @param string $action Action to check (default: edit)
2437 public function isSemiProtected( $action = 'edit' ) {
2438 global $wgSemiprotectedRestrictionLevels;
2440 $restrictions = $this->getRestrictions( $action );
2441 $semi = $wgSemiprotectedRestrictionLevels;
2442 if ( !$restrictions ||
!$semi ) {
2443 // Not protected, or all protection is full protection
2447 // Remap autoconfirmed to editsemiprotected for BC
2448 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2449 $semi[$key] = 'editsemiprotected';
2451 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2452 $restrictions[$key] = 'editsemiprotected';
2455 return !array_diff( $restrictions, $semi );
2459 * Does the title correspond to a protected article?
2461 * @param string $action The action the page is protected from,
2462 * by default checks all actions.
2465 public function isProtected( $action = '' ) {
2466 global $wgRestrictionLevels;
2468 $restrictionTypes = $this->getRestrictionTypes();
2470 # Special pages have inherent protection
2471 if ( $this->isSpecialPage() ) {
2475 # Check regular protection levels
2476 foreach ( $restrictionTypes as $type ) {
2477 if ( $action == $type ||
$action == '' ) {
2478 $r = $this->getRestrictions( $type );
2479 foreach ( $wgRestrictionLevels as $level ) {
2480 if ( in_array( $level, $r ) && $level != '' ) {
2491 * Determines if $user is unable to edit this page because it has been protected
2492 * by $wgNamespaceProtection.
2494 * @param User $user User object to check permissions
2497 public function isNamespaceProtected( User
$user ) {
2498 global $wgNamespaceProtection;
2500 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2501 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2502 if ( $right != '' && !$user->isAllowed( $right ) ) {
2511 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2513 * @return bool If the page is subject to cascading restrictions.
2515 public function isCascadeProtected() {
2516 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2517 return ( $sources > 0 );
2521 * Determines whether cascading protection sources have already been loaded from
2524 * @param bool $getPages True to check if the pages are loaded, or false to check
2525 * if the status is loaded.
2526 * @return bool Whether or not the specified information has been loaded
2529 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2530 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2534 * Cascading protection: Get the source of any cascading restrictions on this page.
2536 * @param bool $getPages Whether or not to retrieve the actual pages
2537 * that the restrictions have come from and the actual restrictions
2539 * @return array Two elements: First is an array of Title objects of the
2540 * pages from which cascading restrictions have come, false for
2541 * none, or true if such restrictions exist but $getPages was not
2542 * set. Second is an array like that returned by
2543 * Title::getAllRestrictions(), or an empty array if $getPages is
2546 public function getCascadeProtectionSources( $getPages = true ) {
2547 $pagerestrictions = [];
2549 if ( $this->mCascadeSources
!== null && $getPages ) {
2550 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2551 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2552 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2555 $dbr = wfGetDB( DB_REPLICA
);
2557 if ( $this->mNamespace
== NS_FILE
) {
2558 $tables = [ 'imagelinks', 'page_restrictions' ];
2560 'il_to' => $this->mDbkeyform
,
2565 $tables = [ 'templatelinks', 'page_restrictions' ];
2567 'tl_namespace' => $this->mNamespace
,
2568 'tl_title' => $this->mDbkeyform
,
2575 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2576 'pr_expiry', 'pr_type', 'pr_level' ];
2577 $where_clauses[] = 'page_id=pr_page';
2580 $cols = [ 'pr_expiry' ];
2583 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2585 $sources = $getPages ?
[] : false;
2586 $now = wfTimestampNow();
2588 foreach ( $res as $row ) {
2589 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2590 if ( $expiry > $now ) {
2592 $page_id = $row->pr_page
;
2593 $page_ns = $row->page_namespace
;
2594 $page_title = $row->page_title
;
2595 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2596 # Add groups needed for each restriction type if its not already there
2597 # Make sure this restriction type still exists
2599 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2600 $pagerestrictions[$row->pr_type
] = [];
2604 isset( $pagerestrictions[$row->pr_type
] )
2605 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2607 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2616 $this->mCascadeSources
= $sources;
2617 $this->mCascadingRestrictions
= $pagerestrictions;
2619 $this->mHasCascadingRestrictions
= $sources;
2622 return [ $sources, $pagerestrictions ];
2626 * Accessor for mRestrictionsLoaded
2628 * @return bool Whether or not the page's restrictions have already been
2629 * loaded from the database
2632 public function areRestrictionsLoaded() {
2633 return $this->mRestrictionsLoaded
;
2637 * Accessor/initialisation for mRestrictions
2639 * @param string $action Action that permission needs to be checked for
2640 * @return array Restriction levels needed to take the action. All levels are
2641 * required. Note that restriction levels are normally user rights, but 'sysop'
2642 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2643 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2645 public function getRestrictions( $action ) {
2646 if ( !$this->mRestrictionsLoaded
) {
2647 $this->loadRestrictions();
2649 return $this->mRestrictions
[$action] ??
[];
2653 * Accessor/initialisation for mRestrictions
2655 * @return array Keys are actions, values are arrays as returned by
2656 * Title::getRestrictions()
2659 public function getAllRestrictions() {
2660 if ( !$this->mRestrictionsLoaded
) {
2661 $this->loadRestrictions();
2663 return $this->mRestrictions
;
2667 * Get the expiry time for the restriction against a given action
2669 * @param string $action
2670 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2671 * or not protected at all, or false if the action is not recognised.
2673 public function getRestrictionExpiry( $action ) {
2674 if ( !$this->mRestrictionsLoaded
) {
2675 $this->loadRestrictions();
2677 return $this->mRestrictionsExpiry
[$action] ??
false;
2681 * Returns cascading restrictions for the current article
2685 function areRestrictionsCascading() {
2686 if ( !$this->mRestrictionsLoaded
) {
2687 $this->loadRestrictions();
2690 return $this->mCascadeRestriction
;
2694 * Compiles list of active page restrictions from both page table (pre 1.10)
2695 * and page_restrictions table for this existing page.
2696 * Public for usage by LiquidThreads.
2698 * @param array $rows Array of db result objects
2699 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2700 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2701 * Edit and move sections are separated by a colon
2702 * Example: "edit=autoconfirmed,sysop:move=sysop"
2704 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2705 // This function will only read rows from a table that we migrated away
2706 // from before adding READ_LATEST support to loadRestrictions, so we
2707 // don't need to support reading from DB_MASTER here.
2708 $dbr = wfGetDB( DB_REPLICA
);
2710 $restrictionTypes = $this->getRestrictionTypes();
2712 foreach ( $restrictionTypes as $type ) {
2713 $this->mRestrictions
[$type] = [];
2714 $this->mRestrictionsExpiry
[$type] = 'infinity';
2717 $this->mCascadeRestriction
= false;
2719 # Backwards-compatibility: also load the restrictions from the page record (old format).
2720 if ( $oldFashionedRestrictions !== null ) {
2721 $this->mOldRestrictions
= $oldFashionedRestrictions;
2724 if ( $this->mOldRestrictions
=== false ) {
2725 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2726 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2727 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2730 if ( $this->mOldRestrictions
!= '' ) {
2731 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2732 $temp = explode( '=', trim( $restrict ) );
2733 if ( count( $temp ) == 1 ) {
2734 // old old format should be treated as edit/move restriction
2735 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2736 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2738 $restriction = trim( $temp[1] );
2739 if ( $restriction != '' ) { // some old entries are empty
2740 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2746 if ( count( $rows ) ) {
2747 # Current system - load second to make them override.
2748 $now = wfTimestampNow();
2750 # Cycle through all the restrictions.
2751 foreach ( $rows as $row ) {
2752 // Don't take care of restrictions types that aren't allowed
2753 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2757 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2759 // Only apply the restrictions if they haven't expired!
2760 if ( !$expiry ||
$expiry > $now ) {
2761 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2762 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2764 $this->mCascadeRestriction |
= $row->pr_cascade
;
2769 $this->mRestrictionsLoaded
= true;
2773 * Load restrictions from the page_restrictions table
2775 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2776 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2777 * Edit and move sections are separated by a colon
2778 * Example: "edit=autoconfirmed,sysop:move=sysop"
2779 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2780 * from the master DB.
2782 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2783 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2784 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2788 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2789 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2790 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2791 $id = $this->getArticleID();
2793 $fname = __METHOD__
;
2794 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2795 return iterator_to_array(
2797 'page_restrictions',
2798 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2799 [ 'pr_page' => $id ],
2805 if ( $readLatest ) {
2806 $dbr = wfGetDB( DB_MASTER
);
2807 $rows = $loadRestrictionsFromDb( $dbr );
2809 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2810 $rows = $cache->getWithSetCallback(
2811 // Page protections always leave a new null revision
2812 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2814 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2815 $dbr = wfGetDB( DB_REPLICA
);
2817 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2818 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2819 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2820 // @TODO: cleanup Title cache and caller assumption mess in general
2821 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2824 return $loadRestrictionsFromDb( $dbr );
2829 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2831 $title_protection = $this->getTitleProtectionInternal();
2833 if ( $title_protection ) {
2834 $now = wfTimestampNow();
2835 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2837 if ( !$expiry ||
$expiry > $now ) {
2838 // Apply the restrictions
2839 $this->mRestrictionsExpiry
['create'] = $expiry;
2840 $this->mRestrictions
['create'] =
2841 explode( ',', trim( $title_protection['permission'] ) );
2842 } else { // Get rid of the old restrictions
2843 $this->mTitleProtection
= false;
2846 $this->mRestrictionsExpiry
['create'] = 'infinity';
2848 $this->mRestrictionsLoaded
= true;
2853 * Flush the protection cache in this object and force reload from the database.
2854 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2856 public function flushRestrictions() {
2857 $this->mRestrictionsLoaded
= false;
2858 $this->mTitleProtection
= null;
2862 * Purge expired restrictions from the page_restrictions table
2864 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2866 static function purgeExpiredRestrictions() {
2867 if ( wfReadOnly() ) {
2871 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2872 wfGetDB( DB_MASTER
),
2874 function ( IDatabase
$dbw, $fname ) {
2875 $config = MediaWikiServices
::getInstance()->getMainConfig();
2876 $ids = $dbw->selectFieldValues(
2877 'page_restrictions',
2879 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2881 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2884 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2889 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2890 wfGetDB( DB_MASTER
),
2892 function ( IDatabase
$dbw, $fname ) {
2895 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2903 * Does this have subpages? (Warning, usually requires an extra DB query.)
2907 public function hasSubpages() {
2909 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2910 hasSubpages( $this->mNamespace
)
2916 # We dynamically add a member variable for the purpose of this method
2917 # alone to cache the result. There's no point in having it hanging
2918 # around uninitialized in every Title object; therefore we only add it
2919 # if needed and don't declare it statically.
2920 if ( $this->mHasSubpages
=== null ) {
2921 $this->mHasSubpages
= false;
2922 $subpages = $this->getSubpages( 1 );
2923 if ( $subpages instanceof TitleArray
) {
2924 $this->mHasSubpages
= (bool)$subpages->current();
2928 return $this->mHasSubpages
;
2932 * Get all subpages of this page.
2934 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2935 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2936 * doesn't allow subpages
2938 public function getSubpages( $limit = -1 ) {
2940 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2941 hasSubpages( $this->mNamespace
)
2946 $dbr = wfGetDB( DB_REPLICA
);
2947 $conds['page_namespace'] = $this->mNamespace
;
2948 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2950 if ( $limit > -1 ) {
2951 $options['LIMIT'] = $limit;
2953 return TitleArray
::newFromResult(
2954 $dbr->select( 'page',
2955 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2964 * Is there a version of this page in the deletion archive?
2966 * @return int The number of archived revisions
2968 public function isDeleted() {
2969 if ( $this->mNamespace
< 0 ) {
2972 $dbr = wfGetDB( DB_REPLICA
);
2974 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2975 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2978 if ( $this->mNamespace
== NS_FILE
) {
2979 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2980 [ 'fa_name' => $this->mDbkeyform
],
2989 * Is there a version of this page in the deletion archive?
2993 public function isDeletedQuick() {
2994 if ( $this->mNamespace
< 0 ) {
2997 $dbr = wfGetDB( DB_REPLICA
);
2998 $deleted = (bool)$dbr->selectField( 'archive', '1',
2999 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3002 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3003 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3004 [ 'fa_name' => $this->mDbkeyform
],
3012 * Get the article ID for this Title from the link cache,
3013 * adding it if necessary
3015 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3017 * @return int The ID
3019 public function getArticleID( $flags = 0 ) {
3020 if ( $this->mNamespace
< 0 ) {
3021 $this->mArticleID
= 0;
3022 return $this->mArticleID
;
3024 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3025 if ( $flags & self
::GAID_FOR_UPDATE
) {
3026 $oldUpdate = $linkCache->forUpdate( true );
3027 $linkCache->clearLink( $this );
3028 $this->mArticleID
= $linkCache->addLinkObj( $this );
3029 $linkCache->forUpdate( $oldUpdate );
3030 } elseif ( $this->mArticleID
== -1 ) {
3031 $this->mArticleID
= $linkCache->addLinkObj( $this );
3033 return $this->mArticleID
;
3037 * Is this an article that is a redirect page?
3038 * Uses link cache, adding it if necessary
3040 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3043 public function isRedirect( $flags = 0 ) {
3044 if ( !is_null( $this->mRedirect
) ) {
3045 return $this->mRedirect
;
3047 if ( !$this->getArticleID( $flags ) ) {
3048 $this->mRedirect
= false;
3049 return $this->mRedirect
;
3052 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3053 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3054 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3055 if ( $cached === null ) {
3056 # Trust LinkCache's state over our own
3057 # LinkCache is telling us that the page doesn't exist, despite there being cached
3058 # data relating to an existing page in $this->mArticleID. Updaters should clear
3059 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3060 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3061 # LinkCache to refresh its data from the master.
3062 $this->mRedirect
= false;
3063 return $this->mRedirect
;
3066 $this->mRedirect
= (bool)$cached;
3068 return $this->mRedirect
;
3072 * What is the length of this page?
3073 * Uses link cache, adding it if necessary
3075 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3078 public function getLength( $flags = 0 ) {
3079 if ( $this->mLength
!= -1 ) {
3080 return $this->mLength
;
3082 if ( !$this->getArticleID( $flags ) ) {
3084 return $this->mLength
;
3086 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3087 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3088 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3089 if ( $cached === null ) {
3090 # Trust LinkCache's state over our own, as for isRedirect()
3092 return $this->mLength
;
3095 $this->mLength
= intval( $cached );
3097 return $this->mLength
;
3101 * What is the page_latest field for this page?
3103 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3104 * @return int Int or 0 if the page doesn't exist
3106 public function getLatestRevID( $flags = 0 ) {
3107 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3108 return intval( $this->mLatestID
);
3110 if ( !$this->getArticleID( $flags ) ) {
3111 $this->mLatestID
= 0;
3112 return $this->mLatestID
;
3114 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3115 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3116 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3117 if ( $cached === null ) {
3118 # Trust LinkCache's state over our own, as for isRedirect()
3119 $this->mLatestID
= 0;
3120 return $this->mLatestID
;
3123 $this->mLatestID
= intval( $cached );
3125 return $this->mLatestID
;
3129 * This clears some fields in this object, and clears any associated
3130 * keys in the "bad links" section of the link cache.
3132 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3133 * loading of the new page_id. It's also called from
3134 * WikiPage::doDeleteArticleReal()
3136 * @param int $newid The new Article ID
3138 public function resetArticleID( $newid ) {
3139 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3140 $linkCache->clearLink( $this );
3142 if ( $newid === false ) {
3143 $this->mArticleID
= -1;
3145 $this->mArticleID
= intval( $newid );
3147 $this->mRestrictionsLoaded
= false;
3148 $this->mRestrictions
= [];
3149 $this->mOldRestrictions
= false;
3150 $this->mRedirect
= null;
3151 $this->mLength
= -1;
3152 $this->mLatestID
= false;
3153 $this->mContentModel
= false;
3154 $this->mEstimateRevisions
= null;
3155 $this->mPageLanguage
= false;
3156 $this->mDbPageLanguage
= false;
3157 $this->mIsBigDeletion
= null;
3160 public static function clearCaches() {
3161 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3162 $linkCache->clear();
3164 $titleCache = self
::getTitleCache();
3165 $titleCache->clear();
3169 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3171 * @param string $text Containing title to capitalize
3172 * @param int $ns Namespace index, defaults to NS_MAIN
3173 * @return string Containing capitalized title
3175 public static function capitalize( $text, $ns = NS_MAIN
) {
3176 $services = MediaWikiServices
::getInstance();
3177 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3178 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3185 * Secure and split - main initialisation function for this object
3187 * Assumes that mDbkeyform has been set, and is urldecoded
3188 * and uses underscores, but not otherwise munged. This function
3189 * removes illegal characters, splits off the interwiki and
3190 * namespace prefixes, sets the other forms, and canonicalizes
3193 * @throws MalformedTitleException On invalid titles
3194 * @return bool True on success
3196 private function secureAndSplit() {
3197 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3198 // the parsing code with Title, while avoiding massive refactoring.
3199 // @todo: get rid of secureAndSplit, refactor parsing code.
3200 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3201 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3202 /** @var MediaWikiTitleCodec $titleCodec */
3203 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3204 // MalformedTitleException can be thrown here
3205 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3208 $this->setFragment( '#' . $parts['fragment'] );
3209 $this->mInterwiki
= $parts['interwiki'];
3210 $this->mLocalInterwiki
= $parts['local_interwiki'];
3211 $this->mNamespace
= $parts['namespace'];
3212 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3214 $this->mDbkeyform
= $parts['dbkey'];
3215 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3216 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3218 # We already know that some pages won't be in the database!
3219 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3220 $this->mArticleID
= 0;
3227 * Get an array of Title objects linking to this Title
3228 * Also stores the IDs in the link cache.
3230 * WARNING: do not use this function on arbitrary user-supplied titles!
3231 * On heavily-used templates it will max out the memory.
3233 * @param array $options May be FOR UPDATE
3234 * @param string $table Table name
3235 * @param string $prefix Fields prefix
3236 * @return Title[] Array of Title objects linking here
3238 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3239 if ( count( $options ) > 0 ) {
3240 $db = wfGetDB( DB_MASTER
);
3242 $db = wfGetDB( DB_REPLICA
);
3247 self
::getSelectFields(),
3249 "{$prefix}_from=page_id",
3250 "{$prefix}_namespace" => $this->mNamespace
,
3251 "{$prefix}_title" => $this->mDbkeyform
],
3257 if ( $res->numRows() ) {
3258 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3259 foreach ( $res as $row ) {
3260 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3262 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3263 $retVal[] = $titleObj;
3271 * Get an array of Title objects using this Title as a template
3272 * Also stores the IDs in the link cache.
3274 * WARNING: do not use this function on arbitrary user-supplied titles!
3275 * On heavily-used templates it will max out the memory.
3277 * @param array $options Query option to Database::select()
3278 * @return Title[] Array of Title the Title objects linking here
3280 public function getTemplateLinksTo( $options = [] ) {
3281 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3285 * Get an array of Title objects linked from this Title
3286 * Also stores the IDs in the link cache.
3288 * WARNING: do not use this function on arbitrary user-supplied titles!
3289 * On heavily-used templates it will max out the memory.
3291 * @param array $options Query option to Database::select()
3292 * @param string $table Table name
3293 * @param string $prefix Fields prefix
3294 * @return array Array of Title objects linking here
3296 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3297 $id = $this->getArticleID();
3299 # If the page doesn't exist; there can't be any link from this page
3304 $db = wfGetDB( DB_REPLICA
);
3306 $blNamespace = "{$prefix}_namespace";
3307 $blTitle = "{$prefix}_title";
3309 $pageQuery = WikiPage
::getQueryInfo();
3311 [ $table, 'nestpage' => $pageQuery['tables'] ],
3313 [ $blNamespace, $blTitle ],
3314 $pageQuery['fields']
3316 [ "{$prefix}_from" => $id ],
3321 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3322 ] ] +
$pageQuery['joins']
3326 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3327 foreach ( $res as $row ) {
3328 if ( $row->page_id
) {
3329 $titleObj = self
::newFromRow( $row );
3331 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3332 $linkCache->addBadLinkObj( $titleObj );
3334 $retVal[] = $titleObj;
3341 * Get an array of Title objects used on this Title as a template
3342 * Also stores the IDs in the link cache.
3344 * WARNING: do not use this function on arbitrary user-supplied titles!
3345 * On heavily-used templates it will max out the memory.
3347 * @param array $options May be FOR UPDATE
3348 * @return Title[] Array of Title the Title objects used here
3350 public function getTemplateLinksFrom( $options = [] ) {
3351 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3355 * Get an array of Title objects referring to non-existent articles linked
3358 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3359 * should use redirect table in this case).
3360 * @return Title[] Array of Title the Title objects
3362 public function getBrokenLinksFrom() {
3363 if ( $this->getArticleID() == 0 ) {
3364 # All links from article ID 0 are false positives
3368 $dbr = wfGetDB( DB_REPLICA
);
3369 $res = $dbr->select(
3370 [ 'page', 'pagelinks' ],
3371 [ 'pl_namespace', 'pl_title' ],
3373 'pl_from' => $this->getArticleID(),
3374 'page_namespace IS NULL'
3380 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3386 foreach ( $res as $row ) {
3387 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3393 * Get a list of URLs to purge from the CDN cache when this
3396 * @return string[] Array of String the URLs
3398 public function getCdnUrls() {
3400 $this->getInternalURL(),
3401 $this->getInternalURL( 'action=history' )
3404 $pageLang = $this->getPageLanguage();
3405 if ( $pageLang->hasVariants() ) {
3406 $variants = $pageLang->getVariants();
3407 foreach ( $variants as $vCode ) {
3408 $urls[] = $this->getInternalURL( $vCode );
3412 // If we are looking at a css/js user subpage, purge the action=raw.
3413 if ( $this->isUserJsConfigPage() ) {
3414 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3415 } elseif ( $this->isUserJsonConfigPage() ) {
3416 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3417 } elseif ( $this->isUserCssConfigPage() ) {
3418 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3421 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3426 * Purge all applicable CDN URLs
3428 public function purgeSquid() {
3429 DeferredUpdates
::addUpdate(
3430 new CdnCacheUpdate( $this->getCdnUrls() ),
3431 DeferredUpdates
::PRESEND
3436 * Check whether a given move operation would be valid.
3437 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3439 * @deprecated since 1.25, use MovePage's methods instead
3440 * @param Title &$nt The new title
3441 * @param bool $auth Whether to check user permissions (uses $wgUser)
3442 * @param string $reason Is the log summary of the move, used for spam checking
3443 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3445 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3446 wfDeprecated( __METHOD__
, '1.25' );
3450 if ( !( $nt instanceof Title
) ) {
3451 // Normally we'd add this to $errors, but we'll get
3452 // lots of syntax errors if $nt is not an object
3453 return [ [ 'badtitletext' ] ];
3456 $mp = new MovePage( $this, $nt );
3457 $errors = $mp->isValidMove()->getErrorsArray();
3459 $errors = wfMergeErrorArrays(
3461 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3465 return $errors ?
: true;
3469 * Move a title to a new location
3471 * @deprecated since 1.25, use the MovePage class instead
3472 * @param Title &$nt The new title
3473 * @param bool $auth Indicates whether $wgUser's permissions
3475 * @param string $reason The reason for the move
3476 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3477 * Ignored if the user doesn't have the suppressredirect right.
3478 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3479 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3481 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3482 array $changeTags = []
3484 wfDeprecated( __METHOD__
, '1.25' );
3488 $mp = new MovePage( $this, $nt );
3489 $method = $auth ?
'moveIfAllowed' : 'move';
3490 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3491 if ( $status->isOK() ) {
3494 return $status->getErrorsArray();
3499 * Move this page's subpages to be subpages of $nt
3501 * @deprecated since 1.34, use MovePage instead
3502 * @param Title $nt Move target
3503 * @param bool $auth Whether $wgUser's permissions should be checked
3504 * @param string $reason The reason for the move
3505 * @param bool $createRedirect Whether to create redirects from the old subpages to
3506 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3507 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3508 * @return array Array with old page titles as keys, and strings (new page titles) or
3509 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3510 * getUserPermissionsErrors()-like error array with numeric indices if
3511 * no pages were moved
3513 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3514 array $changeTags = []
3516 wfDeprecated( __METHOD__
, '1.34' );
3520 $mp = new MovePage( $this, $nt );
3521 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3522 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3524 if ( !$result->isOk() ) {
3525 return $result->getErrorsArray();
3529 foreach ( $result->getValue() as $key => $status ) {
3530 if ( $status->isOK() ) {
3531 $retval[$key] = $status->getValue();
3533 $retval[$key] = $status->getErrorsArray();
3540 * Checks if this page is just a one-rev redirect.
3541 * Adds lock, so don't use just for light purposes.
3545 public function isSingleRevRedirect() {
3546 global $wgContentHandlerUseDB;
3548 $dbw = wfGetDB( DB_MASTER
);
3551 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3552 if ( $wgContentHandlerUseDB ) {
3553 $fields[] = 'page_content_model';
3556 $row = $dbw->selectRow( 'page',
3562 # Cache some fields we may want
3563 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3564 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3565 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3566 $this->mContentModel
= $row && isset( $row->page_content_model
)
3567 ?
strval( $row->page_content_model
)
3570 if ( !$this->mRedirect
) {
3573 # Does the article have a history?
3574 $row = $dbw->selectField( [ 'page', 'revision' ],
3576 [ 'page_namespace' => $this->mNamespace
,
3577 'page_title' => $this->mDbkeyform
,
3579 'page_latest != rev_id'
3584 # Return true if there was no history
3585 return ( $row === false );
3589 * Checks if $this can be moved to a given Title
3590 * - Selects for update, so don't call it unless you mean business
3592 * @deprecated since 1.25, use MovePage's methods instead
3593 * @param Title $nt The new title to check
3596 public function isValidMoveTarget( $nt ) {
3597 wfDeprecated( __METHOD__
, '1.25' );
3599 # Is it an existing file?
3600 if ( $nt->getNamespace() == NS_FILE
) {
3601 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3603 $file->load( File
::READ_LATEST
);
3604 if ( $file->exists() ) {
3605 wfDebug( __METHOD__
. ": file exists\n" );
3609 # Is it a redirect with no history?
3610 if ( !$nt->isSingleRevRedirect() ) {
3611 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3614 # Get the article text
3615 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3616 if ( !is_object( $rev ) ) {
3619 $content = $rev->getContent();
3620 # Does the redirect point to the source?
3621 # Or is it a broken self-redirect, usually caused by namespace collisions?
3622 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3624 if ( $redirTitle ) {
3625 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3626 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3627 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3633 # Fail safe (not a redirect after all. strange.)
3634 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3635 " is a redirect, but it doesn't contain a valid redirect.\n" );
3641 * Get categories to which this Title belongs and return an array of
3642 * categories' names.
3644 * @return array Array of parents in the form:
3645 * $parent => $currentarticle
3647 public function getParentCategories() {
3650 $titleKey = $this->getArticleID();
3652 if ( $titleKey === 0 ) {
3656 $dbr = wfGetDB( DB_REPLICA
);
3658 $res = $dbr->select(
3661 [ 'cl_from' => $titleKey ],
3665 if ( $res->numRows() > 0 ) {
3666 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3667 foreach ( $res as $row ) {
3668 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3669 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3670 $this->getFullText();
3677 * Get a tree of parent categories
3679 * @param array $children Array with the children in the keys, to check for circular refs
3680 * @return array Tree of parent categories
3682 public function getParentCategoryTree( $children = [] ) {
3684 $parents = $this->getParentCategories();
3687 foreach ( $parents as $parent => $current ) {
3688 if ( array_key_exists( $parent, $children ) ) {
3689 # Circular reference
3690 $stack[$parent] = [];
3692 $nt = self
::newFromText( $parent );
3694 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3704 * Get an associative array for selecting this title from
3707 * @return array Array suitable for the $where parameter of DB::select()
3709 public function pageCond() {
3710 if ( $this->mArticleID
> 0 ) {
3711 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3712 return [ 'page_id' => $this->mArticleID
];
3714 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3719 * Get next/previous revision ID relative to another revision ID
3720 * @param int $revId Revision ID. Get the revision that was before this one.
3721 * @param int $flags Title::GAID_FOR_UPDATE
3722 * @param string $dir 'next' or 'prev'
3723 * @return int|bool New revision ID, or false if none exists
3725 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3726 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3727 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3728 $rev = $rl->getRevisionById( $revId, $rlFlags );
3732 $oldRev = $dir === 'next'
3733 ?
$rl->getNextRevision( $rev, $rlFlags )
3734 : $rl->getPreviousRevision( $rev, $rlFlags );
3738 return $oldRev->getId();
3742 * Get the revision ID of the previous revision
3744 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3745 * @param int $revId Revision ID. Get the revision that was before this one.
3746 * @param int $flags Title::GAID_FOR_UPDATE
3747 * @return int|bool Old revision ID, or false if none exists
3749 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3750 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3754 * Get the revision ID of the next revision
3756 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3757 * @param int $revId Revision ID. Get the revision that was after this one.
3758 * @param int $flags Title::GAID_FOR_UPDATE
3759 * @return int|bool Next revision ID, or false if none exists
3761 public function getNextRevisionID( $revId, $flags = 0 ) {
3762 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3766 * Get the first revision of the page
3768 * @param int $flags Title::GAID_FOR_UPDATE
3769 * @return Revision|null If page doesn't exist
3771 public function getFirstRevision( $flags = 0 ) {
3772 $pageId = $this->getArticleID( $flags );
3774 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3775 $revQuery = Revision
::getQueryInfo();
3776 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3777 [ 'rev_page' => $pageId ],
3780 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3781 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3786 return new Revision( $row, 0, $this );
3793 * Get the oldest revision timestamp of this page
3795 * @param int $flags Title::GAID_FOR_UPDATE
3796 * @return string|null MW timestamp
3798 public function getEarliestRevTime( $flags = 0 ) {
3799 $rev = $this->getFirstRevision( $flags );
3800 return $rev ?
$rev->getTimestamp() : null;
3804 * Check if this is a new page
3808 public function isNewPage() {
3809 $dbr = wfGetDB( DB_REPLICA
);
3810 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3814 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3818 public function isBigDeletion() {
3819 global $wgDeleteRevisionsLimit;
3821 if ( !$wgDeleteRevisionsLimit ) {
3825 if ( $this->mIsBigDeletion
=== null ) {
3826 $dbr = wfGetDB( DB_REPLICA
);
3828 $revCount = $dbr->selectRowCount(
3831 [ 'rev_page' => $this->getArticleID() ],
3833 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3836 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3839 return $this->mIsBigDeletion
;
3843 * Get the approximate revision count of this page.
3847 public function estimateRevisionCount() {
3848 if ( !$this->exists() ) {
3852 if ( $this->mEstimateRevisions
=== null ) {
3853 $dbr = wfGetDB( DB_REPLICA
);
3854 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3855 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3858 return $this->mEstimateRevisions
;
3862 * Get the number of revisions between the given revision.
3863 * Used for diffs and other things that really need it.
3865 * @param int|Revision $old Old revision or rev ID (first before range)
3866 * @param int|Revision $new New revision or rev ID (first after range)
3867 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3868 * @return int Number of revisions between these revisions.
3870 public function countRevisionsBetween( $old, $new, $max = null ) {
3871 if ( !( $old instanceof Revision
) ) {
3872 $old = Revision
::newFromTitle( $this, (int)$old );
3874 if ( !( $new instanceof Revision
) ) {
3875 $new = Revision
::newFromTitle( $this, (int)$new );
3877 if ( !$old ||
!$new ) {
3878 return 0; // nothing to compare
3880 $dbr = wfGetDB( DB_REPLICA
);
3882 'rev_page' => $this->getArticleID(),
3883 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3884 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3886 if ( $max !== null ) {
3887 return $dbr->selectRowCount( 'revision', '1',
3890 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3893 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3898 * Get the authors between the given revisions or revision IDs.
3899 * Used for diffs and other things that really need it.
3903 * @param int|Revision $old Old revision or rev ID (first before range by default)
3904 * @param int|Revision $new New revision or rev ID (first after range by default)
3905 * @param int $limit Maximum number of authors
3906 * @param string|array $options (Optional): Single option, or an array of options:
3907 * 'include_old' Include $old in the range; $new is excluded.
3908 * 'include_new' Include $new in the range; $old is excluded.
3909 * 'include_both' Include both $old and $new in the range.
3910 * Unknown option values are ignored.
3911 * @return array|null Names of revision authors in the range; null if not both revisions exist
3913 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3914 if ( !( $old instanceof Revision
) ) {
3915 $old = Revision
::newFromTitle( $this, (int)$old );
3917 if ( !( $new instanceof Revision
) ) {
3918 $new = Revision
::newFromTitle( $this, (int)$new );
3920 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3921 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3922 // in the sanity check below?
3923 if ( !$old ||
!$new ) {
3924 return null; // nothing to compare
3929 $options = (array)$options;
3930 if ( in_array( 'include_old', $options ) ) {
3933 if ( in_array( 'include_new', $options ) ) {
3936 if ( in_array( 'include_both', $options ) ) {
3940 // No DB query needed if $old and $new are the same or successive revisions:
3941 if ( $old->getId() === $new->getId() ) {
3942 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3944 [ $old->getUserText( Revision
::RAW
) ];
3945 } elseif ( $old->getId() === $new->getParentId() ) {
3946 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3947 $authors[] = $old->getUserText( Revision
::RAW
);
3948 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3949 $authors[] = $new->getUserText( Revision
::RAW
);
3951 } elseif ( $old_cmp === '>=' ) {
3952 $authors[] = $old->getUserText( Revision
::RAW
);
3953 } elseif ( $new_cmp === '<=' ) {
3954 $authors[] = $new->getUserText( Revision
::RAW
);
3958 $dbr = wfGetDB( DB_REPLICA
);
3959 $revQuery = Revision
::getQueryInfo();
3960 $authors = $dbr->selectFieldValues(
3961 $revQuery['tables'],
3962 $revQuery['fields']['rev_user_text'],
3964 'rev_page' => $this->getArticleID(),
3965 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3966 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3968 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3975 * Get the number of authors between the given revisions or revision IDs.
3976 * Used for diffs and other things that really need it.
3978 * @param int|Revision $old Old revision or rev ID (first before range by default)
3979 * @param int|Revision $new New revision or rev ID (first after range by default)
3980 * @param int $limit Maximum number of authors
3981 * @param string|array $options (Optional): Single option, or an array of options:
3982 * 'include_old' Include $old in the range; $new is excluded.
3983 * 'include_new' Include $new in the range; $old is excluded.
3984 * 'include_both' Include both $old and $new in the range.
3985 * Unknown option values are ignored.
3986 * @return int Number of revision authors in the range; zero if not both revisions exist
3988 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3989 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3990 return $authors ?
count( $authors ) : 0;
3994 * Compare with another title.
3996 * @param LinkTarget $title
3999 public function equals( LinkTarget
$title ) {
4000 // Note: === is necessary for proper matching of number-like titles.
4001 return $this->mInterwiki
=== $title->getInterwiki()
4002 && $this->mNamespace
== $title->getNamespace()
4003 && $this->mDbkeyform
=== $title->getDBkey();
4007 * Check if this title is a subpage of another title
4009 * @param Title $title
4012 public function isSubpageOf( Title
$title ) {
4013 return $this->mInterwiki
=== $title->mInterwiki
4014 && $this->mNamespace
== $title->mNamespace
4015 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4019 * Check if page exists. For historical reasons, this function simply
4020 * checks for the existence of the title in the page table, and will
4021 * thus return false for interwiki links, special pages and the like.
4022 * If you want to know if a title can be meaningfully viewed, you should
4023 * probably call the isKnown() method instead.
4025 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4026 * from master/for update
4029 public function exists( $flags = 0 ) {
4030 $exists = $this->getArticleID( $flags ) != 0;
4031 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4036 * Should links to this title be shown as potentially viewable (i.e. as
4037 * "bluelinks"), even if there's no record by this title in the page
4040 * This function is semi-deprecated for public use, as well as somewhat
4041 * misleadingly named. You probably just want to call isKnown(), which
4042 * calls this function internally.
4044 * (ISSUE: Most of these checks are cheap, but the file existence check
4045 * can potentially be quite expensive. Including it here fixes a lot of
4046 * existing code, but we might want to add an optional parameter to skip
4047 * it and any other expensive checks.)
4051 public function isAlwaysKnown() {
4055 * Allows overriding default behavior for determining if a page exists.
4056 * If $isKnown is kept as null, regular checks happen. If it's
4057 * a boolean, this value is returned by the isKnown method.
4061 * @param Title $title
4062 * @param bool|null $isKnown
4064 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4066 if ( !is_null( $isKnown ) ) {
4070 if ( $this->isExternal() ) {
4071 return true; // any interwiki link might be viewable, for all we know
4074 $services = MediaWikiServices
::getInstance();
4075 switch ( $this->mNamespace
) {
4078 // file exists, possibly in a foreign repo
4079 return (bool)$services->getRepoGroup()->findFile( $this );
4081 // valid special page
4082 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4084 // selflink, possibly with fragment
4085 return $this->mDbkeyform
== '';
4087 // known system message
4088 return $this->hasSourceText() !== false;
4095 * Does this title refer to a page that can (or might) be meaningfully
4096 * viewed? In particular, this function may be used to determine if
4097 * links to the title should be rendered as "bluelinks" (as opposed to
4098 * "redlinks" to non-existent pages).
4099 * Adding something else to this function will cause inconsistency
4100 * since LinkHolderArray calls isAlwaysKnown() and does its own
4101 * page existence check.
4105 public function isKnown() {
4106 return $this->isAlwaysKnown() ||
$this->exists();
4110 * Does this page have source text?
4114 public function hasSourceText() {
4115 if ( $this->exists() ) {
4119 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4120 // If the page doesn't exist but is a known system message, default
4121 // message content will be displayed, same for language subpages-
4122 // Use always content language to avoid loading hundreds of languages
4123 // to get the link color.
4124 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4125 list( $name, ) = MessageCache
::singleton()->figureMessage(
4126 $contLang->lcfirst( $this->getText() )
4128 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4129 return $message->exists();
4136 * Get the default (plain) message contents for an page that overrides an
4137 * interface message key.
4139 * Primary use cases:
4142 * - Show default when viewing the page. The Article::getSubstituteContent
4143 * method displays the default message content, instead of the
4144 * 'noarticletext' placeholder message normally used.
4147 * - Title of edit page. When creating an interface message override,
4148 * the editor is told they are "Editing the page", instead of
4149 * "Creating the page". (EditPage::setHeaders)
4150 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4151 * or editing a an interface message override. (EditPage::showIntro)
4152 * - Opening the editor. The contents of the localisation message are used
4153 * as contents of the editor when creating a new page in the MediaWiki
4154 * namespace. This simplifies the process for editors when "changing"
4155 * an interface message by creating an override. (EditPage::getContentObject)
4156 * - Showing a diff. The left-hand side of a diff when an editor is
4157 * previewing their changes before saving the creation of a page in the
4158 * MediaWiki namespace. (EditPage::showDiff)
4159 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4160 * page with the proposed content matching the interface message default,
4161 * the save is rejected, the same way we disallow blank pages from being
4162 * created. (EditPage::internalAttemptSave)
4165 * - Default content, when using the 'prepend' or 'append' feature.
4168 * - Label the create action as "Edit", if the page can be an override.
4170 * @return string|bool
4172 public function getDefaultMessageText() {
4173 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4177 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4178 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4180 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4182 if ( $message->exists() ) {
4183 return $message->plain();
4190 * Updates page_touched for this page; called from LinksUpdate.php
4192 * @param string|null $purgeTime [optional] TS_MW timestamp
4193 * @return bool True if the update succeeded
4195 public function invalidateCache( $purgeTime = null ) {
4196 if ( wfReadOnly() ) {
4198 } elseif ( $this->mArticleID
=== 0 ) {
4199 return true; // avoid gap locking if we know it's not there
4202 $dbw = wfGetDB( DB_MASTER
);
4203 $dbw->onTransactionPreCommitOrIdle(
4204 function () use ( $dbw ) {
4205 ResourceLoaderWikiModule
::invalidateModuleCache(
4206 $this, null, null, $dbw->getDomainID() );
4211 $conds = $this->pageCond();
4212 DeferredUpdates
::addUpdate(
4213 new AutoCommitUpdate(
4216 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4217 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4220 [ 'page_touched' => $dbTimestamp ],
4221 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4224 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4227 DeferredUpdates
::PRESEND
4234 * Update page_touched timestamps and send CDN purge messages for
4235 * pages linking to this title. May be sent to the job queue depending
4236 * on the number of links. Typically called on create and delete.
4238 public function touchLinks() {
4239 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4240 if ( $this->mNamespace
== NS_CATEGORY
) {
4241 DeferredUpdates
::addUpdate(
4242 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4248 * Get the last touched timestamp
4250 * @param IDatabase|null $db
4251 * @return string|false Last-touched timestamp
4253 public function getTouched( $db = null ) {
4254 if ( $db === null ) {
4255 $db = wfGetDB( DB_REPLICA
);
4257 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4262 * Get the timestamp when this page was updated since the user last saw it.
4264 * @param User|null $user
4265 * @return string|null
4267 public function getNotificationTimestamp( $user = null ) {
4270 // Assume current user if none given
4274 // Check cache first
4275 $uid = $user->getId();
4279 // avoid isset here, as it'll return false for null entries
4280 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4281 return $this->mNotificationTimestamp
[$uid];
4283 // Don't cache too much!
4284 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4285 $this->mNotificationTimestamp
= [];
4288 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4289 $watchedItem = $store->getWatchedItem( $user, $this );
4290 if ( $watchedItem ) {
4291 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4293 $this->mNotificationTimestamp
[$uid] = false;
4296 return $this->mNotificationTimestamp
[$uid];
4300 * Generate strings used for xml 'id' names in monobook tabs
4302 * @param string $prepend Defaults to 'nstab-'
4303 * @return string XML 'id' name
4305 public function getNamespaceKey( $prepend = 'nstab-' ) {
4306 // Gets the subject namespace of this title
4307 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4308 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4309 // Prefer canonical namespace name for HTML IDs
4310 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4311 if ( $namespaceKey === false ) {
4312 // Fallback to localised text
4313 $namespaceKey = $this->getSubjectNsText();
4315 // Makes namespace key lowercase
4316 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4318 if ( $namespaceKey == '' ) {
4319 $namespaceKey = 'main';
4321 // Changes file to image for backwards compatibility
4322 if ( $namespaceKey == 'file' ) {
4323 $namespaceKey = 'image';
4325 return $prepend . $namespaceKey;
4329 * Get all extant redirects to this Title
4331 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4332 * @return Title[] Array of Title redirects to this title
4334 public function getRedirectsHere( $ns = null ) {
4337 $dbr = wfGetDB( DB_REPLICA
);
4339 'rd_namespace' => $this->mNamespace
,
4340 'rd_title' => $this->mDbkeyform
,
4343 if ( $this->isExternal() ) {
4344 $where['rd_interwiki'] = $this->mInterwiki
;
4346 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4348 if ( !is_null( $ns ) ) {
4349 $where['page_namespace'] = $ns;
4352 $res = $dbr->select(
4353 [ 'redirect', 'page' ],
4354 [ 'page_namespace', 'page_title' ],
4359 foreach ( $res as $row ) {
4360 $redirs[] = self
::newFromRow( $row );
4366 * Check if this Title is a valid redirect target
4370 public function isValidRedirectTarget() {
4371 global $wgInvalidRedirectTargets;
4373 if ( $this->isSpecialPage() ) {
4374 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4375 if ( $this->isSpecial( 'Userlogout' ) ) {
4379 foreach ( $wgInvalidRedirectTargets as $target ) {
4380 if ( $this->isSpecial( $target ) ) {
4390 * Get a backlink cache object
4392 * @return BacklinkCache
4394 public function getBacklinkCache() {
4395 return BacklinkCache
::get( $this );
4399 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4403 public function canUseNoindex() {
4404 global $wgExemptFromUserRobotsControl;
4406 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4407 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4409 return !in_array( $this->mNamespace
, $bannedNamespaces );
4413 * Returns the raw sort key to be used for categories, with the specified
4414 * prefix. This will be fed to Collation::getSortKey() to get a
4415 * binary sortkey that can be used for actual sorting.
4417 * @param string $prefix The prefix to be used, specified using
4418 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4422 public function getCategorySortkey( $prefix = '' ) {
4423 $unprefixed = $this->getText();
4425 // Anything that uses this hook should only depend
4426 // on the Title object passed in, and should probably
4427 // tell the users to run updateCollations.php --force
4428 // in order to re-sort existing category relations.
4429 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4430 if ( $prefix !== '' ) {
4431 # Separate with a line feed, so the unprefixed part is only used as
4432 # a tiebreaker when two pages have the exact same prefix.
4433 # In UCA, tab is the only character that can sort above LF
4434 # so we strip both of them from the original prefix.
4435 $prefix = strtr( $prefix, "\n\t", ' ' );
4436 return "$prefix\n$unprefixed";
4442 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4443 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4444 * the db, it will return NULL.
4446 * @return string|null|bool
4448 private function getDbPageLanguageCode() {
4449 global $wgPageLanguageUseDB;
4451 // check, if the page language could be saved in the database, and if so and
4452 // the value is not requested already, lookup the page language using LinkCache
4453 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4454 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4455 $linkCache->addLinkObj( $this );
4456 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4459 return $this->mDbPageLanguage
;
4463 * Get the language in which the content of this page is written in
4464 * wikitext. Defaults to content language, but in certain cases it can be
4465 * e.g. $wgLang (such as special pages, which are in the user language).
4470 public function getPageLanguage() {
4471 global $wgLang, $wgLanguageCode;
4472 if ( $this->isSpecialPage() ) {
4473 // special pages are in the user language
4477 // Checking if DB language is set
4478 $dbPageLanguage = $this->getDbPageLanguageCode();
4479 if ( $dbPageLanguage ) {
4480 return wfGetLangObj( $dbPageLanguage );
4483 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4484 // Note that this may depend on user settings, so the cache should
4485 // be only per-request.
4486 // NOTE: ContentHandler::getPageLanguage() may need to load the
4487 // content to determine the page language!
4488 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4490 $contentHandler = ContentHandler
::getForTitle( $this );
4491 $langObj = $contentHandler->getPageLanguage( $this );
4492 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4494 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4501 * Get the language in which the content of this page is written when
4502 * viewed by user. Defaults to content language, but in certain cases it can be
4503 * e.g. $wgLang (such as special pages, which are in the user language).
4508 public function getPageViewLanguage() {
4511 if ( $this->isSpecialPage() ) {
4512 // If the user chooses a variant, the content is actually
4513 // in a language whose code is the variant code.
4514 $variant = $wgLang->getPreferredVariant();
4515 if ( $wgLang->getCode() !== $variant ) {
4516 return Language
::factory( $variant );
4522 // Checking if DB language is set
4523 $dbPageLanguage = $this->getDbPageLanguageCode();
4524 if ( $dbPageLanguage ) {
4525 $pageLang = wfGetLangObj( $dbPageLanguage );
4526 $variant = $pageLang->getPreferredVariant();
4527 if ( $pageLang->getCode() !== $variant ) {
4528 $pageLang = Language
::factory( $variant );
4534 // @note Can't be cached persistently, depends on user settings.
4535 // @note ContentHandler::getPageViewLanguage() may need to load the
4536 // content to determine the page language!
4537 $contentHandler = ContentHandler
::getForTitle( $this );
4538 $pageLang = $contentHandler->getPageViewLanguage( $this );
4543 * Get a list of rendered edit notices for this page.
4545 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4546 * they will already be wrapped in paragraphs.
4549 * @param int $oldid Revision ID that's being edited
4552 public function getEditNotices( $oldid = 0 ) {
4555 // Optional notice for the entire namespace
4556 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4557 $msg = wfMessage( $editnotice_ns );
4558 if ( $msg->exists() ) {
4559 $html = $msg->parseAsBlock();
4560 // Edit notices may have complex logic, but output nothing (T91715)
4561 if ( trim( $html ) !== '' ) {
4562 $notices[$editnotice_ns] = Html
::rawElement(
4566 'mw-editnotice-namespace',
4567 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4575 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4576 hasSubpages( $this->mNamespace
)
4578 // Optional notice for page itself and any parent page
4579 $editnotice_base = $editnotice_ns;
4580 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4581 $editnotice_base .= '-' . $part;
4582 $msg = wfMessage( $editnotice_base );
4583 if ( $msg->exists() ) {
4584 $html = $msg->parseAsBlock();
4585 if ( trim( $html ) !== '' ) {
4586 $notices[$editnotice_base] = Html
::rawElement(
4590 'mw-editnotice-base',
4591 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4599 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4600 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4601 $msg = wfMessage( $editnoticeText );
4602 if ( $msg->exists() ) {
4603 $html = $msg->parseAsBlock();
4604 if ( trim( $html ) !== '' ) {
4605 $notices[$editnoticeText] = Html
::rawElement(
4609 'mw-editnotice-page',
4610 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4618 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4625 public function __sleep() {
4633 'mDefaultNamespace',
4637 public function __wakeup() {
4638 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4639 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4640 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );