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 Wikimedia\Rdbms\IDatabase
;
26 use MediaWiki\Linker\LinkTarget
;
27 use MediaWiki\Interwiki\InterwikiLookup
;
28 use MediaWiki\MediaWikiServices
;
31 * Represents a title within MediaWiki.
32 * Optionally may contain an interwiki designation or namespace.
33 * @note This class can fetch various kinds of data from the database;
34 * however, it does so inefficiently.
35 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
36 * and does not rely on global state or the database.
38 class Title
implements LinkTarget
{
39 /** @var HashBagOStuff */
40 static private $titleCache = null;
43 * Title::newFromText maintains a cache to avoid expensive re-normalization of
44 * commonly used titles. On a batch operation this can become a memory leak
45 * if not bounded. After hitting this many titles reset the cache.
47 const CACHE_MAX
= 1000;
50 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
51 * to use the master DB
53 const GAID_FOR_UPDATE
= 1;
56 * @name Private member variables
57 * Please use the accessor functions instead.
62 /** @var string Text form (spaces not underscores) of the main part */
63 public $mTextform = '';
65 /** @var string URL-encoded form of the main part */
66 public $mUrlform = '';
68 /** @var string Main part with underscores */
69 public $mDbkeyform = '';
71 /** @var string Database key with the initial letter in the case specified by the user */
72 protected $mUserCaseDBKey;
74 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
75 public $mNamespace = NS_MAIN
;
77 /** @var string Interwiki prefix */
78 public $mInterwiki = '';
80 /** @var bool Was this Title created from a string with a local interwiki prefix? */
81 private $mLocalInterwiki = false;
83 /** @var string Title fragment (i.e. the bit after the #) */
84 public $mFragment = '';
86 /** @var int Article ID, fetched from the link cache on demand */
87 public $mArticleID = -1;
89 /** @var bool|int ID of most recent revision */
90 protected $mLatestID = false;
93 * @var bool|string ID of the page's content model, i.e. one of the
94 * CONTENT_MODEL_XXX constants
96 private $mContentModel = false;
99 * @var bool If a content model was forced via setContentModel()
100 * this will be true to avoid having other code paths reset it
102 private $mForcedContentModel = false;
104 /** @var int Estimated number of revisions; null of not loaded */
105 private $mEstimateRevisions;
107 /** @var array Array of groups allowed to edit this article */
108 public $mRestrictions = [];
110 /** @var string|bool */
111 protected $mOldRestrictions = false;
113 /** @var bool Cascade restrictions on this page to included templates and images? */
114 public $mCascadeRestriction;
116 /** Caching the results of getCascadeProtectionSources */
117 public $mCascadingRestrictions;
119 /** @var array When do the restrictions on this page expire? */
120 protected $mRestrictionsExpiry = [];
122 /** @var bool Are cascading restrictions in effect on this page? */
123 protected $mHasCascadingRestrictions;
125 /** @var array Where are the cascading restrictions coming from on this page? */
126 public $mCascadeSources;
128 /** @var bool Boolean for initialisation on demand */
129 public $mRestrictionsLoaded = false;
131 /** @var string Text form including namespace/interwiki, initialised on demand */
132 protected $mPrefixedText = null;
134 /** @var mixed Cached value for getTitleProtection (create protection) */
135 public $mTitleProtection;
138 * @var int Namespace index when there is no namespace. Don't change the
139 * following default, NS_MAIN is hardcoded in several places. See T2696.
140 * Zero except in {{transclusion}} tags.
142 public $mDefaultNamespace = NS_MAIN
;
144 /** @var int The page length, 0 for special pages */
145 protected $mLength = -1;
147 /** @var null Is the article at this title a redirect? */
148 public $mRedirect = null;
150 /** @var array Associative array of user ID -> timestamp/false */
151 private $mNotificationTimestamp = [];
153 /** @var bool Whether a page has any subpages */
154 private $mHasSubpages;
156 /** @var bool The (string) language code of the page's language and content code. */
157 private $mPageLanguage = false;
159 /** @var string|bool|null The page language code from the database, null if not saved in
160 * the database or false if not loaded, yet. */
161 private $mDbPageLanguage = false;
163 /** @var TitleValue A corresponding TitleValue object */
164 private $mTitleValue = null;
166 /** @var bool Would deleting this page be a big deletion? */
167 private $mIsBigDeletion = null;
171 * B/C kludge: provide a TitleParser for use by Title.
172 * Ideally, Title would have no methods that need this.
173 * Avoid usage of this singleton by using TitleValue
174 * and the associated services when possible.
176 * @return TitleFormatter
178 private static function getTitleFormatter() {
179 return MediaWikiServices
::getInstance()->getTitleFormatter();
183 * B/C kludge: provide an InterwikiLookup for use by Title.
184 * Ideally, Title would have no methods that need this.
185 * Avoid usage of this singleton by using TitleValue
186 * and the associated services when possible.
188 * @return InterwikiLookup
190 private static function getInterwikiLookup() {
191 return MediaWikiServices
::getInstance()->getInterwikiLookup();
197 function __construct() {
201 * Create a new Title from a prefixed DB key
203 * @param string $key The database key, which has underscores
204 * instead of spaces, possibly including namespace and
206 * @return Title|null Title, or null on an error
208 public static function newFromDBkey( $key ) {
210 $t->mDbkeyform
= $key;
213 $t->secureAndSplit();
215 } catch ( MalformedTitleException
$ex ) {
221 * Create a new Title from a TitleValue
223 * @param TitleValue $titleValue Assumed to be safe.
227 public static function newFromTitleValue( TitleValue
$titleValue ) {
228 return self
::newFromLinkTarget( $titleValue );
232 * Create a new Title from a LinkTarget
234 * @param LinkTarget $linkTarget Assumed to be safe.
238 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
239 if ( $linkTarget instanceof Title
) {
240 // Special case if it's already a Title object
243 return self
::makeTitle(
244 $linkTarget->getNamespace(),
245 $linkTarget->getText(),
246 $linkTarget->getFragment(),
247 $linkTarget->getInterwiki()
252 * Create a new Title from text, such as what one would find in a link. De-
253 * codes any HTML entities in the text.
255 * @param string|int|null $text The link text; spaces, prefixes, and an
256 * initial ':' indicating the main namespace are accepted.
257 * @param int $defaultNamespace The namespace to use if none is specified
258 * by a prefix. If you want to force a specific namespace even if
259 * $text might begin with a namespace prefix, use makeTitle() or
261 * @throws InvalidArgumentException
262 * @return Title|null Title or null on an error.
264 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
265 // DWIM: Integers can be passed in here when page titles are used as array keys.
266 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
267 throw new InvalidArgumentException( '$text must be a string.' );
269 if ( $text === null ) {
274 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
275 } catch ( MalformedTitleException
$ex ) {
281 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
282 * rather than returning null.
284 * The exception subclasses encode detailed information about why the title is invalid.
286 * @see Title::newFromText
289 * @param string $text Title text to check
290 * @param int $defaultNamespace
291 * @throws MalformedTitleException If the title is invalid
294 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
295 if ( is_object( $text ) ) {
296 throw new MWException( '$text must be a string, given an object' );
299 $titleCache = self
::getTitleCache();
301 // Wiki pages often contain multiple links to the same page.
302 // Title normalization and parsing can become expensive on pages with many
303 // links, so we can save a little time by caching them.
304 // In theory these are value objects and won't get changed...
305 if ( $defaultNamespace == NS_MAIN
) {
306 $t = $titleCache->get( $text );
312 // Convert things like é ā or 〗 into normalized (T16952) text
313 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
316 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
317 $t->mDefaultNamespace
= intval( $defaultNamespace );
319 $t->secureAndSplit();
320 if ( $defaultNamespace == NS_MAIN
) {
321 $titleCache->set( $text, $t );
327 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
329 * Example of wrong and broken code:
330 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
332 * Example of right code:
333 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
335 * Create a new Title from URL-encoded text. Ensures that
336 * the given title's length does not exceed the maximum.
338 * @param string $url The title, as might be taken from a URL
339 * @return Title|null The new object, or null on an error
341 public static function newFromURL( $url ) {
344 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
345 # but some URLs used it as a space replacement and they still come
346 # from some external search tools.
347 if ( strpos( self
::legalChars(), '+' ) === false ) {
348 $url = strtr( $url, '+', ' ' );
351 $t->mDbkeyform
= strtr( $url, ' ', '_' );
354 $t->secureAndSplit();
356 } catch ( MalformedTitleException
$ex ) {
362 * @return HashBagOStuff
364 private static function getTitleCache() {
365 if ( self
::$titleCache == null ) {
366 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
368 return self
::$titleCache;
372 * Returns a list of fields that are to be selected for initializing Title
373 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
374 * whether to include page_content_model.
378 protected static function getSelectFields() {
379 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
382 'page_namespace', 'page_title', 'page_id',
383 'page_len', 'page_is_redirect', 'page_latest',
386 if ( $wgContentHandlerUseDB ) {
387 $fields[] = 'page_content_model';
390 if ( $wgPageLanguageUseDB ) {
391 $fields[] = 'page_lang';
398 * Create a new Title from an article ID
400 * @param int $id The page_id corresponding to the Title to create
401 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
402 * @return Title|null The new object, or null on an error
404 public static function newFromID( $id, $flags = 0 ) {
405 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
406 $row = $db->selectRow(
408 self
::getSelectFields(),
409 [ 'page_id' => $id ],
412 if ( $row !== false ) {
413 $title = Title
::newFromRow( $row );
421 * Make an array of titles from an array of IDs
423 * @param int[] $ids Array of IDs
424 * @return Title[] Array of Titles
426 public static function newFromIDs( $ids ) {
427 if ( !count( $ids ) ) {
430 $dbr = wfGetDB( DB_REPLICA
);
434 self
::getSelectFields(),
435 [ 'page_id' => $ids ],
440 foreach ( $res as $row ) {
441 $titles[] = Title
::newFromRow( $row );
447 * Make a Title object from a DB row
449 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
450 * @return Title Corresponding Title
452 public static function newFromRow( $row ) {
453 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
454 $t->loadFromRow( $row );
459 * Load Title object fields from a DB row.
460 * If false is given, the title will be treated as non-existing.
462 * @param stdClass|bool $row Database row
464 public function loadFromRow( $row ) {
465 if ( $row ) { // page found
466 if ( isset( $row->page_id
) ) {
467 $this->mArticleID
= (int)$row->page_id
;
469 if ( isset( $row->page_len
) ) {
470 $this->mLength
= (int)$row->page_len
;
472 if ( isset( $row->page_is_redirect
) ) {
473 $this->mRedirect
= (bool)$row->page_is_redirect
;
475 if ( isset( $row->page_latest
) ) {
476 $this->mLatestID
= (int)$row->page_latest
;
478 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
479 $this->mContentModel
= strval( $row->page_content_model
);
480 } elseif ( !$this->mForcedContentModel
) {
481 $this->mContentModel
= false; # initialized lazily in getContentModel()
483 if ( isset( $row->page_lang
) ) {
484 $this->mDbPageLanguage
= (string)$row->page_lang
;
486 if ( isset( $row->page_restrictions
) ) {
487 $this->mOldRestrictions
= $row->page_restrictions
;
489 } else { // page not found
490 $this->mArticleID
= 0;
492 $this->mRedirect
= false;
493 $this->mLatestID
= 0;
494 if ( !$this->mForcedContentModel
) {
495 $this->mContentModel
= false; # initialized lazily in getContentModel()
501 * Create a new Title from a namespace index and a DB key.
502 * It's assumed that $ns and $title are *valid*, for instance when
503 * they came directly from the database or a special page name.
504 * For convenience, spaces are converted to underscores so that
505 * eg user_text fields can be used directly.
507 * @param int $ns The namespace of the article
508 * @param string $title The unprefixed database key form
509 * @param string $fragment The link fragment (after the "#")
510 * @param string $interwiki The interwiki prefix
511 * @return Title The new object
513 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
515 $t->mInterwiki
= $interwiki;
516 $t->mFragment
= $fragment;
517 $t->mNamespace
= $ns = intval( $ns );
518 $t->mDbkeyform
= strtr( $title, ' ', '_' );
519 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
520 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
521 $t->mTextform
= strtr( $title, '_', ' ' );
522 $t->mContentModel
= false; # initialized lazily in getContentModel()
527 * Create a new Title from a namespace index and a DB key.
528 * The parameters will be checked for validity, which is a bit slower
529 * than makeTitle() but safer for user-provided data.
531 * @param int $ns The namespace of the article
532 * @param string $title Database key form
533 * @param string $fragment The link fragment (after the "#")
534 * @param string $interwiki Interwiki prefix
535 * @return Title|null The new object, or null on an error
537 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
538 if ( !MWNamespace
::exists( $ns ) ) {
543 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
546 $t->secureAndSplit();
548 } catch ( MalformedTitleException
$ex ) {
554 * Create a new Title for the Main Page
556 * @return Title The new object
558 public static function newMainPage() {
559 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
560 // Don't give fatal errors if the message is broken
562 $title = Title
::newFromText( 'Main Page' );
568 * Get the prefixed DB key associated with an ID
570 * @param int $id The page_id of the article
571 * @return Title|null An object representing the article, or null if no such article was found
573 public static function nameOf( $id ) {
574 $dbr = wfGetDB( DB_REPLICA
);
576 $s = $dbr->selectRow(
578 [ 'page_namespace', 'page_title' ],
579 [ 'page_id' => $id ],
582 if ( $s === false ) {
586 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
591 * Get a regex character class describing the legal characters in a link
593 * @return string The list of characters, not delimited
595 public static function legalChars() {
596 global $wgLegalTitleChars;
597 return $wgLegalTitleChars;
601 * Returns a simple regex that will match on characters and sequences invalid in titles.
602 * Note that this doesn't pick up many things that could be wrong with titles, but that
603 * replacing this regex with something valid will make many titles valid.
605 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
607 * @return string Regex string
609 static function getTitleInvalidRegex() {
610 wfDeprecated( __METHOD__
, '1.25' );
611 return MediaWikiTitleCodec
::getTitleInvalidRegex();
615 * Utility method for converting a character sequence from bytes to Unicode.
617 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
618 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
620 * @param string $byteClass
623 public static function convertByteClassToUnicodeClass( $byteClass ) {
624 $length = strlen( $byteClass );
626 $x0 = $x1 = $x2 = '';
628 $d0 = $d1 = $d2 = '';
629 // Decoded integer codepoints
630 $ord0 = $ord1 = $ord2 = 0;
632 $r0 = $r1 = $r2 = '';
636 $allowUnicode = false;
637 for ( $pos = 0; $pos < $length; $pos++
) {
638 // Shift the queues down
647 // Load the current input token and decoded values
648 $inChar = $byteClass[$pos];
649 if ( $inChar == '\\' ) {
650 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
651 $x0 = $inChar . $m[0];
652 $d0 = chr( hexdec( $m[1] ) );
653 $pos +
= strlen( $m[0] );
654 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
655 $x0 = $inChar . $m[0];
656 $d0 = chr( octdec( $m[0] ) );
657 $pos +
= strlen( $m[0] );
658 } elseif ( $pos +
1 >= $length ) {
661 $d0 = $byteClass[$pos +
1];
669 // Load the current re-encoded value
670 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
671 $r0 = sprintf( '\x%02x', $ord0 );
672 } elseif ( $ord0 >= 0x80 ) {
673 // Allow unicode if a single high-bit character appears
674 $r0 = sprintf( '\x%02x', $ord0 );
675 $allowUnicode = true;
676 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
682 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
684 if ( $ord2 > $ord0 ) {
686 } elseif ( $ord0 >= 0x80 ) {
688 $allowUnicode = true;
689 if ( $ord2 < 0x80 ) {
690 // Keep the non-unicode section of the range
697 // Reset state to the initial value
698 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
699 } elseif ( $ord2 < 0x80 ) {
704 if ( $ord1 < 0x80 ) {
707 if ( $ord0 < 0x80 ) {
710 if ( $allowUnicode ) {
711 $out .= '\u0080-\uFFFF';
717 * Make a prefixed DB key from a DB key and a namespace index
719 * @param int $ns Numerical representation of the namespace
720 * @param string $title The DB key form the title
721 * @param string $fragment The link fragment (after the "#")
722 * @param string $interwiki The interwiki prefix
723 * @param bool $canonicalNamespace If true, use the canonical name for
724 * $ns instead of the localized version.
725 * @return string The prefixed form of the title
727 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
728 $canonicalNamespace = false
732 if ( $canonicalNamespace ) {
733 $namespace = MWNamespace
::getCanonicalName( $ns );
735 $namespace = $wgContLang->getNsText( $ns );
737 $name = $namespace == '' ?
$title : "$namespace:$title";
738 if ( strval( $interwiki ) != '' ) {
739 $name = "$interwiki:$name";
741 if ( strval( $fragment ) != '' ) {
742 $name .= '#' . $fragment;
748 * Escape a text fragment, say from a link, for a URL
750 * @param string $fragment Containing a URL or link fragment (after the "#")
751 * @return string Escaped string
753 static function escapeFragmentForURL( $fragment ) {
754 # Note that we don't urlencode the fragment. urlencoded Unicode
755 # fragments appear not to work in IE (at least up to 7) or in at least
756 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
757 # to care if they aren't encoded.
758 return Sanitizer
::escapeId( $fragment, 'noninitial' );
762 * Callback for usort() to do title sorts by (namespace, title)
764 * @param LinkTarget $a
765 * @param LinkTarget $b
767 * @return int Result of string comparison, or namespace comparison
769 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
770 if ( $a->getNamespace() == $b->getNamespace() ) {
771 return strcmp( $a->getText(), $b->getText() );
773 return $a->getNamespace() - $b->getNamespace();
778 * Determine whether the object refers to a page within
779 * this project (either this wiki or a wiki with a local
780 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
782 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
784 public function isLocal() {
785 if ( $this->isExternal() ) {
786 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
788 return $iw->isLocal();
795 * Is this Title interwiki?
799 public function isExternal() {
800 return $this->mInterwiki
!== '';
804 * Get the interwiki prefix
806 * Use Title::isExternal to check if a interwiki is set
808 * @return string Interwiki prefix
810 public function getInterwiki() {
811 return $this->mInterwiki
;
815 * Was this a local interwiki link?
819 public function wasLocalInterwiki() {
820 return $this->mLocalInterwiki
;
824 * Determine whether the object refers to a page within
825 * this project and is transcludable.
827 * @return bool True if this is transcludable
829 public function isTrans() {
830 if ( !$this->isExternal() ) {
834 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
838 * Returns the DB name of the distant wiki which owns the object.
840 * @return string|false The DB name
842 public function getTransWikiID() {
843 if ( !$this->isExternal() ) {
847 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
851 * Get a TitleValue object representing this Title.
853 * @note Not all valid Titles have a corresponding valid TitleValue
854 * (e.g. TitleValues cannot represent page-local links that have a
855 * fragment but no title text).
857 * @return TitleValue|null
859 public function getTitleValue() {
860 if ( $this->mTitleValue
=== null ) {
862 $this->mTitleValue
= new TitleValue(
863 $this->getNamespace(),
865 $this->getFragment(),
866 $this->getInterwiki()
868 } catch ( InvalidArgumentException
$ex ) {
869 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
870 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
874 return $this->mTitleValue
;
878 * Get the text form (spaces not underscores) of the main part
880 * @return string Main part of the title
882 public function getText() {
883 return $this->mTextform
;
887 * Get the URL-encoded form of the main part
889 * @return string Main part of the title, URL-encoded
891 public function getPartialURL() {
892 return $this->mUrlform
;
896 * Get the main part with underscores
898 * @return string Main part of the title, with underscores
900 public function getDBkey() {
901 return $this->mDbkeyform
;
905 * Get the DB key with the initial letter case as specified by the user
907 * @return string DB key
909 function getUserCaseDBKey() {
910 if ( !is_null( $this->mUserCaseDBKey
) ) {
911 return $this->mUserCaseDBKey
;
913 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
914 return $this->mDbkeyform
;
919 * Get the namespace index, i.e. one of the NS_xxxx constants.
921 * @return int Namespace index
923 public function getNamespace() {
924 return $this->mNamespace
;
928 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
930 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
931 * @return string Content model id
933 public function getContentModel( $flags = 0 ) {
934 if ( !$this->mForcedContentModel
935 && ( !$this->mContentModel ||
$flags === Title
::GAID_FOR_UPDATE
)
936 && $this->getArticleID( $flags )
938 $linkCache = LinkCache
::singleton();
939 $linkCache->addLinkObj( $this ); # in case we already had an article ID
940 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
943 if ( !$this->mContentModel
) {
944 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
947 return $this->mContentModel
;
951 * Convenience method for checking a title's content model name
953 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
954 * @return bool True if $this->getContentModel() == $id
956 public function hasContentModel( $id ) {
957 return $this->getContentModel() == $id;
961 * Set a proposed content model for the page for permissions
962 * checking. This does not actually change the content model
965 * Additionally, you should make sure you've checked
966 * ContentHandler::canBeUsedOn() first.
969 * @param string $model CONTENT_MODEL_XXX constant
971 public function setContentModel( $model ) {
972 $this->mContentModel
= $model;
973 $this->mForcedContentModel
= true;
977 * Get the namespace text
979 * @return string|false Namespace text
981 public function getNsText() {
982 if ( $this->isExternal() ) {
983 // This probably shouldn't even happen,
984 // but for interwiki transclusion it sometimes does.
985 // Use the canonical namespaces if possible to try to
986 // resolve a foreign namespace.
987 if ( MWNamespace
::exists( $this->mNamespace
) ) {
988 return MWNamespace
::getCanonicalName( $this->mNamespace
);
993 $formatter = self
::getTitleFormatter();
994 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
995 } catch ( InvalidArgumentException
$ex ) {
996 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1002 * Get the namespace text of the subject (rather than talk) page
1004 * @return string Namespace text
1006 public function getSubjectNsText() {
1008 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1012 * Get the namespace text of the talk page
1014 * @return string Namespace text
1016 public function getTalkNsText() {
1018 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1022 * Could this title have a corresponding talk page?
1026 public function canTalk() {
1027 return MWNamespace
::canTalk( $this->mNamespace
);
1031 * Is this in a namespace that allows actual pages?
1035 public function canExist() {
1036 return $this->mNamespace
>= NS_MAIN
;
1040 * Can this title be added to a user's watchlist?
1044 public function isWatchable() {
1045 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1049 * Returns true if this is a special page.
1053 public function isSpecialPage() {
1054 return $this->getNamespace() == NS_SPECIAL
;
1058 * Returns true if this title resolves to the named special page
1060 * @param string $name The special page name
1063 public function isSpecial( $name ) {
1064 if ( $this->isSpecialPage() ) {
1065 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1066 if ( $name == $thisName ) {
1074 * If the Title refers to a special page alias which is not the local default, resolve
1075 * the alias, and localise the name as necessary. Otherwise, return $this
1079 public function fixSpecialName() {
1080 if ( $this->isSpecialPage() ) {
1081 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1082 if ( $canonicalName ) {
1083 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1084 if ( $localName != $this->mDbkeyform
) {
1085 return Title
::makeTitle( NS_SPECIAL
, $localName );
1093 * Returns true if the title is inside the specified namespace.
1095 * Please make use of this instead of comparing to getNamespace()
1096 * This function is much more resistant to changes we may make
1097 * to namespaces than code that makes direct comparisons.
1098 * @param int $ns The namespace
1102 public function inNamespace( $ns ) {
1103 return MWNamespace
::equals( $this->getNamespace(), $ns );
1107 * Returns true if the title is inside one of the specified namespaces.
1109 * @param int|int[] $namespaces,... The namespaces to check for
1113 public function inNamespaces( /* ... */ ) {
1114 $namespaces = func_get_args();
1115 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1116 $namespaces = $namespaces[0];
1119 foreach ( $namespaces as $ns ) {
1120 if ( $this->inNamespace( $ns ) ) {
1129 * Returns true if the title has the same subject namespace as the
1130 * namespace specified.
1131 * For example this method will take NS_USER and return true if namespace
1132 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1133 * as their subject namespace.
1135 * This is MUCH simpler than individually testing for equivalence
1136 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1141 public function hasSubjectNamespace( $ns ) {
1142 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1146 * Is this Title in a namespace which contains content?
1147 * In other words, is this a content page, for the purposes of calculating
1152 public function isContentPage() {
1153 return MWNamespace
::isContent( $this->getNamespace() );
1157 * Would anybody with sufficient privileges be able to move this page?
1158 * Some pages just aren't movable.
1162 public function isMovable() {
1163 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1164 // Interwiki title or immovable namespace. Hooks don't get to override here
1169 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1174 * Is this the mainpage?
1175 * @note Title::newFromText seems to be sufficiently optimized by the title
1176 * cache that we don't need to over-optimize by doing direct comparisons and
1177 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1178 * ends up reporting something differently than $title->isMainPage();
1183 public function isMainPage() {
1184 return $this->equals( Title
::newMainPage() );
1188 * Is this a subpage?
1192 public function isSubpage() {
1193 return MWNamespace
::hasSubpages( $this->mNamespace
)
1194 ?
strpos( $this->getText(), '/' ) !== false
1199 * Is this a conversion table for the LanguageConverter?
1203 public function isConversionTable() {
1204 // @todo ConversionTable should become a separate content model.
1206 return $this->getNamespace() == NS_MEDIAWIKI
&&
1207 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1211 * Does that page contain wikitext, or it is JS, CSS or whatever?
1215 public function isWikitextPage() {
1216 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1220 * Could this page contain custom CSS or JavaScript for the global UI.
1221 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1222 * or CONTENT_MODEL_JAVASCRIPT.
1224 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1227 * Note that this method should not return true for pages that contain and
1228 * show "inactive" CSS or JS.
1231 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1233 public function isCssOrJsPage() {
1234 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1235 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1236 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1238 return $isCssOrJsPage;
1242 * Is this a .css or .js subpage of a user page?
1244 * @todo FIXME: Rename to isUserConfigPage()
1246 public function isCssJsSubpage() {
1247 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1248 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1249 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1253 * Trim down a .css or .js subpage title to get the corresponding skin name
1255 * @return string Containing skin name from .css or .js subpage title
1257 public function getSkinFromCssJsSubpage() {
1258 $subpage = explode( '/', $this->mTextform
);
1259 $subpage = $subpage[count( $subpage ) - 1];
1260 $lastdot = strrpos( $subpage, '.' );
1261 if ( $lastdot === false ) {
1262 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1264 return substr( $subpage, 0, $lastdot );
1268 * Is this a .css subpage of a user page?
1272 public function isCssSubpage() {
1273 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1274 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1278 * Is this a .js subpage of a user page?
1282 public function isJsSubpage() {
1283 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1284 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1288 * Is this a talk page of some sort?
1292 public function isTalkPage() {
1293 return MWNamespace
::isTalk( $this->getNamespace() );
1297 * Get a Title object associated with the talk page of this article
1299 * @return Title The object for the talk page
1301 public function getTalkPage() {
1302 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1306 * Get a title object associated with the subject page of this
1309 * @return Title The object for the subject page
1311 public function getSubjectPage() {
1312 // Is this the same title?
1313 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1314 if ( $this->getNamespace() == $subjectNS ) {
1317 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1321 * Get the other title for this page, if this is a subject page
1322 * get the talk page, if it is a subject page get the talk page
1325 * @throws MWException
1328 public function getOtherPage() {
1329 if ( $this->isSpecialPage() ) {
1330 throw new MWException( 'Special pages cannot have other pages' );
1332 if ( $this->isTalkPage() ) {
1333 return $this->getSubjectPage();
1335 return $this->getTalkPage();
1340 * Get the default namespace index, for when there is no namespace
1342 * @return int Default namespace index
1344 public function getDefaultNamespace() {
1345 return $this->mDefaultNamespace
;
1349 * Get the Title fragment (i.e.\ the bit after the #) in text form
1351 * Use Title::hasFragment to check for a fragment
1353 * @return string Title fragment
1355 public function getFragment() {
1356 return $this->mFragment
;
1360 * Check if a Title fragment is set
1365 public function hasFragment() {
1366 return $this->mFragment
!== '';
1370 * Get the fragment in URL form, including the "#" character if there is one
1371 * @return string Fragment in URL form
1373 public function getFragmentForURL() {
1374 if ( !$this->hasFragment() ) {
1377 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1382 * Set the fragment for this title. Removes the first character from the
1383 * specified fragment before setting, so it assumes you're passing it with
1386 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1387 * or Title::createFragmentTarget().
1388 * Still in active use privately.
1391 * @param string $fragment Text
1393 public function setFragment( $fragment ) {
1394 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1398 * Creates a new Title for a different fragment of the same page.
1401 * @param string $fragment
1404 public function createFragmentTarget( $fragment ) {
1405 return self
::makeTitle(
1406 $this->getNamespace(),
1409 $this->getInterwiki()
1414 * Prefix some arbitrary text with the namespace or interwiki prefix
1417 * @param string $name The text
1418 * @return string The prefixed text
1420 private function prefix( $name ) {
1422 if ( $this->isExternal() ) {
1423 $p = $this->mInterwiki
. ':';
1426 if ( 0 != $this->mNamespace
) {
1427 $p .= $this->getNsText() . ':';
1433 * Get the prefixed database key form
1435 * @return string The prefixed title, with underscores and
1436 * any interwiki and namespace prefixes
1438 public function getPrefixedDBkey() {
1439 $s = $this->prefix( $this->mDbkeyform
);
1440 $s = strtr( $s, ' ', '_' );
1445 * Get the prefixed title with spaces.
1446 * This is the form usually used for display
1448 * @return string The prefixed title, with spaces
1450 public function getPrefixedText() {
1451 if ( $this->mPrefixedText
=== null ) {
1452 $s = $this->prefix( $this->mTextform
);
1453 $s = strtr( $s, '_', ' ' );
1454 $this->mPrefixedText
= $s;
1456 return $this->mPrefixedText
;
1460 * Return a string representation of this title
1462 * @return string Representation of this title
1464 public function __toString() {
1465 return $this->getPrefixedText();
1469 * Get the prefixed title with spaces, plus any fragment
1470 * (part beginning with '#')
1472 * @return string The prefixed title, with spaces and the fragment, including '#'
1474 public function getFullText() {
1475 $text = $this->getPrefixedText();
1476 if ( $this->hasFragment() ) {
1477 $text .= '#' . $this->getFragment();
1483 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1487 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1491 * @return string Root name
1494 public function getRootText() {
1495 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1496 return $this->getText();
1499 return strtok( $this->getText(), '/' );
1503 * Get the root page name title, i.e. the leftmost part before any slashes
1507 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1508 * # returns: Title{User:Foo}
1511 * @return Title Root title
1514 public function getRootTitle() {
1515 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1519 * Get the base page name without a namespace, i.e. the part before the subpage name
1523 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1524 * # returns: 'Foo/Bar'
1527 * @return string Base name
1529 public function getBaseText() {
1530 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1531 return $this->getText();
1534 $parts = explode( '/', $this->getText() );
1535 # Don't discard the real title if there's no subpage involved
1536 if ( count( $parts ) > 1 ) {
1537 unset( $parts[count( $parts ) - 1] );
1539 return implode( '/', $parts );
1543 * Get the base page name title, i.e. the part before the subpage name
1547 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1548 * # returns: Title{User:Foo/Bar}
1551 * @return Title Base title
1554 public function getBaseTitle() {
1555 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1559 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1563 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1567 * @return string Subpage name
1569 public function getSubpageText() {
1570 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1571 return $this->mTextform
;
1573 $parts = explode( '/', $this->mTextform
);
1574 return $parts[count( $parts ) - 1];
1578 * Get the title for a subpage of the current page
1582 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1583 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1586 * @param string $text The subpage name to add to the title
1587 * @return Title Subpage title
1590 public function getSubpage( $text ) {
1591 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1595 * Get a URL-encoded form of the subpage text
1597 * @return string URL-encoded subpage name
1599 public function getSubpageUrlForm() {
1600 $text = $this->getSubpageText();
1601 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1606 * Get a URL-encoded title (not an actual URL) including interwiki
1608 * @return string The URL-encoded form
1610 public function getPrefixedURL() {
1611 $s = $this->prefix( $this->mDbkeyform
);
1612 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1617 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1618 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1619 * second argument named variant. This was deprecated in favor
1620 * of passing an array of option with a "variant" key
1621 * Once $query2 is removed for good, this helper can be dropped
1622 * and the wfArrayToCgi moved to getLocalURL();
1624 * @since 1.19 (r105919)
1625 * @param array|string $query
1626 * @param string|string[]|bool $query2
1629 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1630 if ( $query2 !== false ) {
1631 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1632 "method called with a second parameter is deprecated. Add your " .
1633 "parameter to an array passed as the first parameter.", "1.19" );
1635 if ( is_array( $query ) ) {
1636 $query = wfArrayToCgi( $query );
1639 if ( is_string( $query2 ) ) {
1640 // $query2 is a string, we will consider this to be
1641 // a deprecated $variant argument and add it to the query
1642 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1644 $query2 = wfArrayToCgi( $query2 );
1646 // If we have $query content add a & to it first
1650 // Now append the queries together
1657 * Get a real URL referring to this title, with interwiki link and
1660 * @see self::getLocalURL for the arguments.
1662 * @param string|string[] $query
1663 * @param string|string[]|bool $query2
1664 * @param string $proto Protocol type to use in URL
1665 * @return string The URL
1667 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1668 $query = self
::fixUrlQueryArgs( $query, $query2 );
1670 # Hand off all the decisions on urls to getLocalURL
1671 $url = $this->getLocalURL( $query );
1673 # Expand the url to make it a full url. Note that getLocalURL has the
1674 # potential to output full urls for a variety of reasons, so we use
1675 # wfExpandUrl instead of simply prepending $wgServer
1676 $url = wfExpandUrl( $url, $proto );
1678 # Finally, add the fragment.
1679 $url .= $this->getFragmentForURL();
1680 // Avoid PHP 7.1 warning from passing $this by reference
1682 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1687 * Get a URL with no fragment or server name (relative URL) from a Title object.
1688 * If this page is generated with action=render, however,
1689 * $wgServer is prepended to make an absolute URL.
1691 * @see self::getFullURL to always get an absolute URL.
1692 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1693 * valid to link, locally, to the current Title.
1694 * @see self::newFromText to produce a Title object.
1696 * @param string|string[] $query An optional query string,
1697 * not used for interwiki links. Can be specified as an associative array as well,
1698 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1699 * Some query patterns will trigger various shorturl path replacements.
1700 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1701 * be an array. If a string is passed it will be interpreted as a deprecated
1702 * variant argument and urlencoded into a variant= argument.
1703 * This second query argument will be added to the $query
1704 * The second parameter is deprecated since 1.19. Pass it as a key,value
1705 * pair in the first parameter array instead.
1707 * @return string String of the URL.
1709 public function getLocalURL( $query = '', $query2 = false ) {
1710 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1712 $query = self
::fixUrlQueryArgs( $query, $query2 );
1714 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1716 $namespace = $this->getNsText();
1717 if ( $namespace != '' ) {
1718 # Can this actually happen? Interwikis shouldn't be parsed.
1719 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1722 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1723 $url = wfAppendQuery( $url, $query );
1725 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1726 if ( $query == '' ) {
1727 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1728 // Avoid PHP 7.1 warning from passing $this by reference
1730 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1732 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1736 if ( !empty( $wgActionPaths )
1737 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1739 $action = urldecode( $matches[2] );
1740 if ( isset( $wgActionPaths[$action] ) ) {
1741 $query = $matches[1];
1742 if ( isset( $matches[4] ) ) {
1743 $query .= $matches[4];
1745 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1746 if ( $query != '' ) {
1747 $url = wfAppendQuery( $url, $query );
1753 && $wgVariantArticlePath
1754 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1755 && $this->getPageLanguage()->equals( $wgContLang )
1756 && $this->getPageLanguage()->hasVariants()
1758 $variant = urldecode( $matches[1] );
1759 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1760 // Only do the variant replacement if the given variant is a valid
1761 // variant for the page's language.
1762 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1763 $url = str_replace( '$1', $dbkey, $url );
1767 if ( $url === false ) {
1768 if ( $query == '-' ) {
1771 $url = "{$wgScript}?title={$dbkey}&{$query}";
1774 // Avoid PHP 7.1 warning from passing $this by reference
1776 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1778 // @todo FIXME: This causes breakage in various places when we
1779 // actually expected a local URL and end up with dupe prefixes.
1780 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1781 $url = $wgServer . $url;
1784 // Avoid PHP 7.1 warning from passing $this by reference
1786 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1791 * Get a URL that's the simplest URL that will be valid to link, locally,
1792 * to the current Title. It includes the fragment, but does not include
1793 * the server unless action=render is used (or the link is external). If
1794 * there's a fragment but the prefixed text is empty, we just return a link
1797 * The result obviously should not be URL-escaped, but does need to be
1798 * HTML-escaped if it's being output in HTML.
1800 * @param string|string[] $query
1801 * @param bool $query2
1802 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1803 * or false (default) for no expansion
1804 * @see self::getLocalURL for the arguments.
1805 * @return string The URL
1807 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1808 if ( $this->isExternal() ||
$proto !== false ) {
1809 $ret = $this->getFullURL( $query, $query2, $proto );
1810 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1811 $ret = $this->getFragmentForURL();
1813 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1819 * Get the URL form for an internal link.
1820 * - Used in various CDN-related code, in case we have a different
1821 * internal hostname for the server from the exposed one.
1823 * This uses $wgInternalServer to qualify the path, or $wgServer
1824 * if $wgInternalServer is not set. If the server variable used is
1825 * protocol-relative, the URL will be expanded to http://
1827 * @see self::getLocalURL for the arguments.
1828 * @return string The URL
1830 public function getInternalURL( $query = '', $query2 = false ) {
1831 global $wgInternalServer, $wgServer;
1832 $query = self
::fixUrlQueryArgs( $query, $query2 );
1833 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1834 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1835 // Avoid PHP 7.1 warning from passing $this by reference
1837 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1842 * Get the URL for a canonical link, for use in things like IRC and
1843 * e-mail notifications. Uses $wgCanonicalServer and the
1844 * GetCanonicalURL hook.
1846 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1848 * @see self::getLocalURL for the arguments.
1849 * @return string The URL
1852 public function getCanonicalURL( $query = '', $query2 = false ) {
1853 $query = self
::fixUrlQueryArgs( $query, $query2 );
1854 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1855 // Avoid PHP 7.1 warning from passing $this by reference
1857 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1862 * Get the edit URL for this Title
1864 * @return string The URL, or a null string if this is an interwiki link
1866 public function getEditURL() {
1867 if ( $this->isExternal() ) {
1870 $s = $this->getLocalURL( 'action=edit' );
1876 * Can $user perform $action on this page?
1877 * This skips potentially expensive cascading permission checks
1878 * as well as avoids expensive error formatting
1880 * Suitable for use for nonessential UI controls in common cases, but
1881 * _not_ for functional access control.
1883 * May provide false positives, but should never provide a false negative.
1885 * @param string $action Action that permission needs to be checked for
1886 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1889 public function quickUserCan( $action, $user = null ) {
1890 return $this->userCan( $action, $user, false );
1894 * Can $user perform $action on this page?
1896 * @param string $action Action that permission needs to be checked for
1897 * @param User $user User to check (since 1.19); $wgUser will be used if not
1899 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1902 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1903 if ( !$user instanceof User
) {
1908 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1912 * Can $user perform $action on this page?
1914 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1916 * @param string $action Action that permission needs to be checked for
1917 * @param User $user User to check
1918 * @param string $rigor One of (quick,full,secure)
1919 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1920 * - full : does cheap and expensive checks possibly from a replica DB
1921 * - secure : does cheap and expensive checks, using the master as needed
1922 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1923 * whose corresponding errors may be ignored.
1924 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1926 public function getUserPermissionsErrors(
1927 $action, $user, $rigor = 'secure', $ignoreErrors = []
1929 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1931 // Remove the errors being ignored.
1932 foreach ( $errors as $index => $error ) {
1933 $errKey = is_array( $error ) ?
$error[0] : $error;
1935 if ( in_array( $errKey, $ignoreErrors ) ) {
1936 unset( $errors[$index] );
1938 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1939 unset( $errors[$index] );
1947 * Permissions checks that fail most often, and which are easiest to test.
1949 * @param string $action The action to check
1950 * @param User $user User to check
1951 * @param array $errors List of current errors
1952 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1953 * @param bool $short Short circuit on first error
1955 * @return array List of errors
1957 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1958 if ( !Hooks
::run( 'TitleQuickPermissions',
1959 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1964 if ( $action == 'create' ) {
1966 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1967 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1969 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1971 } elseif ( $action == 'move' ) {
1972 if ( !$user->isAllowed( 'move-rootuserpages' )
1973 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1974 // Show user page-specific message only if the user can move other pages
1975 $errors[] = [ 'cant-move-user-page' ];
1978 // Check if user is allowed to move files if it's a file
1979 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1980 $errors[] = [ 'movenotallowedfile' ];
1983 // Check if user is allowed to move category pages if it's a category page
1984 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1985 $errors[] = [ 'cant-move-category-page' ];
1988 if ( !$user->isAllowed( 'move' ) ) {
1989 // User can't move anything
1990 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1991 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1992 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1993 // custom message if logged-in users without any special rights can move
1994 $errors[] = [ 'movenologintext' ];
1996 $errors[] = [ 'movenotallowed' ];
1999 } elseif ( $action == 'move-target' ) {
2000 if ( !$user->isAllowed( 'move' ) ) {
2001 // User can't move anything
2002 $errors[] = [ 'movenotallowed' ];
2003 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2004 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2005 // Show user page-specific message only if the user can move other pages
2006 $errors[] = [ 'cant-move-to-user-page' ];
2007 } elseif ( !$user->isAllowed( 'move-categorypages' )
2008 && $this->mNamespace
== NS_CATEGORY
) {
2009 // Show category page-specific message only if the user can move other pages
2010 $errors[] = [ 'cant-move-to-category-page' ];
2012 } elseif ( !$user->isAllowed( $action ) ) {
2013 $errors[] = $this->missingPermissionError( $action, $short );
2020 * Add the resulting error code to the errors array
2022 * @param array $errors List of current errors
2023 * @param array $result Result of errors
2025 * @return array List of errors
2027 private function resultToError( $errors, $result ) {
2028 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2029 // A single array representing an error
2030 $errors[] = $result;
2031 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2032 // A nested array representing multiple errors
2033 $errors = array_merge( $errors, $result );
2034 } elseif ( $result !== '' && is_string( $result ) ) {
2035 // A string representing a message-id
2036 $errors[] = [ $result ];
2037 } elseif ( $result instanceof MessageSpecifier
) {
2038 // A message specifier representing an error
2039 $errors[] = [ $result ];
2040 } elseif ( $result === false ) {
2041 // a generic "We don't want them to do that"
2042 $errors[] = [ 'badaccess-group0' ];
2048 * Check various permission hooks
2050 * @param string $action The action to check
2051 * @param User $user User to check
2052 * @param array $errors List of current errors
2053 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2054 * @param bool $short Short circuit on first error
2056 * @return array List of errors
2058 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2059 // Use getUserPermissionsErrors instead
2061 // Avoid PHP 7.1 warning from passing $this by reference
2063 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2064 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2066 // Check getUserPermissionsErrors hook
2067 // Avoid PHP 7.1 warning from passing $this by reference
2069 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2070 $errors = $this->resultToError( $errors, $result );
2072 // Check getUserPermissionsErrorsExpensive hook
2075 && !( $short && count( $errors ) > 0 )
2076 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2078 $errors = $this->resultToError( $errors, $result );
2085 * Check permissions on special pages & namespaces
2087 * @param string $action The action to check
2088 * @param User $user User to check
2089 * @param array $errors List of current errors
2090 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2091 * @param bool $short Short circuit on first error
2093 * @return array List of errors
2095 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2096 # Only 'createaccount' can be performed on special pages,
2097 # which don't actually exist in the DB.
2098 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2099 $errors[] = [ 'ns-specialprotected' ];
2102 # Check $wgNamespaceProtection for restricted namespaces
2103 if ( $this->isNamespaceProtected( $user ) ) {
2104 $ns = $this->mNamespace
== NS_MAIN ?
2105 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2106 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2107 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2114 * Check CSS/JS sub-page permissions
2116 * @param string $action The action to check
2117 * @param User $user User to check
2118 * @param array $errors List of current errors
2119 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2120 * @param bool $short Short circuit on first error
2122 * @return array List of errors
2124 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2125 # Protect css/js subpages of user pages
2126 # XXX: this might be better using restrictions
2127 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2128 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2129 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2130 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2131 $errors[] = [ 'mycustomcssprotected', $action ];
2132 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2133 $errors[] = [ 'mycustomjsprotected', $action ];
2136 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2137 $errors[] = [ 'customcssprotected', $action ];
2138 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2139 $errors[] = [ 'customjsprotected', $action ];
2148 * Check against page_restrictions table requirements on this
2149 * page. The user must possess all required rights for this
2152 * @param string $action The action to check
2153 * @param User $user User to check
2154 * @param array $errors List of current errors
2155 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2156 * @param bool $short Short circuit on first error
2158 * @return array List of errors
2160 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2161 foreach ( $this->getRestrictions( $action ) as $right ) {
2162 // Backwards compatibility, rewrite sysop -> editprotected
2163 if ( $right == 'sysop' ) {
2164 $right = 'editprotected';
2166 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2167 if ( $right == 'autoconfirmed' ) {
2168 $right = 'editsemiprotected';
2170 if ( $right == '' ) {
2173 if ( !$user->isAllowed( $right ) ) {
2174 $errors[] = [ 'protectedpagetext', $right, $action ];
2175 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2176 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2184 * Check restrictions on cascading pages.
2186 * @param string $action The action to check
2187 * @param User $user User to check
2188 * @param array $errors List of current errors
2189 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2190 * @param bool $short Short circuit on first error
2192 * @return array List of errors
2194 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2195 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2196 # We /could/ use the protection level on the source page, but it's
2197 # fairly ugly as we have to establish a precedence hierarchy for pages
2198 # included by multiple cascade-protected pages. So just restrict
2199 # it to people with 'protect' permission, as they could remove the
2200 # protection anyway.
2201 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2202 # Cascading protection depends on more than this page...
2203 # Several cascading protected pages may include this page...
2204 # Check each cascading level
2205 # This is only for protection restrictions, not for all actions
2206 if ( isset( $restrictions[$action] ) ) {
2207 foreach ( $restrictions[$action] as $right ) {
2208 // Backwards compatibility, rewrite sysop -> editprotected
2209 if ( $right == 'sysop' ) {
2210 $right = 'editprotected';
2212 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2213 if ( $right == 'autoconfirmed' ) {
2214 $right = 'editsemiprotected';
2216 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2218 foreach ( $cascadingSources as $page ) {
2219 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2221 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2231 * Check action permissions not already checked in checkQuickPermissions
2233 * @param string $action The action to check
2234 * @param User $user User to check
2235 * @param array $errors List of current errors
2236 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2237 * @param bool $short Short circuit on first error
2239 * @return array List of errors
2241 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2242 global $wgDeleteRevisionsLimit, $wgLang;
2244 if ( $action == 'protect' ) {
2245 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2246 // If they can't edit, they shouldn't protect.
2247 $errors[] = [ 'protect-cantedit' ];
2249 } elseif ( $action == 'create' ) {
2250 $title_protection = $this->getTitleProtection();
2251 if ( $title_protection ) {
2252 if ( $title_protection['permission'] == ''
2253 ||
!$user->isAllowed( $title_protection['permission'] )
2257 User
::whoIs( $title_protection['user'] ),
2258 $title_protection['reason']
2262 } elseif ( $action == 'move' ) {
2263 // Check for immobile pages
2264 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2265 // Specific message for this case
2266 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2267 } elseif ( !$this->isMovable() ) {
2268 // Less specific message for rarer cases
2269 $errors[] = [ 'immobile-source-page' ];
2271 } elseif ( $action == 'move-target' ) {
2272 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2273 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2274 } elseif ( !$this->isMovable() ) {
2275 $errors[] = [ 'immobile-target-page' ];
2277 } elseif ( $action == 'delete' ) {
2278 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2279 if ( !$tempErrors ) {
2280 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2281 $user, $tempErrors, $rigor, true );
2283 if ( $tempErrors ) {
2284 // If protection keeps them from editing, they shouldn't be able to delete.
2285 $errors[] = [ 'deleteprotected' ];
2287 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2288 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2290 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2297 * Check that the user isn't blocked from editing.
2299 * @param string $action The action to check
2300 * @param User $user User to check
2301 * @param array $errors List of current errors
2302 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2303 * @param bool $short Short circuit on first error
2305 * @return array List of errors
2307 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2308 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2309 // Account creation blocks handled at userlogin.
2310 // Unblocking handled in SpecialUnblock
2311 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2315 // Optimize for a very common case
2316 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2320 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2321 $errors[] = [ 'confirmedittext' ];
2324 $useSlave = ( $rigor !== 'secure' );
2325 if ( ( $action == 'edit' ||
$action == 'create' )
2326 && !$user->isBlockedFrom( $this, $useSlave )
2328 // Don't block the user from editing their own talk page unless they've been
2329 // explicitly blocked from that too.
2330 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2331 // @todo FIXME: Pass the relevant context into this function.
2332 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2339 * Check that the user is allowed to read this page.
2341 * @param string $action The action to check
2342 * @param User $user User to check
2343 * @param array $errors List of current errors
2344 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2345 * @param bool $short Short circuit on first error
2347 * @return array List of errors
2349 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2350 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2352 $whitelisted = false;
2353 if ( User
::isEveryoneAllowed( 'read' ) ) {
2354 # Shortcut for public wikis, allows skipping quite a bit of code
2355 $whitelisted = true;
2356 } elseif ( $user->isAllowed( 'read' ) ) {
2357 # If the user is allowed to read pages, he is allowed to read all pages
2358 $whitelisted = true;
2359 } elseif ( $this->isSpecial( 'Userlogin' )
2360 ||
$this->isSpecial( 'PasswordReset' )
2361 ||
$this->isSpecial( 'Userlogout' )
2363 # Always grant access to the login page.
2364 # Even anons need to be able to log in.
2365 $whitelisted = true;
2366 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2367 # Time to check the whitelist
2368 # Only do these checks is there's something to check against
2369 $name = $this->getPrefixedText();
2370 $dbName = $this->getPrefixedDBkey();
2372 // Check for explicit whitelisting with and without underscores
2373 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2374 $whitelisted = true;
2375 } elseif ( $this->getNamespace() == NS_MAIN
) {
2376 # Old settings might have the title prefixed with
2377 # a colon for main-namespace pages
2378 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2379 $whitelisted = true;
2381 } elseif ( $this->isSpecialPage() ) {
2382 # If it's a special page, ditch the subpage bit and check again
2383 $name = $this->getDBkey();
2384 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2386 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2387 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2388 $whitelisted = true;
2394 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2395 $name = $this->getPrefixedText();
2396 // Check for regex whitelisting
2397 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2398 if ( preg_match( $listItem, $name ) ) {
2399 $whitelisted = true;
2405 if ( !$whitelisted ) {
2406 # If the title is not whitelisted, give extensions a chance to do so...
2407 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2408 if ( !$whitelisted ) {
2409 $errors[] = $this->missingPermissionError( $action, $short );
2417 * Get a description array when the user doesn't have the right to perform
2418 * $action (i.e. when User::isAllowed() returns false)
2420 * @param string $action The action to check
2421 * @param bool $short Short circuit on first error
2422 * @return array Array containing an error message key and any parameters
2424 private function missingPermissionError( $action, $short ) {
2425 // We avoid expensive display logic for quickUserCan's and such
2427 return [ 'badaccess-group0' ];
2430 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2434 * Can $user perform $action on this page? This is an internal function,
2435 * with multiple levels of checks depending on performance needs; see $rigor below.
2436 * It does not check wfReadOnly().
2438 * @param string $action Action that permission needs to be checked for
2439 * @param User $user User to check
2440 * @param string $rigor One of (quick,full,secure)
2441 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2442 * - full : does cheap and expensive checks possibly from a replica DB
2443 * - secure : does cheap and expensive checks, using the master as needed
2444 * @param bool $short Set this to true to stop after the first permission error.
2445 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2447 protected function getUserPermissionsErrorsInternal(
2448 $action, $user, $rigor = 'secure', $short = false
2450 if ( $rigor === true ) {
2451 $rigor = 'secure'; // b/c
2452 } elseif ( $rigor === false ) {
2453 $rigor = 'quick'; // b/c
2454 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2455 throw new Exception( "Invalid rigor parameter '$rigor'." );
2458 # Read has special handling
2459 if ( $action == 'read' ) {
2461 'checkPermissionHooks',
2462 'checkReadPermissions',
2463 'checkUserBlock', // for wgBlockDisablesLogin
2465 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2466 # here as it will lead to duplicate error messages. This is okay to do
2467 # since anywhere that checks for create will also check for edit, and
2468 # those checks are called for edit.
2469 } elseif ( $action == 'create' ) {
2471 'checkQuickPermissions',
2472 'checkPermissionHooks',
2473 'checkPageRestrictions',
2474 'checkCascadingSourcesRestrictions',
2475 'checkActionPermissions',
2480 'checkQuickPermissions',
2481 'checkPermissionHooks',
2482 'checkSpecialsAndNSPermissions',
2483 'checkCSSandJSPermissions',
2484 'checkPageRestrictions',
2485 'checkCascadingSourcesRestrictions',
2486 'checkActionPermissions',
2492 while ( count( $checks ) > 0 &&
2493 !( $short && count( $errors ) > 0 ) ) {
2494 $method = array_shift( $checks );
2495 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2502 * Get a filtered list of all restriction types supported by this wiki.
2503 * @param bool $exists True to get all restriction types that apply to
2504 * titles that do exist, False for all restriction types that apply to
2505 * titles that do not exist
2508 public static function getFilteredRestrictionTypes( $exists = true ) {
2509 global $wgRestrictionTypes;
2510 $types = $wgRestrictionTypes;
2512 # Remove the create restriction for existing titles
2513 $types = array_diff( $types, [ 'create' ] );
2515 # Only the create and upload restrictions apply to non-existing titles
2516 $types = array_intersect( $types, [ 'create', 'upload' ] );
2522 * Returns restriction types for the current Title
2524 * @return array Applicable restriction types
2526 public function getRestrictionTypes() {
2527 if ( $this->isSpecialPage() ) {
2531 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2533 if ( $this->getNamespace() != NS_FILE
) {
2534 # Remove the upload restriction for non-file titles
2535 $types = array_diff( $types, [ 'upload' ] );
2538 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2540 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2541 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2547 * Is this title subject to title protection?
2548 * Title protection is the one applied against creation of such title.
2550 * @return array|bool An associative array representing any existent title
2551 * protection, or false if there's none.
2553 public function getTitleProtection() {
2554 $protection = $this->getTitleProtectionInternal();
2555 if ( $protection ) {
2556 if ( $protection['permission'] == 'sysop' ) {
2557 $protection['permission'] = 'editprotected'; // B/C
2559 if ( $protection['permission'] == 'autoconfirmed' ) {
2560 $protection['permission'] = 'editsemiprotected'; // B/C
2567 * Fetch title protection settings
2569 * To work correctly, $this->loadRestrictions() needs to have access to the
2570 * actual protections in the database without munging 'sysop' =>
2571 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2572 * callers probably want $this->getTitleProtection() instead.
2574 * @return array|bool
2576 protected function getTitleProtectionInternal() {
2577 // Can't protect pages in special namespaces
2578 if ( $this->getNamespace() < 0 ) {
2582 // Can't protect pages that exist.
2583 if ( $this->exists() ) {
2587 if ( $this->mTitleProtection
=== null ) {
2588 $dbr = wfGetDB( DB_REPLICA
);
2589 $res = $dbr->select(
2592 'user' => 'pt_user',
2593 'reason' => 'pt_reason',
2594 'expiry' => 'pt_expiry',
2595 'permission' => 'pt_create_perm'
2597 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2601 // fetchRow returns false if there are no rows.
2602 $row = $dbr->fetchRow( $res );
2604 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2606 $this->mTitleProtection
= $row;
2608 return $this->mTitleProtection
;
2612 * Remove any title protection due to page existing
2614 public function deleteTitleProtection() {
2615 $dbw = wfGetDB( DB_MASTER
);
2619 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2622 $this->mTitleProtection
= false;
2626 * Is this page "semi-protected" - the *only* protection levels are listed
2627 * in $wgSemiprotectedRestrictionLevels?
2629 * @param string $action Action to check (default: edit)
2632 public function isSemiProtected( $action = 'edit' ) {
2633 global $wgSemiprotectedRestrictionLevels;
2635 $restrictions = $this->getRestrictions( $action );
2636 $semi = $wgSemiprotectedRestrictionLevels;
2637 if ( !$restrictions ||
!$semi ) {
2638 // Not protected, or all protection is full protection
2642 // Remap autoconfirmed to editsemiprotected for BC
2643 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2644 $semi[$key] = 'editsemiprotected';
2646 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2647 $restrictions[$key] = 'editsemiprotected';
2650 return !array_diff( $restrictions, $semi );
2654 * Does the title correspond to a protected article?
2656 * @param string $action The action the page is protected from,
2657 * by default checks all actions.
2660 public function isProtected( $action = '' ) {
2661 global $wgRestrictionLevels;
2663 $restrictionTypes = $this->getRestrictionTypes();
2665 # Special pages have inherent protection
2666 if ( $this->isSpecialPage() ) {
2670 # Check regular protection levels
2671 foreach ( $restrictionTypes as $type ) {
2672 if ( $action == $type ||
$action == '' ) {
2673 $r = $this->getRestrictions( $type );
2674 foreach ( $wgRestrictionLevels as $level ) {
2675 if ( in_array( $level, $r ) && $level != '' ) {
2686 * Determines if $user is unable to edit this page because it has been protected
2687 * by $wgNamespaceProtection.
2689 * @param User $user User object to check permissions
2692 public function isNamespaceProtected( User
$user ) {
2693 global $wgNamespaceProtection;
2695 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2696 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2697 if ( $right != '' && !$user->isAllowed( $right ) ) {
2706 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2708 * @return bool If the page is subject to cascading restrictions.
2710 public function isCascadeProtected() {
2711 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2712 return ( $sources > 0 );
2716 * Determines whether cascading protection sources have already been loaded from
2719 * @param bool $getPages True to check if the pages are loaded, or false to check
2720 * if the status is loaded.
2721 * @return bool Whether or not the specified information has been loaded
2724 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2725 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2729 * Cascading protection: Get the source of any cascading restrictions on this page.
2731 * @param bool $getPages Whether or not to retrieve the actual pages
2732 * that the restrictions have come from and the actual restrictions
2734 * @return array Two elements: First is an array of Title objects of the
2735 * pages from which cascading restrictions have come, false for
2736 * none, or true if such restrictions exist but $getPages was not
2737 * set. Second is an array like that returned by
2738 * Title::getAllRestrictions(), or an empty array if $getPages is
2741 public function getCascadeProtectionSources( $getPages = true ) {
2742 $pagerestrictions = [];
2744 if ( $this->mCascadeSources
!== null && $getPages ) {
2745 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2746 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2747 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2750 $dbr = wfGetDB( DB_REPLICA
);
2752 if ( $this->getNamespace() == NS_FILE
) {
2753 $tables = [ 'imagelinks', 'page_restrictions' ];
2755 'il_to' => $this->getDBkey(),
2760 $tables = [ 'templatelinks', 'page_restrictions' ];
2762 'tl_namespace' => $this->getNamespace(),
2763 'tl_title' => $this->getDBkey(),
2770 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2771 'pr_expiry', 'pr_type', 'pr_level' ];
2772 $where_clauses[] = 'page_id=pr_page';
2775 $cols = [ 'pr_expiry' ];
2778 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2780 $sources = $getPages ?
[] : false;
2781 $now = wfTimestampNow();
2783 foreach ( $res as $row ) {
2784 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2785 if ( $expiry > $now ) {
2787 $page_id = $row->pr_page
;
2788 $page_ns = $row->page_namespace
;
2789 $page_title = $row->page_title
;
2790 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2791 # Add groups needed for each restriction type if its not already there
2792 # Make sure this restriction type still exists
2794 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2795 $pagerestrictions[$row->pr_type
] = [];
2799 isset( $pagerestrictions[$row->pr_type
] )
2800 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2802 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2811 $this->mCascadeSources
= $sources;
2812 $this->mCascadingRestrictions
= $pagerestrictions;
2814 $this->mHasCascadingRestrictions
= $sources;
2817 return [ $sources, $pagerestrictions ];
2821 * Accessor for mRestrictionsLoaded
2823 * @return bool Whether or not the page's restrictions have already been
2824 * loaded from the database
2827 public function areRestrictionsLoaded() {
2828 return $this->mRestrictionsLoaded
;
2832 * Accessor/initialisation for mRestrictions
2834 * @param string $action Action that permission needs to be checked for
2835 * @return array Restriction levels needed to take the action. All levels are
2836 * required. Note that restriction levels are normally user rights, but 'sysop'
2837 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2838 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2840 public function getRestrictions( $action ) {
2841 if ( !$this->mRestrictionsLoaded
) {
2842 $this->loadRestrictions();
2844 return isset( $this->mRestrictions
[$action] )
2845 ?
$this->mRestrictions
[$action]
2850 * Accessor/initialisation for mRestrictions
2852 * @return array Keys are actions, values are arrays as returned by
2853 * Title::getRestrictions()
2856 public function getAllRestrictions() {
2857 if ( !$this->mRestrictionsLoaded
) {
2858 $this->loadRestrictions();
2860 return $this->mRestrictions
;
2864 * Get the expiry time for the restriction against a given action
2866 * @param string $action
2867 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2868 * or not protected at all, or false if the action is not recognised.
2870 public function getRestrictionExpiry( $action ) {
2871 if ( !$this->mRestrictionsLoaded
) {
2872 $this->loadRestrictions();
2874 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2878 * Returns cascading restrictions for the current article
2882 function areRestrictionsCascading() {
2883 if ( !$this->mRestrictionsLoaded
) {
2884 $this->loadRestrictions();
2887 return $this->mCascadeRestriction
;
2891 * Compiles list of active page restrictions from both page table (pre 1.10)
2892 * and page_restrictions table for this existing page.
2893 * Public for usage by LiquidThreads.
2895 * @param array $rows Array of db result objects
2896 * @param string $oldFashionedRestrictions Comma-separated list of page
2897 * restrictions from page table (pre 1.10)
2899 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2900 $dbr = wfGetDB( DB_REPLICA
);
2902 $restrictionTypes = $this->getRestrictionTypes();
2904 foreach ( $restrictionTypes as $type ) {
2905 $this->mRestrictions
[$type] = [];
2906 $this->mRestrictionsExpiry
[$type] = 'infinity';
2909 $this->mCascadeRestriction
= false;
2911 # Backwards-compatibility: also load the restrictions from the page record (old format).
2912 if ( $oldFashionedRestrictions !== null ) {
2913 $this->mOldRestrictions
= $oldFashionedRestrictions;
2916 if ( $this->mOldRestrictions
=== false ) {
2917 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2918 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2921 if ( $this->mOldRestrictions
!= '' ) {
2922 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2923 $temp = explode( '=', trim( $restrict ) );
2924 if ( count( $temp ) == 1 ) {
2925 // old old format should be treated as edit/move restriction
2926 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2927 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2929 $restriction = trim( $temp[1] );
2930 if ( $restriction != '' ) { // some old entries are empty
2931 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2937 if ( count( $rows ) ) {
2938 # Current system - load second to make them override.
2939 $now = wfTimestampNow();
2941 # Cycle through all the restrictions.
2942 foreach ( $rows as $row ) {
2943 // Don't take care of restrictions types that aren't allowed
2944 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2948 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2950 // Only apply the restrictions if they haven't expired!
2951 if ( !$expiry ||
$expiry > $now ) {
2952 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2953 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2955 $this->mCascadeRestriction |
= $row->pr_cascade
;
2960 $this->mRestrictionsLoaded
= true;
2964 * Load restrictions from the page_restrictions table
2966 * @param string $oldFashionedRestrictions Comma-separated list of page
2967 * restrictions from page table (pre 1.10)
2969 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2970 if ( $this->mRestrictionsLoaded
) {
2974 $id = $this->getArticleID();
2976 $cache = ObjectCache
::getMainWANInstance();
2977 $rows = $cache->getWithSetCallback(
2978 // Page protections always leave a new null revision
2979 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
2981 function ( $curValue, &$ttl, array &$setOpts ) {
2982 $dbr = wfGetDB( DB_REPLICA
);
2984 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2986 return iterator_to_array(
2988 'page_restrictions',
2989 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2990 [ 'pr_page' => $this->getArticleID() ],
2997 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2999 $title_protection = $this->getTitleProtectionInternal();
3001 if ( $title_protection ) {
3002 $now = wfTimestampNow();
3003 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3005 if ( !$expiry ||
$expiry > $now ) {
3006 // Apply the restrictions
3007 $this->mRestrictionsExpiry
['create'] = $expiry;
3008 $this->mRestrictions
['create'] =
3009 explode( ',', trim( $title_protection['permission'] ) );
3010 } else { // Get rid of the old restrictions
3011 $this->mTitleProtection
= false;
3014 $this->mRestrictionsExpiry
['create'] = 'infinity';
3016 $this->mRestrictionsLoaded
= true;
3021 * Flush the protection cache in this object and force reload from the database.
3022 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3024 public function flushRestrictions() {
3025 $this->mRestrictionsLoaded
= false;
3026 $this->mTitleProtection
= null;
3030 * Purge expired restrictions from the page_restrictions table
3032 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3034 static function purgeExpiredRestrictions() {
3035 if ( wfReadOnly() ) {
3039 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3040 wfGetDB( DB_MASTER
),
3042 function ( IDatabase
$dbw, $fname ) {
3043 $config = MediaWikiServices
::getInstance()->getMainConfig();
3044 $ids = $dbw->selectFieldValues(
3045 'page_restrictions',
3047 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3049 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3052 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3057 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3058 wfGetDB( DB_MASTER
),
3060 function ( IDatabase
$dbw, $fname ) {
3063 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3071 * Does this have subpages? (Warning, usually requires an extra DB query.)
3075 public function hasSubpages() {
3076 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3081 # We dynamically add a member variable for the purpose of this method
3082 # alone to cache the result. There's no point in having it hanging
3083 # around uninitialized in every Title object; therefore we only add it
3084 # if needed and don't declare it statically.
3085 if ( $this->mHasSubpages
=== null ) {
3086 $this->mHasSubpages
= false;
3087 $subpages = $this->getSubpages( 1 );
3088 if ( $subpages instanceof TitleArray
) {
3089 $this->mHasSubpages
= (bool)$subpages->count();
3093 return $this->mHasSubpages
;
3097 * Get all subpages of this page.
3099 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3100 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3101 * doesn't allow subpages
3103 public function getSubpages( $limit = -1 ) {
3104 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3108 $dbr = wfGetDB( DB_REPLICA
);
3109 $conds['page_namespace'] = $this->getNamespace();
3110 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3112 if ( $limit > -1 ) {
3113 $options['LIMIT'] = $limit;
3115 $this->mSubpages
= TitleArray
::newFromResult(
3116 $dbr->select( 'page',
3117 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3123 return $this->mSubpages
;
3127 * Is there a version of this page in the deletion archive?
3129 * @return int The number of archived revisions
3131 public function isDeleted() {
3132 if ( $this->getNamespace() < 0 ) {
3135 $dbr = wfGetDB( DB_REPLICA
);
3137 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3138 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3141 if ( $this->getNamespace() == NS_FILE
) {
3142 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3143 [ 'fa_name' => $this->getDBkey() ],
3152 * Is there a version of this page in the deletion archive?
3156 public function isDeletedQuick() {
3157 if ( $this->getNamespace() < 0 ) {
3160 $dbr = wfGetDB( DB_REPLICA
);
3161 $deleted = (bool)$dbr->selectField( 'archive', '1',
3162 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3165 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3166 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3167 [ 'fa_name' => $this->getDBkey() ],
3175 * Get the article ID for this Title from the link cache,
3176 * adding it if necessary
3178 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3180 * @return int The ID
3182 public function getArticleID( $flags = 0 ) {
3183 if ( $this->getNamespace() < 0 ) {
3184 $this->mArticleID
= 0;
3185 return $this->mArticleID
;
3187 $linkCache = LinkCache
::singleton();
3188 if ( $flags & self
::GAID_FOR_UPDATE
) {
3189 $oldUpdate = $linkCache->forUpdate( true );
3190 $linkCache->clearLink( $this );
3191 $this->mArticleID
= $linkCache->addLinkObj( $this );
3192 $linkCache->forUpdate( $oldUpdate );
3194 if ( -1 == $this->mArticleID
) {
3195 $this->mArticleID
= $linkCache->addLinkObj( $this );
3198 return $this->mArticleID
;
3202 * Is this an article that is a redirect page?
3203 * Uses link cache, adding it if necessary
3205 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3208 public function isRedirect( $flags = 0 ) {
3209 if ( !is_null( $this->mRedirect
) ) {
3210 return $this->mRedirect
;
3212 if ( !$this->getArticleID( $flags ) ) {
3213 $this->mRedirect
= false;
3214 return $this->mRedirect
;
3217 $linkCache = LinkCache
::singleton();
3218 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3219 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3220 if ( $cached === null ) {
3221 # Trust LinkCache's state over our own
3222 # LinkCache is telling us that the page doesn't exist, despite there being cached
3223 # data relating to an existing page in $this->mArticleID. Updaters should clear
3224 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3225 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3226 # LinkCache to refresh its data from the master.
3227 $this->mRedirect
= false;
3228 return $this->mRedirect
;
3231 $this->mRedirect
= (bool)$cached;
3233 return $this->mRedirect
;
3237 * What is the length of this page?
3238 * Uses link cache, adding it if necessary
3240 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3243 public function getLength( $flags = 0 ) {
3244 if ( $this->mLength
!= -1 ) {
3245 return $this->mLength
;
3247 if ( !$this->getArticleID( $flags ) ) {
3249 return $this->mLength
;
3251 $linkCache = LinkCache
::singleton();
3252 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3253 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3254 if ( $cached === null ) {
3255 # Trust LinkCache's state over our own, as for isRedirect()
3257 return $this->mLength
;
3260 $this->mLength
= intval( $cached );
3262 return $this->mLength
;
3266 * What is the page_latest field for this page?
3268 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3269 * @return int Int or 0 if the page doesn't exist
3271 public function getLatestRevID( $flags = 0 ) {
3272 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3273 return intval( $this->mLatestID
);
3275 if ( !$this->getArticleID( $flags ) ) {
3276 $this->mLatestID
= 0;
3277 return $this->mLatestID
;
3279 $linkCache = LinkCache
::singleton();
3280 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3281 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3282 if ( $cached === null ) {
3283 # Trust LinkCache's state over our own, as for isRedirect()
3284 $this->mLatestID
= 0;
3285 return $this->mLatestID
;
3288 $this->mLatestID
= intval( $cached );
3290 return $this->mLatestID
;
3294 * This clears some fields in this object, and clears any associated
3295 * keys in the "bad links" section of the link cache.
3297 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3298 * loading of the new page_id. It's also called from
3299 * WikiPage::doDeleteArticleReal()
3301 * @param int $newid The new Article ID
3303 public function resetArticleID( $newid ) {
3304 $linkCache = LinkCache
::singleton();
3305 $linkCache->clearLink( $this );
3307 if ( $newid === false ) {
3308 $this->mArticleID
= -1;
3310 $this->mArticleID
= intval( $newid );
3312 $this->mRestrictionsLoaded
= false;
3313 $this->mRestrictions
= [];
3314 $this->mOldRestrictions
= false;
3315 $this->mRedirect
= null;
3316 $this->mLength
= -1;
3317 $this->mLatestID
= false;
3318 $this->mContentModel
= false;
3319 $this->mEstimateRevisions
= null;
3320 $this->mPageLanguage
= false;
3321 $this->mDbPageLanguage
= false;
3322 $this->mIsBigDeletion
= null;
3325 public static function clearCaches() {
3326 $linkCache = LinkCache
::singleton();
3327 $linkCache->clear();
3329 $titleCache = self
::getTitleCache();
3330 $titleCache->clear();
3334 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3336 * @param string $text Containing title to capitalize
3337 * @param int $ns Namespace index, defaults to NS_MAIN
3338 * @return string Containing capitalized title
3340 public static function capitalize( $text, $ns = NS_MAIN
) {
3343 if ( MWNamespace
::isCapitalized( $ns ) ) {
3344 return $wgContLang->ucfirst( $text );
3351 * Secure and split - main initialisation function for this object
3353 * Assumes that mDbkeyform has been set, and is urldecoded
3354 * and uses underscores, but not otherwise munged. This function
3355 * removes illegal characters, splits off the interwiki and
3356 * namespace prefixes, sets the other forms, and canonicalizes
3359 * @throws MalformedTitleException On invalid titles
3360 * @return bool True on success
3362 private function secureAndSplit() {
3364 $this->mInterwiki
= '';
3365 $this->mFragment
= '';
3366 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3368 $dbkey = $this->mDbkeyform
;
3370 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3371 // the parsing code with Title, while avoiding massive refactoring.
3372 // @todo: get rid of secureAndSplit, refactor parsing code.
3373 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3374 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3375 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3376 // MalformedTitleException can be thrown here
3377 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3380 $this->setFragment( '#' . $parts['fragment'] );
3381 $this->mInterwiki
= $parts['interwiki'];
3382 $this->mLocalInterwiki
= $parts['local_interwiki'];
3383 $this->mNamespace
= $parts['namespace'];
3384 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3386 $this->mDbkeyform
= $parts['dbkey'];
3387 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3388 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3390 # We already know that some pages won't be in the database!
3391 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3392 $this->mArticleID
= 0;
3399 * Get an array of Title objects linking to this Title
3400 * Also stores the IDs in the link cache.
3402 * WARNING: do not use this function on arbitrary user-supplied titles!
3403 * On heavily-used templates it will max out the memory.
3405 * @param array $options May be FOR UPDATE
3406 * @param string $table Table name
3407 * @param string $prefix Fields prefix
3408 * @return Title[] Array of Title objects linking here
3410 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3411 if ( count( $options ) > 0 ) {
3412 $db = wfGetDB( DB_MASTER
);
3414 $db = wfGetDB( DB_REPLICA
);
3419 self
::getSelectFields(),
3421 "{$prefix}_from=page_id",
3422 "{$prefix}_namespace" => $this->getNamespace(),
3423 "{$prefix}_title" => $this->getDBkey() ],
3429 if ( $res->numRows() ) {
3430 $linkCache = LinkCache
::singleton();
3431 foreach ( $res as $row ) {
3432 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3434 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3435 $retVal[] = $titleObj;
3443 * Get an array of Title objects using this Title as a template
3444 * Also stores the IDs in the link cache.
3446 * WARNING: do not use this function on arbitrary user-supplied titles!
3447 * On heavily-used templates it will max out the memory.
3449 * @param array $options Query option to Database::select()
3450 * @return Title[] Array of Title the Title objects linking here
3452 public function getTemplateLinksTo( $options = [] ) {
3453 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3457 * Get an array of Title objects linked from this Title
3458 * Also stores the IDs in the link cache.
3460 * WARNING: do not use this function on arbitrary user-supplied titles!
3461 * On heavily-used templates it will max out the memory.
3463 * @param array $options Query option to Database::select()
3464 * @param string $table Table name
3465 * @param string $prefix Fields prefix
3466 * @return array Array of Title objects linking here
3468 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3469 $id = $this->getArticleID();
3471 # If the page doesn't exist; there can't be any link from this page
3476 $db = wfGetDB( DB_REPLICA
);
3478 $blNamespace = "{$prefix}_namespace";
3479 $blTitle = "{$prefix}_title";
3484 [ $blNamespace, $blTitle ],
3485 WikiPage
::selectFields()
3487 [ "{$prefix}_from" => $id ],
3492 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3497 $linkCache = LinkCache
::singleton();
3498 foreach ( $res as $row ) {
3499 if ( $row->page_id
) {
3500 $titleObj = Title
::newFromRow( $row );
3502 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3503 $linkCache->addBadLinkObj( $titleObj );
3505 $retVal[] = $titleObj;
3512 * Get an array of Title objects used on this Title as a template
3513 * Also stores the IDs in the link cache.
3515 * WARNING: do not use this function on arbitrary user-supplied titles!
3516 * On heavily-used templates it will max out the memory.
3518 * @param array $options May be FOR UPDATE
3519 * @return Title[] Array of Title the Title objects used here
3521 public function getTemplateLinksFrom( $options = [] ) {
3522 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3526 * Get an array of Title objects referring to non-existent articles linked
3529 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3530 * should use redirect table in this case).
3531 * @return Title[] Array of Title the Title objects
3533 public function getBrokenLinksFrom() {
3534 if ( $this->getArticleID() == 0 ) {
3535 # All links from article ID 0 are false positives
3539 $dbr = wfGetDB( DB_REPLICA
);
3540 $res = $dbr->select(
3541 [ 'page', 'pagelinks' ],
3542 [ 'pl_namespace', 'pl_title' ],
3544 'pl_from' => $this->getArticleID(),
3545 'page_namespace IS NULL'
3551 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3557 foreach ( $res as $row ) {
3558 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3564 * Get a list of URLs to purge from the CDN cache when this
3567 * @return string[] Array of String the URLs
3569 public function getCdnUrls() {
3571 $this->getInternalURL(),
3572 $this->getInternalURL( 'action=history' )
3575 $pageLang = $this->getPageLanguage();
3576 if ( $pageLang->hasVariants() ) {
3577 $variants = $pageLang->getVariants();
3578 foreach ( $variants as $vCode ) {
3579 $urls[] = $this->getInternalURL( $vCode );
3583 // If we are looking at a css/js user subpage, purge the action=raw.
3584 if ( $this->isJsSubpage() ) {
3585 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3586 } elseif ( $this->isCssSubpage() ) {
3587 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3590 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3595 * @deprecated since 1.27 use getCdnUrls()
3597 public function getSquidURLs() {
3598 return $this->getCdnUrls();
3602 * Purge all applicable CDN URLs
3604 public function purgeSquid() {
3605 DeferredUpdates
::addUpdate(
3606 new CdnCacheUpdate( $this->getCdnUrls() ),
3607 DeferredUpdates
::PRESEND
3612 * Check whether a given move operation would be valid.
3613 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3615 * @deprecated since 1.25, use MovePage's methods instead
3616 * @param Title $nt The new title
3617 * @param bool $auth Whether to check user permissions (uses $wgUser)
3618 * @param string $reason Is the log summary of the move, used for spam checking
3619 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3621 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3624 if ( !( $nt instanceof Title
) ) {
3625 // Normally we'd add this to $errors, but we'll get
3626 // lots of syntax errors if $nt is not an object
3627 return [ [ 'badtitletext' ] ];
3630 $mp = new MovePage( $this, $nt );
3631 $errors = $mp->isValidMove()->getErrorsArray();
3633 $errors = wfMergeErrorArrays(
3635 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3639 return $errors ?
: true;
3643 * Check if the requested move target is a valid file move target
3644 * @todo move this to MovePage
3645 * @param Title $nt Target title
3646 * @return array List of errors
3648 protected function validateFileMoveOperation( $nt ) {
3653 $destFile = wfLocalFile( $nt );
3654 $destFile->load( File
::READ_LATEST
);
3655 if ( !$wgUser->isAllowed( 'reupload-shared' )
3656 && !$destFile->exists() && wfFindFile( $nt )
3658 $errors[] = [ 'file-exists-sharedrepo' ];
3665 * Move a title to a new location
3667 * @deprecated since 1.25, use the MovePage class instead
3668 * @param Title $nt The new title
3669 * @param bool $auth Indicates whether $wgUser's permissions
3671 * @param string $reason The reason for the move
3672 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3673 * Ignored if the user doesn't have the suppressredirect right.
3674 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3675 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3677 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3678 array $changeTags = [] ) {
3681 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3682 if ( is_array( $err ) ) {
3683 // Auto-block user's IP if the account was "hard" blocked
3684 $wgUser->spreadAnyEditBlock();
3687 // Check suppressredirect permission
3688 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3689 $createRedirect = true;
3692 $mp = new MovePage( $this, $nt );
3693 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3694 if ( $status->isOK() ) {
3697 return $status->getErrorsArray();
3702 * Move this page's subpages to be subpages of $nt
3704 * @param Title $nt Move target
3705 * @param bool $auth Whether $wgUser's permissions should be checked
3706 * @param string $reason The reason for the move
3707 * @param bool $createRedirect Whether to create redirects from the old subpages to
3708 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3709 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3710 * @return array Array with old page titles as keys, and strings (new page titles) or
3711 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3712 * getUserPermissionsErrors()-like error array with numeric indices if
3713 * no pages were moved
3715 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3716 array $changeTags = [] ) {
3718 global $wgMaximumMovedPages;
3719 // Check permissions
3720 if ( !$this->userCan( 'move-subpages' ) ) {
3722 [ 'cant-move-subpages' ],
3725 // Do the source and target namespaces support subpages?
3726 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3728 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3731 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3733 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3737 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3740 foreach ( $subpages as $oldSubpage ) {
3742 if ( $count > $wgMaximumMovedPages ) {
3743 $retval[$oldSubpage->getPrefixedText()] = [
3744 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3749 // We don't know whether this function was called before
3750 // or after moving the root page, so check both
3752 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3753 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3755 // When moving a page to a subpage of itself,
3756 // don't move it twice
3759 $newPageName = preg_replace(
3760 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3761 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3762 $oldSubpage->getDBkey() );
3763 if ( $oldSubpage->isTalkPage() ) {
3764 $newNs = $nt->getTalkPage()->getNamespace();
3766 $newNs = $nt->getSubjectPage()->getNamespace();
3768 # T16385: we need makeTitleSafe because the new page names may
3769 # be longer than 255 characters.
3770 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3772 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3773 if ( $success === true ) {
3774 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3776 $retval[$oldSubpage->getPrefixedText()] = $success;
3783 * Checks if this page is just a one-rev redirect.
3784 * Adds lock, so don't use just for light purposes.
3788 public function isSingleRevRedirect() {
3789 global $wgContentHandlerUseDB;
3791 $dbw = wfGetDB( DB_MASTER
);
3794 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3795 if ( $wgContentHandlerUseDB ) {
3796 $fields[] = 'page_content_model';
3799 $row = $dbw->selectRow( 'page',
3805 # Cache some fields we may want
3806 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3807 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3808 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3809 $this->mContentModel
= $row && isset( $row->page_content_model
)
3810 ?
strval( $row->page_content_model
)
3813 if ( !$this->mRedirect
) {
3816 # Does the article have a history?
3817 $row = $dbw->selectField( [ 'page', 'revision' ],
3819 [ 'page_namespace' => $this->getNamespace(),
3820 'page_title' => $this->getDBkey(),
3822 'page_latest != rev_id'
3827 # Return true if there was no history
3828 return ( $row === false );
3832 * Checks if $this can be moved to a given Title
3833 * - Selects for update, so don't call it unless you mean business
3835 * @deprecated since 1.25, use MovePage's methods instead
3836 * @param Title $nt The new title to check
3839 public function isValidMoveTarget( $nt ) {
3840 # Is it an existing file?
3841 if ( $nt->getNamespace() == NS_FILE
) {
3842 $file = wfLocalFile( $nt );
3843 $file->load( File
::READ_LATEST
);
3844 if ( $file->exists() ) {
3845 wfDebug( __METHOD__
. ": file exists\n" );
3849 # Is it a redirect with no history?
3850 if ( !$nt->isSingleRevRedirect() ) {
3851 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3854 # Get the article text
3855 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3856 if ( !is_object( $rev ) ) {
3859 $content = $rev->getContent();
3860 # Does the redirect point to the source?
3861 # Or is it a broken self-redirect, usually caused by namespace collisions?
3862 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3864 if ( $redirTitle ) {
3865 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3866 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3867 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3873 # Fail safe (not a redirect after all. strange.)
3874 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3875 " is a redirect, but it doesn't contain a valid redirect.\n" );
3881 * Get categories to which this Title belongs and return an array of
3882 * categories' names.
3884 * @return array Array of parents in the form:
3885 * $parent => $currentarticle
3887 public function getParentCategories() {
3892 $titleKey = $this->getArticleID();
3894 if ( $titleKey === 0 ) {
3898 $dbr = wfGetDB( DB_REPLICA
);
3900 $res = $dbr->select(
3903 [ 'cl_from' => $titleKey ],
3907 if ( $res->numRows() > 0 ) {
3908 foreach ( $res as $row ) {
3909 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3910 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3917 * Get a tree of parent categories
3919 * @param array $children Array with the children in the keys, to check for circular refs
3920 * @return array Tree of parent categories
3922 public function getParentCategoryTree( $children = [] ) {
3924 $parents = $this->getParentCategories();
3927 foreach ( $parents as $parent => $current ) {
3928 if ( array_key_exists( $parent, $children ) ) {
3929 # Circular reference
3930 $stack[$parent] = [];
3932 $nt = Title
::newFromText( $parent );
3934 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3944 * Get an associative array for selecting this title from
3947 * @return array Array suitable for the $where parameter of DB::select()
3949 public function pageCond() {
3950 if ( $this->mArticleID
> 0 ) {
3951 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3952 return [ 'page_id' => $this->mArticleID
];
3954 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3959 * Get the revision ID of the previous revision
3961 * @param int $revId Revision ID. Get the revision that was before this one.
3962 * @param int $flags Title::GAID_FOR_UPDATE
3963 * @return int|bool Old revision ID, or false if none exists
3965 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3966 /* This function and getNextRevisionID have bad performance when
3967 used on a page with many revisions on mysql. An explicit extended
3968 primary key may help in some cases, if the PRIMARY KEY is banned:
3970 if ( $flags & self
::GAID_FOR_UPDATE
) {
3971 $db = wfGetDB( DB_MASTER
);
3973 $db = wfGetDB( DB_REPLICA
, 'contributions' );
3975 $revId = $db->selectField( 'revision', 'rev_id',
3977 'rev_page' => $this->getArticleID( $flags ),
3978 'rev_id < ' . intval( $revId )
3981 [ 'ORDER BY' => 'rev_id DESC', 'IGNORE INDEX' => 'PRIMARY' ]
3984 if ( $revId === false ) {
3987 return intval( $revId );
3992 * Get the revision ID of the next revision
3994 * @param int $revId Revision ID. Get the revision that was after this one.
3995 * @param int $flags Title::GAID_FOR_UPDATE
3996 * @return int|bool Next revision ID, or false if none exists
3998 public function getNextRevisionID( $revId, $flags = 0 ) {
3999 if ( $flags & self
::GAID_FOR_UPDATE
) {
4000 $db = wfGetDB( DB_MASTER
);
4002 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4004 $revId = $db->selectField( 'revision', 'rev_id',
4006 'rev_page' => $this->getArticleID( $flags ),
4007 'rev_id > ' . intval( $revId )
4010 [ 'ORDER BY' => 'rev_id', 'IGNORE INDEX' => 'PRIMARY' ]
4013 if ( $revId === false ) {
4016 return intval( $revId );
4021 * Get the first revision of the page
4023 * @param int $flags Title::GAID_FOR_UPDATE
4024 * @return Revision|null If page doesn't exist
4026 public function getFirstRevision( $flags = 0 ) {
4027 $pageId = $this->getArticleID( $flags );
4029 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4030 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4031 [ 'rev_page' => $pageId ],
4033 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
4036 return new Revision( $row );
4043 * Get the oldest revision timestamp of this page
4045 * @param int $flags Title::GAID_FOR_UPDATE
4046 * @return string MW timestamp
4048 public function getEarliestRevTime( $flags = 0 ) {
4049 $rev = $this->getFirstRevision( $flags );
4050 return $rev ?
$rev->getTimestamp() : null;
4054 * Check if this is a new page
4058 public function isNewPage() {
4059 $dbr = wfGetDB( DB_REPLICA
);
4060 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4064 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4068 public function isBigDeletion() {
4069 global $wgDeleteRevisionsLimit;
4071 if ( !$wgDeleteRevisionsLimit ) {
4075 if ( $this->mIsBigDeletion
=== null ) {
4076 $dbr = wfGetDB( DB_REPLICA
);
4078 $revCount = $dbr->selectRowCount(
4081 [ 'rev_page' => $this->getArticleID() ],
4083 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4086 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4089 return $this->mIsBigDeletion
;
4093 * Get the approximate revision count of this page.
4097 public function estimateRevisionCount() {
4098 if ( !$this->exists() ) {
4102 if ( $this->mEstimateRevisions
=== null ) {
4103 $dbr = wfGetDB( DB_REPLICA
);
4104 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4105 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4108 return $this->mEstimateRevisions
;
4112 * Get the number of revisions between the given revision.
4113 * Used for diffs and other things that really need it.
4115 * @param int|Revision $old Old revision or rev ID (first before range)
4116 * @param int|Revision $new New revision or rev ID (first after range)
4117 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4118 * @return int Number of revisions between these revisions.
4120 public function countRevisionsBetween( $old, $new, $max = null ) {
4121 if ( !( $old instanceof Revision
) ) {
4122 $old = Revision
::newFromTitle( $this, (int)$old );
4124 if ( !( $new instanceof Revision
) ) {
4125 $new = Revision
::newFromTitle( $this, (int)$new );
4127 if ( !$old ||
!$new ) {
4128 return 0; // nothing to compare
4130 $dbr = wfGetDB( DB_REPLICA
);
4132 'rev_page' => $this->getArticleID(),
4133 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4134 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4136 if ( $max !== null ) {
4137 return $dbr->selectRowCount( 'revision', '1',
4140 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4143 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4148 * Get the authors between the given revisions or revision IDs.
4149 * Used for diffs and other things that really need it.
4153 * @param int|Revision $old Old revision or rev ID (first before range by default)
4154 * @param int|Revision $new New revision or rev ID (first after range by default)
4155 * @param int $limit Maximum number of authors
4156 * @param string|array $options (Optional): Single option, or an array of options:
4157 * 'include_old' Include $old in the range; $new is excluded.
4158 * 'include_new' Include $new in the range; $old is excluded.
4159 * 'include_both' Include both $old and $new in the range.
4160 * Unknown option values are ignored.
4161 * @return array|null Names of revision authors in the range; null if not both revisions exist
4163 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4164 if ( !( $old instanceof Revision
) ) {
4165 $old = Revision
::newFromTitle( $this, (int)$old );
4167 if ( !( $new instanceof Revision
) ) {
4168 $new = Revision
::newFromTitle( $this, (int)$new );
4170 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4171 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4172 // in the sanity check below?
4173 if ( !$old ||
!$new ) {
4174 return null; // nothing to compare
4179 $options = (array)$options;
4180 if ( in_array( 'include_old', $options ) ) {
4183 if ( in_array( 'include_new', $options ) ) {
4186 if ( in_array( 'include_both', $options ) ) {
4190 // No DB query needed if $old and $new are the same or successive revisions:
4191 if ( $old->getId() === $new->getId() ) {
4192 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4194 [ $old->getUserText( Revision
::RAW
) ];
4195 } elseif ( $old->getId() === $new->getParentId() ) {
4196 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4197 $authors[] = $old->getUserText( Revision
::RAW
);
4198 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4199 $authors[] = $new->getUserText( Revision
::RAW
);
4201 } elseif ( $old_cmp === '>=' ) {
4202 $authors[] = $old->getUserText( Revision
::RAW
);
4203 } elseif ( $new_cmp === '<=' ) {
4204 $authors[] = $new->getUserText( Revision
::RAW
);
4208 $dbr = wfGetDB( DB_REPLICA
);
4209 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4211 'rev_page' => $this->getArticleID(),
4212 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4213 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4215 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4217 foreach ( $res as $row ) {
4218 $authors[] = $row->rev_user_text
;
4224 * Get the number of authors between the given revisions or revision IDs.
4225 * Used for diffs and other things that really need it.
4227 * @param int|Revision $old Old revision or rev ID (first before range by default)
4228 * @param int|Revision $new New revision or rev ID (first after range by default)
4229 * @param int $limit Maximum number of authors
4230 * @param string|array $options (Optional): Single option, or an array of options:
4231 * 'include_old' Include $old in the range; $new is excluded.
4232 * 'include_new' Include $new in the range; $old is excluded.
4233 * 'include_both' Include both $old and $new in the range.
4234 * Unknown option values are ignored.
4235 * @return int Number of revision authors in the range; zero if not both revisions exist
4237 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4238 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4239 return $authors ?
count( $authors ) : 0;
4243 * Compare with another title.
4245 * @param Title $title
4248 public function equals( Title
$title ) {
4249 // Note: === is necessary for proper matching of number-like titles.
4250 return $this->getInterwiki() === $title->getInterwiki()
4251 && $this->getNamespace() == $title->getNamespace()
4252 && $this->getDBkey() === $title->getDBkey();
4256 * Check if this title is a subpage of another title
4258 * @param Title $title
4261 public function isSubpageOf( Title
$title ) {
4262 return $this->getInterwiki() === $title->getInterwiki()
4263 && $this->getNamespace() == $title->getNamespace()
4264 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4268 * Check if page exists. For historical reasons, this function simply
4269 * checks for the existence of the title in the page table, and will
4270 * thus return false for interwiki links, special pages and the like.
4271 * If you want to know if a title can be meaningfully viewed, you should
4272 * probably call the isKnown() method instead.
4274 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4275 * from master/for update
4278 public function exists( $flags = 0 ) {
4279 $exists = $this->getArticleID( $flags ) != 0;
4280 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4285 * Should links to this title be shown as potentially viewable (i.e. as
4286 * "bluelinks"), even if there's no record by this title in the page
4289 * This function is semi-deprecated for public use, as well as somewhat
4290 * misleadingly named. You probably just want to call isKnown(), which
4291 * calls this function internally.
4293 * (ISSUE: Most of these checks are cheap, but the file existence check
4294 * can potentially be quite expensive. Including it here fixes a lot of
4295 * existing code, but we might want to add an optional parameter to skip
4296 * it and any other expensive checks.)
4300 public function isAlwaysKnown() {
4304 * Allows overriding default behavior for determining if a page exists.
4305 * If $isKnown is kept as null, regular checks happen. If it's
4306 * a boolean, this value is returned by the isKnown method.
4310 * @param Title $title
4311 * @param bool|null $isKnown
4313 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4315 if ( !is_null( $isKnown ) ) {
4319 if ( $this->isExternal() ) {
4320 return true; // any interwiki link might be viewable, for all we know
4323 switch ( $this->mNamespace
) {
4326 // file exists, possibly in a foreign repo
4327 return (bool)wfFindFile( $this );
4329 // valid special page
4330 return SpecialPageFactory
::exists( $this->getDBkey() );
4332 // selflink, possibly with fragment
4333 return $this->mDbkeyform
== '';
4335 // known system message
4336 return $this->hasSourceText() !== false;
4343 * Does this title refer to a page that can (or might) be meaningfully
4344 * viewed? In particular, this function may be used to determine if
4345 * links to the title should be rendered as "bluelinks" (as opposed to
4346 * "redlinks" to non-existent pages).
4347 * Adding something else to this function will cause inconsistency
4348 * since LinkHolderArray calls isAlwaysKnown() and does its own
4349 * page existence check.
4353 public function isKnown() {
4354 return $this->isAlwaysKnown() ||
$this->exists();
4358 * Does this page have source text?
4362 public function hasSourceText() {
4363 if ( $this->exists() ) {
4367 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4368 // If the page doesn't exist but is a known system message, default
4369 // message content will be displayed, same for language subpages-
4370 // Use always content language to avoid loading hundreds of languages
4371 // to get the link color.
4373 list( $name, ) = MessageCache
::singleton()->figureMessage(
4374 $wgContLang->lcfirst( $this->getText() )
4376 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4377 return $message->exists();
4384 * Get the default message text or false if the message doesn't exist
4386 * @return string|bool
4388 public function getDefaultMessageText() {
4391 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4395 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4396 $wgContLang->lcfirst( $this->getText() )
4398 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4400 if ( $message->exists() ) {
4401 return $message->plain();
4408 * Updates page_touched for this page; called from LinksUpdate.php
4410 * @param string $purgeTime [optional] TS_MW timestamp
4411 * @return bool True if the update succeeded
4413 public function invalidateCache( $purgeTime = null ) {
4414 if ( wfReadOnly() ) {
4416 } elseif ( $this->mArticleID
=== 0 ) {
4417 return true; // avoid gap locking if we know it's not there
4420 $dbw = wfGetDB( DB_MASTER
);
4421 $dbw->onTransactionPreCommitOrIdle( function () {
4422 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4425 $conds = $this->pageCond();
4426 DeferredUpdates
::addUpdate(
4427 new AutoCommitUpdate(
4430 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4431 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4434 [ 'page_touched' => $dbTimestamp ],
4435 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4438 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4441 DeferredUpdates
::PRESEND
4448 * Update page_touched timestamps and send CDN purge messages for
4449 * pages linking to this title. May be sent to the job queue depending
4450 * on the number of links. Typically called on create and delete.
4452 public function touchLinks() {
4453 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4454 if ( $this->getNamespace() == NS_CATEGORY
) {
4455 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4460 * Get the last touched timestamp
4462 * @param IDatabase $db Optional db
4463 * @return string|false Last-touched timestamp
4465 public function getTouched( $db = null ) {
4466 if ( $db === null ) {
4467 $db = wfGetDB( DB_REPLICA
);
4469 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4474 * Get the timestamp when this page was updated since the user last saw it.
4477 * @return string|null
4479 public function getNotificationTimestamp( $user = null ) {
4482 // Assume current user if none given
4486 // Check cache first
4487 $uid = $user->getId();
4491 // avoid isset here, as it'll return false for null entries
4492 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4493 return $this->mNotificationTimestamp
[$uid];
4495 // Don't cache too much!
4496 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4497 $this->mNotificationTimestamp
= [];
4500 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4501 $watchedItem = $store->getWatchedItem( $user, $this );
4502 if ( $watchedItem ) {
4503 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4505 $this->mNotificationTimestamp
[$uid] = false;
4508 return $this->mNotificationTimestamp
[$uid];
4512 * Generate strings used for xml 'id' names in monobook tabs
4514 * @param string $prepend Defaults to 'nstab-'
4515 * @return string XML 'id' name
4517 public function getNamespaceKey( $prepend = 'nstab-' ) {
4519 // Gets the subject namespace if this title
4520 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4521 // Checks if canonical namespace name exists for namespace
4522 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4523 // Uses canonical namespace name
4524 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4526 // Uses text of namespace
4527 $namespaceKey = $this->getSubjectNsText();
4529 // Makes namespace key lowercase
4530 $namespaceKey = $wgContLang->lc( $namespaceKey );
4532 if ( $namespaceKey == '' ) {
4533 $namespaceKey = 'main';
4535 // Changes file to image for backwards compatibility
4536 if ( $namespaceKey == 'file' ) {
4537 $namespaceKey = 'image';
4539 return $prepend . $namespaceKey;
4543 * Get all extant redirects to this Title
4545 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4546 * @return Title[] Array of Title redirects to this title
4548 public function getRedirectsHere( $ns = null ) {
4551 $dbr = wfGetDB( DB_REPLICA
);
4553 'rd_namespace' => $this->getNamespace(),
4554 'rd_title' => $this->getDBkey(),
4557 if ( $this->isExternal() ) {
4558 $where['rd_interwiki'] = $this->getInterwiki();
4560 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4562 if ( !is_null( $ns ) ) {
4563 $where['page_namespace'] = $ns;
4566 $res = $dbr->select(
4567 [ 'redirect', 'page' ],
4568 [ 'page_namespace', 'page_title' ],
4573 foreach ( $res as $row ) {
4574 $redirs[] = self
::newFromRow( $row );
4580 * Check if this Title is a valid redirect target
4584 public function isValidRedirectTarget() {
4585 global $wgInvalidRedirectTargets;
4587 if ( $this->isSpecialPage() ) {
4588 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4589 if ( $this->isSpecial( 'Userlogout' ) ) {
4593 foreach ( $wgInvalidRedirectTargets as $target ) {
4594 if ( $this->isSpecial( $target ) ) {
4604 * Get a backlink cache object
4606 * @return BacklinkCache
4608 public function getBacklinkCache() {
4609 return BacklinkCache
::get( $this );
4613 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4617 public function canUseNoindex() {
4618 global $wgExemptFromUserRobotsControl;
4620 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4621 ? MWNamespace
::getContentNamespaces()
4622 : $wgExemptFromUserRobotsControl;
4624 return !in_array( $this->mNamespace
, $bannedNamespaces );
4628 * Returns the raw sort key to be used for categories, with the specified
4629 * prefix. This will be fed to Collation::getSortKey() to get a
4630 * binary sortkey that can be used for actual sorting.
4632 * @param string $prefix The prefix to be used, specified using
4633 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4637 public function getCategorySortkey( $prefix = '' ) {
4638 $unprefixed = $this->getText();
4640 // Anything that uses this hook should only depend
4641 // on the Title object passed in, and should probably
4642 // tell the users to run updateCollations.php --force
4643 // in order to re-sort existing category relations.
4644 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4645 if ( $prefix !== '' ) {
4646 # Separate with a line feed, so the unprefixed part is only used as
4647 # a tiebreaker when two pages have the exact same prefix.
4648 # In UCA, tab is the only character that can sort above LF
4649 # so we strip both of them from the original prefix.
4650 $prefix = strtr( $prefix, "\n\t", ' ' );
4651 return "$prefix\n$unprefixed";
4657 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4658 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4659 * the db, it will return NULL.
4661 * @return string|null|bool
4663 private function getDbPageLanguageCode() {
4664 global $wgPageLanguageUseDB;
4666 // check, if the page language could be saved in the database, and if so and
4667 // the value is not requested already, lookup the page language using LinkCache
4668 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4669 $linkCache = LinkCache
::singleton();
4670 $linkCache->addLinkObj( $this );
4671 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4674 return $this->mDbPageLanguage
;
4678 * Get the language in which the content of this page is written in
4679 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4680 * e.g. $wgLang (such as special pages, which are in the user language).
4685 public function getPageLanguage() {
4686 global $wgLang, $wgLanguageCode;
4687 if ( $this->isSpecialPage() ) {
4688 // special pages are in the user language
4692 // Checking if DB language is set
4693 $dbPageLanguage = $this->getDbPageLanguageCode();
4694 if ( $dbPageLanguage ) {
4695 return wfGetLangObj( $dbPageLanguage );
4698 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4699 // Note that this may depend on user settings, so the cache should
4700 // be only per-request.
4701 // NOTE: ContentHandler::getPageLanguage() may need to load the
4702 // content to determine the page language!
4703 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4705 $contentHandler = ContentHandler
::getForTitle( $this );
4706 $langObj = $contentHandler->getPageLanguage( $this );
4707 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4709 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4716 * Get the language in which the content of this page is written when
4717 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4718 * e.g. $wgLang (such as special pages, which are in the user language).
4723 public function getPageViewLanguage() {
4726 if ( $this->isSpecialPage() ) {
4727 // If the user chooses a variant, the content is actually
4728 // in a language whose code is the variant code.
4729 $variant = $wgLang->getPreferredVariant();
4730 if ( $wgLang->getCode() !== $variant ) {
4731 return Language
::factory( $variant );
4737 // Checking if DB language is set
4738 $dbPageLanguage = $this->getDbPageLanguageCode();
4739 if ( $dbPageLanguage ) {
4740 $pageLang = wfGetLangObj( $dbPageLanguage );
4741 $variant = $pageLang->getPreferredVariant();
4742 if ( $pageLang->getCode() !== $variant ) {
4743 $pageLang = Language
::factory( $variant );
4749 // @note Can't be cached persistently, depends on user settings.
4750 // @note ContentHandler::getPageViewLanguage() may need to load the
4751 // content to determine the page language!
4752 $contentHandler = ContentHandler
::getForTitle( $this );
4753 $pageLang = $contentHandler->getPageViewLanguage( $this );
4758 * Get a list of rendered edit notices for this page.
4760 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4761 * they will already be wrapped in paragraphs.
4764 * @param int $oldid Revision ID that's being edited
4767 public function getEditNotices( $oldid = 0 ) {
4770 // Optional notice for the entire namespace
4771 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4772 $msg = wfMessage( $editnotice_ns );
4773 if ( $msg->exists() ) {
4774 $html = $msg->parseAsBlock();
4775 // Edit notices may have complex logic, but output nothing (T91715)
4776 if ( trim( $html ) !== '' ) {
4777 $notices[$editnotice_ns] = Html
::rawElement(
4781 'mw-editnotice-namespace',
4782 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4789 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4790 // Optional notice for page itself and any parent page
4791 $parts = explode( '/', $this->getDBkey() );
4792 $editnotice_base = $editnotice_ns;
4793 while ( count( $parts ) > 0 ) {
4794 $editnotice_base .= '-' . array_shift( $parts );
4795 $msg = wfMessage( $editnotice_base );
4796 if ( $msg->exists() ) {
4797 $html = $msg->parseAsBlock();
4798 if ( trim( $html ) !== '' ) {
4799 $notices[$editnotice_base] = Html
::rawElement(
4803 'mw-editnotice-base',
4804 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4812 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4813 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4814 $msg = wfMessage( $editnoticeText );
4815 if ( $msg->exists() ) {
4816 $html = $msg->parseAsBlock();
4817 if ( trim( $html ) !== '' ) {
4818 $notices[$editnoticeText] = Html
::rawElement(
4822 'mw-editnotice-page',
4823 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4831 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4838 public function __sleep() {
4846 'mDefaultNamespace',
4850 public function __wakeup() {
4851 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4852 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4853 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );