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 MediaWiki\Storage\RevisionRecord
;
27 use Wikimedia\Assert\Assert
;
28 use Wikimedia\Rdbms\Database
;
29 use Wikimedia\Rdbms\IDatabase
;
30 use MediaWiki\Linker\LinkTarget
;
31 use MediaWiki\Interwiki\InterwikiLookup
;
32 use MediaWiki\MediaWikiServices
;
35 * Represents a title within MediaWiki.
36 * Optionally may contain an interwiki designation or namespace.
37 * @note This class can fetch various kinds of data from the database;
38 * however, it does so inefficiently.
39 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
40 * and does not rely on global state or the database.
42 class Title
implements LinkTarget
, IDBAccessObject
{
43 /** @var MapCacheLRU|null */
44 private static $titleCache = null;
47 * Title::newFromText maintains a cache to avoid expensive re-normalization of
48 * commonly used titles. On a batch operation this can become a memory leak
49 * if not bounded. After hitting this many titles reset the cache.
51 const CACHE_MAX
= 1000;
54 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
55 * to use the master DB
57 const GAID_FOR_UPDATE
= 1;
60 * Flag for use with factory methods like newFromLinkTarget() that have
61 * a $forceClone parameter. If set, the method must return a new instance.
62 * Without this flag, some factory methods may return existing instances.
66 const NEW_CLONE
= 'clone';
69 * @name Private member variables
70 * Please use the accessor functions instead.
75 /** @var string Text form (spaces not underscores) of the main part */
76 public $mTextform = '';
78 /** @var string URL-encoded form of the main part */
79 public $mUrlform = '';
81 /** @var string Main part with underscores */
82 public $mDbkeyform = '';
84 /** @var string Database key with the initial letter in the case specified by the user */
85 protected $mUserCaseDBKey;
87 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
88 public $mNamespace = NS_MAIN
;
90 /** @var string Interwiki prefix */
91 public $mInterwiki = '';
93 /** @var bool Was this Title created from a string with a local interwiki prefix? */
94 private $mLocalInterwiki = false;
96 /** @var string Title fragment (i.e. the bit after the #) */
97 public $mFragment = '';
99 /** @var int Article ID, fetched from the link cache on demand */
100 public $mArticleID = -1;
102 /** @var bool|int ID of most recent revision */
103 protected $mLatestID = false;
106 * @var bool|string ID of the page's content model, i.e. one of the
107 * CONTENT_MODEL_XXX constants
109 private $mContentModel = false;
112 * @var bool If a content model was forced via setContentModel()
113 * this will be true to avoid having other code paths reset it
115 private $mForcedContentModel = false;
117 /** @var int Estimated number of revisions; null of not loaded */
118 private $mEstimateRevisions;
120 /** @var array Array of groups allowed to edit this article */
121 public $mRestrictions = [];
124 * @var string|bool Comma-separated set of permission keys
125 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
126 * Edit and move sections are separated by a colon
127 * Example: "edit=autoconfirmed,sysop:move=sysop"
129 protected $mOldRestrictions = false;
131 /** @var bool Cascade restrictions on this page to included templates and images? */
132 public $mCascadeRestriction;
134 /** Caching the results of getCascadeProtectionSources */
135 public $mCascadingRestrictions;
137 /** @var array When do the restrictions on this page expire? */
138 protected $mRestrictionsExpiry = [];
140 /** @var bool Are cascading restrictions in effect on this page? */
141 protected $mHasCascadingRestrictions;
143 /** @var array Where are the cascading restrictions coming from on this page? */
144 public $mCascadeSources;
146 /** @var bool Boolean for initialisation on demand */
147 public $mRestrictionsLoaded = false;
150 * Text form including namespace/interwiki, initialised on demand
152 * Only public to share cache with TitleFormatter
157 public $prefixedText = null;
159 /** @var mixed Cached value for getTitleProtection (create protection) */
160 public $mTitleProtection;
163 * @var int Namespace index when there is no namespace. Don't change the
164 * following default, NS_MAIN is hardcoded in several places. See T2696.
165 * Zero except in {{transclusion}} tags.
167 public $mDefaultNamespace = NS_MAIN
;
169 /** @var int The page length, 0 for special pages */
170 protected $mLength = -1;
172 /** @var null Is the article at this title a redirect? */
173 public $mRedirect = null;
175 /** @var array Associative array of user ID -> timestamp/false */
176 private $mNotificationTimestamp = [];
178 /** @var bool Whether a page has any subpages */
179 private $mHasSubpages;
181 /** @var bool The (string) language code of the page's language and content code. */
182 private $mPageLanguage = false;
184 /** @var string|bool|null The page language code from the database, null if not saved in
185 * the database or false if not loaded, yet. */
186 private $mDbPageLanguage = false;
188 /** @var TitleValue|null A corresponding TitleValue object */
189 private $mTitleValue = null;
191 /** @var bool|null Would deleting this page be a big deletion? */
192 private $mIsBigDeletion = null;
196 * B/C kludge: provide a TitleParser for use by Title.
197 * Ideally, Title would have no methods that need this.
198 * Avoid usage of this singleton by using TitleValue
199 * and the associated services when possible.
201 * @return TitleFormatter
203 private static function getTitleFormatter() {
204 return MediaWikiServices
::getInstance()->getTitleFormatter();
208 * B/C kludge: provide an InterwikiLookup for use by Title.
209 * Ideally, Title would have no methods that need this.
210 * Avoid usage of this singleton by using TitleValue
211 * and the associated services when possible.
213 * @return InterwikiLookup
215 private static function getInterwikiLookup() {
216 return MediaWikiServices
::getInstance()->getInterwikiLookup();
222 function __construct() {
226 * Create a new Title from a prefixed DB key
228 * @param string $key The database key, which has underscores
229 * instead of spaces, possibly including namespace and
231 * @return Title|null Title, or null on an error
233 public static function newFromDBkey( $key ) {
235 $t->mDbkeyform
= $key;
238 $t->secureAndSplit();
240 } catch ( MalformedTitleException
$ex ) {
246 * Returns a Title given a TitleValue.
247 * If the given TitleValue is already a Title instance, that instance is returned,
248 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
249 * is already a Title instance, that instance is copied using the clone operator.
251 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
253 * @param TitleValue $titleValue Assumed to be safe.
254 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
258 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
259 return self
::newFromLinkTarget( $titleValue, $forceClone );
263 * Returns a Title given a LinkTarget.
264 * If the given LinkTarget is already a Title instance, that instance is returned,
265 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
266 * is already a Title instance, that instance is copied using the clone operator.
268 * @param LinkTarget $linkTarget Assumed to be safe.
269 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
273 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
274 if ( $linkTarget instanceof Title
) {
275 // Special case if it's already a Title object
276 if ( $forceClone === self
::NEW_CLONE
) {
277 return clone $linkTarget;
282 return self
::makeTitle(
283 $linkTarget->getNamespace(),
284 $linkTarget->getText(),
285 $linkTarget->getFragment(),
286 $linkTarget->getInterwiki()
291 * Same as newFromLinkTarget, but if passed null, returns null.
293 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
297 public static function castFromLinkTarget( $linkTarget ) {
298 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
302 * Create a new Title from text, such as what one would find in a link. De-
303 * codes any HTML entities in the text.
305 * Title objects returned by this method are guaranteed to be valid, and
306 * thus return true from the isValid() method.
308 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
309 * It may instead be a cached instance created previously, with references to it remaining
312 * @param string|int|null $text The link text; spaces, prefixes, and an
313 * initial ':' indicating the main namespace are accepted.
314 * @param int $defaultNamespace The namespace to use if none is specified
315 * by a prefix. If you want to force a specific namespace even if
316 * $text might begin with a namespace prefix, use makeTitle() or
318 * @throws InvalidArgumentException
319 * @return Title|null Title or null on an error.
321 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
322 // DWIM: Integers can be passed in here when page titles are used as array keys.
323 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
324 throw new InvalidArgumentException( '$text must be a string.' );
326 if ( $text === null ) {
331 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
332 } catch ( MalformedTitleException
$ex ) {
338 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
339 * rather than returning null.
341 * The exception subclasses encode detailed information about why the title is invalid.
343 * Title objects returned by this method are guaranteed to be valid, and
344 * thus return true from the isValid() method.
346 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
347 * It may instead be a cached instance created previously, with references to it remaining
350 * @see Title::newFromText
353 * @param string $text Title text to check
354 * @param int $defaultNamespace
355 * @throws MalformedTitleException If the title is invalid
358 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
359 if ( is_object( $text ) ) {
360 throw new MWException( '$text must be a string, given an object' );
361 } elseif ( $text === null ) {
362 // Legacy code relies on MalformedTitleException being thrown in this case
363 // (happens when URL with no title in it is parsed). TODO fix
364 throw new MalformedTitleException( 'title-invalid-empty' );
367 $titleCache = self
::getTitleCache();
369 // Wiki pages often contain multiple links to the same page.
370 // Title normalization and parsing can become expensive on pages with many
371 // links, so we can save a little time by caching them.
372 // In theory these are value objects and won't get changed...
373 if ( $defaultNamespace == NS_MAIN
) {
374 $t = $titleCache->get( $text );
380 // Convert things like é ā or 〗 into normalized (T16952) text
381 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
384 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
385 $t->mDefaultNamespace
= (int)$defaultNamespace;
387 $t->secureAndSplit();
388 if ( $defaultNamespace == NS_MAIN
) {
389 $titleCache->set( $text, $t );
395 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
397 * Example of wrong and broken code:
398 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
400 * Example of right code:
401 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
403 * Create a new Title from URL-encoded text. Ensures that
404 * the given title's length does not exceed the maximum.
406 * @param string $url The title, as might be taken from a URL
407 * @return Title|null The new object, or null on an error
409 public static function newFromURL( $url ) {
412 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
413 # but some URLs used it as a space replacement and they still come
414 # from some external search tools.
415 if ( strpos( self
::legalChars(), '+' ) === false ) {
416 $url = strtr( $url, '+', ' ' );
419 $t->mDbkeyform
= strtr( $url, ' ', '_' );
422 $t->secureAndSplit();
424 } catch ( MalformedTitleException
$ex ) {
430 * @return MapCacheLRU
432 private static function getTitleCache() {
433 if ( self
::$titleCache === null ) {
434 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
436 return self
::$titleCache;
440 * Returns a list of fields that are to be selected for initializing Title
441 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
442 * whether to include page_content_model.
446 protected static function getSelectFields() {
447 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
450 'page_namespace', 'page_title', 'page_id',
451 'page_len', 'page_is_redirect', 'page_latest',
454 if ( $wgContentHandlerUseDB ) {
455 $fields[] = 'page_content_model';
458 if ( $wgPageLanguageUseDB ) {
459 $fields[] = 'page_lang';
466 * Create a new Title from an article ID
468 * @param int $id The page_id corresponding to the Title to create
469 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
470 * @return Title|null The new object, or null on an error
472 public static function newFromID( $id, $flags = 0 ) {
473 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
474 $row = $db->selectRow(
476 self
::getSelectFields(),
477 [ 'page_id' => $id ],
480 if ( $row !== false ) {
481 $title = self
::newFromRow( $row );
490 * Make an array of titles from an array of IDs
492 * @param int[] $ids Array of IDs
493 * @return Title[] Array of Titles
495 public static function newFromIDs( $ids ) {
496 if ( !count( $ids ) ) {
499 $dbr = wfGetDB( DB_REPLICA
);
503 self
::getSelectFields(),
504 [ 'page_id' => $ids ],
509 foreach ( $res as $row ) {
510 $titles[] = self
::newFromRow( $row );
516 * Make a Title object from a DB row
518 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
519 * @return Title Corresponding Title
521 public static function newFromRow( $row ) {
522 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
523 $t->loadFromRow( $row );
528 * Load Title object fields from a DB row.
529 * If false is given, the title will be treated as non-existing.
531 * @param stdClass|bool $row Database row
533 public function loadFromRow( $row ) {
534 if ( $row ) { // page found
535 if ( isset( $row->page_id
) ) {
536 $this->mArticleID
= (int)$row->page_id
;
538 if ( isset( $row->page_len
) ) {
539 $this->mLength
= (int)$row->page_len
;
541 if ( isset( $row->page_is_redirect
) ) {
542 $this->mRedirect
= (bool)$row->page_is_redirect
;
544 if ( isset( $row->page_latest
) ) {
545 $this->mLatestID
= (int)$row->page_latest
;
547 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
548 $this->mContentModel
= (string)$row->page_content_model
;
549 } elseif ( !$this->mForcedContentModel
) {
550 $this->mContentModel
= false; # initialized lazily in getContentModel()
552 if ( isset( $row->page_lang
) ) {
553 $this->mDbPageLanguage
= (string)$row->page_lang
;
555 if ( isset( $row->page_restrictions
) ) {
556 $this->mOldRestrictions
= $row->page_restrictions
;
558 } else { // page not found
559 $this->mArticleID
= 0;
561 $this->mRedirect
= false;
562 $this->mLatestID
= 0;
563 if ( !$this->mForcedContentModel
) {
564 $this->mContentModel
= false; # initialized lazily in getContentModel()
570 * Create a new Title from a namespace index and a DB key.
572 * It's assumed that $ns and $title are safe, for instance when
573 * they came directly from the database or a special page name,
574 * not from user input.
576 * No validation is applied. For convenience, spaces are normalized
577 * to underscores, so that e.g. user_text fields can be used directly.
579 * @note This method may return Title objects that are "invalid"
580 * according to the isValid() method. This is usually caused by
581 * configuration changes: e.g. a namespace that was once defined is
582 * no longer configured, or a character that was once allowed in
583 * titles is now forbidden.
585 * @param int $ns The namespace of the article
586 * @param string $title The unprefixed database key form
587 * @param string $fragment The link fragment (after the "#")
588 * @param string $interwiki The interwiki prefix
589 * @return Title The new object
591 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
593 $t->mInterwiki
= $interwiki;
594 $t->mFragment
= $fragment;
595 $t->mNamespace
= $ns = (int)$ns;
596 $t->mDbkeyform
= strtr( $title, ' ', '_' );
597 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
598 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
599 $t->mTextform
= strtr( $title, '_', ' ' );
600 $t->mContentModel
= false; # initialized lazily in getContentModel()
605 * Create a new Title from a namespace index and a DB key.
606 * The parameters will be checked for validity, which is a bit slower
607 * than makeTitle() but safer for user-provided data.
609 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
610 * that is, they return true from the isValid() method. If no valid Title
611 * can be constructed from the input, this method returns null.
613 * @param int $ns The namespace of the article
614 * @param string $title Database key form
615 * @param string $fragment The link fragment (after the "#")
616 * @param string $interwiki Interwiki prefix
617 * @return Title|null The new object, or null on an error
619 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
620 // NOTE: ideally, this would just call makeTitle() and then isValid(),
621 // but presently, that means more overhead on a potential performance hotspot.
623 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
628 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
631 $t->secureAndSplit();
633 } catch ( MalformedTitleException
$ex ) {
639 * Create a new Title for the Main Page
641 * This uses the 'mainpage' interface message, which could be specified in
642 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
643 * will use the user language, which would involve initialising the session
644 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
645 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
646 * or ResourceloaderContext) to prevent an error.
648 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
649 * It may instead be a cached instance created previously, with references to it remaining
652 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
655 public static function newMainPage( MessageLocalizer
$localizer = null ) {
657 $msg = $localizer->msg( 'mainpage' );
659 $msg = wfMessage( 'mainpage' );
662 $title = self
::newFromText( $msg->inContentLanguage()->text() );
664 // Every page renders at least one link to the Main Page (e.g. sidebar).
665 // If the localised value is invalid, don't produce fatal errors that
666 // would make the wiki inaccessible (and hard to fix the invalid message).
667 // Gracefully fallback...
669 $title = self
::newFromText( 'Main Page' );
675 * Get the prefixed DB key associated with an ID
677 * @param int $id The page_id of the article
678 * @return Title|null An object representing the article, or null if no such article was found
680 public static function nameOf( $id ) {
681 $dbr = wfGetDB( DB_REPLICA
);
683 $s = $dbr->selectRow(
685 [ 'page_namespace', 'page_title' ],
686 [ 'page_id' => $id ],
689 if ( $s === false ) {
693 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
698 * Get a regex character class describing the legal characters in a link
700 * @return string The list of characters, not delimited
702 public static function legalChars() {
703 global $wgLegalTitleChars;
704 return $wgLegalTitleChars;
708 * Utility method for converting a character sequence from bytes to Unicode.
710 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
711 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
713 * @param string $byteClass
716 public static function convertByteClassToUnicodeClass( $byteClass ) {
717 $length = strlen( $byteClass );
719 $x0 = $x1 = $x2 = '';
721 $d0 = $d1 = $d2 = '';
722 // Decoded integer codepoints
723 $ord0 = $ord1 = $ord2 = 0;
725 $r0 = $r1 = $r2 = '';
729 $allowUnicode = false;
730 for ( $pos = 0; $pos < $length; $pos++
) {
731 // Shift the queues down
740 // Load the current input token and decoded values
741 $inChar = $byteClass[$pos];
742 if ( $inChar == '\\' ) {
743 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
744 $x0 = $inChar . $m[0];
745 $d0 = chr( hexdec( $m[1] ) );
746 $pos +
= strlen( $m[0] );
747 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
748 $x0 = $inChar . $m[0];
749 $d0 = chr( octdec( $m[0] ) );
750 $pos +
= strlen( $m[0] );
751 } elseif ( $pos +
1 >= $length ) {
754 $d0 = $byteClass[$pos +
1];
762 // Load the current re-encoded value
763 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
764 $r0 = sprintf( '\x%02x', $ord0 );
765 } elseif ( $ord0 >= 0x80 ) {
766 // Allow unicode if a single high-bit character appears
767 $r0 = sprintf( '\x%02x', $ord0 );
768 $allowUnicode = true;
769 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
770 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
776 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
778 if ( $ord2 > $ord0 ) {
780 } elseif ( $ord0 >= 0x80 ) {
782 $allowUnicode = true;
783 if ( $ord2 < 0x80 ) {
784 // Keep the non-unicode section of the range
791 // Reset state to the initial value
792 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
793 } elseif ( $ord2 < 0x80 ) {
798 if ( $ord1 < 0x80 ) {
801 if ( $ord0 < 0x80 ) {
804 if ( $allowUnicode ) {
805 $out .= '\u0080-\uFFFF';
811 * Make a prefixed DB key from a DB key and a namespace index
813 * @param int $ns Numerical representation of the namespace
814 * @param string $title The DB key form the title
815 * @param string $fragment The link fragment (after the "#")
816 * @param string $interwiki The interwiki prefix
817 * @param bool $canonicalNamespace If true, use the canonical name for
818 * $ns instead of the localized version.
819 * @return string The prefixed form of the title
821 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
822 $canonicalNamespace = false
824 if ( $canonicalNamespace ) {
825 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
826 getCanonicalName( $ns );
828 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
830 $name = $namespace == '' ?
$title : "$namespace:$title";
831 if ( strval( $interwiki ) != '' ) {
832 $name = "$interwiki:$name";
834 if ( strval( $fragment ) != '' ) {
835 $name .= '#' . $fragment;
841 * Callback for usort() to do title sorts by (namespace, title)
843 * @param LinkTarget $a
844 * @param LinkTarget $b
846 * @return int Result of string comparison, or namespace comparison
848 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
849 return $a->getNamespace() <=> $b->getNamespace()
850 ?
: strcmp( $a->getText(), $b->getText() );
854 * Returns true if the title is valid, false if it is invalid.
856 * Valid titles can be round-tripped via makeTitle() and newFromText().
857 * Their DB key can be used in the database, though it may not have the correct
860 * Invalid titles may get returned from makeTitle(), and it may be useful to
861 * allow them to exist, e.g. in order to process log entries about pages in
862 * namespaces that belong to extensions that are no longer installed.
864 * @note This method is relatively expensive. When constructing Title
865 * objects that need to be valid, use an instantiator method that is guaranteed
866 * to return valid titles, such as makeTitleSafe() or newFromText().
870 public function isValid() {
871 $services = MediaWikiServices
::getInstance();
872 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
877 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
878 } catch ( MalformedTitleException
$ex ) {
883 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
890 } catch ( InvalidArgumentException
$ex ) {
898 * Determine whether the object refers to a page within
899 * this project (either this wiki or a wiki with a local
900 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
902 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
904 public function isLocal() {
905 if ( $this->isExternal() ) {
906 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
908 return $iw->isLocal();
915 * Is this Title interwiki?
919 public function isExternal() {
920 return $this->mInterwiki
!== '';
924 * Get the interwiki prefix
926 * Use Title::isExternal to check if a interwiki is set
928 * @return string Interwiki prefix
930 public function getInterwiki() {
931 return $this->mInterwiki
;
935 * Was this a local interwiki link?
939 public function wasLocalInterwiki() {
940 return $this->mLocalInterwiki
;
944 * Determine whether the object refers to a page within
945 * this project and is transcludable.
947 * @return bool True if this is transcludable
949 public function isTrans() {
950 if ( !$this->isExternal() ) {
954 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
958 * Returns the DB name of the distant wiki which owns the object.
960 * @return string|false The DB name
962 public function getTransWikiID() {
963 if ( !$this->isExternal() ) {
967 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
971 * Get a TitleValue object representing this Title.
973 * @note Not all valid Titles have a corresponding valid TitleValue
974 * (e.g. TitleValues cannot represent page-local links that have a
975 * fragment but no title text).
977 * @return TitleValue|null
979 public function getTitleValue() {
980 if ( $this->mTitleValue
=== null ) {
982 $this->mTitleValue
= new TitleValue(
988 } catch ( InvalidArgumentException
$ex ) {
989 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
990 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
994 return $this->mTitleValue
;
998 * Get the text form (spaces not underscores) of the main part
1000 * @return string Main part of the title
1002 public function getText() {
1003 return $this->mTextform
;
1007 * Get the URL-encoded form of the main part
1009 * @return string Main part of the title, URL-encoded
1011 public function getPartialURL() {
1012 return $this->mUrlform
;
1016 * Get the main part with underscores
1018 * @return string Main part of the title, with underscores
1020 public function getDBkey() {
1021 return $this->mDbkeyform
;
1025 * Get the DB key with the initial letter case as specified by the user
1026 * @deprecated since 1.33; please use Title::getDBKey() instead
1028 * @return string DB key
1030 function getUserCaseDBKey() {
1031 if ( !is_null( $this->mUserCaseDBKey
) ) {
1032 return $this->mUserCaseDBKey
;
1034 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1035 return $this->mDbkeyform
;
1040 * Get the namespace index, i.e. one of the NS_xxxx constants.
1042 * @return int Namespace index
1044 public function getNamespace() {
1045 return $this->mNamespace
;
1049 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1051 * @todo Deprecate this in favor of SlotRecord::getModel()
1053 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1054 * @return string Content model id
1056 public function getContentModel( $flags = 0 ) {
1057 if ( !$this->mForcedContentModel
1058 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1059 && $this->getArticleID( $flags )
1061 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1062 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1063 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1066 if ( !$this->mContentModel
) {
1067 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1070 return $this->mContentModel
;
1074 * Convenience method for checking a title's content model name
1076 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1077 * @return bool True if $this->getContentModel() == $id
1079 public function hasContentModel( $id ) {
1080 return $this->getContentModel() == $id;
1084 * Set a proposed content model for the page for permissions
1085 * checking. This does not actually change the content model
1088 * Additionally, you should make sure you've checked
1089 * ContentHandler::canBeUsedOn() first.
1092 * @param string $model CONTENT_MODEL_XXX constant
1094 public function setContentModel( $model ) {
1095 $this->mContentModel
= $model;
1096 $this->mForcedContentModel
= true;
1100 * Get the namespace text
1102 * @return string|false Namespace text
1104 public function getNsText() {
1105 if ( $this->isExternal() ) {
1106 // This probably shouldn't even happen, except for interwiki transclusion.
1107 // If possible, use the canonical name for the foreign namespace.
1108 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1109 getCanonicalName( $this->mNamespace
);
1110 if ( $nsText !== false ) {
1116 $formatter = self
::getTitleFormatter();
1117 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1118 } catch ( InvalidArgumentException
$ex ) {
1119 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1125 * Get the namespace text of the subject (rather than talk) page
1127 * @return string Namespace text
1129 public function getSubjectNsText() {
1130 $services = MediaWikiServices
::getInstance();
1131 return $services->getContentLanguage()->
1132 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1136 * Get the namespace text of the talk page
1138 * @return string Namespace text
1140 public function getTalkNsText() {
1141 $services = MediaWikiServices
::getInstance();
1142 return $services->getContentLanguage()->
1143 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1147 * Can this title have a corresponding talk page?
1149 * False for relative section links (with getText() === ''),
1150 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1152 * @see NamespaceInfo::canHaveTalkPage
1155 * @return bool True if this title either is a talk page or can have a talk page associated.
1157 public function canHaveTalkPage() {
1158 return MediaWikiServices
::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1162 * Is this in a namespace that allows actual pages?
1166 public function canExist() {
1167 return $this->mNamespace
>= NS_MAIN
;
1171 * Can this title be added to a user's watchlist?
1173 * False for relative section links (with getText() === ''),
1174 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1178 public function isWatchable() {
1179 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
1180 return $this->getText() !== '' && !$this->isExternal() &&
1181 $nsInfo->isWatchable( $this->mNamespace
);
1185 * Returns true if this is a special page.
1189 public function isSpecialPage() {
1190 return $this->mNamespace
== NS_SPECIAL
;
1194 * Returns true if this title resolves to the named special page
1196 * @param string $name The special page name
1199 public function isSpecial( $name ) {
1200 if ( $this->isSpecialPage() ) {
1201 list( $thisName, /* $subpage */ ) =
1202 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1203 resolveAlias( $this->mDbkeyform
);
1204 if ( $name == $thisName ) {
1212 * If the Title refers to a special page alias which is not the local default, resolve
1213 * the alias, and localise the name as necessary. Otherwise, return $this
1217 public function fixSpecialName() {
1218 if ( $this->isSpecialPage() ) {
1219 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1220 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1221 if ( $canonicalName ) {
1222 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1223 if ( $localName != $this->mDbkeyform
) {
1224 return self
::makeTitle( NS_SPECIAL
, $localName );
1232 * Returns true if the title is inside the specified namespace.
1234 * Please make use of this instead of comparing to getNamespace()
1235 * This function is much more resistant to changes we may make
1236 * to namespaces than code that makes direct comparisons.
1237 * @param int $ns The namespace
1241 public function inNamespace( $ns ) {
1242 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1243 equals( $this->mNamespace
, $ns );
1247 * Returns true if the title is inside one of the specified namespaces.
1249 * @param int|int[] $namespaces,... The namespaces to check for
1253 public function inNamespaces( /* ... */ ) {
1254 $namespaces = func_get_args();
1255 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1256 $namespaces = $namespaces[0];
1259 foreach ( $namespaces as $ns ) {
1260 if ( $this->inNamespace( $ns ) ) {
1269 * Returns true if the title has the same subject namespace as the
1270 * namespace specified.
1271 * For example this method will take NS_USER and return true if namespace
1272 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1273 * as their subject namespace.
1275 * This is MUCH simpler than individually testing for equivalence
1276 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1281 public function hasSubjectNamespace( $ns ) {
1282 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1283 subjectEquals( $this->mNamespace
, $ns );
1287 * Is this Title in a namespace which contains content?
1288 * In other words, is this a content page, for the purposes of calculating
1293 public function isContentPage() {
1294 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1295 isContent( $this->mNamespace
);
1299 * Would anybody with sufficient privileges be able to move this page?
1300 * Some pages just aren't movable.
1304 public function isMovable() {
1306 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1307 isMovable( $this->mNamespace
) ||
$this->isExternal()
1309 // Interwiki title or immovable namespace. Hooks don't get to override here
1314 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1319 * Is this the mainpage?
1320 * @note Title::newFromText seems to be sufficiently optimized by the title
1321 * cache that we don't need to over-optimize by doing direct comparisons and
1322 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1323 * ends up reporting something differently than $title->isMainPage();
1328 public function isMainPage() {
1329 return $this->equals( self
::newMainPage() );
1333 * Is this a subpage?
1337 public function isSubpage() {
1338 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1339 hasSubpages( $this->mNamespace
)
1340 ?
strpos( $this->getText(), '/' ) !== false
1345 * Is this a conversion table for the LanguageConverter?
1349 public function isConversionTable() {
1350 // @todo ConversionTable should become a separate content model.
1352 return $this->mNamespace
== NS_MEDIAWIKI
&&
1353 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1357 * Does that page contain wikitext, or it is JS, CSS or whatever?
1361 public function isWikitextPage() {
1362 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1366 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1367 * global UI. This is generally true for pages in the MediaWiki namespace having
1368 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1370 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1373 * Note that this method should not return true for pages that contain and show
1374 * "inactive" CSS, JSON, or JS.
1379 public function isSiteConfigPage() {
1381 $this->isSiteCssConfigPage()
1382 ||
$this->isSiteJsonConfigPage()
1383 ||
$this->isSiteJsConfigPage()
1388 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1393 public function isUserConfigPage() {
1395 $this->isUserCssConfigPage()
1396 ||
$this->isUserJsonConfigPage()
1397 ||
$this->isUserJsConfigPage()
1402 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1404 * @return string Containing skin name from .css, .json, or .js subpage title
1407 public function getSkinFromConfigSubpage() {
1408 $subpage = explode( '/', $this->mTextform
);
1409 $subpage = $subpage[count( $subpage ) - 1];
1410 $lastdot = strrpos( $subpage, '.' );
1411 if ( $lastdot === false ) {
1412 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1414 return substr( $subpage, 0, $lastdot );
1418 * Is this a CSS "config" sub-page of a user page?
1423 public function isUserCssConfigPage() {
1425 NS_USER
== $this->mNamespace
1426 && $this->isSubpage()
1427 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1432 * Is this a JSON "config" sub-page of a user page?
1437 public function isUserJsonConfigPage() {
1439 NS_USER
== $this->mNamespace
1440 && $this->isSubpage()
1441 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1446 * Is this a JS "config" sub-page of a user page?
1451 public function isUserJsConfigPage() {
1453 NS_USER
== $this->mNamespace
1454 && $this->isSubpage()
1455 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1460 * Is this a sitewide CSS "config" page?
1465 public function isSiteCssConfigPage() {
1467 NS_MEDIAWIKI
== $this->mNamespace
1469 $this->hasContentModel( CONTENT_MODEL_CSS
)
1470 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1471 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1472 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1478 * Is this a sitewide JSON "config" page?
1483 public function isSiteJsonConfigPage() {
1485 NS_MEDIAWIKI
== $this->mNamespace
1487 $this->hasContentModel( CONTENT_MODEL_JSON
)
1488 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1489 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1490 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1496 * Is this a sitewide JS "config" page?
1501 public function isSiteJsConfigPage() {
1503 NS_MEDIAWIKI
== $this->mNamespace
1505 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1506 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1507 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1508 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1514 * Is this a message which can contain raw HTML?
1519 public function isRawHtmlMessage() {
1520 global $wgRawHtmlMessages;
1522 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1525 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1526 return in_array( $message, $wgRawHtmlMessages, true );
1530 * Is this a talk page of some sort?
1534 public function isTalkPage() {
1535 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1536 isTalk( $this->mNamespace
);
1540 * Get a Title object associated with the talk page of this article
1542 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1543 * with NamespaceInfo::canHaveTalkPage().
1544 * @return Title The object for the talk page
1545 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1546 * or because it's a relative link, or an interwiki link.
1548 public function getTalkPage() {
1549 return self
::castFromLinkTarget(
1550 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1554 * Get a Title object associated with the talk page of this article,
1555 * if such a talk page can exist.
1559 * @return Title|null The object for the talk page,
1560 * or null if no associated talk page can exist, according to canHaveTalkPage().
1562 public function getTalkPageIfDefined() {
1563 if ( !$this->canHaveTalkPage() ) {
1567 return $this->getTalkPage();
1571 * Get a title object associated with the subject page of this
1574 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1575 * @return Title The object for the subject page
1577 public function getSubjectPage() {
1578 return self
::castFromLinkTarget(
1579 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1583 * Get the other title for this page, if this is a subject page
1584 * get the talk page, if it is a subject page get the talk page
1586 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1588 * @throws MWException If the page doesn't have an other page
1591 public function getOtherPage() {
1592 return self
::castFromLinkTarget(
1593 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1597 * Get the default namespace index, for when there is no namespace
1599 * @return int Default namespace index
1601 public function getDefaultNamespace() {
1602 return $this->mDefaultNamespace
;
1606 * Get the Title fragment (i.e.\ the bit after the #) in text form
1608 * Use Title::hasFragment to check for a fragment
1610 * @return string Title fragment
1612 public function getFragment() {
1613 return $this->mFragment
;
1617 * Check if a Title fragment is set
1622 public function hasFragment() {
1623 return $this->mFragment
!== '';
1627 * Get the fragment in URL form, including the "#" character if there is one
1629 * @return string Fragment in URL form
1631 public function getFragmentForURL() {
1632 if ( !$this->hasFragment() ) {
1634 } elseif ( $this->isExternal() ) {
1635 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1636 // so we treat it like a local interwiki.
1637 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1638 if ( $interwiki && !$interwiki->isLocal() ) {
1639 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1643 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1647 * Set the fragment for this title. Removes the first character from the
1648 * specified fragment before setting, so it assumes you're passing it with
1651 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1652 * or Title::createFragmentTarget().
1653 * Still in active use privately.
1656 * @param string $fragment Text
1658 public function setFragment( $fragment ) {
1659 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1663 * Creates a new Title for a different fragment of the same page.
1666 * @param string $fragment
1669 public function createFragmentTarget( $fragment ) {
1670 return self
::makeTitle(
1679 * Prefix some arbitrary text with the namespace or interwiki prefix
1682 * @param string $name The text
1683 * @return string The prefixed text
1685 private function prefix( $name ) {
1687 if ( $this->isExternal() ) {
1688 $p = $this->mInterwiki
. ':';
1691 if ( $this->mNamespace
!= 0 ) {
1692 $nsText = $this->getNsText();
1694 if ( $nsText === false ) {
1695 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1696 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1697 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1700 $p .= $nsText . ':';
1706 * Get the prefixed database key form
1708 * @return string The prefixed title, with underscores and
1709 * any interwiki and namespace prefixes
1711 public function getPrefixedDBkey() {
1712 $s = $this->prefix( $this->mDbkeyform
);
1713 $s = strtr( $s, ' ', '_' );
1718 * Get the prefixed title with spaces.
1719 * This is the form usually used for display
1721 * @return string The prefixed title, with spaces
1723 public function getPrefixedText() {
1724 if ( $this->prefixedText
=== null ) {
1725 $s = $this->prefix( $this->mTextform
);
1726 $s = strtr( $s, '_', ' ' );
1727 $this->prefixedText
= $s;
1729 return $this->prefixedText
;
1733 * Return a string representation of this title
1735 * @return string Representation of this title
1737 public function __toString() {
1738 return $this->getPrefixedText();
1742 * Get the prefixed title with spaces, plus any fragment
1743 * (part beginning with '#')
1745 * @return string The prefixed title, with spaces and the fragment, including '#'
1747 public function getFullText() {
1748 $text = $this->getPrefixedText();
1749 if ( $this->hasFragment() ) {
1750 $text .= '#' . $this->mFragment
;
1756 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1758 * @note the return value may contain trailing whitespace and is thus
1759 * not safe for use with makeTitle or TitleValue.
1763 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1767 * @return string Root name
1770 public function getRootText() {
1772 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1773 hasSubpages( $this->mNamespace
)
1774 ||
strtok( $this->getText(), '/' ) === false
1776 return $this->getText();
1779 return strtok( $this->getText(), '/' );
1783 * Get the root page name title, i.e. the leftmost part before any slashes
1787 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1788 * # returns: Title{User:Foo}
1791 * @return Title Root title
1794 public function getRootTitle() {
1795 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getRootText() );
1796 Assert
::postcondition(
1798 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1804 * Get the base page name without a namespace, i.e. the part before the subpage name
1806 * @note the return value may contain trailing whitespace and is thus
1807 * not safe for use with makeTitle or TitleValue.
1811 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1812 * # returns: 'Foo/Bar'
1815 * @return string Base name
1817 public function getBaseText() {
1818 $text = $this->getText();
1820 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1821 hasSubpages( $this->mNamespace
)
1826 $lastSlashPos = strrpos( $text, '/' );
1827 // Don't discard the real title if there's no subpage involved
1828 if ( $lastSlashPos === false ) {
1832 return substr( $text, 0, $lastSlashPos );
1836 * Get the base page name title, i.e. the part before the subpage name.
1840 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1841 * # returns: Title{User:Foo/Bar}
1844 * @return Title Base title
1847 public function getBaseTitle() {
1848 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getBaseText() );
1849 Assert
::postcondition(
1851 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1857 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1861 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1865 * @return string Subpage name
1867 public function getSubpageText() {
1869 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1870 hasSubpages( $this->mNamespace
)
1872 return $this->mTextform
;
1874 $parts = explode( '/', $this->mTextform
);
1875 return $parts[count( $parts ) - 1];
1879 * Get the title for a subpage of the current page
1883 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1884 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1887 * @param string $text The subpage name to add to the title
1888 * @return Title|null Subpage title, or null on an error
1891 public function getSubpage( $text ) {
1892 return self
::makeTitleSafe(
1894 $this->getText() . '/' . $text,
1901 * Get a URL-encoded form of the subpage text
1903 * @return string URL-encoded subpage name
1905 public function getSubpageUrlForm() {
1906 $text = $this->getSubpageText();
1907 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1912 * Get a URL-encoded title (not an actual URL) including interwiki
1914 * @return string The URL-encoded form
1916 public function getPrefixedURL() {
1917 $s = $this->prefix( $this->mDbkeyform
);
1918 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1923 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1924 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1925 * second argument named variant. This was deprecated in favor
1926 * of passing an array of option with a "variant" key
1927 * Once $query2 is removed for good, this helper can be dropped
1928 * and the wfArrayToCgi moved to getLocalURL();
1930 * @since 1.19 (r105919)
1931 * @param array|string $query
1932 * @param string|string[]|bool $query2
1935 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1936 if ( $query2 !== false ) {
1937 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1938 "method called with a second parameter is deprecated. Add your " .
1939 "parameter to an array passed as the first parameter.", "1.19" );
1941 if ( is_array( $query ) ) {
1942 $query = wfArrayToCgi( $query );
1945 if ( is_string( $query2 ) ) {
1946 // $query2 is a string, we will consider this to be
1947 // a deprecated $variant argument and add it to the query
1948 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1950 $query2 = wfArrayToCgi( $query2 );
1952 // If we have $query content add a & to it first
1956 // Now append the queries together
1963 * Get a real URL referring to this title, with interwiki link and
1966 * @see self::getLocalURL for the arguments.
1968 * @param string|string[] $query
1969 * @param string|string[]|bool $query2
1970 * @param string|int|null $proto Protocol type to use in URL
1971 * @return string The URL
1973 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1974 $query = self
::fixUrlQueryArgs( $query, $query2 );
1976 # Hand off all the decisions on urls to getLocalURL
1977 $url = $this->getLocalURL( $query );
1979 # Expand the url to make it a full url. Note that getLocalURL has the
1980 # potential to output full urls for a variety of reasons, so we use
1981 # wfExpandUrl instead of simply prepending $wgServer
1982 $url = wfExpandUrl( $url, $proto );
1984 # Finally, add the fragment.
1985 $url .= $this->getFragmentForURL();
1986 // Avoid PHP 7.1 warning from passing $this by reference
1988 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1993 * Get a url appropriate for making redirects based on an untrusted url arg
1995 * This is basically the same as getFullUrl(), but in the case of external
1996 * interwikis, we send the user to a landing page, to prevent possible
1997 * phishing attacks and the like.
1999 * @note Uses current protocol by default, since technically relative urls
2000 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2001 * places where the url gets cached, as might pollute between
2002 * https and non-https users.
2003 * @see self::getLocalURL for the arguments.
2004 * @param array|string $query
2005 * @param string $proto Protocol type to use in URL
2006 * @return string A url suitable to use in an HTTP location header.
2008 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
2010 if ( $this->isExternal() ) {
2011 $target = SpecialPage
::getTitleFor(
2013 $this->getPrefixedDBkey()
2016 return $target->getFullURL( $query, false, $proto );
2020 * Get a URL with no fragment or server name (relative URL) from a Title object.
2021 * If this page is generated with action=render, however,
2022 * $wgServer is prepended to make an absolute URL.
2024 * @see self::getFullURL to always get an absolute URL.
2025 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2026 * valid to link, locally, to the current Title.
2027 * @see self::newFromText to produce a Title object.
2029 * @param string|string[] $query An optional query string,
2030 * not used for interwiki links. Can be specified as an associative array as well,
2031 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2032 * Some query patterns will trigger various shorturl path replacements.
2033 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2034 * be an array. If a string is passed it will be interpreted as a deprecated
2035 * variant argument and urlencoded into a variant= argument.
2036 * This second query argument will be added to the $query
2037 * The second parameter is deprecated since 1.19. Pass it as a key,value
2038 * pair in the first parameter array instead.
2040 * @return string String of the URL.
2042 public function getLocalURL( $query = '', $query2 = false ) {
2043 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
2045 $query = self
::fixUrlQueryArgs( $query, $query2 );
2047 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2049 $namespace = $this->getNsText();
2050 if ( $namespace != '' ) {
2051 # Can this actually happen? Interwikis shouldn't be parsed.
2052 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2055 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2056 $url = wfAppendQuery( $url, $query );
2058 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2059 if ( $query == '' ) {
2060 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2061 // Avoid PHP 7.1 warning from passing $this by reference
2063 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2065 global $wgVariantArticlePath, $wgActionPaths;
2069 if ( !empty( $wgActionPaths )
2070 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2072 $action = urldecode( $matches[2] );
2073 if ( isset( $wgActionPaths[$action] ) ) {
2074 $query = $matches[1];
2075 if ( isset( $matches[4] ) ) {
2076 $query .= $matches[4];
2078 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2079 if ( $query != '' ) {
2080 $url = wfAppendQuery( $url, $query );
2086 && $wgVariantArticlePath
2087 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2088 && $this->getPageLanguage()->equals(
2089 MediaWikiServices
::getInstance()->getContentLanguage() )
2090 && $this->getPageLanguage()->hasVariants()
2092 $variant = urldecode( $matches[1] );
2093 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2094 // Only do the variant replacement if the given variant is a valid
2095 // variant for the page's language.
2096 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2097 $url = str_replace( '$1', $dbkey, $url );
2101 if ( $url === false ) {
2102 if ( $query == '-' ) {
2105 $url = "{$wgScript}?title={$dbkey}&{$query}";
2108 // Avoid PHP 7.1 warning from passing $this by reference
2110 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2112 // @todo FIXME: This causes breakage in various places when we
2113 // actually expected a local URL and end up with dupe prefixes.
2114 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2115 $url = $wgServer . $url;
2118 // Avoid PHP 7.1 warning from passing $this by reference
2120 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2125 * Get a URL that's the simplest URL that will be valid to link, locally,
2126 * to the current Title. It includes the fragment, but does not include
2127 * the server unless action=render is used (or the link is external). If
2128 * there's a fragment but the prefixed text is empty, we just return a link
2131 * The result obviously should not be URL-escaped, but does need to be
2132 * HTML-escaped if it's being output in HTML.
2134 * @param string|string[] $query
2135 * @param bool $query2
2136 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2137 * or false (default) for no expansion
2138 * @see self::getLocalURL for the arguments.
2139 * @return string The URL
2141 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2142 if ( $this->isExternal() ||
$proto !== false ) {
2143 $ret = $this->getFullURL( $query, $query2, $proto );
2144 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2145 $ret = $this->getFragmentForURL();
2147 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2153 * Get the URL form for an internal link.
2154 * - Used in various CDN-related code, in case we have a different
2155 * internal hostname for the server from the exposed one.
2157 * This uses $wgInternalServer to qualify the path, or $wgServer
2158 * if $wgInternalServer is not set. If the server variable used is
2159 * protocol-relative, the URL will be expanded to http://
2161 * @see self::getLocalURL for the arguments.
2162 * @param string|string[] $query
2163 * @param string|bool $query2 Deprecated
2164 * @return string The URL
2166 public function getInternalURL( $query = '', $query2 = false ) {
2167 global $wgInternalServer, $wgServer;
2168 $query = self
::fixUrlQueryArgs( $query, $query2 );
2169 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2170 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2171 // Avoid PHP 7.1 warning from passing $this by reference
2173 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2178 * Get the URL for a canonical link, for use in things like IRC and
2179 * e-mail notifications. Uses $wgCanonicalServer and the
2180 * GetCanonicalURL hook.
2182 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2184 * @see self::getLocalURL for the arguments.
2185 * @param string|string[] $query
2186 * @param string|bool $query2 Deprecated
2187 * @return string The URL
2190 public function getCanonicalURL( $query = '', $query2 = false ) {
2191 $query = self
::fixUrlQueryArgs( $query, $query2 );
2192 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2193 // Avoid PHP 7.1 warning from passing $this by reference
2195 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2200 * Get the edit URL for this Title
2202 * @return string The URL, or a null string if this is an interwiki link
2204 public function getEditURL() {
2205 if ( $this->isExternal() ) {
2208 $s = $this->getLocalURL( 'action=edit' );
2214 * Can $user perform $action on this page?
2215 * This skips potentially expensive cascading permission checks
2216 * as well as avoids expensive error formatting
2218 * Suitable for use for nonessential UI controls in common cases, but
2219 * _not_ for functional access control.
2221 * May provide false positives, but should never provide a false negative.
2223 * @param string $action Action that permission needs to be checked for
2224 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2229 * @deprecated since 1.33,
2230 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2233 public function quickUserCan( $action, $user = null ) {
2234 return $this->userCan( $action, $user, false );
2238 * Can $user perform $action on this page?
2240 * @param string $action Action that permission needs to be checked for
2241 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2243 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2248 * @deprecated since 1.33,
2249 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2252 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2253 if ( !$user instanceof User
) {
2258 // TODO: this is for b/c, eventually will be removed
2259 if ( $rigor === true ) {
2260 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2261 } elseif ( $rigor === false ) {
2262 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2265 return MediaWikiServices
::getInstance()->getPermissionManager()
2266 ->userCan( $action, $user, $this, $rigor );
2270 * Can $user perform $action on this page?
2272 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2274 * @param string $action Action that permission needs to be checked for
2275 * @param User $user User to check
2276 * @param string $rigor One of (quick,full,secure)
2277 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2278 * - full : does cheap and expensive checks possibly from a replica DB
2279 * - secure : does cheap and expensive checks, using the master as needed
2280 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2281 * whose corresponding errors may be ignored.
2283 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2286 * @deprecated since 1.33,
2287 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2290 public function getUserPermissionsErrors(
2291 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2293 // TODO: this is for b/c, eventually will be removed
2294 if ( $rigor === true ) {
2295 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2296 } elseif ( $rigor === false ) {
2297 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2300 return MediaWikiServices
::getInstance()->getPermissionManager()
2301 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2305 * Get a filtered list of all restriction types supported by this wiki.
2306 * @param bool $exists True to get all restriction types that apply to
2307 * titles that do exist, False for all restriction types that apply to
2308 * titles that do not exist
2311 public static function getFilteredRestrictionTypes( $exists = true ) {
2312 global $wgRestrictionTypes;
2313 $types = $wgRestrictionTypes;
2315 # Remove the create restriction for existing titles
2316 $types = array_diff( $types, [ 'create' ] );
2318 # Only the create and upload restrictions apply to non-existing titles
2319 $types = array_intersect( $types, [ 'create', 'upload' ] );
2325 * Returns restriction types for the current Title
2327 * @return array Applicable restriction types
2329 public function getRestrictionTypes() {
2330 if ( $this->isSpecialPage() ) {
2334 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2336 if ( $this->mNamespace
!= NS_FILE
) {
2337 # Remove the upload restriction for non-file titles
2338 $types = array_diff( $types, [ 'upload' ] );
2341 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2343 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2344 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2350 * Is this title subject to title protection?
2351 * Title protection is the one applied against creation of such title.
2353 * @return array|bool An associative array representing any existent title
2354 * protection, or false if there's none.
2356 public function getTitleProtection() {
2357 $protection = $this->getTitleProtectionInternal();
2358 if ( $protection ) {
2359 if ( $protection['permission'] == 'sysop' ) {
2360 $protection['permission'] = 'editprotected'; // B/C
2362 if ( $protection['permission'] == 'autoconfirmed' ) {
2363 $protection['permission'] = 'editsemiprotected'; // B/C
2370 * Fetch title protection settings
2372 * To work correctly, $this->loadRestrictions() needs to have access to the
2373 * actual protections in the database without munging 'sysop' =>
2374 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2375 * callers probably want $this->getTitleProtection() instead.
2377 * @return array|bool
2379 protected function getTitleProtectionInternal() {
2380 // Can't protect pages in special namespaces
2381 if ( $this->mNamespace
< 0 ) {
2385 // Can't protect pages that exist.
2386 if ( $this->exists() ) {
2390 if ( $this->mTitleProtection
=== null ) {
2391 $dbr = wfGetDB( DB_REPLICA
);
2392 $commentStore = CommentStore
::getStore();
2393 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2394 $res = $dbr->select(
2395 [ 'protected_titles' ] +
$commentQuery['tables'],
2397 'user' => 'pt_user',
2398 'expiry' => 'pt_expiry',
2399 'permission' => 'pt_create_perm'
2400 ] +
$commentQuery['fields'],
2401 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2404 $commentQuery['joins']
2407 // fetchRow returns false if there are no rows.
2408 $row = $dbr->fetchRow( $res );
2410 $this->mTitleProtection
= [
2411 'user' => $row['user'],
2412 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2413 'permission' => $row['permission'],
2414 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2417 $this->mTitleProtection
= false;
2420 return $this->mTitleProtection
;
2424 * Remove any title protection due to page existing
2426 public function deleteTitleProtection() {
2427 $dbw = wfGetDB( DB_MASTER
);
2431 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2434 $this->mTitleProtection
= false;
2438 * Is this page "semi-protected" - the *only* protection levels are listed
2439 * in $wgSemiprotectedRestrictionLevels?
2441 * @param string $action Action to check (default: edit)
2444 public function isSemiProtected( $action = 'edit' ) {
2445 global $wgSemiprotectedRestrictionLevels;
2447 $restrictions = $this->getRestrictions( $action );
2448 $semi = $wgSemiprotectedRestrictionLevels;
2449 if ( !$restrictions ||
!$semi ) {
2450 // Not protected, or all protection is full protection
2454 // Remap autoconfirmed to editsemiprotected for BC
2455 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2456 $semi[$key] = 'editsemiprotected';
2458 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2459 $restrictions[$key] = 'editsemiprotected';
2462 return !array_diff( $restrictions, $semi );
2466 * Does the title correspond to a protected article?
2468 * @param string $action The action the page is protected from,
2469 * by default checks all actions.
2472 public function isProtected( $action = '' ) {
2473 global $wgRestrictionLevels;
2475 $restrictionTypes = $this->getRestrictionTypes();
2477 # Special pages have inherent protection
2478 if ( $this->isSpecialPage() ) {
2482 # Check regular protection levels
2483 foreach ( $restrictionTypes as $type ) {
2484 if ( $action == $type ||
$action == '' ) {
2485 $r = $this->getRestrictions( $type );
2486 foreach ( $wgRestrictionLevels as $level ) {
2487 if ( in_array( $level, $r ) && $level != '' ) {
2498 * Determines if $user is unable to edit this page because it has been protected
2499 * by $wgNamespaceProtection.
2501 * @param User $user User object to check permissions
2504 public function isNamespaceProtected( User
$user ) {
2505 global $wgNamespaceProtection;
2507 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2508 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2509 if ( $right != '' && !$user->isAllowed( $right ) ) {
2518 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2520 * @return bool If the page is subject to cascading restrictions.
2522 public function isCascadeProtected() {
2523 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2524 return ( $sources > 0 );
2528 * Determines whether cascading protection sources have already been loaded from
2531 * @param bool $getPages True to check if the pages are loaded, or false to check
2532 * if the status is loaded.
2533 * @return bool Whether or not the specified information has been loaded
2536 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2537 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2541 * Cascading protection: Get the source of any cascading restrictions on this page.
2543 * @param bool $getPages Whether or not to retrieve the actual pages
2544 * that the restrictions have come from and the actual restrictions
2546 * @return array Two elements: First is an array of Title objects of the
2547 * pages from which cascading restrictions have come, false for
2548 * none, or true if such restrictions exist but $getPages was not
2549 * set. Second is an array like that returned by
2550 * Title::getAllRestrictions(), or an empty array if $getPages is
2553 public function getCascadeProtectionSources( $getPages = true ) {
2554 $pagerestrictions = [];
2556 if ( $this->mCascadeSources
!== null && $getPages ) {
2557 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2558 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2559 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2562 $dbr = wfGetDB( DB_REPLICA
);
2564 if ( $this->mNamespace
== NS_FILE
) {
2565 $tables = [ 'imagelinks', 'page_restrictions' ];
2567 'il_to' => $this->mDbkeyform
,
2572 $tables = [ 'templatelinks', 'page_restrictions' ];
2574 'tl_namespace' => $this->mNamespace
,
2575 'tl_title' => $this->mDbkeyform
,
2582 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2583 'pr_expiry', 'pr_type', 'pr_level' ];
2584 $where_clauses[] = 'page_id=pr_page';
2587 $cols = [ 'pr_expiry' ];
2590 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2592 $sources = $getPages ?
[] : false;
2593 $now = wfTimestampNow();
2595 foreach ( $res as $row ) {
2596 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2597 if ( $expiry > $now ) {
2599 $page_id = $row->pr_page
;
2600 $page_ns = $row->page_namespace
;
2601 $page_title = $row->page_title
;
2602 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2603 # Add groups needed for each restriction type if its not already there
2604 # Make sure this restriction type still exists
2606 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2607 $pagerestrictions[$row->pr_type
] = [];
2611 isset( $pagerestrictions[$row->pr_type
] )
2612 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2614 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2623 $this->mCascadeSources
= $sources;
2624 $this->mCascadingRestrictions
= $pagerestrictions;
2626 $this->mHasCascadingRestrictions
= $sources;
2629 return [ $sources, $pagerestrictions ];
2633 * Accessor for mRestrictionsLoaded
2635 * @return bool Whether or not the page's restrictions have already been
2636 * loaded from the database
2639 public function areRestrictionsLoaded() {
2640 return $this->mRestrictionsLoaded
;
2644 * Accessor/initialisation for mRestrictions
2646 * @param string $action Action that permission needs to be checked for
2647 * @return array Restriction levels needed to take the action. All levels are
2648 * required. Note that restriction levels are normally user rights, but 'sysop'
2649 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2650 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2652 public function getRestrictions( $action ) {
2653 if ( !$this->mRestrictionsLoaded
) {
2654 $this->loadRestrictions();
2656 return $this->mRestrictions
[$action] ??
[];
2660 * Accessor/initialisation for mRestrictions
2662 * @return array Keys are actions, values are arrays as returned by
2663 * Title::getRestrictions()
2666 public function getAllRestrictions() {
2667 if ( !$this->mRestrictionsLoaded
) {
2668 $this->loadRestrictions();
2670 return $this->mRestrictions
;
2674 * Get the expiry time for the restriction against a given action
2676 * @param string $action
2677 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2678 * or not protected at all, or false if the action is not recognised.
2680 public function getRestrictionExpiry( $action ) {
2681 if ( !$this->mRestrictionsLoaded
) {
2682 $this->loadRestrictions();
2684 return $this->mRestrictionsExpiry
[$action] ??
false;
2688 * Returns cascading restrictions for the current article
2692 function areRestrictionsCascading() {
2693 if ( !$this->mRestrictionsLoaded
) {
2694 $this->loadRestrictions();
2697 return $this->mCascadeRestriction
;
2701 * Compiles list of active page restrictions from both page table (pre 1.10)
2702 * and page_restrictions table for this existing page.
2703 * Public for usage by LiquidThreads.
2705 * @param array $rows Array of db result objects
2706 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2707 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2708 * Edit and move sections are separated by a colon
2709 * Example: "edit=autoconfirmed,sysop:move=sysop"
2711 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2712 // This function will only read rows from a table that we migrated away
2713 // from before adding READ_LATEST support to loadRestrictions, so we
2714 // don't need to support reading from DB_MASTER here.
2715 $dbr = wfGetDB( DB_REPLICA
);
2717 $restrictionTypes = $this->getRestrictionTypes();
2719 foreach ( $restrictionTypes as $type ) {
2720 $this->mRestrictions
[$type] = [];
2721 $this->mRestrictionsExpiry
[$type] = 'infinity';
2724 $this->mCascadeRestriction
= false;
2726 # Backwards-compatibility: also load the restrictions from the page record (old format).
2727 if ( $oldFashionedRestrictions !== null ) {
2728 $this->mOldRestrictions
= $oldFashionedRestrictions;
2731 if ( $this->mOldRestrictions
=== false ) {
2732 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2733 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2734 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2737 if ( $this->mOldRestrictions
!= '' ) {
2738 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2739 $temp = explode( '=', trim( $restrict ) );
2740 if ( count( $temp ) == 1 ) {
2741 // old old format should be treated as edit/move restriction
2742 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2743 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2745 $restriction = trim( $temp[1] );
2746 if ( $restriction != '' ) { // some old entries are empty
2747 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2753 if ( count( $rows ) ) {
2754 # Current system - load second to make them override.
2755 $now = wfTimestampNow();
2757 # Cycle through all the restrictions.
2758 foreach ( $rows as $row ) {
2759 // Don't take care of restrictions types that aren't allowed
2760 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2764 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2766 // Only apply the restrictions if they haven't expired!
2767 if ( !$expiry ||
$expiry > $now ) {
2768 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2769 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2771 $this->mCascadeRestriction |
= $row->pr_cascade
;
2776 $this->mRestrictionsLoaded
= true;
2780 * Load restrictions from the page_restrictions table
2782 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2783 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2784 * Edit and move sections are separated by a colon
2785 * Example: "edit=autoconfirmed,sysop:move=sysop"
2786 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2787 * from the master DB.
2789 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2790 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2791 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2795 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2796 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2797 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2798 $id = $this->getArticleID();
2800 $fname = __METHOD__
;
2801 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2802 return iterator_to_array(
2804 'page_restrictions',
2805 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2806 [ 'pr_page' => $id ],
2812 if ( $readLatest ) {
2813 $dbr = wfGetDB( DB_MASTER
);
2814 $rows = $loadRestrictionsFromDb( $dbr );
2816 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2817 $rows = $cache->getWithSetCallback(
2818 // Page protections always leave a new null revision
2819 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2821 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2822 $dbr = wfGetDB( DB_REPLICA
);
2824 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2825 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2826 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2827 // @TODO: cleanup Title cache and caller assumption mess in general
2828 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2831 return $loadRestrictionsFromDb( $dbr );
2836 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2838 $title_protection = $this->getTitleProtectionInternal();
2840 if ( $title_protection ) {
2841 $now = wfTimestampNow();
2842 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2844 if ( !$expiry ||
$expiry > $now ) {
2845 // Apply the restrictions
2846 $this->mRestrictionsExpiry
['create'] = $expiry;
2847 $this->mRestrictions
['create'] =
2848 explode( ',', trim( $title_protection['permission'] ) );
2849 } else { // Get rid of the old restrictions
2850 $this->mTitleProtection
= false;
2853 $this->mRestrictionsExpiry
['create'] = 'infinity';
2855 $this->mRestrictionsLoaded
= true;
2860 * Flush the protection cache in this object and force reload from the database.
2861 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2863 public function flushRestrictions() {
2864 $this->mRestrictionsLoaded
= false;
2865 $this->mTitleProtection
= null;
2869 * Purge expired restrictions from the page_restrictions table
2871 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2873 static function purgeExpiredRestrictions() {
2874 if ( wfReadOnly() ) {
2878 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2879 wfGetDB( DB_MASTER
),
2881 function ( IDatabase
$dbw, $fname ) {
2882 $config = MediaWikiServices
::getInstance()->getMainConfig();
2883 $ids = $dbw->selectFieldValues(
2884 'page_restrictions',
2886 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2888 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2891 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2896 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2897 wfGetDB( DB_MASTER
),
2899 function ( IDatabase
$dbw, $fname ) {
2902 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2910 * Does this have subpages? (Warning, usually requires an extra DB query.)
2914 public function hasSubpages() {
2916 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2917 hasSubpages( $this->mNamespace
)
2923 # We dynamically add a member variable for the purpose of this method
2924 # alone to cache the result. There's no point in having it hanging
2925 # around uninitialized in every Title object; therefore we only add it
2926 # if needed and don't declare it statically.
2927 if ( $this->mHasSubpages
=== null ) {
2928 $this->mHasSubpages
= false;
2929 $subpages = $this->getSubpages( 1 );
2930 if ( $subpages instanceof TitleArray
) {
2931 $this->mHasSubpages
= (bool)$subpages->current();
2935 return $this->mHasSubpages
;
2939 * Get all subpages of this page.
2941 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2942 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2943 * doesn't allow subpages
2945 public function getSubpages( $limit = -1 ) {
2947 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2948 hasSubpages( $this->mNamespace
)
2953 $dbr = wfGetDB( DB_REPLICA
);
2954 $conds['page_namespace'] = $this->mNamespace
;
2955 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2957 if ( $limit > -1 ) {
2958 $options['LIMIT'] = $limit;
2960 return TitleArray
::newFromResult(
2961 $dbr->select( 'page',
2962 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2971 * Is there a version of this page in the deletion archive?
2973 * @return int The number of archived revisions
2975 public function isDeleted() {
2976 if ( $this->mNamespace
< 0 ) {
2979 $dbr = wfGetDB( DB_REPLICA
);
2981 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2982 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2985 if ( $this->mNamespace
== NS_FILE
) {
2986 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2987 [ 'fa_name' => $this->mDbkeyform
],
2996 * Is there a version of this page in the deletion archive?
3000 public function isDeletedQuick() {
3001 if ( $this->mNamespace
< 0 ) {
3004 $dbr = wfGetDB( DB_REPLICA
);
3005 $deleted = (bool)$dbr->selectField( 'archive', '1',
3006 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3009 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3010 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3011 [ 'fa_name' => $this->mDbkeyform
],
3019 * Get the article ID for this Title from the link cache,
3020 * adding it if necessary
3022 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3024 * @return int The ID
3026 public function getArticleID( $flags = 0 ) {
3027 if ( $this->mNamespace
< 0 ) {
3028 $this->mArticleID
= 0;
3029 return $this->mArticleID
;
3031 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3032 if ( $flags & self
::GAID_FOR_UPDATE
) {
3033 $oldUpdate = $linkCache->forUpdate( true );
3034 $linkCache->clearLink( $this );
3035 $this->mArticleID
= $linkCache->addLinkObj( $this );
3036 $linkCache->forUpdate( $oldUpdate );
3037 } elseif ( $this->mArticleID
== -1 ) {
3038 $this->mArticleID
= $linkCache->addLinkObj( $this );
3040 return $this->mArticleID
;
3044 * Is this an article that is a redirect page?
3045 * Uses link cache, adding it if necessary
3047 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3050 public function isRedirect( $flags = 0 ) {
3051 if ( !is_null( $this->mRedirect
) ) {
3052 return $this->mRedirect
;
3054 if ( !$this->getArticleID( $flags ) ) {
3055 $this->mRedirect
= false;
3056 return $this->mRedirect
;
3059 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3060 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3061 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3062 if ( $cached === null ) {
3063 # Trust LinkCache's state over our own
3064 # LinkCache is telling us that the page doesn't exist, despite there being cached
3065 # data relating to an existing page in $this->mArticleID. Updaters should clear
3066 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3067 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3068 # LinkCache to refresh its data from the master.
3069 $this->mRedirect
= false;
3070 return $this->mRedirect
;
3073 $this->mRedirect
= (bool)$cached;
3075 return $this->mRedirect
;
3079 * What is the length of this page?
3080 * Uses link cache, adding it if necessary
3082 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3085 public function getLength( $flags = 0 ) {
3086 if ( $this->mLength
!= -1 ) {
3087 return $this->mLength
;
3089 if ( !$this->getArticleID( $flags ) ) {
3091 return $this->mLength
;
3093 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3094 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3095 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3096 if ( $cached === null ) {
3097 # Trust LinkCache's state over our own, as for isRedirect()
3099 return $this->mLength
;
3102 $this->mLength
= intval( $cached );
3104 return $this->mLength
;
3108 * What is the page_latest field for this page?
3110 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3111 * @return int Int or 0 if the page doesn't exist
3113 public function getLatestRevID( $flags = 0 ) {
3114 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3115 return intval( $this->mLatestID
);
3117 if ( !$this->getArticleID( $flags ) ) {
3118 $this->mLatestID
= 0;
3119 return $this->mLatestID
;
3121 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3122 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3123 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3124 if ( $cached === null ) {
3125 # Trust LinkCache's state over our own, as for isRedirect()
3126 $this->mLatestID
= 0;
3127 return $this->mLatestID
;
3130 $this->mLatestID
= intval( $cached );
3132 return $this->mLatestID
;
3136 * This clears some fields in this object, and clears any associated
3137 * keys in the "bad links" section of the link cache.
3139 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3140 * loading of the new page_id. It's also called from
3141 * WikiPage::doDeleteArticleReal()
3143 * @param int $newid The new Article ID
3145 public function resetArticleID( $newid ) {
3146 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3147 $linkCache->clearLink( $this );
3149 if ( $newid === false ) {
3150 $this->mArticleID
= -1;
3152 $this->mArticleID
= intval( $newid );
3154 $this->mRestrictionsLoaded
= false;
3155 $this->mRestrictions
= [];
3156 $this->mOldRestrictions
= false;
3157 $this->mRedirect
= null;
3158 $this->mLength
= -1;
3159 $this->mLatestID
= false;
3160 $this->mContentModel
= false;
3161 $this->mEstimateRevisions
= null;
3162 $this->mPageLanguage
= false;
3163 $this->mDbPageLanguage
= false;
3164 $this->mIsBigDeletion
= null;
3167 public static function clearCaches() {
3168 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3169 $linkCache->clear();
3171 $titleCache = self
::getTitleCache();
3172 $titleCache->clear();
3176 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3178 * @param string $text Containing title to capitalize
3179 * @param int $ns Namespace index, defaults to NS_MAIN
3180 * @return string Containing capitalized title
3182 public static function capitalize( $text, $ns = NS_MAIN
) {
3183 $services = MediaWikiServices
::getInstance();
3184 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3185 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3192 * Secure and split - main initialisation function for this object
3194 * Assumes that mDbkeyform has been set, and is urldecoded
3195 * and uses underscores, but not otherwise munged. This function
3196 * removes illegal characters, splits off the interwiki and
3197 * namespace prefixes, sets the other forms, and canonicalizes
3200 * @throws MalformedTitleException On invalid titles
3201 * @return bool True on success
3203 private function secureAndSplit() {
3204 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3205 // the parsing code with Title, while avoiding massive refactoring.
3206 // @todo: get rid of secureAndSplit, refactor parsing code.
3207 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3208 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3209 /** @var MediaWikiTitleCodec $titleCodec */
3210 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3211 // MalformedTitleException can be thrown here
3212 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3215 $this->setFragment( '#' . $parts['fragment'] );
3216 $this->mInterwiki
= $parts['interwiki'];
3217 $this->mLocalInterwiki
= $parts['local_interwiki'];
3218 $this->mNamespace
= $parts['namespace'];
3219 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3221 $this->mDbkeyform
= $parts['dbkey'];
3222 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3223 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3225 # We already know that some pages won't be in the database!
3226 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3227 $this->mArticleID
= 0;
3234 * Get an array of Title objects linking to this Title
3235 * Also stores the IDs in the link cache.
3237 * WARNING: do not use this function on arbitrary user-supplied titles!
3238 * On heavily-used templates it will max out the memory.
3240 * @param array $options May be FOR UPDATE
3241 * @param string $table Table name
3242 * @param string $prefix Fields prefix
3243 * @return Title[] Array of Title objects linking here
3245 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3246 if ( count( $options ) > 0 ) {
3247 $db = wfGetDB( DB_MASTER
);
3249 $db = wfGetDB( DB_REPLICA
);
3254 self
::getSelectFields(),
3256 "{$prefix}_from=page_id",
3257 "{$prefix}_namespace" => $this->mNamespace
,
3258 "{$prefix}_title" => $this->mDbkeyform
],
3264 if ( $res->numRows() ) {
3265 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3266 foreach ( $res as $row ) {
3267 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3269 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3270 $retVal[] = $titleObj;
3278 * Get an array of Title objects using this Title as a template
3279 * Also stores the IDs in the link cache.
3281 * WARNING: do not use this function on arbitrary user-supplied titles!
3282 * On heavily-used templates it will max out the memory.
3284 * @param array $options Query option to Database::select()
3285 * @return Title[] Array of Title the Title objects linking here
3287 public function getTemplateLinksTo( $options = [] ) {
3288 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3292 * Get an array of Title objects linked from this Title
3293 * Also stores the IDs in the link cache.
3295 * WARNING: do not use this function on arbitrary user-supplied titles!
3296 * On heavily-used templates it will max out the memory.
3298 * @param array $options Query option to Database::select()
3299 * @param string $table Table name
3300 * @param string $prefix Fields prefix
3301 * @return array Array of Title objects linking here
3303 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3304 $id = $this->getArticleID();
3306 # If the page doesn't exist; there can't be any link from this page
3311 $db = wfGetDB( DB_REPLICA
);
3313 $blNamespace = "{$prefix}_namespace";
3314 $blTitle = "{$prefix}_title";
3316 $pageQuery = WikiPage
::getQueryInfo();
3318 [ $table, 'nestpage' => $pageQuery['tables'] ],
3320 [ $blNamespace, $blTitle ],
3321 $pageQuery['fields']
3323 [ "{$prefix}_from" => $id ],
3328 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3329 ] ] +
$pageQuery['joins']
3333 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3334 foreach ( $res as $row ) {
3335 if ( $row->page_id
) {
3336 $titleObj = self
::newFromRow( $row );
3338 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3339 $linkCache->addBadLinkObj( $titleObj );
3341 $retVal[] = $titleObj;
3348 * Get an array of Title objects used on this Title as a template
3349 * Also stores the IDs in the link cache.
3351 * WARNING: do not use this function on arbitrary user-supplied titles!
3352 * On heavily-used templates it will max out the memory.
3354 * @param array $options May be FOR UPDATE
3355 * @return Title[] Array of Title the Title objects used here
3357 public function getTemplateLinksFrom( $options = [] ) {
3358 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3362 * Get an array of Title objects referring to non-existent articles linked
3365 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3366 * should use redirect table in this case).
3367 * @return Title[] Array of Title the Title objects
3369 public function getBrokenLinksFrom() {
3370 if ( $this->getArticleID() == 0 ) {
3371 # All links from article ID 0 are false positives
3375 $dbr = wfGetDB( DB_REPLICA
);
3376 $res = $dbr->select(
3377 [ 'page', 'pagelinks' ],
3378 [ 'pl_namespace', 'pl_title' ],
3380 'pl_from' => $this->getArticleID(),
3381 'page_namespace IS NULL'
3387 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3393 foreach ( $res as $row ) {
3394 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3400 * Get a list of URLs to purge from the CDN cache when this
3403 * @return string[] Array of String the URLs
3405 public function getCdnUrls() {
3407 $this->getInternalURL(),
3408 $this->getInternalURL( 'action=history' )
3411 $pageLang = $this->getPageLanguage();
3412 if ( $pageLang->hasVariants() ) {
3413 $variants = $pageLang->getVariants();
3414 foreach ( $variants as $vCode ) {
3415 $urls[] = $this->getInternalURL( $vCode );
3419 // If we are looking at a css/js user subpage, purge the action=raw.
3420 if ( $this->isUserJsConfigPage() ) {
3421 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3422 } elseif ( $this->isUserJsonConfigPage() ) {
3423 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3424 } elseif ( $this->isUserCssConfigPage() ) {
3425 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3428 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3433 * Purge all applicable CDN URLs
3435 public function purgeSquid() {
3436 DeferredUpdates
::addUpdate(
3437 new CdnCacheUpdate( $this->getCdnUrls() ),
3438 DeferredUpdates
::PRESEND
3443 * Check whether a given move operation would be valid.
3444 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3446 * @deprecated since 1.25, use MovePage's methods instead
3447 * @param Title &$nt The new title
3448 * @param bool $auth Whether to check user permissions (uses $wgUser)
3449 * @param string $reason Is the log summary of the move, used for spam checking
3450 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3452 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3453 wfDeprecated( __METHOD__
, '1.25' );
3457 if ( !( $nt instanceof Title
) ) {
3458 // Normally we'd add this to $errors, but we'll get
3459 // lots of syntax errors if $nt is not an object
3460 return [ [ 'badtitletext' ] ];
3463 $mp = new MovePage( $this, $nt );
3464 $errors = $mp->isValidMove()->getErrorsArray();
3466 $errors = wfMergeErrorArrays(
3468 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3472 return $errors ?
: true;
3476 * Move a title to a new location
3478 * @deprecated since 1.25, use the MovePage class instead
3479 * @param Title &$nt The new title
3480 * @param bool $auth Indicates whether $wgUser's permissions
3482 * @param string $reason The reason for the move
3483 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3484 * Ignored if the user doesn't have the suppressredirect right.
3485 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3486 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3488 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3489 array $changeTags = []
3491 wfDeprecated( __METHOD__
, '1.25' );
3495 $mp = new MovePage( $this, $nt );
3496 $method = $auth ?
'moveIfAllowed' : 'move';
3497 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3498 if ( $status->isOK() ) {
3501 return $status->getErrorsArray();
3506 * Move this page's subpages to be subpages of $nt
3508 * @deprecated since 1.34, use MovePage instead
3509 * @param Title $nt Move target
3510 * @param bool $auth Whether $wgUser's permissions should be checked
3511 * @param string $reason The reason for the move
3512 * @param bool $createRedirect Whether to create redirects from the old subpages to
3513 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3514 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3515 * @return array Array with old page titles as keys, and strings (new page titles) or
3516 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3517 * getUserPermissionsErrors()-like error array with numeric indices if
3518 * no pages were moved
3520 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3521 array $changeTags = []
3523 wfDeprecated( __METHOD__
, '1.34' );
3527 $mp = new MovePage( $this, $nt );
3528 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3529 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3531 if ( !$result->isOk() ) {
3532 return $result->getErrorsArray();
3536 foreach ( $result->getValue() as $key => $status ) {
3537 if ( $status->isOK() ) {
3538 $retval[$key] = $status->getValue();
3540 $retval[$key] = $status->getErrorsArray();
3547 * Checks if this page is just a one-rev redirect.
3548 * Adds lock, so don't use just for light purposes.
3552 public function isSingleRevRedirect() {
3553 global $wgContentHandlerUseDB;
3555 $dbw = wfGetDB( DB_MASTER
);
3558 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3559 if ( $wgContentHandlerUseDB ) {
3560 $fields[] = 'page_content_model';
3563 $row = $dbw->selectRow( 'page',
3569 # Cache some fields we may want
3570 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3571 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3572 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3573 $this->mContentModel
= $row && isset( $row->page_content_model
)
3574 ?
strval( $row->page_content_model
)
3577 if ( !$this->mRedirect
) {
3580 # Does the article have a history?
3581 $row = $dbw->selectField( [ 'page', 'revision' ],
3583 [ 'page_namespace' => $this->mNamespace
,
3584 'page_title' => $this->mDbkeyform
,
3586 'page_latest != rev_id'
3591 # Return true if there was no history
3592 return ( $row === false );
3596 * Checks if $this can be moved to a given Title
3597 * - Selects for update, so don't call it unless you mean business
3599 * @deprecated since 1.25, use MovePage's methods instead
3600 * @param Title $nt The new title to check
3603 public function isValidMoveTarget( $nt ) {
3604 wfDeprecated( __METHOD__
, '1.25' );
3606 # Is it an existing file?
3607 if ( $nt->getNamespace() == NS_FILE
) {
3608 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3610 $file->load( File
::READ_LATEST
);
3611 if ( $file->exists() ) {
3612 wfDebug( __METHOD__
. ": file exists\n" );
3616 # Is it a redirect with no history?
3617 if ( !$nt->isSingleRevRedirect() ) {
3618 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3621 # Get the article text
3622 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3623 if ( !is_object( $rev ) ) {
3626 $content = $rev->getContent();
3627 # Does the redirect point to the source?
3628 # Or is it a broken self-redirect, usually caused by namespace collisions?
3629 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3631 if ( $redirTitle ) {
3632 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3633 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3634 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3640 # Fail safe (not a redirect after all. strange.)
3641 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3642 " is a redirect, but it doesn't contain a valid redirect.\n" );
3648 * Get categories to which this Title belongs and return an array of
3649 * categories' names.
3651 * @return array Array of parents in the form:
3652 * $parent => $currentarticle
3654 public function getParentCategories() {
3657 $titleKey = $this->getArticleID();
3659 if ( $titleKey === 0 ) {
3663 $dbr = wfGetDB( DB_REPLICA
);
3665 $res = $dbr->select(
3668 [ 'cl_from' => $titleKey ],
3672 if ( $res->numRows() > 0 ) {
3673 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3674 foreach ( $res as $row ) {
3675 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3676 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3677 $this->getFullText();
3684 * Get a tree of parent categories
3686 * @param array $children Array with the children in the keys, to check for circular refs
3687 * @return array Tree of parent categories
3689 public function getParentCategoryTree( $children = [] ) {
3691 $parents = $this->getParentCategories();
3694 foreach ( $parents as $parent => $current ) {
3695 if ( array_key_exists( $parent, $children ) ) {
3696 # Circular reference
3697 $stack[$parent] = [];
3699 $nt = self
::newFromText( $parent );
3701 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3711 * Get an associative array for selecting this title from
3714 * @return array Array suitable for the $where parameter of DB::select()
3716 public function pageCond() {
3717 if ( $this->mArticleID
> 0 ) {
3718 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3719 return [ 'page_id' => $this->mArticleID
];
3721 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3726 * Get next/previous revision ID relative to another revision ID
3727 * @param int $revId Revision ID. Get the revision that was before this one.
3728 * @param int $flags Title::GAID_FOR_UPDATE
3729 * @param string $dir 'next' or 'prev'
3730 * @return int|bool New revision ID, or false if none exists
3732 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3733 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3734 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3735 $rev = $rl->getRevisionById( $revId, $rlFlags );
3739 $oldRev = $dir === 'next'
3740 ?
$rl->getNextRevision( $rev, $rlFlags )
3741 : $rl->getPreviousRevision( $rev, $rlFlags );
3745 return $oldRev->getId();
3749 * Get the revision ID of the previous revision
3751 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3752 * @param int $revId Revision ID. Get the revision that was before this one.
3753 * @param int $flags Title::GAID_FOR_UPDATE
3754 * @return int|bool Old revision ID, or false if none exists
3756 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3757 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3761 * Get the revision ID of the next revision
3763 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3764 * @param int $revId Revision ID. Get the revision that was after this one.
3765 * @param int $flags Title::GAID_FOR_UPDATE
3766 * @return int|bool Next revision ID, or false if none exists
3768 public function getNextRevisionID( $revId, $flags = 0 ) {
3769 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3773 * Get the first revision of the page
3775 * @param int $flags Title::GAID_FOR_UPDATE
3776 * @return Revision|null If page doesn't exist
3778 public function getFirstRevision( $flags = 0 ) {
3779 $pageId = $this->getArticleID( $flags );
3781 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3782 $revQuery = Revision
::getQueryInfo();
3783 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3784 [ 'rev_page' => $pageId ],
3787 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3788 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3793 return new Revision( $row, 0, $this );
3800 * Get the oldest revision timestamp of this page
3802 * @param int $flags Title::GAID_FOR_UPDATE
3803 * @return string|null MW timestamp
3805 public function getEarliestRevTime( $flags = 0 ) {
3806 $rev = $this->getFirstRevision( $flags );
3807 return $rev ?
$rev->getTimestamp() : null;
3811 * Check if this is a new page
3815 public function isNewPage() {
3816 $dbr = wfGetDB( DB_REPLICA
);
3817 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3821 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3825 public function isBigDeletion() {
3826 global $wgDeleteRevisionsLimit;
3828 if ( !$wgDeleteRevisionsLimit ) {
3832 if ( $this->mIsBigDeletion
=== null ) {
3833 $dbr = wfGetDB( DB_REPLICA
);
3835 $revCount = $dbr->selectRowCount(
3838 [ 'rev_page' => $this->getArticleID() ],
3840 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3843 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3846 return $this->mIsBigDeletion
;
3850 * Get the approximate revision count of this page.
3854 public function estimateRevisionCount() {
3855 if ( !$this->exists() ) {
3859 if ( $this->mEstimateRevisions
=== null ) {
3860 $dbr = wfGetDB( DB_REPLICA
);
3861 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3862 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3865 return $this->mEstimateRevisions
;
3869 * Get the number of revisions between the given revision.
3870 * Used for diffs and other things that really need it.
3872 * @param int|Revision $old Old revision or rev ID (first before range)
3873 * @param int|Revision $new New revision or rev ID (first after range)
3874 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3875 * @return int Number of revisions between these revisions.
3877 public function countRevisionsBetween( $old, $new, $max = null ) {
3878 if ( !( $old instanceof Revision
) ) {
3879 $old = Revision
::newFromTitle( $this, (int)$old );
3881 if ( !( $new instanceof Revision
) ) {
3882 $new = Revision
::newFromTitle( $this, (int)$new );
3884 if ( !$old ||
!$new ) {
3885 return 0; // nothing to compare
3887 $dbr = wfGetDB( DB_REPLICA
);
3889 'rev_page' => $this->getArticleID(),
3890 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3891 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3893 if ( $max !== null ) {
3894 return $dbr->selectRowCount( 'revision', '1',
3897 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3900 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3905 * Get the authors between the given revisions or revision IDs.
3906 * Used for diffs and other things that really need it.
3910 * @param int|Revision $old Old revision or rev ID (first before range by default)
3911 * @param int|Revision $new New revision or rev ID (first after range by default)
3912 * @param int $limit Maximum number of authors
3913 * @param string|array $options (Optional): Single option, or an array of options:
3914 * 'include_old' Include $old in the range; $new is excluded.
3915 * 'include_new' Include $new in the range; $old is excluded.
3916 * 'include_both' Include both $old and $new in the range.
3917 * Unknown option values are ignored.
3918 * @return array|null Names of revision authors in the range; null if not both revisions exist
3920 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3921 if ( !( $old instanceof Revision
) ) {
3922 $old = Revision
::newFromTitle( $this, (int)$old );
3924 if ( !( $new instanceof Revision
) ) {
3925 $new = Revision
::newFromTitle( $this, (int)$new );
3927 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3928 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3929 // in the sanity check below?
3930 if ( !$old ||
!$new ) {
3931 return null; // nothing to compare
3936 $options = (array)$options;
3937 if ( in_array( 'include_old', $options ) ) {
3940 if ( in_array( 'include_new', $options ) ) {
3943 if ( in_array( 'include_both', $options ) ) {
3947 // No DB query needed if $old and $new are the same or successive revisions:
3948 if ( $old->getId() === $new->getId() ) {
3949 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3951 [ $old->getUserText( RevisionRecord
::RAW
) ];
3952 } elseif ( $old->getId() === $new->getParentId() ) {
3953 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3954 $authors[] = $oldUserText = $old->getUserText( RevisionRecord
::RAW
);
3955 $newUserText = $new->getUserText( RevisionRecord
::RAW
);
3956 if ( $oldUserText != $newUserText ) {
3957 $authors[] = $newUserText;
3959 } elseif ( $old_cmp === '>=' ) {
3960 $authors[] = $old->getUserText( RevisionRecord
::RAW
);
3961 } elseif ( $new_cmp === '<=' ) {
3962 $authors[] = $new->getUserText( RevisionRecord
::RAW
);
3966 $dbr = wfGetDB( DB_REPLICA
);
3967 $revQuery = Revision
::getQueryInfo();
3968 $authors = $dbr->selectFieldValues(
3969 $revQuery['tables'],
3970 $revQuery['fields']['rev_user_text'],
3972 'rev_page' => $this->getArticleID(),
3973 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3974 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3976 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3983 * Get the number of authors between the given revisions or revision IDs.
3984 * Used for diffs and other things that really need it.
3986 * @param int|Revision $old Old revision or rev ID (first before range by default)
3987 * @param int|Revision $new New revision or rev ID (first after range by default)
3988 * @param int $limit Maximum number of authors
3989 * @param string|array $options (Optional): Single option, or an array of options:
3990 * 'include_old' Include $old in the range; $new is excluded.
3991 * 'include_new' Include $new in the range; $old is excluded.
3992 * 'include_both' Include both $old and $new in the range.
3993 * Unknown option values are ignored.
3994 * @return int Number of revision authors in the range; zero if not both revisions exist
3996 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3997 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3998 return $authors ?
count( $authors ) : 0;
4002 * Compare with another title.
4004 * @param LinkTarget $title
4007 public function equals( LinkTarget
$title ) {
4008 // Note: === is necessary for proper matching of number-like titles.
4009 return $this->mInterwiki
=== $title->getInterwiki()
4010 && $this->mNamespace
== $title->getNamespace()
4011 && $this->mDbkeyform
=== $title->getDBkey();
4015 * Check if this title is a subpage of another title
4017 * @param Title $title
4020 public function isSubpageOf( Title
$title ) {
4021 return $this->mInterwiki
=== $title->mInterwiki
4022 && $this->mNamespace
== $title->mNamespace
4023 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4027 * Check if page exists. For historical reasons, this function simply
4028 * checks for the existence of the title in the page table, and will
4029 * thus return false for interwiki links, special pages and the like.
4030 * If you want to know if a title can be meaningfully viewed, you should
4031 * probably call the isKnown() method instead.
4033 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4034 * from master/for update
4037 public function exists( $flags = 0 ) {
4038 $exists = $this->getArticleID( $flags ) != 0;
4039 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4044 * Should links to this title be shown as potentially viewable (i.e. as
4045 * "bluelinks"), even if there's no record by this title in the page
4048 * This function is semi-deprecated for public use, as well as somewhat
4049 * misleadingly named. You probably just want to call isKnown(), which
4050 * calls this function internally.
4052 * (ISSUE: Most of these checks are cheap, but the file existence check
4053 * can potentially be quite expensive. Including it here fixes a lot of
4054 * existing code, but we might want to add an optional parameter to skip
4055 * it and any other expensive checks.)
4059 public function isAlwaysKnown() {
4063 * Allows overriding default behavior for determining if a page exists.
4064 * If $isKnown is kept as null, regular checks happen. If it's
4065 * a boolean, this value is returned by the isKnown method.
4069 * @param Title $title
4070 * @param bool|null $isKnown
4072 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4074 if ( !is_null( $isKnown ) ) {
4078 if ( $this->isExternal() ) {
4079 return true; // any interwiki link might be viewable, for all we know
4082 $services = MediaWikiServices
::getInstance();
4083 switch ( $this->mNamespace
) {
4086 // file exists, possibly in a foreign repo
4087 return (bool)$services->getRepoGroup()->findFile( $this );
4089 // valid special page
4090 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4092 // selflink, possibly with fragment
4093 return $this->mDbkeyform
== '';
4095 // known system message
4096 return $this->hasSourceText() !== false;
4103 * Does this title refer to a page that can (or might) be meaningfully
4104 * viewed? In particular, this function may be used to determine if
4105 * links to the title should be rendered as "bluelinks" (as opposed to
4106 * "redlinks" to non-existent pages).
4107 * Adding something else to this function will cause inconsistency
4108 * since LinkHolderArray calls isAlwaysKnown() and does its own
4109 * page existence check.
4113 public function isKnown() {
4114 return $this->isAlwaysKnown() ||
$this->exists();
4118 * Does this page have source text?
4122 public function hasSourceText() {
4123 if ( $this->exists() ) {
4127 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4128 // If the page doesn't exist but is a known system message, default
4129 // message content will be displayed, same for language subpages-
4130 // Use always content language to avoid loading hundreds of languages
4131 // to get the link color.
4132 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4133 list( $name, ) = MessageCache
::singleton()->figureMessage(
4134 $contLang->lcfirst( $this->getText() )
4136 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4137 return $message->exists();
4144 * Get the default (plain) message contents for an page that overrides an
4145 * interface message key.
4147 * Primary use cases:
4150 * - Show default when viewing the page. The Article::getSubstituteContent
4151 * method displays the default message content, instead of the
4152 * 'noarticletext' placeholder message normally used.
4155 * - Title of edit page. When creating an interface message override,
4156 * the editor is told they are "Editing the page", instead of
4157 * "Creating the page". (EditPage::setHeaders)
4158 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4159 * or editing a an interface message override. (EditPage::showIntro)
4160 * - Opening the editor. The contents of the localisation message are used
4161 * as contents of the editor when creating a new page in the MediaWiki
4162 * namespace. This simplifies the process for editors when "changing"
4163 * an interface message by creating an override. (EditPage::getContentObject)
4164 * - Showing a diff. The left-hand side of a diff when an editor is
4165 * previewing their changes before saving the creation of a page in the
4166 * MediaWiki namespace. (EditPage::showDiff)
4167 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4168 * page with the proposed content matching the interface message default,
4169 * the save is rejected, the same way we disallow blank pages from being
4170 * created. (EditPage::internalAttemptSave)
4173 * - Default content, when using the 'prepend' or 'append' feature.
4176 * - Label the create action as "Edit", if the page can be an override.
4178 * @return string|bool
4180 public function getDefaultMessageText() {
4181 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4185 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4186 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4188 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4190 if ( $message->exists() ) {
4191 return $message->plain();
4198 * Updates page_touched for this page; called from LinksUpdate.php
4200 * @param string|null $purgeTime [optional] TS_MW timestamp
4201 * @return bool True if the update succeeded
4203 public function invalidateCache( $purgeTime = null ) {
4204 if ( wfReadOnly() ) {
4206 } elseif ( $this->mArticleID
=== 0 ) {
4207 return true; // avoid gap locking if we know it's not there
4210 $dbw = wfGetDB( DB_MASTER
);
4211 $dbw->onTransactionPreCommitOrIdle(
4212 function () use ( $dbw ) {
4213 ResourceLoaderWikiModule
::invalidateModuleCache(
4214 $this, null, null, $dbw->getDomainID() );
4219 $conds = $this->pageCond();
4220 DeferredUpdates
::addUpdate(
4221 new AutoCommitUpdate(
4224 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4225 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4228 [ 'page_touched' => $dbTimestamp ],
4229 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4232 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4235 DeferredUpdates
::PRESEND
4242 * Update page_touched timestamps and send CDN purge messages for
4243 * pages linking to this title. May be sent to the job queue depending
4244 * on the number of links. Typically called on create and delete.
4246 public function touchLinks() {
4247 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4248 if ( $this->mNamespace
== NS_CATEGORY
) {
4249 DeferredUpdates
::addUpdate(
4250 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4256 * Get the last touched timestamp
4258 * @param IDatabase|null $db
4259 * @return string|false Last-touched timestamp
4261 public function getTouched( $db = null ) {
4262 if ( $db === null ) {
4263 $db = wfGetDB( DB_REPLICA
);
4265 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4270 * Get the timestamp when this page was updated since the user last saw it.
4272 * @param User|null $user
4273 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4275 public function getNotificationTimestamp( $user = null ) {
4278 // Assume current user if none given
4282 // Check cache first
4283 $uid = $user->getId();
4287 // avoid isset here, as it'll return false for null entries
4288 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4289 return $this->mNotificationTimestamp
[$uid];
4291 // Don't cache too much!
4292 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4293 $this->mNotificationTimestamp
= [];
4296 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4297 $watchedItem = $store->getWatchedItem( $user, $this );
4298 if ( $watchedItem ) {
4299 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4301 $this->mNotificationTimestamp
[$uid] = false;
4304 return $this->mNotificationTimestamp
[$uid];
4308 * Generate strings used for xml 'id' names in monobook tabs
4310 * @param string $prepend Defaults to 'nstab-'
4311 * @return string XML 'id' name
4313 public function getNamespaceKey( $prepend = 'nstab-' ) {
4314 // Gets the subject namespace of this title
4315 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4316 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4317 // Prefer canonical namespace name for HTML IDs
4318 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4319 if ( $namespaceKey === false ) {
4320 // Fallback to localised text
4321 $namespaceKey = $this->getSubjectNsText();
4323 // Makes namespace key lowercase
4324 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4326 if ( $namespaceKey == '' ) {
4327 $namespaceKey = 'main';
4329 // Changes file to image for backwards compatibility
4330 if ( $namespaceKey == 'file' ) {
4331 $namespaceKey = 'image';
4333 return $prepend . $namespaceKey;
4337 * Get all extant redirects to this Title
4339 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4340 * @return Title[] Array of Title redirects to this title
4342 public function getRedirectsHere( $ns = null ) {
4345 $dbr = wfGetDB( DB_REPLICA
);
4347 'rd_namespace' => $this->mNamespace
,
4348 'rd_title' => $this->mDbkeyform
,
4351 if ( $this->isExternal() ) {
4352 $where['rd_interwiki'] = $this->mInterwiki
;
4354 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4356 if ( !is_null( $ns ) ) {
4357 $where['page_namespace'] = $ns;
4360 $res = $dbr->select(
4361 [ 'redirect', 'page' ],
4362 [ 'page_namespace', 'page_title' ],
4367 foreach ( $res as $row ) {
4368 $redirs[] = self
::newFromRow( $row );
4374 * Check if this Title is a valid redirect target
4378 public function isValidRedirectTarget() {
4379 global $wgInvalidRedirectTargets;
4381 if ( $this->isSpecialPage() ) {
4382 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4383 if ( $this->isSpecial( 'Userlogout' ) ) {
4387 foreach ( $wgInvalidRedirectTargets as $target ) {
4388 if ( $this->isSpecial( $target ) ) {
4398 * Get a backlink cache object
4400 * @return BacklinkCache
4402 public function getBacklinkCache() {
4403 return BacklinkCache
::get( $this );
4407 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4411 public function canUseNoindex() {
4412 global $wgExemptFromUserRobotsControl;
4414 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4415 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4417 return !in_array( $this->mNamespace
, $bannedNamespaces );
4421 * Returns the raw sort key to be used for categories, with the specified
4422 * prefix. This will be fed to Collation::getSortKey() to get a
4423 * binary sortkey that can be used for actual sorting.
4425 * @param string $prefix The prefix to be used, specified using
4426 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4430 public function getCategorySortkey( $prefix = '' ) {
4431 $unprefixed = $this->getText();
4433 // Anything that uses this hook should only depend
4434 // on the Title object passed in, and should probably
4435 // tell the users to run updateCollations.php --force
4436 // in order to re-sort existing category relations.
4437 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4438 if ( $prefix !== '' ) {
4439 # Separate with a line feed, so the unprefixed part is only used as
4440 # a tiebreaker when two pages have the exact same prefix.
4441 # In UCA, tab is the only character that can sort above LF
4442 # so we strip both of them from the original prefix.
4443 $prefix = strtr( $prefix, "\n\t", ' ' );
4444 return "$prefix\n$unprefixed";
4450 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4451 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4452 * the db, it will return NULL.
4454 * @return string|null|bool
4456 private function getDbPageLanguageCode() {
4457 global $wgPageLanguageUseDB;
4459 // check, if the page language could be saved in the database, and if so and
4460 // the value is not requested already, lookup the page language using LinkCache
4461 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4462 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4463 $linkCache->addLinkObj( $this );
4464 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4467 return $this->mDbPageLanguage
;
4471 * Get the language in which the content of this page is written in
4472 * wikitext. Defaults to content language, but in certain cases it can be
4473 * e.g. $wgLang (such as special pages, which are in the user language).
4478 public function getPageLanguage() {
4479 global $wgLang, $wgLanguageCode;
4480 if ( $this->isSpecialPage() ) {
4481 // special pages are in the user language
4485 // Checking if DB language is set
4486 $dbPageLanguage = $this->getDbPageLanguageCode();
4487 if ( $dbPageLanguage ) {
4488 return wfGetLangObj( $dbPageLanguage );
4491 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4492 // Note that this may depend on user settings, so the cache should
4493 // be only per-request.
4494 // NOTE: ContentHandler::getPageLanguage() may need to load the
4495 // content to determine the page language!
4496 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4498 $contentHandler = ContentHandler
::getForTitle( $this );
4499 $langObj = $contentHandler->getPageLanguage( $this );
4500 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4502 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4509 * Get the language in which the content of this page is written when
4510 * viewed by user. Defaults to content language, but in certain cases it can be
4511 * e.g. $wgLang (such as special pages, which are in the user language).
4516 public function getPageViewLanguage() {
4519 if ( $this->isSpecialPage() ) {
4520 // If the user chooses a variant, the content is actually
4521 // in a language whose code is the variant code.
4522 $variant = $wgLang->getPreferredVariant();
4523 if ( $wgLang->getCode() !== $variant ) {
4524 return Language
::factory( $variant );
4530 // Checking if DB language is set
4531 $dbPageLanguage = $this->getDbPageLanguageCode();
4532 if ( $dbPageLanguage ) {
4533 $pageLang = wfGetLangObj( $dbPageLanguage );
4534 $variant = $pageLang->getPreferredVariant();
4535 if ( $pageLang->getCode() !== $variant ) {
4536 $pageLang = Language
::factory( $variant );
4542 // @note Can't be cached persistently, depends on user settings.
4543 // @note ContentHandler::getPageViewLanguage() may need to load the
4544 // content to determine the page language!
4545 $contentHandler = ContentHandler
::getForTitle( $this );
4546 $pageLang = $contentHandler->getPageViewLanguage( $this );
4551 * Get a list of rendered edit notices for this page.
4553 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4554 * they will already be wrapped in paragraphs.
4557 * @param int $oldid Revision ID that's being edited
4560 public function getEditNotices( $oldid = 0 ) {
4563 // Optional notice for the entire namespace
4564 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4565 $msg = wfMessage( $editnotice_ns );
4566 if ( $msg->exists() ) {
4567 $html = $msg->parseAsBlock();
4568 // Edit notices may have complex logic, but output nothing (T91715)
4569 if ( trim( $html ) !== '' ) {
4570 $notices[$editnotice_ns] = Html
::rawElement(
4574 'mw-editnotice-namespace',
4575 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4583 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4584 hasSubpages( $this->mNamespace
)
4586 // Optional notice for page itself and any parent page
4587 $editnotice_base = $editnotice_ns;
4588 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4589 $editnotice_base .= '-' . $part;
4590 $msg = wfMessage( $editnotice_base );
4591 if ( $msg->exists() ) {
4592 $html = $msg->parseAsBlock();
4593 if ( trim( $html ) !== '' ) {
4594 $notices[$editnotice_base] = Html
::rawElement(
4598 'mw-editnotice-base',
4599 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4607 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4608 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4609 $msg = wfMessage( $editnoticeText );
4610 if ( $msg->exists() ) {
4611 $html = $msg->parseAsBlock();
4612 if ( trim( $html ) !== '' ) {
4613 $notices[$editnoticeText] = Html
::rawElement(
4617 'mw-editnotice-page',
4618 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4626 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4633 public function __sleep() {
4641 'mDefaultNamespace',
4645 public function __wakeup() {
4646 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4647 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4648 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );