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\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
{
40 /** @var HashBagOStuff */
41 static private $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
111 /** @var string|bool */
112 protected $mOldRestrictions = false;
114 /** @var bool Cascade restrictions on this page to included templates and images? */
115 public $mCascadeRestriction;
117 /** Caching the results of getCascadeProtectionSources */
118 public $mCascadingRestrictions;
120 /** @var array When do the restrictions on this page expire? */
121 protected $mRestrictionsExpiry = [];
123 /** @var bool Are cascading restrictions in effect on this page? */
124 protected $mHasCascadingRestrictions;
126 /** @var array Where are the cascading restrictions coming from on this page? */
127 public $mCascadeSources;
129 /** @var bool Boolean for initialisation on demand */
130 public $mRestrictionsLoaded = false;
132 /** @var string Text form including namespace/interwiki, initialised on demand */
133 protected $mPrefixedText = null;
135 /** @var mixed Cached value for getTitleProtection (create protection) */
136 public $mTitleProtection;
139 * @var int Namespace index when there is no namespace. Don't change the
140 * following default, NS_MAIN is hardcoded in several places. See T2696.
141 * Zero except in {{transclusion}} tags.
143 public $mDefaultNamespace = NS_MAIN
;
145 /** @var int The page length, 0 for special pages */
146 protected $mLength = -1;
148 /** @var null Is the article at this title a redirect? */
149 public $mRedirect = null;
151 /** @var array Associative array of user ID -> timestamp/false */
152 private $mNotificationTimestamp = [];
154 /** @var bool Whether a page has any subpages */
155 private $mHasSubpages;
157 /** @var bool The (string) language code of the page's language and content code. */
158 private $mPageLanguage = false;
160 /** @var string|bool|null The page language code from the database, null if not saved in
161 * the database or false if not loaded, yet. */
162 private $mDbPageLanguage = false;
164 /** @var TitleValue A corresponding TitleValue object */
165 private $mTitleValue = null;
167 /** @var bool Would deleting this page be a big deletion? */
168 private $mIsBigDeletion = null;
172 * B/C kludge: provide a TitleParser for use by Title.
173 * Ideally, Title would have no methods that need this.
174 * Avoid usage of this singleton by using TitleValue
175 * and the associated services when possible.
177 * @return TitleFormatter
179 private static function getTitleFormatter() {
180 return MediaWikiServices
::getInstance()->getTitleFormatter();
184 * B/C kludge: provide an InterwikiLookup for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
189 * @return InterwikiLookup
191 private static function getInterwikiLookup() {
192 return MediaWikiServices
::getInstance()->getInterwikiLookup();
198 function __construct() {
202 * Create a new Title from a prefixed DB key
204 * @param string $key The database key, which has underscores
205 * instead of spaces, possibly including namespace and
207 * @return Title|null Title, or null on an error
209 public static function newFromDBkey( $key ) {
211 $t->mDbkeyform
= $key;
214 $t->secureAndSplit();
216 } catch ( MalformedTitleException
$ex ) {
222 * Create a new Title from a TitleValue
224 * @param TitleValue $titleValue Assumed to be safe.
228 public static function newFromTitleValue( TitleValue
$titleValue ) {
229 return self
::newFromLinkTarget( $titleValue );
233 * Create a new Title from a LinkTarget
235 * @param LinkTarget $linkTarget Assumed to be safe.
239 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
240 if ( $linkTarget instanceof Title
) {
241 // Special case if it's already a Title object
244 return self
::makeTitle(
245 $linkTarget->getNamespace(),
246 $linkTarget->getText(),
247 $linkTarget->getFragment(),
248 $linkTarget->getInterwiki()
253 * Create a new Title from text, such as what one would find in a link. De-
254 * codes any HTML entities in the text.
256 * @param string|int|null $text The link text; spaces, prefixes, and an
257 * initial ':' indicating the main namespace are accepted.
258 * @param int $defaultNamespace The namespace to use if none is specified
259 * by a prefix. If you want to force a specific namespace even if
260 * $text might begin with a namespace prefix, use makeTitle() or
262 * @throws InvalidArgumentException
263 * @return Title|null Title or null on an error.
265 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
266 // DWIM: Integers can be passed in here when page titles are used as array keys.
267 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
268 throw new InvalidArgumentException( '$text must be a string.' );
270 if ( $text === null ) {
275 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
276 } catch ( MalformedTitleException
$ex ) {
282 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
283 * rather than returning null.
285 * The exception subclasses encode detailed information about why the title is invalid.
287 * @see Title::newFromText
290 * @param string $text Title text to check
291 * @param int $defaultNamespace
292 * @throws MalformedTitleException If the title is invalid
295 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
296 if ( is_object( $text ) ) {
297 throw new MWException( '$text must be a string, given an object' );
300 $titleCache = self
::getTitleCache();
302 // Wiki pages often contain multiple links to the same page.
303 // Title normalization and parsing can become expensive on pages with many
304 // links, so we can save a little time by caching them.
305 // In theory these are value objects and won't get changed...
306 if ( $defaultNamespace == NS_MAIN
) {
307 $t = $titleCache->get( $text );
313 // Convert things like é ā or 〗 into normalized (T16952) text
314 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
317 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
318 $t->mDefaultNamespace
= intval( $defaultNamespace );
320 $t->secureAndSplit();
321 if ( $defaultNamespace == NS_MAIN
) {
322 $titleCache->set( $text, $t );
328 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
330 * Example of wrong and broken code:
331 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
333 * Example of right code:
334 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
336 * Create a new Title from URL-encoded text. Ensures that
337 * the given title's length does not exceed the maximum.
339 * @param string $url The title, as might be taken from a URL
340 * @return Title|null The new object, or null on an error
342 public static function newFromURL( $url ) {
345 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
346 # but some URLs used it as a space replacement and they still come
347 # from some external search tools.
348 if ( strpos( self
::legalChars(), '+' ) === false ) {
349 $url = strtr( $url, '+', ' ' );
352 $t->mDbkeyform
= strtr( $url, ' ', '_' );
355 $t->secureAndSplit();
357 } catch ( MalformedTitleException
$ex ) {
363 * @return HashBagOStuff
365 private static function getTitleCache() {
366 if ( self
::$titleCache == null ) {
367 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
369 return self
::$titleCache;
373 * Returns a list of fields that are to be selected for initializing Title
374 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
375 * whether to include page_content_model.
379 protected static function getSelectFields() {
380 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
383 'page_namespace', 'page_title', 'page_id',
384 'page_len', 'page_is_redirect', 'page_latest',
387 if ( $wgContentHandlerUseDB ) {
388 $fields[] = 'page_content_model';
391 if ( $wgPageLanguageUseDB ) {
392 $fields[] = 'page_lang';
399 * Create a new Title from an article ID
401 * @param int $id The page_id corresponding to the Title to create
402 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
403 * @return Title|null The new object, or null on an error
405 public static function newFromID( $id, $flags = 0 ) {
406 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
407 $row = $db->selectRow(
409 self
::getSelectFields(),
410 [ 'page_id' => $id ],
413 if ( $row !== false ) {
414 $title = Title
::newFromRow( $row );
422 * Make an array of titles from an array of IDs
424 * @param int[] $ids Array of IDs
425 * @return Title[] Array of Titles
427 public static function newFromIDs( $ids ) {
428 if ( !count( $ids ) ) {
431 $dbr = wfGetDB( DB_REPLICA
);
435 self
::getSelectFields(),
436 [ 'page_id' => $ids ],
441 foreach ( $res as $row ) {
442 $titles[] = Title
::newFromRow( $row );
448 * Make a Title object from a DB row
450 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
451 * @return Title Corresponding Title
453 public static function newFromRow( $row ) {
454 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
455 $t->loadFromRow( $row );
460 * Load Title object fields from a DB row.
461 * If false is given, the title will be treated as non-existing.
463 * @param stdClass|bool $row Database row
465 public function loadFromRow( $row ) {
466 if ( $row ) { // page found
467 if ( isset( $row->page_id
) ) {
468 $this->mArticleID
= (int)$row->page_id
;
470 if ( isset( $row->page_len
) ) {
471 $this->mLength
= (int)$row->page_len
;
473 if ( isset( $row->page_is_redirect
) ) {
474 $this->mRedirect
= (bool)$row->page_is_redirect
;
476 if ( isset( $row->page_latest
) ) {
477 $this->mLatestID
= (int)$row->page_latest
;
479 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
480 $this->mContentModel
= strval( $row->page_content_model
);
481 } elseif ( !$this->mForcedContentModel
) {
482 $this->mContentModel
= false; # initialized lazily in getContentModel()
484 if ( isset( $row->page_lang
) ) {
485 $this->mDbPageLanguage
= (string)$row->page_lang
;
487 if ( isset( $row->page_restrictions
) ) {
488 $this->mOldRestrictions
= $row->page_restrictions
;
490 } else { // page not found
491 $this->mArticleID
= 0;
493 $this->mRedirect
= false;
494 $this->mLatestID
= 0;
495 if ( !$this->mForcedContentModel
) {
496 $this->mContentModel
= false; # initialized lazily in getContentModel()
502 * Create a new Title from a namespace index and a DB key.
503 * It's assumed that $ns and $title are *valid*, for instance when
504 * they came directly from the database or a special page name.
505 * For convenience, spaces are converted to underscores so that
506 * eg user_text fields can be used directly.
508 * @param int $ns The namespace of the article
509 * @param string $title The unprefixed database key form
510 * @param string $fragment The link fragment (after the "#")
511 * @param string $interwiki The interwiki prefix
512 * @return Title The new object
514 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
516 $t->mInterwiki
= $interwiki;
517 $t->mFragment
= $fragment;
518 $t->mNamespace
= $ns = intval( $ns );
519 $t->mDbkeyform
= strtr( $title, ' ', '_' );
520 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
521 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
522 $t->mTextform
= strtr( $title, '_', ' ' );
523 $t->mContentModel
= false; # initialized lazily in getContentModel()
528 * Create a new Title from a namespace index and a DB key.
529 * The parameters will be checked for validity, which is a bit slower
530 * than makeTitle() but safer for user-provided data.
532 * @param int $ns The namespace of the article
533 * @param string $title Database key form
534 * @param string $fragment The link fragment (after the "#")
535 * @param string $interwiki Interwiki prefix
536 * @return Title|null The new object, or null on an error
538 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
539 if ( !MWNamespace
::exists( $ns ) ) {
544 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
547 $t->secureAndSplit();
549 } catch ( MalformedTitleException
$ex ) {
555 * Create a new Title for the Main Page
557 * @return Title The new object
559 public static function newMainPage() {
560 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
561 // Don't give fatal errors if the message is broken
563 $title = Title
::newFromText( 'Main Page' );
569 * Get the prefixed DB key associated with an ID
571 * @param int $id The page_id of the article
572 * @return Title|null An object representing the article, or null if no such article was found
574 public static function nameOf( $id ) {
575 $dbr = wfGetDB( DB_REPLICA
);
577 $s = $dbr->selectRow(
579 [ 'page_namespace', 'page_title' ],
580 [ 'page_id' => $id ],
583 if ( $s === false ) {
587 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
592 * Get a regex character class describing the legal characters in a link
594 * @return string The list of characters, not delimited
596 public static function legalChars() {
597 global $wgLegalTitleChars;
598 return $wgLegalTitleChars;
602 * Returns a simple regex that will match on characters and sequences invalid in titles.
603 * Note that this doesn't pick up many things that could be wrong with titles, but that
604 * replacing this regex with something valid will make many titles valid.
606 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
608 * @return string Regex string
610 static function getTitleInvalidRegex() {
611 wfDeprecated( __METHOD__
, '1.25' );
612 return MediaWikiTitleCodec
::getTitleInvalidRegex();
616 * Utility method for converting a character sequence from bytes to Unicode.
618 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
619 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
621 * @param string $byteClass
624 public static function convertByteClassToUnicodeClass( $byteClass ) {
625 $length = strlen( $byteClass );
627 $x0 = $x1 = $x2 = '';
629 $d0 = $d1 = $d2 = '';
630 // Decoded integer codepoints
631 $ord0 = $ord1 = $ord2 = 0;
633 $r0 = $r1 = $r2 = '';
637 $allowUnicode = false;
638 for ( $pos = 0; $pos < $length; $pos++
) {
639 // Shift the queues down
648 // Load the current input token and decoded values
649 $inChar = $byteClass[$pos];
650 if ( $inChar == '\\' ) {
651 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
652 $x0 = $inChar . $m[0];
653 $d0 = chr( hexdec( $m[1] ) );
654 $pos +
= strlen( $m[0] );
655 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
656 $x0 = $inChar . $m[0];
657 $d0 = chr( octdec( $m[0] ) );
658 $pos +
= strlen( $m[0] );
659 } elseif ( $pos +
1 >= $length ) {
662 $d0 = $byteClass[$pos +
1];
670 // Load the current re-encoded value
671 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
672 $r0 = sprintf( '\x%02x', $ord0 );
673 } elseif ( $ord0 >= 0x80 ) {
674 // Allow unicode if a single high-bit character appears
675 $r0 = sprintf( '\x%02x', $ord0 );
676 $allowUnicode = true;
677 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
683 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
685 if ( $ord2 > $ord0 ) {
687 } elseif ( $ord0 >= 0x80 ) {
689 $allowUnicode = true;
690 if ( $ord2 < 0x80 ) {
691 // Keep the non-unicode section of the range
698 // Reset state to the initial value
699 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
700 } elseif ( $ord2 < 0x80 ) {
705 if ( $ord1 < 0x80 ) {
708 if ( $ord0 < 0x80 ) {
711 if ( $allowUnicode ) {
712 $out .= '\u0080-\uFFFF';
718 * Make a prefixed DB key from a DB key and a namespace index
720 * @param int $ns Numerical representation of the namespace
721 * @param string $title The DB key form the title
722 * @param string $fragment The link fragment (after the "#")
723 * @param string $interwiki The interwiki prefix
724 * @param bool $canonicalNamespace If true, use the canonical name for
725 * $ns instead of the localized version.
726 * @return string The prefixed form of the title
728 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
729 $canonicalNamespace = false
733 if ( $canonicalNamespace ) {
734 $namespace = MWNamespace
::getCanonicalName( $ns );
736 $namespace = $wgContLang->getNsText( $ns );
738 $name = $namespace == '' ?
$title : "$namespace:$title";
739 if ( strval( $interwiki ) != '' ) {
740 $name = "$interwiki:$name";
742 if ( strval( $fragment ) != '' ) {
743 $name .= '#' . $fragment;
749 * Escape a text fragment, say from a link, for a URL
751 * @param string $fragment Containing a URL or link fragment (after the "#")
752 * @return string Escaped string
754 static function escapeFragmentForURL( $fragment ) {
755 # Note that we don't urlencode the fragment. urlencoded Unicode
756 # fragments appear not to work in IE (at least up to 7) or in at least
757 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
758 # to care if they aren't encoded.
759 return Sanitizer
::escapeId( $fragment, 'noninitial' );
763 * Callback for usort() to do title sorts by (namespace, title)
765 * @param LinkTarget $a
766 * @param LinkTarget $b
768 * @return int Result of string comparison, or namespace comparison
770 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
771 if ( $a->getNamespace() == $b->getNamespace() ) {
772 return strcmp( $a->getText(), $b->getText() );
774 return $a->getNamespace() - $b->getNamespace();
779 * Determine whether the object refers to a page within
780 * this project (either this wiki or a wiki with a local
781 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
783 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
785 public function isLocal() {
786 if ( $this->isExternal() ) {
787 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
789 return $iw->isLocal();
796 * Is this Title interwiki?
800 public function isExternal() {
801 return $this->mInterwiki
!== '';
805 * Get the interwiki prefix
807 * Use Title::isExternal to check if a interwiki is set
809 * @return string Interwiki prefix
811 public function getInterwiki() {
812 return $this->mInterwiki
;
816 * Was this a local interwiki link?
820 public function wasLocalInterwiki() {
821 return $this->mLocalInterwiki
;
825 * Determine whether the object refers to a page within
826 * this project and is transcludable.
828 * @return bool True if this is transcludable
830 public function isTrans() {
831 if ( !$this->isExternal() ) {
835 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
839 * Returns the DB name of the distant wiki which owns the object.
841 * @return string|false The DB name
843 public function getTransWikiID() {
844 if ( !$this->isExternal() ) {
848 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
852 * Get a TitleValue object representing this Title.
854 * @note Not all valid Titles have a corresponding valid TitleValue
855 * (e.g. TitleValues cannot represent page-local links that have a
856 * fragment but no title text).
858 * @return TitleValue|null
860 public function getTitleValue() {
861 if ( $this->mTitleValue
=== null ) {
863 $this->mTitleValue
= new TitleValue(
864 $this->getNamespace(),
866 $this->getFragment(),
867 $this->getInterwiki()
869 } catch ( InvalidArgumentException
$ex ) {
870 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
871 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
875 return $this->mTitleValue
;
879 * Get the text form (spaces not underscores) of the main part
881 * @return string Main part of the title
883 public function getText() {
884 return $this->mTextform
;
888 * Get the URL-encoded form of the main part
890 * @return string Main part of the title, URL-encoded
892 public function getPartialURL() {
893 return $this->mUrlform
;
897 * Get the main part with underscores
899 * @return string Main part of the title, with underscores
901 public function getDBkey() {
902 return $this->mDbkeyform
;
906 * Get the DB key with the initial letter case as specified by the user
908 * @return string DB key
910 function getUserCaseDBKey() {
911 if ( !is_null( $this->mUserCaseDBKey
) ) {
912 return $this->mUserCaseDBKey
;
914 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
915 return $this->mDbkeyform
;
920 * Get the namespace index, i.e. one of the NS_xxxx constants.
922 * @return int Namespace index
924 public function getNamespace() {
925 return $this->mNamespace
;
929 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
931 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
932 * @return string Content model id
934 public function getContentModel( $flags = 0 ) {
935 if ( !$this->mForcedContentModel
936 && ( !$this->mContentModel ||
$flags === Title
::GAID_FOR_UPDATE
)
937 && $this->getArticleID( $flags )
939 $linkCache = LinkCache
::singleton();
940 $linkCache->addLinkObj( $this ); # in case we already had an article ID
941 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
944 if ( !$this->mContentModel
) {
945 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
948 return $this->mContentModel
;
952 * Convenience method for checking a title's content model name
954 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
955 * @return bool True if $this->getContentModel() == $id
957 public function hasContentModel( $id ) {
958 return $this->getContentModel() == $id;
962 * Set a proposed content model for the page for permissions
963 * checking. This does not actually change the content model
966 * Additionally, you should make sure you've checked
967 * ContentHandler::canBeUsedOn() first.
970 * @param string $model CONTENT_MODEL_XXX constant
972 public function setContentModel( $model ) {
973 $this->mContentModel
= $model;
974 $this->mForcedContentModel
= true;
978 * Get the namespace text
980 * @return string|false Namespace text
982 public function getNsText() {
983 if ( $this->isExternal() ) {
984 // This probably shouldn't even happen,
985 // but for interwiki transclusion it sometimes does.
986 // Use the canonical namespaces if possible to try to
987 // resolve a foreign namespace.
988 if ( MWNamespace
::exists( $this->mNamespace
) ) {
989 return MWNamespace
::getCanonicalName( $this->mNamespace
);
994 $formatter = self
::getTitleFormatter();
995 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
996 } catch ( InvalidArgumentException
$ex ) {
997 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1003 * Get the namespace text of the subject (rather than talk) page
1005 * @return string Namespace text
1007 public function getSubjectNsText() {
1009 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1013 * Get the namespace text of the talk page
1015 * @return string Namespace text
1017 public function getTalkNsText() {
1019 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1023 * Can this title have a corresponding talk page?
1025 * @deprecated since 1.30, use canHaveTalkPage() instead.
1027 * @return bool True if this title either is a talk page or can have a talk page associated.
1029 public function canTalk() {
1030 return $this->canHaveTalkPage();
1034 * Can this title have a corresponding talk page?
1036 * @see MWNamespace::hasTalkNamespace
1038 * @return bool True if this title either is a talk page or can have a talk page associated.
1040 public function canHaveTalkPage() {
1041 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1045 * Is this in a namespace that allows actual pages?
1049 public function canExist() {
1050 return $this->mNamespace
>= NS_MAIN
;
1054 * Can this title be added to a user's watchlist?
1058 public function isWatchable() {
1059 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1063 * Returns true if this is a special page.
1067 public function isSpecialPage() {
1068 return $this->getNamespace() == NS_SPECIAL
;
1072 * Returns true if this title resolves to the named special page
1074 * @param string $name The special page name
1077 public function isSpecial( $name ) {
1078 if ( $this->isSpecialPage() ) {
1079 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1080 if ( $name == $thisName ) {
1088 * If the Title refers to a special page alias which is not the local default, resolve
1089 * the alias, and localise the name as necessary. Otherwise, return $this
1093 public function fixSpecialName() {
1094 if ( $this->isSpecialPage() ) {
1095 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1096 if ( $canonicalName ) {
1097 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1098 if ( $localName != $this->mDbkeyform
) {
1099 return Title
::makeTitle( NS_SPECIAL
, $localName );
1107 * Returns true if the title is inside the specified namespace.
1109 * Please make use of this instead of comparing to getNamespace()
1110 * This function is much more resistant to changes we may make
1111 * to namespaces than code that makes direct comparisons.
1112 * @param int $ns The namespace
1116 public function inNamespace( $ns ) {
1117 return MWNamespace
::equals( $this->getNamespace(), $ns );
1121 * Returns true if the title is inside one of the specified namespaces.
1123 * @param int|int[] $namespaces,... The namespaces to check for
1127 public function inNamespaces( /* ... */ ) {
1128 $namespaces = func_get_args();
1129 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1130 $namespaces = $namespaces[0];
1133 foreach ( $namespaces as $ns ) {
1134 if ( $this->inNamespace( $ns ) ) {
1143 * Returns true if the title has the same subject namespace as the
1144 * namespace specified.
1145 * For example this method will take NS_USER and return true if namespace
1146 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1147 * as their subject namespace.
1149 * This is MUCH simpler than individually testing for equivalence
1150 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1155 public function hasSubjectNamespace( $ns ) {
1156 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1160 * Is this Title in a namespace which contains content?
1161 * In other words, is this a content page, for the purposes of calculating
1166 public function isContentPage() {
1167 return MWNamespace
::isContent( $this->getNamespace() );
1171 * Would anybody with sufficient privileges be able to move this page?
1172 * Some pages just aren't movable.
1176 public function isMovable() {
1177 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1178 // Interwiki title or immovable namespace. Hooks don't get to override here
1183 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1188 * Is this the mainpage?
1189 * @note Title::newFromText seems to be sufficiently optimized by the title
1190 * cache that we don't need to over-optimize by doing direct comparisons and
1191 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1192 * ends up reporting something differently than $title->isMainPage();
1197 public function isMainPage() {
1198 return $this->equals( Title
::newMainPage() );
1202 * Is this a subpage?
1206 public function isSubpage() {
1207 return MWNamespace
::hasSubpages( $this->mNamespace
)
1208 ?
strpos( $this->getText(), '/' ) !== false
1213 * Is this a conversion table for the LanguageConverter?
1217 public function isConversionTable() {
1218 // @todo ConversionTable should become a separate content model.
1220 return $this->getNamespace() == NS_MEDIAWIKI
&&
1221 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1225 * Does that page contain wikitext, or it is JS, CSS or whatever?
1229 public function isWikitextPage() {
1230 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1234 * Could this page contain custom CSS or JavaScript for the global UI.
1235 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1236 * or CONTENT_MODEL_JAVASCRIPT.
1238 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1241 * Note that this method should not return true for pages that contain and
1242 * show "inactive" CSS or JS.
1245 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1247 public function isCssOrJsPage() {
1248 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1249 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1250 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1252 return $isCssOrJsPage;
1256 * Is this a .css or .js subpage of a user page?
1258 * @todo FIXME: Rename to isUserConfigPage()
1260 public function isCssJsSubpage() {
1261 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1262 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1263 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1267 * Trim down a .css or .js subpage title to get the corresponding skin name
1269 * @return string Containing skin name from .css or .js subpage title
1271 public function getSkinFromCssJsSubpage() {
1272 $subpage = explode( '/', $this->mTextform
);
1273 $subpage = $subpage[count( $subpage ) - 1];
1274 $lastdot = strrpos( $subpage, '.' );
1275 if ( $lastdot === false ) {
1276 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1278 return substr( $subpage, 0, $lastdot );
1282 * Is this a .css subpage of a user page?
1286 public function isCssSubpage() {
1287 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1288 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1292 * Is this a .js subpage of a user page?
1296 public function isJsSubpage() {
1297 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1298 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1302 * Is this a talk page of some sort?
1306 public function isTalkPage() {
1307 return MWNamespace
::isTalk( $this->getNamespace() );
1311 * Get a Title object associated with the talk page of this article
1313 * @return Title The object for the talk page
1315 public function getTalkPage() {
1316 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1320 * Get a title object associated with the subject page of this
1323 * @return Title The object for the subject page
1325 public function getSubjectPage() {
1326 // Is this the same title?
1327 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1328 if ( $this->getNamespace() == $subjectNS ) {
1331 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1335 * Get the other title for this page, if this is a subject page
1336 * get the talk page, if it is a subject page get the talk page
1339 * @throws MWException
1342 public function getOtherPage() {
1343 if ( $this->isSpecialPage() ) {
1344 throw new MWException( 'Special pages cannot have other pages' );
1346 if ( $this->isTalkPage() ) {
1347 return $this->getSubjectPage();
1349 return $this->getTalkPage();
1354 * Get the default namespace index, for when there is no namespace
1356 * @return int Default namespace index
1358 public function getDefaultNamespace() {
1359 return $this->mDefaultNamespace
;
1363 * Get the Title fragment (i.e.\ the bit after the #) in text form
1365 * Use Title::hasFragment to check for a fragment
1367 * @return string Title fragment
1369 public function getFragment() {
1370 return $this->mFragment
;
1374 * Check if a Title fragment is set
1379 public function hasFragment() {
1380 return $this->mFragment
!== '';
1384 * Get the fragment in URL form, including the "#" character if there is one
1385 * @return string Fragment in URL form
1387 public function getFragmentForURL() {
1388 if ( !$this->hasFragment() ) {
1391 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1396 * Set the fragment for this title. Removes the first character from the
1397 * specified fragment before setting, so it assumes you're passing it with
1400 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1401 * or Title::createFragmentTarget().
1402 * Still in active use privately.
1405 * @param string $fragment Text
1407 public function setFragment( $fragment ) {
1408 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1412 * Creates a new Title for a different fragment of the same page.
1415 * @param string $fragment
1418 public function createFragmentTarget( $fragment ) {
1419 return self
::makeTitle(
1420 $this->getNamespace(),
1423 $this->getInterwiki()
1428 * Prefix some arbitrary text with the namespace or interwiki prefix
1431 * @param string $name The text
1432 * @return string The prefixed text
1434 private function prefix( $name ) {
1438 if ( $this->isExternal() ) {
1439 $p = $this->mInterwiki
. ':';
1442 if ( 0 != $this->mNamespace
) {
1443 $nsText = $this->getNsText();
1445 if ( $nsText === false ) {
1446 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1447 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1450 $p .= $nsText . ':';
1456 * Get the prefixed database key form
1458 * @return string The prefixed title, with underscores and
1459 * any interwiki and namespace prefixes
1461 public function getPrefixedDBkey() {
1462 $s = $this->prefix( $this->mDbkeyform
);
1463 $s = strtr( $s, ' ', '_' );
1468 * Get the prefixed title with spaces.
1469 * This is the form usually used for display
1471 * @return string The prefixed title, with spaces
1473 public function getPrefixedText() {
1474 if ( $this->mPrefixedText
=== null ) {
1475 $s = $this->prefix( $this->mTextform
);
1476 $s = strtr( $s, '_', ' ' );
1477 $this->mPrefixedText
= $s;
1479 return $this->mPrefixedText
;
1483 * Return a string representation of this title
1485 * @return string Representation of this title
1487 public function __toString() {
1488 return $this->getPrefixedText();
1492 * Get the prefixed title with spaces, plus any fragment
1493 * (part beginning with '#')
1495 * @return string The prefixed title, with spaces and the fragment, including '#'
1497 public function getFullText() {
1498 $text = $this->getPrefixedText();
1499 if ( $this->hasFragment() ) {
1500 $text .= '#' . $this->getFragment();
1506 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1510 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1514 * @return string Root name
1517 public function getRootText() {
1518 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1519 return $this->getText();
1522 return strtok( $this->getText(), '/' );
1526 * Get the root page name title, i.e. the leftmost part before any slashes
1530 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1531 * # returns: Title{User:Foo}
1534 * @return Title Root title
1537 public function getRootTitle() {
1538 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1542 * Get the base page name without a namespace, i.e. the part before the subpage name
1546 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1547 * # returns: 'Foo/Bar'
1550 * @return string Base name
1552 public function getBaseText() {
1553 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1554 return $this->getText();
1557 $parts = explode( '/', $this->getText() );
1558 # Don't discard the real title if there's no subpage involved
1559 if ( count( $parts ) > 1 ) {
1560 unset( $parts[count( $parts ) - 1] );
1562 return implode( '/', $parts );
1566 * Get the base page name title, i.e. the part before the subpage name
1570 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1571 * # returns: Title{User:Foo/Bar}
1574 * @return Title Base title
1577 public function getBaseTitle() {
1578 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1582 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1586 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1590 * @return string Subpage name
1592 public function getSubpageText() {
1593 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1594 return $this->mTextform
;
1596 $parts = explode( '/', $this->mTextform
);
1597 return $parts[count( $parts ) - 1];
1601 * Get the title for a subpage of the current page
1605 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1606 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1609 * @param string $text The subpage name to add to the title
1610 * @return Title Subpage title
1613 public function getSubpage( $text ) {
1614 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1618 * Get a URL-encoded form of the subpage text
1620 * @return string URL-encoded subpage name
1622 public function getSubpageUrlForm() {
1623 $text = $this->getSubpageText();
1624 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1629 * Get a URL-encoded title (not an actual URL) including interwiki
1631 * @return string The URL-encoded form
1633 public function getPrefixedURL() {
1634 $s = $this->prefix( $this->mDbkeyform
);
1635 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1640 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1641 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1642 * second argument named variant. This was deprecated in favor
1643 * of passing an array of option with a "variant" key
1644 * Once $query2 is removed for good, this helper can be dropped
1645 * and the wfArrayToCgi moved to getLocalURL();
1647 * @since 1.19 (r105919)
1648 * @param array|string $query
1649 * @param string|string[]|bool $query2
1652 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1653 if ( $query2 !== false ) {
1654 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1655 "method called with a second parameter is deprecated. Add your " .
1656 "parameter to an array passed as the first parameter.", "1.19" );
1658 if ( is_array( $query ) ) {
1659 $query = wfArrayToCgi( $query );
1662 if ( is_string( $query2 ) ) {
1663 // $query2 is a string, we will consider this to be
1664 // a deprecated $variant argument and add it to the query
1665 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1667 $query2 = wfArrayToCgi( $query2 );
1669 // If we have $query content add a & to it first
1673 // Now append the queries together
1680 * Get a real URL referring to this title, with interwiki link and
1683 * @see self::getLocalURL for the arguments.
1685 * @param string|string[] $query
1686 * @param string|string[]|bool $query2
1687 * @param string $proto Protocol type to use in URL
1688 * @return string The URL
1690 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1691 $query = self
::fixUrlQueryArgs( $query, $query2 );
1693 # Hand off all the decisions on urls to getLocalURL
1694 $url = $this->getLocalURL( $query );
1696 # Expand the url to make it a full url. Note that getLocalURL has the
1697 # potential to output full urls for a variety of reasons, so we use
1698 # wfExpandUrl instead of simply prepending $wgServer
1699 $url = wfExpandUrl( $url, $proto );
1701 # Finally, add the fragment.
1702 $url .= $this->getFragmentForURL();
1703 // Avoid PHP 7.1 warning from passing $this by reference
1705 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1710 * Get a url appropriate for making redirects based on an untrusted url arg
1712 * This is basically the same as getFullUrl(), but in the case of external
1713 * interwikis, we send the user to a landing page, to prevent possible
1714 * phishing attacks and the like.
1716 * @note Uses current protocol by default, since technically relative urls
1717 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1718 * places where the url gets cached, as might pollute between
1719 * https and non-https users.
1720 * @see self::getLocalURL for the arguments.
1721 * @param array|string $query
1722 * @param string $proto Protocol type to use in URL
1723 * @return String. A url suitable to use in an HTTP location header.
1725 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1727 if ( $this->isExternal() ) {
1728 $target = SpecialPage
::getTitleFor(
1730 $this->getPrefixedDBKey()
1733 return $target->getFullUrl( $query, false, $proto );
1737 * Get a URL with no fragment or server name (relative URL) from a Title object.
1738 * If this page is generated with action=render, however,
1739 * $wgServer is prepended to make an absolute URL.
1741 * @see self::getFullURL to always get an absolute URL.
1742 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1743 * valid to link, locally, to the current Title.
1744 * @see self::newFromText to produce a Title object.
1746 * @param string|string[] $query An optional query string,
1747 * not used for interwiki links. Can be specified as an associative array as well,
1748 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1749 * Some query patterns will trigger various shorturl path replacements.
1750 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1751 * be an array. If a string is passed it will be interpreted as a deprecated
1752 * variant argument and urlencoded into a variant= argument.
1753 * This second query argument will be added to the $query
1754 * The second parameter is deprecated since 1.19. Pass it as a key,value
1755 * pair in the first parameter array instead.
1757 * @return string String of the URL.
1759 public function getLocalURL( $query = '', $query2 = false ) {
1760 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1762 $query = self
::fixUrlQueryArgs( $query, $query2 );
1764 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1766 $namespace = $this->getNsText();
1767 if ( $namespace != '' ) {
1768 # Can this actually happen? Interwikis shouldn't be parsed.
1769 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1772 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1773 $url = wfAppendQuery( $url, $query );
1775 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1776 if ( $query == '' ) {
1777 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1778 // Avoid PHP 7.1 warning from passing $this by reference
1780 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1782 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1786 if ( !empty( $wgActionPaths )
1787 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1789 $action = urldecode( $matches[2] );
1790 if ( isset( $wgActionPaths[$action] ) ) {
1791 $query = $matches[1];
1792 if ( isset( $matches[4] ) ) {
1793 $query .= $matches[4];
1795 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1796 if ( $query != '' ) {
1797 $url = wfAppendQuery( $url, $query );
1803 && $wgVariantArticlePath
1804 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1805 && $this->getPageLanguage()->equals( $wgContLang )
1806 && $this->getPageLanguage()->hasVariants()
1808 $variant = urldecode( $matches[1] );
1809 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1810 // Only do the variant replacement if the given variant is a valid
1811 // variant for the page's language.
1812 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1813 $url = str_replace( '$1', $dbkey, $url );
1817 if ( $url === false ) {
1818 if ( $query == '-' ) {
1821 $url = "{$wgScript}?title={$dbkey}&{$query}";
1824 // Avoid PHP 7.1 warning from passing $this by reference
1826 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1828 // @todo FIXME: This causes breakage in various places when we
1829 // actually expected a local URL and end up with dupe prefixes.
1830 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1831 $url = $wgServer . $url;
1834 // Avoid PHP 7.1 warning from passing $this by reference
1836 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1841 * Get a URL that's the simplest URL that will be valid to link, locally,
1842 * to the current Title. It includes the fragment, but does not include
1843 * the server unless action=render is used (or the link is external). If
1844 * there's a fragment but the prefixed text is empty, we just return a link
1847 * The result obviously should not be URL-escaped, but does need to be
1848 * HTML-escaped if it's being output in HTML.
1850 * @param string|string[] $query
1851 * @param bool $query2
1852 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1853 * or false (default) for no expansion
1854 * @see self::getLocalURL for the arguments.
1855 * @return string The URL
1857 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1858 if ( $this->isExternal() ||
$proto !== false ) {
1859 $ret = $this->getFullURL( $query, $query2, $proto );
1860 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1861 $ret = $this->getFragmentForURL();
1863 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1869 * Get the URL form for an internal link.
1870 * - Used in various CDN-related code, in case we have a different
1871 * internal hostname for the server from the exposed one.
1873 * This uses $wgInternalServer to qualify the path, or $wgServer
1874 * if $wgInternalServer is not set. If the server variable used is
1875 * protocol-relative, the URL will be expanded to http://
1877 * @see self::getLocalURL for the arguments.
1878 * @return string The URL
1880 public function getInternalURL( $query = '', $query2 = false ) {
1881 global $wgInternalServer, $wgServer;
1882 $query = self
::fixUrlQueryArgs( $query, $query2 );
1883 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1884 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1885 // Avoid PHP 7.1 warning from passing $this by reference
1887 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1892 * Get the URL for a canonical link, for use in things like IRC and
1893 * e-mail notifications. Uses $wgCanonicalServer and the
1894 * GetCanonicalURL hook.
1896 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1898 * @see self::getLocalURL for the arguments.
1899 * @return string The URL
1902 public function getCanonicalURL( $query = '', $query2 = false ) {
1903 $query = self
::fixUrlQueryArgs( $query, $query2 );
1904 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1905 // Avoid PHP 7.1 warning from passing $this by reference
1907 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1912 * Get the edit URL for this Title
1914 * @return string The URL, or a null string if this is an interwiki link
1916 public function getEditURL() {
1917 if ( $this->isExternal() ) {
1920 $s = $this->getLocalURL( 'action=edit' );
1926 * Can $user perform $action on this page?
1927 * This skips potentially expensive cascading permission checks
1928 * as well as avoids expensive error formatting
1930 * Suitable for use for nonessential UI controls in common cases, but
1931 * _not_ for functional access control.
1933 * May provide false positives, but should never provide a false negative.
1935 * @param string $action Action that permission needs to be checked for
1936 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1939 public function quickUserCan( $action, $user = null ) {
1940 return $this->userCan( $action, $user, false );
1944 * Can $user perform $action on this page?
1946 * @param string $action Action that permission needs to be checked for
1947 * @param User $user User to check (since 1.19); $wgUser will be used if not
1949 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1952 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1953 if ( !$user instanceof User
) {
1958 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1962 * Can $user perform $action on this page?
1964 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1966 * @param string $action Action that permission needs to be checked for
1967 * @param User $user User to check
1968 * @param string $rigor One of (quick,full,secure)
1969 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1970 * - full : does cheap and expensive checks possibly from a replica DB
1971 * - secure : does cheap and expensive checks, using the master as needed
1972 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1973 * whose corresponding errors may be ignored.
1974 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1976 public function getUserPermissionsErrors(
1977 $action, $user, $rigor = 'secure', $ignoreErrors = []
1979 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1981 // Remove the errors being ignored.
1982 foreach ( $errors as $index => $error ) {
1983 $errKey = is_array( $error ) ?
$error[0] : $error;
1985 if ( in_array( $errKey, $ignoreErrors ) ) {
1986 unset( $errors[$index] );
1988 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1989 unset( $errors[$index] );
1997 * Permissions checks that fail most often, and which are easiest to test.
1999 * @param string $action The action to check
2000 * @param User $user User to check
2001 * @param array $errors List of current errors
2002 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2003 * @param bool $short Short circuit on first error
2005 * @return array List of errors
2007 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2008 if ( !Hooks
::run( 'TitleQuickPermissions',
2009 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2014 if ( $action == 'create' ) {
2016 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2017 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2019 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2021 } elseif ( $action == 'move' ) {
2022 if ( !$user->isAllowed( 'move-rootuserpages' )
2023 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2024 // Show user page-specific message only if the user can move other pages
2025 $errors[] = [ 'cant-move-user-page' ];
2028 // Check if user is allowed to move files if it's a file
2029 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2030 $errors[] = [ 'movenotallowedfile' ];
2033 // Check if user is allowed to move category pages if it's a category page
2034 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2035 $errors[] = [ 'cant-move-category-page' ];
2038 if ( !$user->isAllowed( 'move' ) ) {
2039 // User can't move anything
2040 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2041 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2042 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2043 // custom message if logged-in users without any special rights can move
2044 $errors[] = [ 'movenologintext' ];
2046 $errors[] = [ 'movenotallowed' ];
2049 } elseif ( $action == 'move-target' ) {
2050 if ( !$user->isAllowed( 'move' ) ) {
2051 // User can't move anything
2052 $errors[] = [ 'movenotallowed' ];
2053 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2054 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2055 // Show user page-specific message only if the user can move other pages
2056 $errors[] = [ 'cant-move-to-user-page' ];
2057 } elseif ( !$user->isAllowed( 'move-categorypages' )
2058 && $this->mNamespace
== NS_CATEGORY
) {
2059 // Show category page-specific message only if the user can move other pages
2060 $errors[] = [ 'cant-move-to-category-page' ];
2062 } elseif ( !$user->isAllowed( $action ) ) {
2063 $errors[] = $this->missingPermissionError( $action, $short );
2070 * Add the resulting error code to the errors array
2072 * @param array $errors List of current errors
2073 * @param array $result Result of errors
2075 * @return array List of errors
2077 private function resultToError( $errors, $result ) {
2078 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2079 // A single array representing an error
2080 $errors[] = $result;
2081 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2082 // A nested array representing multiple errors
2083 $errors = array_merge( $errors, $result );
2084 } elseif ( $result !== '' && is_string( $result ) ) {
2085 // A string representing a message-id
2086 $errors[] = [ $result ];
2087 } elseif ( $result instanceof MessageSpecifier
) {
2088 // A message specifier representing an error
2089 $errors[] = [ $result ];
2090 } elseif ( $result === false ) {
2091 // a generic "We don't want them to do that"
2092 $errors[] = [ 'badaccess-group0' ];
2098 * Check various permission hooks
2100 * @param string $action The action to check
2101 * @param User $user User to check
2102 * @param array $errors List of current errors
2103 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2104 * @param bool $short Short circuit on first error
2106 * @return array List of errors
2108 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2109 // Use getUserPermissionsErrors instead
2111 // Avoid PHP 7.1 warning from passing $this by reference
2113 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2114 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2116 // Check getUserPermissionsErrors hook
2117 // Avoid PHP 7.1 warning from passing $this by reference
2119 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2120 $errors = $this->resultToError( $errors, $result );
2122 // Check getUserPermissionsErrorsExpensive hook
2125 && !( $short && count( $errors ) > 0 )
2126 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2128 $errors = $this->resultToError( $errors, $result );
2135 * Check permissions on special pages & namespaces
2137 * @param string $action The action to check
2138 * @param User $user User to check
2139 * @param array $errors List of current errors
2140 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2141 * @param bool $short Short circuit on first error
2143 * @return array List of errors
2145 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2146 # Only 'createaccount' can be performed on special pages,
2147 # which don't actually exist in the DB.
2148 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2149 $errors[] = [ 'ns-specialprotected' ];
2152 # Check $wgNamespaceProtection for restricted namespaces
2153 if ( $this->isNamespaceProtected( $user ) ) {
2154 $ns = $this->mNamespace
== NS_MAIN ?
2155 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2156 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2157 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2164 * Check CSS/JS sub-page permissions
2166 * @param string $action The action to check
2167 * @param User $user User to check
2168 * @param array $errors List of current errors
2169 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2170 * @param bool $short Short circuit on first error
2172 * @return array List of errors
2174 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2175 # Protect css/js subpages of user pages
2176 # XXX: this might be better using restrictions
2177 if ( $action != 'patrol' ) {
2178 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2179 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2180 $errors[] = [ 'mycustomcssprotected', $action ];
2181 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2182 $errors[] = [ 'mycustomjsprotected', $action ];
2185 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2186 $errors[] = [ 'customcssprotected', $action ];
2187 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2188 $errors[] = [ 'customjsprotected', $action ];
2197 * Check against page_restrictions table requirements on this
2198 * page. The user must possess all required rights for this
2201 * @param string $action The action to check
2202 * @param User $user User to check
2203 * @param array $errors List of current errors
2204 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2205 * @param bool $short Short circuit on first error
2207 * @return array List of errors
2209 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2210 foreach ( $this->getRestrictions( $action ) as $right ) {
2211 // Backwards compatibility, rewrite sysop -> editprotected
2212 if ( $right == 'sysop' ) {
2213 $right = 'editprotected';
2215 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2216 if ( $right == 'autoconfirmed' ) {
2217 $right = 'editsemiprotected';
2219 if ( $right == '' ) {
2222 if ( !$user->isAllowed( $right ) ) {
2223 $errors[] = [ 'protectedpagetext', $right, $action ];
2224 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2225 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2233 * Check restrictions on cascading pages.
2235 * @param string $action The action to check
2236 * @param User $user User to check
2237 * @param array $errors List of current errors
2238 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2239 * @param bool $short Short circuit on first error
2241 * @return array List of errors
2243 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2244 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2245 # We /could/ use the protection level on the source page, but it's
2246 # fairly ugly as we have to establish a precedence hierarchy for pages
2247 # included by multiple cascade-protected pages. So just restrict
2248 # it to people with 'protect' permission, as they could remove the
2249 # protection anyway.
2250 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2251 # Cascading protection depends on more than this page...
2252 # Several cascading protected pages may include this page...
2253 # Check each cascading level
2254 # This is only for protection restrictions, not for all actions
2255 if ( isset( $restrictions[$action] ) ) {
2256 foreach ( $restrictions[$action] as $right ) {
2257 // Backwards compatibility, rewrite sysop -> editprotected
2258 if ( $right == 'sysop' ) {
2259 $right = 'editprotected';
2261 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2262 if ( $right == 'autoconfirmed' ) {
2263 $right = 'editsemiprotected';
2265 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2267 foreach ( $cascadingSources as $page ) {
2268 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2270 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2280 * Check action permissions not already checked in checkQuickPermissions
2282 * @param string $action The action to check
2283 * @param User $user User to check
2284 * @param array $errors List of current errors
2285 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2286 * @param bool $short Short circuit on first error
2288 * @return array List of errors
2290 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2291 global $wgDeleteRevisionsLimit, $wgLang;
2293 if ( $action == 'protect' ) {
2294 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2295 // If they can't edit, they shouldn't protect.
2296 $errors[] = [ 'protect-cantedit' ];
2298 } elseif ( $action == 'create' ) {
2299 $title_protection = $this->getTitleProtection();
2300 if ( $title_protection ) {
2301 if ( $title_protection['permission'] == ''
2302 ||
!$user->isAllowed( $title_protection['permission'] )
2306 User
::whoIs( $title_protection['user'] ),
2307 $title_protection['reason']
2311 } elseif ( $action == 'move' ) {
2312 // Check for immobile pages
2313 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2314 // Specific message for this case
2315 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2316 } elseif ( !$this->isMovable() ) {
2317 // Less specific message for rarer cases
2318 $errors[] = [ 'immobile-source-page' ];
2320 } elseif ( $action == 'move-target' ) {
2321 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2322 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2323 } elseif ( !$this->isMovable() ) {
2324 $errors[] = [ 'immobile-target-page' ];
2326 } elseif ( $action == 'delete' ) {
2327 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2328 if ( !$tempErrors ) {
2329 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2330 $user, $tempErrors, $rigor, true );
2332 if ( $tempErrors ) {
2333 // If protection keeps them from editing, they shouldn't be able to delete.
2334 $errors[] = [ 'deleteprotected' ];
2336 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2337 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2339 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2341 } elseif ( $action === 'undelete' ) {
2342 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2343 // Undeleting implies editing
2344 $errors[] = [ 'undelete-cantedit' ];
2346 if ( !$this->exists()
2347 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2349 // Undeleting where nothing currently exists implies creating
2350 $errors[] = [ 'undelete-cantcreate' ];
2357 * Check that the user isn't blocked from editing.
2359 * @param string $action The action to check
2360 * @param User $user User to check
2361 * @param array $errors List of current errors
2362 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2363 * @param bool $short Short circuit on first error
2365 * @return array List of errors
2367 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2368 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2369 // Account creation blocks handled at userlogin.
2370 // Unblocking handled in SpecialUnblock
2371 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2375 // Optimize for a very common case
2376 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2380 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2381 $errors[] = [ 'confirmedittext' ];
2384 $useSlave = ( $rigor !== 'secure' );
2385 if ( ( $action == 'edit' ||
$action == 'create' )
2386 && !$user->isBlockedFrom( $this, $useSlave )
2388 // Don't block the user from editing their own talk page unless they've been
2389 // explicitly blocked from that too.
2390 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2391 // @todo FIXME: Pass the relevant context into this function.
2392 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2399 * Check that the user is allowed to read this page.
2401 * @param string $action The action to check
2402 * @param User $user User to check
2403 * @param array $errors List of current errors
2404 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2405 * @param bool $short Short circuit on first error
2407 * @return array List of errors
2409 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2410 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2412 $whitelisted = false;
2413 if ( User
::isEveryoneAllowed( 'read' ) ) {
2414 # Shortcut for public wikis, allows skipping quite a bit of code
2415 $whitelisted = true;
2416 } elseif ( $user->isAllowed( 'read' ) ) {
2417 # If the user is allowed to read pages, he is allowed to read all pages
2418 $whitelisted = true;
2419 } elseif ( $this->isSpecial( 'Userlogin' )
2420 ||
$this->isSpecial( 'PasswordReset' )
2421 ||
$this->isSpecial( 'Userlogout' )
2423 # Always grant access to the login page.
2424 # Even anons need to be able to log in.
2425 $whitelisted = true;
2426 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2427 # Time to check the whitelist
2428 # Only do these checks is there's something to check against
2429 $name = $this->getPrefixedText();
2430 $dbName = $this->getPrefixedDBkey();
2432 // Check for explicit whitelisting with and without underscores
2433 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2434 $whitelisted = true;
2435 } elseif ( $this->getNamespace() == NS_MAIN
) {
2436 # Old settings might have the title prefixed with
2437 # a colon for main-namespace pages
2438 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2439 $whitelisted = true;
2441 } elseif ( $this->isSpecialPage() ) {
2442 # If it's a special page, ditch the subpage bit and check again
2443 $name = $this->getDBkey();
2444 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2446 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2447 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2448 $whitelisted = true;
2454 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2455 $name = $this->getPrefixedText();
2456 // Check for regex whitelisting
2457 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2458 if ( preg_match( $listItem, $name ) ) {
2459 $whitelisted = true;
2465 if ( !$whitelisted ) {
2466 # If the title is not whitelisted, give extensions a chance to do so...
2467 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2468 if ( !$whitelisted ) {
2469 $errors[] = $this->missingPermissionError( $action, $short );
2477 * Get a description array when the user doesn't have the right to perform
2478 * $action (i.e. when User::isAllowed() returns false)
2480 * @param string $action The action to check
2481 * @param bool $short Short circuit on first error
2482 * @return array Array containing an error message key and any parameters
2484 private function missingPermissionError( $action, $short ) {
2485 // We avoid expensive display logic for quickUserCan's and such
2487 return [ 'badaccess-group0' ];
2490 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2494 * Can $user perform $action on this page? This is an internal function,
2495 * with multiple levels of checks depending on performance needs; see $rigor below.
2496 * It does not check wfReadOnly().
2498 * @param string $action Action that permission needs to be checked for
2499 * @param User $user User to check
2500 * @param string $rigor One of (quick,full,secure)
2501 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2502 * - full : does cheap and expensive checks possibly from a replica DB
2503 * - secure : does cheap and expensive checks, using the master as needed
2504 * @param bool $short Set this to true to stop after the first permission error.
2505 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2507 protected function getUserPermissionsErrorsInternal(
2508 $action, $user, $rigor = 'secure', $short = false
2510 if ( $rigor === true ) {
2511 $rigor = 'secure'; // b/c
2512 } elseif ( $rigor === false ) {
2513 $rigor = 'quick'; // b/c
2514 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2515 throw new Exception( "Invalid rigor parameter '$rigor'." );
2518 # Read has special handling
2519 if ( $action == 'read' ) {
2521 'checkPermissionHooks',
2522 'checkReadPermissions',
2523 'checkUserBlock', // for wgBlockDisablesLogin
2525 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2526 # here as it will lead to duplicate error messages. This is okay to do
2527 # since anywhere that checks for create will also check for edit, and
2528 # those checks are called for edit.
2529 } elseif ( $action == 'create' ) {
2531 'checkQuickPermissions',
2532 'checkPermissionHooks',
2533 'checkPageRestrictions',
2534 'checkCascadingSourcesRestrictions',
2535 'checkActionPermissions',
2540 'checkQuickPermissions',
2541 'checkPermissionHooks',
2542 'checkSpecialsAndNSPermissions',
2543 'checkCSSandJSPermissions',
2544 'checkPageRestrictions',
2545 'checkCascadingSourcesRestrictions',
2546 'checkActionPermissions',
2552 while ( count( $checks ) > 0 &&
2553 !( $short && count( $errors ) > 0 ) ) {
2554 $method = array_shift( $checks );
2555 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2562 * Get a filtered list of all restriction types supported by this wiki.
2563 * @param bool $exists True to get all restriction types that apply to
2564 * titles that do exist, False for all restriction types that apply to
2565 * titles that do not exist
2568 public static function getFilteredRestrictionTypes( $exists = true ) {
2569 global $wgRestrictionTypes;
2570 $types = $wgRestrictionTypes;
2572 # Remove the create restriction for existing titles
2573 $types = array_diff( $types, [ 'create' ] );
2575 # Only the create and upload restrictions apply to non-existing titles
2576 $types = array_intersect( $types, [ 'create', 'upload' ] );
2582 * Returns restriction types for the current Title
2584 * @return array Applicable restriction types
2586 public function getRestrictionTypes() {
2587 if ( $this->isSpecialPage() ) {
2591 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2593 if ( $this->getNamespace() != NS_FILE
) {
2594 # Remove the upload restriction for non-file titles
2595 $types = array_diff( $types, [ 'upload' ] );
2598 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2600 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2601 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2607 * Is this title subject to title protection?
2608 * Title protection is the one applied against creation of such title.
2610 * @return array|bool An associative array representing any existent title
2611 * protection, or false if there's none.
2613 public function getTitleProtection() {
2614 $protection = $this->getTitleProtectionInternal();
2615 if ( $protection ) {
2616 if ( $protection['permission'] == 'sysop' ) {
2617 $protection['permission'] = 'editprotected'; // B/C
2619 if ( $protection['permission'] == 'autoconfirmed' ) {
2620 $protection['permission'] = 'editsemiprotected'; // B/C
2627 * Fetch title protection settings
2629 * To work correctly, $this->loadRestrictions() needs to have access to the
2630 * actual protections in the database without munging 'sysop' =>
2631 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2632 * callers probably want $this->getTitleProtection() instead.
2634 * @return array|bool
2636 protected function getTitleProtectionInternal() {
2637 // Can't protect pages in special namespaces
2638 if ( $this->getNamespace() < 0 ) {
2642 // Can't protect pages that exist.
2643 if ( $this->exists() ) {
2647 if ( $this->mTitleProtection
=== null ) {
2648 $dbr = wfGetDB( DB_REPLICA
);
2649 $res = $dbr->select(
2652 'user' => 'pt_user',
2653 'reason' => 'pt_reason',
2654 'expiry' => 'pt_expiry',
2655 'permission' => 'pt_create_perm'
2657 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2661 // fetchRow returns false if there are no rows.
2662 $row = $dbr->fetchRow( $res );
2664 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2666 $this->mTitleProtection
= $row;
2668 return $this->mTitleProtection
;
2672 * Remove any title protection due to page existing
2674 public function deleteTitleProtection() {
2675 $dbw = wfGetDB( DB_MASTER
);
2679 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2682 $this->mTitleProtection
= false;
2686 * Is this page "semi-protected" - the *only* protection levels are listed
2687 * in $wgSemiprotectedRestrictionLevels?
2689 * @param string $action Action to check (default: edit)
2692 public function isSemiProtected( $action = 'edit' ) {
2693 global $wgSemiprotectedRestrictionLevels;
2695 $restrictions = $this->getRestrictions( $action );
2696 $semi = $wgSemiprotectedRestrictionLevels;
2697 if ( !$restrictions ||
!$semi ) {
2698 // Not protected, or all protection is full protection
2702 // Remap autoconfirmed to editsemiprotected for BC
2703 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2704 $semi[$key] = 'editsemiprotected';
2706 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2707 $restrictions[$key] = 'editsemiprotected';
2710 return !array_diff( $restrictions, $semi );
2714 * Does the title correspond to a protected article?
2716 * @param string $action The action the page is protected from,
2717 * by default checks all actions.
2720 public function isProtected( $action = '' ) {
2721 global $wgRestrictionLevels;
2723 $restrictionTypes = $this->getRestrictionTypes();
2725 # Special pages have inherent protection
2726 if ( $this->isSpecialPage() ) {
2730 # Check regular protection levels
2731 foreach ( $restrictionTypes as $type ) {
2732 if ( $action == $type ||
$action == '' ) {
2733 $r = $this->getRestrictions( $type );
2734 foreach ( $wgRestrictionLevels as $level ) {
2735 if ( in_array( $level, $r ) && $level != '' ) {
2746 * Determines if $user is unable to edit this page because it has been protected
2747 * by $wgNamespaceProtection.
2749 * @param User $user User object to check permissions
2752 public function isNamespaceProtected( User
$user ) {
2753 global $wgNamespaceProtection;
2755 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2756 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2757 if ( $right != '' && !$user->isAllowed( $right ) ) {
2766 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2768 * @return bool If the page is subject to cascading restrictions.
2770 public function isCascadeProtected() {
2771 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2772 return ( $sources > 0 );
2776 * Determines whether cascading protection sources have already been loaded from
2779 * @param bool $getPages True to check if the pages are loaded, or false to check
2780 * if the status is loaded.
2781 * @return bool Whether or not the specified information has been loaded
2784 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2785 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2789 * Cascading protection: Get the source of any cascading restrictions on this page.
2791 * @param bool $getPages Whether or not to retrieve the actual pages
2792 * that the restrictions have come from and the actual restrictions
2794 * @return array Two elements: First is an array of Title objects of the
2795 * pages from which cascading restrictions have come, false for
2796 * none, or true if such restrictions exist but $getPages was not
2797 * set. Second is an array like that returned by
2798 * Title::getAllRestrictions(), or an empty array if $getPages is
2801 public function getCascadeProtectionSources( $getPages = true ) {
2802 $pagerestrictions = [];
2804 if ( $this->mCascadeSources
!== null && $getPages ) {
2805 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2806 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2807 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2810 $dbr = wfGetDB( DB_REPLICA
);
2812 if ( $this->getNamespace() == NS_FILE
) {
2813 $tables = [ 'imagelinks', 'page_restrictions' ];
2815 'il_to' => $this->getDBkey(),
2820 $tables = [ 'templatelinks', 'page_restrictions' ];
2822 'tl_namespace' => $this->getNamespace(),
2823 'tl_title' => $this->getDBkey(),
2830 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2831 'pr_expiry', 'pr_type', 'pr_level' ];
2832 $where_clauses[] = 'page_id=pr_page';
2835 $cols = [ 'pr_expiry' ];
2838 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2840 $sources = $getPages ?
[] : false;
2841 $now = wfTimestampNow();
2843 foreach ( $res as $row ) {
2844 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2845 if ( $expiry > $now ) {
2847 $page_id = $row->pr_page
;
2848 $page_ns = $row->page_namespace
;
2849 $page_title = $row->page_title
;
2850 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2851 # Add groups needed for each restriction type if its not already there
2852 # Make sure this restriction type still exists
2854 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2855 $pagerestrictions[$row->pr_type
] = [];
2859 isset( $pagerestrictions[$row->pr_type
] )
2860 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2862 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2871 $this->mCascadeSources
= $sources;
2872 $this->mCascadingRestrictions
= $pagerestrictions;
2874 $this->mHasCascadingRestrictions
= $sources;
2877 return [ $sources, $pagerestrictions ];
2881 * Accessor for mRestrictionsLoaded
2883 * @return bool Whether or not the page's restrictions have already been
2884 * loaded from the database
2887 public function areRestrictionsLoaded() {
2888 return $this->mRestrictionsLoaded
;
2892 * Accessor/initialisation for mRestrictions
2894 * @param string $action Action that permission needs to be checked for
2895 * @return array Restriction levels needed to take the action. All levels are
2896 * required. Note that restriction levels are normally user rights, but 'sysop'
2897 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2898 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2900 public function getRestrictions( $action ) {
2901 if ( !$this->mRestrictionsLoaded
) {
2902 $this->loadRestrictions();
2904 return isset( $this->mRestrictions
[$action] )
2905 ?
$this->mRestrictions
[$action]
2910 * Accessor/initialisation for mRestrictions
2912 * @return array Keys are actions, values are arrays as returned by
2913 * Title::getRestrictions()
2916 public function getAllRestrictions() {
2917 if ( !$this->mRestrictionsLoaded
) {
2918 $this->loadRestrictions();
2920 return $this->mRestrictions
;
2924 * Get the expiry time for the restriction against a given action
2926 * @param string $action
2927 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2928 * or not protected at all, or false if the action is not recognised.
2930 public function getRestrictionExpiry( $action ) {
2931 if ( !$this->mRestrictionsLoaded
) {
2932 $this->loadRestrictions();
2934 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2938 * Returns cascading restrictions for the current article
2942 function areRestrictionsCascading() {
2943 if ( !$this->mRestrictionsLoaded
) {
2944 $this->loadRestrictions();
2947 return $this->mCascadeRestriction
;
2951 * Compiles list of active page restrictions from both page table (pre 1.10)
2952 * and page_restrictions table for this existing page.
2953 * Public for usage by LiquidThreads.
2955 * @param array $rows Array of db result objects
2956 * @param string $oldFashionedRestrictions Comma-separated list of page
2957 * restrictions from page table (pre 1.10)
2959 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2960 $dbr = wfGetDB( DB_REPLICA
);
2962 $restrictionTypes = $this->getRestrictionTypes();
2964 foreach ( $restrictionTypes as $type ) {
2965 $this->mRestrictions
[$type] = [];
2966 $this->mRestrictionsExpiry
[$type] = 'infinity';
2969 $this->mCascadeRestriction
= false;
2971 # Backwards-compatibility: also load the restrictions from the page record (old format).
2972 if ( $oldFashionedRestrictions !== null ) {
2973 $this->mOldRestrictions
= $oldFashionedRestrictions;
2976 if ( $this->mOldRestrictions
=== false ) {
2977 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2978 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2981 if ( $this->mOldRestrictions
!= '' ) {
2982 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2983 $temp = explode( '=', trim( $restrict ) );
2984 if ( count( $temp ) == 1 ) {
2985 // old old format should be treated as edit/move restriction
2986 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2987 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2989 $restriction = trim( $temp[1] );
2990 if ( $restriction != '' ) { // some old entries are empty
2991 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2997 if ( count( $rows ) ) {
2998 # Current system - load second to make them override.
2999 $now = wfTimestampNow();
3001 # Cycle through all the restrictions.
3002 foreach ( $rows as $row ) {
3003 // Don't take care of restrictions types that aren't allowed
3004 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3008 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3010 // Only apply the restrictions if they haven't expired!
3011 if ( !$expiry ||
$expiry > $now ) {
3012 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3013 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3015 $this->mCascadeRestriction |
= $row->pr_cascade
;
3020 $this->mRestrictionsLoaded
= true;
3024 * Load restrictions from the page_restrictions table
3026 * @param string $oldFashionedRestrictions Comma-separated list of page
3027 * restrictions from page table (pre 1.10)
3029 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3030 if ( $this->mRestrictionsLoaded
) {
3034 $id = $this->getArticleID();
3036 $cache = ObjectCache
::getMainWANInstance();
3037 $rows = $cache->getWithSetCallback(
3038 // Page protections always leave a new null revision
3039 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3041 function ( $curValue, &$ttl, array &$setOpts ) {
3042 $dbr = wfGetDB( DB_REPLICA
);
3044 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3046 return iterator_to_array(
3048 'page_restrictions',
3049 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3050 [ 'pr_page' => $this->getArticleID() ],
3057 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3059 $title_protection = $this->getTitleProtectionInternal();
3061 if ( $title_protection ) {
3062 $now = wfTimestampNow();
3063 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3065 if ( !$expiry ||
$expiry > $now ) {
3066 // Apply the restrictions
3067 $this->mRestrictionsExpiry
['create'] = $expiry;
3068 $this->mRestrictions
['create'] =
3069 explode( ',', trim( $title_protection['permission'] ) );
3070 } else { // Get rid of the old restrictions
3071 $this->mTitleProtection
= false;
3074 $this->mRestrictionsExpiry
['create'] = 'infinity';
3076 $this->mRestrictionsLoaded
= true;
3081 * Flush the protection cache in this object and force reload from the database.
3082 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3084 public function flushRestrictions() {
3085 $this->mRestrictionsLoaded
= false;
3086 $this->mTitleProtection
= null;
3090 * Purge expired restrictions from the page_restrictions table
3092 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3094 static function purgeExpiredRestrictions() {
3095 if ( wfReadOnly() ) {
3099 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3100 wfGetDB( DB_MASTER
),
3102 function ( IDatabase
$dbw, $fname ) {
3103 $config = MediaWikiServices
::getInstance()->getMainConfig();
3104 $ids = $dbw->selectFieldValues(
3105 'page_restrictions',
3107 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3109 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3112 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3117 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3118 wfGetDB( DB_MASTER
),
3120 function ( IDatabase
$dbw, $fname ) {
3123 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3131 * Does this have subpages? (Warning, usually requires an extra DB query.)
3135 public function hasSubpages() {
3136 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3141 # We dynamically add a member variable for the purpose of this method
3142 # alone to cache the result. There's no point in having it hanging
3143 # around uninitialized in every Title object; therefore we only add it
3144 # if needed and don't declare it statically.
3145 if ( $this->mHasSubpages
=== null ) {
3146 $this->mHasSubpages
= false;
3147 $subpages = $this->getSubpages( 1 );
3148 if ( $subpages instanceof TitleArray
) {
3149 $this->mHasSubpages
= (bool)$subpages->count();
3153 return $this->mHasSubpages
;
3157 * Get all subpages of this page.
3159 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3160 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3161 * doesn't allow subpages
3163 public function getSubpages( $limit = -1 ) {
3164 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3168 $dbr = wfGetDB( DB_REPLICA
);
3169 $conds['page_namespace'] = $this->getNamespace();
3170 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3172 if ( $limit > -1 ) {
3173 $options['LIMIT'] = $limit;
3175 $this->mSubpages
= TitleArray
::newFromResult(
3176 $dbr->select( 'page',
3177 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3183 return $this->mSubpages
;
3187 * Is there a version of this page in the deletion archive?
3189 * @return int The number of archived revisions
3191 public function isDeleted() {
3192 if ( $this->getNamespace() < 0 ) {
3195 $dbr = wfGetDB( DB_REPLICA
);
3197 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3198 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3201 if ( $this->getNamespace() == NS_FILE
) {
3202 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3203 [ 'fa_name' => $this->getDBkey() ],
3212 * Is there a version of this page in the deletion archive?
3216 public function isDeletedQuick() {
3217 if ( $this->getNamespace() < 0 ) {
3220 $dbr = wfGetDB( DB_REPLICA
);
3221 $deleted = (bool)$dbr->selectField( 'archive', '1',
3222 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3225 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3226 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3227 [ 'fa_name' => $this->getDBkey() ],
3235 * Get the article ID for this Title from the link cache,
3236 * adding it if necessary
3238 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3240 * @return int The ID
3242 public function getArticleID( $flags = 0 ) {
3243 if ( $this->getNamespace() < 0 ) {
3244 $this->mArticleID
= 0;
3245 return $this->mArticleID
;
3247 $linkCache = LinkCache
::singleton();
3248 if ( $flags & self
::GAID_FOR_UPDATE
) {
3249 $oldUpdate = $linkCache->forUpdate( true );
3250 $linkCache->clearLink( $this );
3251 $this->mArticleID
= $linkCache->addLinkObj( $this );
3252 $linkCache->forUpdate( $oldUpdate );
3254 if ( -1 == $this->mArticleID
) {
3255 $this->mArticleID
= $linkCache->addLinkObj( $this );
3258 return $this->mArticleID
;
3262 * Is this an article that is a redirect page?
3263 * Uses link cache, adding it if necessary
3265 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3268 public function isRedirect( $flags = 0 ) {
3269 if ( !is_null( $this->mRedirect
) ) {
3270 return $this->mRedirect
;
3272 if ( !$this->getArticleID( $flags ) ) {
3273 $this->mRedirect
= false;
3274 return $this->mRedirect
;
3277 $linkCache = LinkCache
::singleton();
3278 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3279 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3280 if ( $cached === null ) {
3281 # Trust LinkCache's state over our own
3282 # LinkCache is telling us that the page doesn't exist, despite there being cached
3283 # data relating to an existing page in $this->mArticleID. Updaters should clear
3284 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3285 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3286 # LinkCache to refresh its data from the master.
3287 $this->mRedirect
= false;
3288 return $this->mRedirect
;
3291 $this->mRedirect
= (bool)$cached;
3293 return $this->mRedirect
;
3297 * What is the length of this page?
3298 * Uses link cache, adding it if necessary
3300 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3303 public function getLength( $flags = 0 ) {
3304 if ( $this->mLength
!= -1 ) {
3305 return $this->mLength
;
3307 if ( !$this->getArticleID( $flags ) ) {
3309 return $this->mLength
;
3311 $linkCache = LinkCache
::singleton();
3312 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3313 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3314 if ( $cached === null ) {
3315 # Trust LinkCache's state over our own, as for isRedirect()
3317 return $this->mLength
;
3320 $this->mLength
= intval( $cached );
3322 return $this->mLength
;
3326 * What is the page_latest field for this page?
3328 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3329 * @return int Int or 0 if the page doesn't exist
3331 public function getLatestRevID( $flags = 0 ) {
3332 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3333 return intval( $this->mLatestID
);
3335 if ( !$this->getArticleID( $flags ) ) {
3336 $this->mLatestID
= 0;
3337 return $this->mLatestID
;
3339 $linkCache = LinkCache
::singleton();
3340 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3341 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3342 if ( $cached === null ) {
3343 # Trust LinkCache's state over our own, as for isRedirect()
3344 $this->mLatestID
= 0;
3345 return $this->mLatestID
;
3348 $this->mLatestID
= intval( $cached );
3350 return $this->mLatestID
;
3354 * This clears some fields in this object, and clears any associated
3355 * keys in the "bad links" section of the link cache.
3357 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3358 * loading of the new page_id. It's also called from
3359 * WikiPage::doDeleteArticleReal()
3361 * @param int $newid The new Article ID
3363 public function resetArticleID( $newid ) {
3364 $linkCache = LinkCache
::singleton();
3365 $linkCache->clearLink( $this );
3367 if ( $newid === false ) {
3368 $this->mArticleID
= -1;
3370 $this->mArticleID
= intval( $newid );
3372 $this->mRestrictionsLoaded
= false;
3373 $this->mRestrictions
= [];
3374 $this->mOldRestrictions
= false;
3375 $this->mRedirect
= null;
3376 $this->mLength
= -1;
3377 $this->mLatestID
= false;
3378 $this->mContentModel
= false;
3379 $this->mEstimateRevisions
= null;
3380 $this->mPageLanguage
= false;
3381 $this->mDbPageLanguage
= false;
3382 $this->mIsBigDeletion
= null;
3385 public static function clearCaches() {
3386 $linkCache = LinkCache
::singleton();
3387 $linkCache->clear();
3389 $titleCache = self
::getTitleCache();
3390 $titleCache->clear();
3394 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3396 * @param string $text Containing title to capitalize
3397 * @param int $ns Namespace index, defaults to NS_MAIN
3398 * @return string Containing capitalized title
3400 public static function capitalize( $text, $ns = NS_MAIN
) {
3403 if ( MWNamespace
::isCapitalized( $ns ) ) {
3404 return $wgContLang->ucfirst( $text );
3411 * Secure and split - main initialisation function for this object
3413 * Assumes that mDbkeyform has been set, and is urldecoded
3414 * and uses underscores, but not otherwise munged. This function
3415 * removes illegal characters, splits off the interwiki and
3416 * namespace prefixes, sets the other forms, and canonicalizes
3419 * @throws MalformedTitleException On invalid titles
3420 * @return bool True on success
3422 private function secureAndSplit() {
3424 $this->mInterwiki
= '';
3425 $this->mFragment
= '';
3426 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3428 $dbkey = $this->mDbkeyform
;
3430 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3431 // the parsing code with Title, while avoiding massive refactoring.
3432 // @todo: get rid of secureAndSplit, refactor parsing code.
3433 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3434 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3435 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3436 // MalformedTitleException can be thrown here
3437 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3440 $this->setFragment( '#' . $parts['fragment'] );
3441 $this->mInterwiki
= $parts['interwiki'];
3442 $this->mLocalInterwiki
= $parts['local_interwiki'];
3443 $this->mNamespace
= $parts['namespace'];
3444 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3446 $this->mDbkeyform
= $parts['dbkey'];
3447 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3448 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3450 # We already know that some pages won't be in the database!
3451 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3452 $this->mArticleID
= 0;
3459 * Get an array of Title objects linking to this Title
3460 * Also stores the IDs in the link cache.
3462 * WARNING: do not use this function on arbitrary user-supplied titles!
3463 * On heavily-used templates it will max out the memory.
3465 * @param array $options May be FOR UPDATE
3466 * @param string $table Table name
3467 * @param string $prefix Fields prefix
3468 * @return Title[] Array of Title objects linking here
3470 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3471 if ( count( $options ) > 0 ) {
3472 $db = wfGetDB( DB_MASTER
);
3474 $db = wfGetDB( DB_REPLICA
);
3479 self
::getSelectFields(),
3481 "{$prefix}_from=page_id",
3482 "{$prefix}_namespace" => $this->getNamespace(),
3483 "{$prefix}_title" => $this->getDBkey() ],
3489 if ( $res->numRows() ) {
3490 $linkCache = LinkCache
::singleton();
3491 foreach ( $res as $row ) {
3492 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3494 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3495 $retVal[] = $titleObj;
3503 * Get an array of Title objects using this Title as a template
3504 * Also stores the IDs in the link cache.
3506 * WARNING: do not use this function on arbitrary user-supplied titles!
3507 * On heavily-used templates it will max out the memory.
3509 * @param array $options Query option to Database::select()
3510 * @return Title[] Array of Title the Title objects linking here
3512 public function getTemplateLinksTo( $options = [] ) {
3513 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3517 * Get an array of Title objects linked from this Title
3518 * Also stores the IDs in the link cache.
3520 * WARNING: do not use this function on arbitrary user-supplied titles!
3521 * On heavily-used templates it will max out the memory.
3523 * @param array $options Query option to Database::select()
3524 * @param string $table Table name
3525 * @param string $prefix Fields prefix
3526 * @return array Array of Title objects linking here
3528 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3529 $id = $this->getArticleID();
3531 # If the page doesn't exist; there can't be any link from this page
3536 $db = wfGetDB( DB_REPLICA
);
3538 $blNamespace = "{$prefix}_namespace";
3539 $blTitle = "{$prefix}_title";
3544 [ $blNamespace, $blTitle ],
3545 WikiPage
::selectFields()
3547 [ "{$prefix}_from" => $id ],
3552 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3557 $linkCache = LinkCache
::singleton();
3558 foreach ( $res as $row ) {
3559 if ( $row->page_id
) {
3560 $titleObj = Title
::newFromRow( $row );
3562 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3563 $linkCache->addBadLinkObj( $titleObj );
3565 $retVal[] = $titleObj;
3572 * Get an array of Title objects used on this Title as a template
3573 * Also stores the IDs in the link cache.
3575 * WARNING: do not use this function on arbitrary user-supplied titles!
3576 * On heavily-used templates it will max out the memory.
3578 * @param array $options May be FOR UPDATE
3579 * @return Title[] Array of Title the Title objects used here
3581 public function getTemplateLinksFrom( $options = [] ) {
3582 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3586 * Get an array of Title objects referring to non-existent articles linked