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 self
::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 = self
::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[] = self
::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
= self
::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 = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
561 // Don't give fatal errors if the message is broken
563 $title = self
::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 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
753 * @param string $fragment Containing a URL or link fragment (after the "#")
754 * @return string Escaped string
756 static function escapeFragmentForURL( $fragment ) {
757 # Note that we don't urlencode the fragment. urlencoded Unicode
758 # fragments appear not to work in IE (at least up to 7) or in at least
759 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
760 # to care if they aren't encoded.
761 return Sanitizer
::escapeId( $fragment, 'noninitial' );
765 * Callback for usort() to do title sorts by (namespace, title)
767 * @param LinkTarget $a
768 * @param LinkTarget $b
770 * @return int Result of string comparison, or namespace comparison
772 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
773 if ( $a->getNamespace() == $b->getNamespace() ) {
774 return strcmp( $a->getText(), $b->getText() );
776 return $a->getNamespace() - $b->getNamespace();
781 * Determine whether the object refers to a page within
782 * this project (either this wiki or a wiki with a local
783 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
785 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
787 public function isLocal() {
788 if ( $this->isExternal() ) {
789 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
791 return $iw->isLocal();
798 * Is this Title interwiki?
802 public function isExternal() {
803 return $this->mInterwiki
!== '';
807 * Get the interwiki prefix
809 * Use Title::isExternal to check if a interwiki is set
811 * @return string Interwiki prefix
813 public function getInterwiki() {
814 return $this->mInterwiki
;
818 * Was this a local interwiki link?
822 public function wasLocalInterwiki() {
823 return $this->mLocalInterwiki
;
827 * Determine whether the object refers to a page within
828 * this project and is transcludable.
830 * @return bool True if this is transcludable
832 public function isTrans() {
833 if ( !$this->isExternal() ) {
837 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
841 * Returns the DB name of the distant wiki which owns the object.
843 * @return string|false The DB name
845 public function getTransWikiID() {
846 if ( !$this->isExternal() ) {
850 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
854 * Get a TitleValue object representing this Title.
856 * @note Not all valid Titles have a corresponding valid TitleValue
857 * (e.g. TitleValues cannot represent page-local links that have a
858 * fragment but no title text).
860 * @return TitleValue|null
862 public function getTitleValue() {
863 if ( $this->mTitleValue
=== null ) {
865 $this->mTitleValue
= new TitleValue(
866 $this->getNamespace(),
868 $this->getFragment(),
869 $this->getInterwiki()
871 } catch ( InvalidArgumentException
$ex ) {
872 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
873 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
877 return $this->mTitleValue
;
881 * Get the text form (spaces not underscores) of the main part
883 * @return string Main part of the title
885 public function getText() {
886 return $this->mTextform
;
890 * Get the URL-encoded form of the main part
892 * @return string Main part of the title, URL-encoded
894 public function getPartialURL() {
895 return $this->mUrlform
;
899 * Get the main part with underscores
901 * @return string Main part of the title, with underscores
903 public function getDBkey() {
904 return $this->mDbkeyform
;
908 * Get the DB key with the initial letter case as specified by the user
910 * @return string DB key
912 function getUserCaseDBKey() {
913 if ( !is_null( $this->mUserCaseDBKey
) ) {
914 return $this->mUserCaseDBKey
;
916 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
917 return $this->mDbkeyform
;
922 * Get the namespace index, i.e. one of the NS_xxxx constants.
924 * @return int Namespace index
926 public function getNamespace() {
927 return $this->mNamespace
;
931 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
933 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
934 * @return string Content model id
936 public function getContentModel( $flags = 0 ) {
937 if ( !$this->mForcedContentModel
938 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
939 && $this->getArticleID( $flags )
941 $linkCache = LinkCache
::singleton();
942 $linkCache->addLinkObj( $this ); # in case we already had an article ID
943 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
946 if ( !$this->mContentModel
) {
947 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
950 return $this->mContentModel
;
954 * Convenience method for checking a title's content model name
956 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
957 * @return bool True if $this->getContentModel() == $id
959 public function hasContentModel( $id ) {
960 return $this->getContentModel() == $id;
964 * Set a proposed content model for the page for permissions
965 * checking. This does not actually change the content model
968 * Additionally, you should make sure you've checked
969 * ContentHandler::canBeUsedOn() first.
972 * @param string $model CONTENT_MODEL_XXX constant
974 public function setContentModel( $model ) {
975 $this->mContentModel
= $model;
976 $this->mForcedContentModel
= true;
980 * Get the namespace text
982 * @return string|false Namespace text
984 public function getNsText() {
985 if ( $this->isExternal() ) {
986 // This probably shouldn't even happen,
987 // but for interwiki transclusion it sometimes does.
988 // Use the canonical namespaces if possible to try to
989 // resolve a foreign namespace.
990 if ( MWNamespace
::exists( $this->mNamespace
) ) {
991 return MWNamespace
::getCanonicalName( $this->mNamespace
);
996 $formatter = self
::getTitleFormatter();
997 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
998 } catch ( InvalidArgumentException
$ex ) {
999 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1005 * Get the namespace text of the subject (rather than talk) page
1007 * @return string Namespace text
1009 public function getSubjectNsText() {
1011 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1015 * Get the namespace text of the talk page
1017 * @return string Namespace text
1019 public function getTalkNsText() {
1021 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1025 * Can this title have a corresponding talk page?
1027 * @deprecated since 1.30, use canHaveTalkPage() instead.
1029 * @return bool True if this title either is a talk page or can have a talk page associated.
1031 public function canTalk() {
1032 return $this->canHaveTalkPage();
1036 * Can this title have a corresponding talk page?
1038 * @see MWNamespace::hasTalkNamespace
1041 * @return bool True if this title either is a talk page or can have a talk page associated.
1043 public function canHaveTalkPage() {
1044 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1048 * Is this in a namespace that allows actual pages?
1052 public function canExist() {
1053 return $this->mNamespace
>= NS_MAIN
;
1057 * Can this title be added to a user's watchlist?
1061 public function isWatchable() {
1062 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1066 * Returns true if this is a special page.
1070 public function isSpecialPage() {
1071 return $this->getNamespace() == NS_SPECIAL
;
1075 * Returns true if this title resolves to the named special page
1077 * @param string $name The special page name
1080 public function isSpecial( $name ) {
1081 if ( $this->isSpecialPage() ) {
1082 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1083 if ( $name == $thisName ) {
1091 * If the Title refers to a special page alias which is not the local default, resolve
1092 * the alias, and localise the name as necessary. Otherwise, return $this
1096 public function fixSpecialName() {
1097 if ( $this->isSpecialPage() ) {
1098 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1099 if ( $canonicalName ) {
1100 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1101 if ( $localName != $this->mDbkeyform
) {
1102 return self
::makeTitle( NS_SPECIAL
, $localName );
1110 * Returns true if the title is inside the specified namespace.
1112 * Please make use of this instead of comparing to getNamespace()
1113 * This function is much more resistant to changes we may make
1114 * to namespaces than code that makes direct comparisons.
1115 * @param int $ns The namespace
1119 public function inNamespace( $ns ) {
1120 return MWNamespace
::equals( $this->getNamespace(), $ns );
1124 * Returns true if the title is inside one of the specified namespaces.
1126 * @param int|int[] $namespaces,... The namespaces to check for
1130 public function inNamespaces( /* ... */ ) {
1131 $namespaces = func_get_args();
1132 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1133 $namespaces = $namespaces[0];
1136 foreach ( $namespaces as $ns ) {
1137 if ( $this->inNamespace( $ns ) ) {
1146 * Returns true if the title has the same subject namespace as the
1147 * namespace specified.
1148 * For example this method will take NS_USER and return true if namespace
1149 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1150 * as their subject namespace.
1152 * This is MUCH simpler than individually testing for equivalence
1153 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1158 public function hasSubjectNamespace( $ns ) {
1159 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1163 * Is this Title in a namespace which contains content?
1164 * In other words, is this a content page, for the purposes of calculating
1169 public function isContentPage() {
1170 return MWNamespace
::isContent( $this->getNamespace() );
1174 * Would anybody with sufficient privileges be able to move this page?
1175 * Some pages just aren't movable.
1179 public function isMovable() {
1180 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1181 // Interwiki title or immovable namespace. Hooks don't get to override here
1186 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1191 * Is this the mainpage?
1192 * @note Title::newFromText seems to be sufficiently optimized by the title
1193 * cache that we don't need to over-optimize by doing direct comparisons and
1194 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1195 * ends up reporting something differently than $title->isMainPage();
1200 public function isMainPage() {
1201 return $this->equals( self
::newMainPage() );
1205 * Is this a subpage?
1209 public function isSubpage() {
1210 return MWNamespace
::hasSubpages( $this->mNamespace
)
1211 ?
strpos( $this->getText(), '/' ) !== false
1216 * Is this a conversion table for the LanguageConverter?
1220 public function isConversionTable() {
1221 // @todo ConversionTable should become a separate content model.
1223 return $this->getNamespace() == NS_MEDIAWIKI
&&
1224 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1228 * Does that page contain wikitext, or it is JS, CSS or whatever?
1232 public function isWikitextPage() {
1233 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1237 * Could this page contain custom CSS or JavaScript for the global UI.
1238 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1239 * or CONTENT_MODEL_JAVASCRIPT.
1241 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1244 * Note that this method should not return true for pages that contain and
1245 * show "inactive" CSS or JS.
1248 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1250 public function isCssOrJsPage() {
1251 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1252 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1253 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1255 return $isCssOrJsPage;
1259 * Is this a .css or .js subpage of a user page?
1261 * @todo FIXME: Rename to isUserConfigPage()
1263 public function isCssJsSubpage() {
1264 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1265 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1266 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1270 * Trim down a .css or .js subpage title to get the corresponding skin name
1272 * @return string Containing skin name from .css or .js subpage title
1274 public function getSkinFromCssJsSubpage() {
1275 $subpage = explode( '/', $this->mTextform
);
1276 $subpage = $subpage[count( $subpage ) - 1];
1277 $lastdot = strrpos( $subpage, '.' );
1278 if ( $lastdot === false ) {
1279 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1281 return substr( $subpage, 0, $lastdot );
1285 * Is this a .css subpage of a user page?
1289 public function isCssSubpage() {
1290 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1291 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1295 * Is this a .js subpage of a user page?
1299 public function isJsSubpage() {
1300 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1301 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1305 * Is this a talk page of some sort?
1309 public function isTalkPage() {
1310 return MWNamespace
::isTalk( $this->getNamespace() );
1314 * Get a Title object associated with the talk page of this article
1316 * @return Title The object for the talk page
1318 public function getTalkPage() {
1319 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1323 * Get a Title object associated with the talk page of this article,
1324 * if such a talk page can exist.
1328 * @return Title The object for the talk page,
1329 * or null if no associated talk page can exist, according to canHaveTalkPage().
1331 public function getTalkPageIfDefined() {
1332 if ( !$this->canHaveTalkPage() ) {
1336 return $this->getTalkPage();
1340 * Get a title object associated with the subject page of this
1343 * @return Title The object for the subject page
1345 public function getSubjectPage() {
1346 // Is this the same title?
1347 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1348 if ( $this->getNamespace() == $subjectNS ) {
1351 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1355 * Get the other title for this page, if this is a subject page
1356 * get the talk page, if it is a subject page get the talk page
1359 * @throws MWException
1362 public function getOtherPage() {
1363 if ( $this->isSpecialPage() ) {
1364 throw new MWException( 'Special pages cannot have other pages' );
1366 if ( $this->isTalkPage() ) {
1367 return $this->getSubjectPage();
1369 return $this->getTalkPage();
1374 * Get the default namespace index, for when there is no namespace
1376 * @return int Default namespace index
1378 public function getDefaultNamespace() {
1379 return $this->mDefaultNamespace
;
1383 * Get the Title fragment (i.e.\ the bit after the #) in text form
1385 * Use Title::hasFragment to check for a fragment
1387 * @return string Title fragment
1389 public function getFragment() {
1390 return $this->mFragment
;
1394 * Check if a Title fragment is set
1399 public function hasFragment() {
1400 return $this->mFragment
!== '';
1404 * Get the fragment in URL form, including the "#" character if there is one
1406 * @return string Fragment in URL form
1408 public function getFragmentForURL() {
1409 if ( !$this->hasFragment() ) {
1411 } elseif ( $this->isExternal() && !$this->getTransWikiID() ) {
1412 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1414 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1418 * Set the fragment for this title. Removes the first character from the
1419 * specified fragment before setting, so it assumes you're passing it with
1422 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1423 * or Title::createFragmentTarget().
1424 * Still in active use privately.
1427 * @param string $fragment Text
1429 public function setFragment( $fragment ) {
1430 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1434 * Creates a new Title for a different fragment of the same page.
1437 * @param string $fragment
1440 public function createFragmentTarget( $fragment ) {
1441 return self
::makeTitle(
1442 $this->getNamespace(),
1445 $this->getInterwiki()
1450 * Prefix some arbitrary text with the namespace or interwiki prefix
1453 * @param string $name The text
1454 * @return string The prefixed text
1456 private function prefix( $name ) {
1460 if ( $this->isExternal() ) {
1461 $p = $this->mInterwiki
. ':';
1464 if ( 0 != $this->mNamespace
) {
1465 $nsText = $this->getNsText();
1467 if ( $nsText === false ) {
1468 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1469 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1472 $p .= $nsText . ':';
1478 * Get the prefixed database key form
1480 * @return string The prefixed title, with underscores and
1481 * any interwiki and namespace prefixes
1483 public function getPrefixedDBkey() {
1484 $s = $this->prefix( $this->mDbkeyform
);
1485 $s = strtr( $s, ' ', '_' );
1490 * Get the prefixed title with spaces.
1491 * This is the form usually used for display
1493 * @return string The prefixed title, with spaces
1495 public function getPrefixedText() {
1496 if ( $this->mPrefixedText
=== null ) {
1497 $s = $this->prefix( $this->mTextform
);
1498 $s = strtr( $s, '_', ' ' );
1499 $this->mPrefixedText
= $s;
1501 return $this->mPrefixedText
;
1505 * Return a string representation of this title
1507 * @return string Representation of this title
1509 public function __toString() {
1510 return $this->getPrefixedText();
1514 * Get the prefixed title with spaces, plus any fragment
1515 * (part beginning with '#')
1517 * @return string The prefixed title, with spaces and the fragment, including '#'
1519 public function getFullText() {
1520 $text = $this->getPrefixedText();
1521 if ( $this->hasFragment() ) {
1522 $text .= '#' . $this->getFragment();
1528 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1532 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1536 * @return string Root name
1539 public function getRootText() {
1540 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1541 return $this->getText();
1544 return strtok( $this->getText(), '/' );
1548 * Get the root page name title, i.e. the leftmost part before any slashes
1552 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1553 * # returns: Title{User:Foo}
1556 * @return Title Root title
1559 public function getRootTitle() {
1560 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1564 * Get the base page name without a namespace, i.e. the part before the subpage name
1568 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1569 * # returns: 'Foo/Bar'
1572 * @return string Base name
1574 public function getBaseText() {
1575 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1576 return $this->getText();
1579 $parts = explode( '/', $this->getText() );
1580 # Don't discard the real title if there's no subpage involved
1581 if ( count( $parts ) > 1 ) {
1582 unset( $parts[count( $parts ) - 1] );
1584 return implode( '/', $parts );
1588 * Get the base page name title, i.e. the part before the subpage name
1592 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1593 * # returns: Title{User:Foo/Bar}
1596 * @return Title Base title
1599 public function getBaseTitle() {
1600 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1604 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1608 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1612 * @return string Subpage name
1614 public function getSubpageText() {
1615 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1616 return $this->mTextform
;
1618 $parts = explode( '/', $this->mTextform
);
1619 return $parts[count( $parts ) - 1];
1623 * Get the title for a subpage of the current page
1627 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1628 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1631 * @param string $text The subpage name to add to the title
1632 * @return Title Subpage title
1635 public function getSubpage( $text ) {
1636 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1640 * Get a URL-encoded form of the subpage text
1642 * @return string URL-encoded subpage name
1644 public function getSubpageUrlForm() {
1645 $text = $this->getSubpageText();
1646 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1651 * Get a URL-encoded title (not an actual URL) including interwiki
1653 * @return string The URL-encoded form
1655 public function getPrefixedURL() {
1656 $s = $this->prefix( $this->mDbkeyform
);
1657 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1662 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1663 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1664 * second argument named variant. This was deprecated in favor
1665 * of passing an array of option with a "variant" key
1666 * Once $query2 is removed for good, this helper can be dropped
1667 * and the wfArrayToCgi moved to getLocalURL();
1669 * @since 1.19 (r105919)
1670 * @param array|string $query
1671 * @param string|string[]|bool $query2
1674 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1675 if ( $query2 !== false ) {
1676 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1677 "method called with a second parameter is deprecated. Add your " .
1678 "parameter to an array passed as the first parameter.", "1.19" );
1680 if ( is_array( $query ) ) {
1681 $query = wfArrayToCgi( $query );
1684 if ( is_string( $query2 ) ) {
1685 // $query2 is a string, we will consider this to be
1686 // a deprecated $variant argument and add it to the query
1687 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1689 $query2 = wfArrayToCgi( $query2 );
1691 // If we have $query content add a & to it first
1695 // Now append the queries together
1702 * Get a real URL referring to this title, with interwiki link and
1705 * @see self::getLocalURL for the arguments.
1707 * @param string|string[] $query
1708 * @param string|string[]|bool $query2
1709 * @param string $proto Protocol type to use in URL
1710 * @return string The URL
1712 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1713 $query = self
::fixUrlQueryArgs( $query, $query2 );
1715 # Hand off all the decisions on urls to getLocalURL
1716 $url = $this->getLocalURL( $query );
1718 # Expand the url to make it a full url. Note that getLocalURL has the
1719 # potential to output full urls for a variety of reasons, so we use
1720 # wfExpandUrl instead of simply prepending $wgServer
1721 $url = wfExpandUrl( $url, $proto );
1723 # Finally, add the fragment.
1724 $url .= $this->getFragmentForURL();
1725 // Avoid PHP 7.1 warning from passing $this by reference
1727 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1732 * Get a url appropriate for making redirects based on an untrusted url arg
1734 * This is basically the same as getFullUrl(), but in the case of external
1735 * interwikis, we send the user to a landing page, to prevent possible
1736 * phishing attacks and the like.
1738 * @note Uses current protocol by default, since technically relative urls
1739 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1740 * places where the url gets cached, as might pollute between
1741 * https and non-https users.
1742 * @see self::getLocalURL for the arguments.
1743 * @param array|string $query
1744 * @param string $proto Protocol type to use in URL
1745 * @return String. A url suitable to use in an HTTP location header.
1747 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1749 if ( $this->isExternal() ) {
1750 $target = SpecialPage
::getTitleFor(
1752 $this->getPrefixedDBKey()
1755 return $target->getFullUrl( $query, false, $proto );
1759 * Get a URL with no fragment or server name (relative URL) from a Title object.
1760 * If this page is generated with action=render, however,
1761 * $wgServer is prepended to make an absolute URL.
1763 * @see self::getFullURL to always get an absolute URL.
1764 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1765 * valid to link, locally, to the current Title.
1766 * @see self::newFromText to produce a Title object.
1768 * @param string|string[] $query An optional query string,
1769 * not used for interwiki links. Can be specified as an associative array as well,
1770 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1771 * Some query patterns will trigger various shorturl path replacements.
1772 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1773 * be an array. If a string is passed it will be interpreted as a deprecated
1774 * variant argument and urlencoded into a variant= argument.
1775 * This second query argument will be added to the $query
1776 * The second parameter is deprecated since 1.19. Pass it as a key,value
1777 * pair in the first parameter array instead.
1779 * @return string String of the URL.
1781 public function getLocalURL( $query = '', $query2 = false ) {
1782 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1784 $query = self
::fixUrlQueryArgs( $query, $query2 );
1786 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1788 $namespace = $this->getNsText();
1789 if ( $namespace != '' ) {
1790 # Can this actually happen? Interwikis shouldn't be parsed.
1791 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1794 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1795 $url = wfAppendQuery( $url, $query );
1797 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1798 if ( $query == '' ) {
1799 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1800 // Avoid PHP 7.1 warning from passing $this by reference
1802 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1804 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1808 if ( !empty( $wgActionPaths )
1809 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1811 $action = urldecode( $matches[2] );
1812 if ( isset( $wgActionPaths[$action] ) ) {
1813 $query = $matches[1];
1814 if ( isset( $matches[4] ) ) {
1815 $query .= $matches[4];
1817 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1818 if ( $query != '' ) {
1819 $url = wfAppendQuery( $url, $query );
1825 && $wgVariantArticlePath
1826 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1827 && $this->getPageLanguage()->equals( $wgContLang )
1828 && $this->getPageLanguage()->hasVariants()
1830 $variant = urldecode( $matches[1] );
1831 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1832 // Only do the variant replacement if the given variant is a valid
1833 // variant for the page's language.
1834 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1835 $url = str_replace( '$1', $dbkey, $url );
1839 if ( $url === false ) {
1840 if ( $query == '-' ) {
1843 $url = "{$wgScript}?title={$dbkey}&{$query}";
1846 // Avoid PHP 7.1 warning from passing $this by reference
1848 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1850 // @todo FIXME: This causes breakage in various places when we
1851 // actually expected a local URL and end up with dupe prefixes.
1852 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1853 $url = $wgServer . $url;
1856 // Avoid PHP 7.1 warning from passing $this by reference
1858 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1863 * Get a URL that's the simplest URL that will be valid to link, locally,
1864 * to the current Title. It includes the fragment, but does not include
1865 * the server unless action=render is used (or the link is external). If
1866 * there's a fragment but the prefixed text is empty, we just return a link
1869 * The result obviously should not be URL-escaped, but does need to be
1870 * HTML-escaped if it's being output in HTML.
1872 * @param string|string[] $query
1873 * @param bool $query2
1874 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1875 * or false (default) for no expansion
1876 * @see self::getLocalURL for the arguments.
1877 * @return string The URL
1879 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1880 if ( $this->isExternal() ||
$proto !== false ) {
1881 $ret = $this->getFullURL( $query, $query2, $proto );
1882 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1883 $ret = $this->getFragmentForURL();
1885 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1891 * Get the URL form for an internal link.
1892 * - Used in various CDN-related code, in case we have a different
1893 * internal hostname for the server from the exposed one.
1895 * This uses $wgInternalServer to qualify the path, or $wgServer
1896 * if $wgInternalServer is not set. If the server variable used is
1897 * protocol-relative, the URL will be expanded to http://
1899 * @see self::getLocalURL for the arguments.
1900 * @param string $query
1901 * @param string|bool $query2
1902 * @return string The URL
1904 public function getInternalURL( $query = '', $query2 = false ) {
1905 global $wgInternalServer, $wgServer;
1906 $query = self
::fixUrlQueryArgs( $query, $query2 );
1907 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1908 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1909 // Avoid PHP 7.1 warning from passing $this by reference
1911 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1916 * Get the URL for a canonical link, for use in things like IRC and
1917 * e-mail notifications. Uses $wgCanonicalServer and the
1918 * GetCanonicalURL hook.
1920 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1922 * @see self::getLocalURL for the arguments.
1923 * @return string The URL
1926 public function getCanonicalURL( $query = '', $query2 = false ) {
1927 $query = self
::fixUrlQueryArgs( $query, $query2 );
1928 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1929 // Avoid PHP 7.1 warning from passing $this by reference
1931 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1936 * Get the edit URL for this Title
1938 * @return string The URL, or a null string if this is an interwiki link
1940 public function getEditURL() {
1941 if ( $this->isExternal() ) {
1944 $s = $this->getLocalURL( 'action=edit' );
1950 * Can $user perform $action on this page?
1951 * This skips potentially expensive cascading permission checks
1952 * as well as avoids expensive error formatting
1954 * Suitable for use for nonessential UI controls in common cases, but
1955 * _not_ for functional access control.
1957 * May provide false positives, but should never provide a false negative.
1959 * @param string $action Action that permission needs to be checked for
1960 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1963 public function quickUserCan( $action, $user = null ) {
1964 return $this->userCan( $action, $user, false );
1968 * Can $user perform $action on this page?
1970 * @param string $action Action that permission needs to be checked for
1971 * @param User $user User to check (since 1.19); $wgUser will be used if not
1973 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1976 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1977 if ( !$user instanceof User
) {
1982 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1986 * Can $user perform $action on this page?
1988 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1990 * @param string $action Action that permission needs to be checked for
1991 * @param User $user User to check
1992 * @param string $rigor One of (quick,full,secure)
1993 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1994 * - full : does cheap and expensive checks possibly from a replica DB
1995 * - secure : does cheap and expensive checks, using the master as needed
1996 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1997 * whose corresponding errors may be ignored.
1998 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2000 public function getUserPermissionsErrors(
2001 $action, $user, $rigor = 'secure', $ignoreErrors = []
2003 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2005 // Remove the errors being ignored.
2006 foreach ( $errors as $index => $error ) {
2007 $errKey = is_array( $error ) ?
$error[0] : $error;
2009 if ( in_array( $errKey, $ignoreErrors ) ) {
2010 unset( $errors[$index] );
2012 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2013 unset( $errors[$index] );
2021 * Permissions checks that fail most often, and which are easiest to test.
2023 * @param string $action The action to check
2024 * @param User $user User to check
2025 * @param array $errors List of current errors
2026 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2027 * @param bool $short Short circuit on first error
2029 * @return array List of errors
2031 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2032 if ( !Hooks
::run( 'TitleQuickPermissions',
2033 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2038 if ( $action == 'create' ) {
2040 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2041 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2043 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2045 } elseif ( $action == 'move' ) {
2046 if ( !$user->isAllowed( 'move-rootuserpages' )
2047 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2048 // Show user page-specific message only if the user can move other pages
2049 $errors[] = [ 'cant-move-user-page' ];
2052 // Check if user is allowed to move files if it's a file
2053 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2054 $errors[] = [ 'movenotallowedfile' ];
2057 // Check if user is allowed to move category pages if it's a category page
2058 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2059 $errors[] = [ 'cant-move-category-page' ];
2062 if ( !$user->isAllowed( 'move' ) ) {
2063 // User can't move anything
2064 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2065 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2066 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2067 // custom message if logged-in users without any special rights can move
2068 $errors[] = [ 'movenologintext' ];
2070 $errors[] = [ 'movenotallowed' ];
2073 } elseif ( $action == 'move-target' ) {
2074 if ( !$user->isAllowed( 'move' ) ) {
2075 // User can't move anything
2076 $errors[] = [ 'movenotallowed' ];
2077 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2078 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2079 // Show user page-specific message only if the user can move other pages
2080 $errors[] = [ 'cant-move-to-user-page' ];
2081 } elseif ( !$user->isAllowed( 'move-categorypages' )
2082 && $this->mNamespace
== NS_CATEGORY
) {
2083 // Show category page-specific message only if the user can move other pages
2084 $errors[] = [ 'cant-move-to-category-page' ];
2086 } elseif ( !$user->isAllowed( $action ) ) {
2087 $errors[] = $this->missingPermissionError( $action, $short );
2094 * Add the resulting error code to the errors array
2096 * @param array $errors List of current errors
2097 * @param array $result Result of errors
2099 * @return array List of errors
2101 private function resultToError( $errors, $result ) {
2102 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2103 // A single array representing an error
2104 $errors[] = $result;
2105 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2106 // A nested array representing multiple errors
2107 $errors = array_merge( $errors, $result );
2108 } elseif ( $result !== '' && is_string( $result ) ) {
2109 // A string representing a message-id
2110 $errors[] = [ $result ];
2111 } elseif ( $result instanceof MessageSpecifier
) {
2112 // A message specifier representing an error
2113 $errors[] = [ $result ];
2114 } elseif ( $result === false ) {
2115 // a generic "We don't want them to do that"
2116 $errors[] = [ 'badaccess-group0' ];
2122 * Check various permission hooks
2124 * @param string $action The action to check
2125 * @param User $user User to check
2126 * @param array $errors List of current errors
2127 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2128 * @param bool $short Short circuit on first error
2130 * @return array List of errors
2132 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2133 // Use getUserPermissionsErrors instead
2135 // Avoid PHP 7.1 warning from passing $this by reference
2137 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2138 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2140 // Check getUserPermissionsErrors hook
2141 // Avoid PHP 7.1 warning from passing $this by reference
2143 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2144 $errors = $this->resultToError( $errors, $result );
2146 // Check getUserPermissionsErrorsExpensive hook
2149 && !( $short && count( $errors ) > 0 )
2150 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2152 $errors = $this->resultToError( $errors, $result );
2159 * Check permissions on special pages & namespaces
2161 * @param string $action The action to check
2162 * @param User $user User to check
2163 * @param array $errors List of current errors
2164 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2165 * @param bool $short Short circuit on first error
2167 * @return array List of errors
2169 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2170 # Only 'createaccount' can be performed on special pages,
2171 # which don't actually exist in the DB.
2172 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2173 $errors[] = [ 'ns-specialprotected' ];
2176 # Check $wgNamespaceProtection for restricted namespaces
2177 if ( $this->isNamespaceProtected( $user ) ) {
2178 $ns = $this->mNamespace
== NS_MAIN ?
2179 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2180 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2181 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2188 * Check CSS/JS sub-page permissions
2190 * @param string $action The action to check
2191 * @param User $user User to check
2192 * @param array $errors List of current errors
2193 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2194 * @param bool $short Short circuit on first error
2196 * @return array List of errors
2198 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2199 # Protect css/js subpages of user pages
2200 # XXX: this might be better using restrictions
2201 if ( $action != 'patrol' ) {
2202 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2203 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2204 $errors[] = [ 'mycustomcssprotected', $action ];
2205 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2206 $errors[] = [ 'mycustomjsprotected', $action ];
2209 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2210 $errors[] = [ 'customcssprotected', $action ];
2211 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2212 $errors[] = [ 'customjsprotected', $action ];
2221 * Check against page_restrictions table requirements on this
2222 * page. The user must possess all required rights for this
2225 * @param string $action The action to check
2226 * @param User $user User to check
2227 * @param array $errors List of current errors
2228 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2229 * @param bool $short Short circuit on first error
2231 * @return array List of errors
2233 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2234 foreach ( $this->getRestrictions( $action ) as $right ) {
2235 // Backwards compatibility, rewrite sysop -> editprotected
2236 if ( $right == 'sysop' ) {
2237 $right = 'editprotected';
2239 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2240 if ( $right == 'autoconfirmed' ) {
2241 $right = 'editsemiprotected';
2243 if ( $right == '' ) {
2246 if ( !$user->isAllowed( $right ) ) {
2247 $errors[] = [ 'protectedpagetext', $right, $action ];
2248 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2249 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2257 * Check restrictions on cascading pages.
2259 * @param string $action The action to check
2260 * @param User $user User to check
2261 * @param array $errors List of current errors
2262 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2263 * @param bool $short Short circuit on first error
2265 * @return array List of errors
2267 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2268 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2269 # We /could/ use the protection level on the source page, but it's
2270 # fairly ugly as we have to establish a precedence hierarchy for pages
2271 # included by multiple cascade-protected pages. So just restrict
2272 # it to people with 'protect' permission, as they could remove the
2273 # protection anyway.
2274 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2275 # Cascading protection depends on more than this page...
2276 # Several cascading protected pages may include this page...
2277 # Check each cascading level
2278 # This is only for protection restrictions, not for all actions
2279 if ( isset( $restrictions[$action] ) ) {
2280 foreach ( $restrictions[$action] as $right ) {
2281 // Backwards compatibility, rewrite sysop -> editprotected
2282 if ( $right == 'sysop' ) {
2283 $right = 'editprotected';
2285 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2286 if ( $right == 'autoconfirmed' ) {
2287 $right = 'editsemiprotected';
2289 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2291 foreach ( $cascadingSources as $page ) {
2292 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2294 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2304 * Check action permissions not already checked in checkQuickPermissions
2306 * @param string $action The action to check
2307 * @param User $user User to check
2308 * @param array $errors List of current errors
2309 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2310 * @param bool $short Short circuit on first error
2312 * @return array List of errors
2314 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2315 global $wgDeleteRevisionsLimit, $wgLang;
2317 if ( $action == 'protect' ) {
2318 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2319 // If they can't edit, they shouldn't protect.
2320 $errors[] = [ 'protect-cantedit' ];
2322 } elseif ( $action == 'create' ) {
2323 $title_protection = $this->getTitleProtection();
2324 if ( $title_protection ) {
2325 if ( $title_protection['permission'] == ''
2326 ||
!$user->isAllowed( $title_protection['permission'] )
2330 User
::whoIs( $title_protection['user'] ),
2331 $title_protection['reason']
2335 } elseif ( $action == 'move' ) {
2336 // Check for immobile pages
2337 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2338 // Specific message for this case
2339 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2340 } elseif ( !$this->isMovable() ) {
2341 // Less specific message for rarer cases
2342 $errors[] = [ 'immobile-source-page' ];
2344 } elseif ( $action == 'move-target' ) {
2345 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2346 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2347 } elseif ( !$this->isMovable() ) {
2348 $errors[] = [ 'immobile-target-page' ];
2350 } elseif ( $action == 'delete' ) {
2351 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2352 if ( !$tempErrors ) {
2353 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2354 $user, $tempErrors, $rigor, true );
2356 if ( $tempErrors ) {
2357 // If protection keeps them from editing, they shouldn't be able to delete.
2358 $errors[] = [ 'deleteprotected' ];
2360 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2361 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2363 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2365 } elseif ( $action === 'undelete' ) {
2366 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2367 // Undeleting implies editing
2368 $errors[] = [ 'undelete-cantedit' ];
2370 if ( !$this->exists()
2371 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2373 // Undeleting where nothing currently exists implies creating
2374 $errors[] = [ 'undelete-cantcreate' ];
2381 * Check that the user isn't blocked from editing.
2383 * @param string $action The action to check
2384 * @param User $user User to check
2385 * @param array $errors List of current errors
2386 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2387 * @param bool $short Short circuit on first error
2389 * @return array List of errors
2391 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2392 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2393 // Account creation blocks handled at userlogin.
2394 // Unblocking handled in SpecialUnblock
2395 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2399 // Optimize for a very common case
2400 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2404 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2405 $errors[] = [ 'confirmedittext' ];
2408 $useSlave = ( $rigor !== 'secure' );
2409 if ( ( $action == 'edit' ||
$action == 'create' )
2410 && !$user->isBlockedFrom( $this, $useSlave )
2412 // Don't block the user from editing their own talk page unless they've been
2413 // explicitly blocked from that too.
2414 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2415 // @todo FIXME: Pass the relevant context into this function.
2416 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2423 * Check that the user is allowed to read this page.
2425 * @param string $action The action to check
2426 * @param User $user User to check
2427 * @param array $errors List of current errors
2428 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2429 * @param bool $short Short circuit on first error
2431 * @return array List of errors
2433 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2434 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2436 $whitelisted = false;
2437 if ( User
::isEveryoneAllowed( 'read' ) ) {
2438 # Shortcut for public wikis, allows skipping quite a bit of code
2439 $whitelisted = true;
2440 } elseif ( $user->isAllowed( 'read' ) ) {
2441 # If the user is allowed to read pages, he is allowed to read all pages
2442 $whitelisted = true;
2443 } elseif ( $this->isSpecial( 'Userlogin' )
2444 ||
$this->isSpecial( 'PasswordReset' )
2445 ||
$this->isSpecial( 'Userlogout' )
2447 # Always grant access to the login page.
2448 # Even anons need to be able to log in.
2449 $whitelisted = true;
2450 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2451 # Time to check the whitelist
2452 # Only do these checks is there's something to check against
2453 $name = $this->getPrefixedText();
2454 $dbName = $this->getPrefixedDBkey();
2456 // Check for explicit whitelisting with and without underscores
2457 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2458 $whitelisted = true;
2459 } elseif ( $this->getNamespace() == NS_MAIN
) {
2460 # Old settings might have the title prefixed with
2461 # a colon for main-namespace pages
2462 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2463 $whitelisted = true;
2465 } elseif ( $this->isSpecialPage() ) {
2466 # If it's a special page, ditch the subpage bit and check again
2467 $name = $this->getDBkey();
2468 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2470 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2471 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2472 $whitelisted = true;
2478 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2479 $name = $this->getPrefixedText();
2480 // Check for regex whitelisting
2481 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2482 if ( preg_match( $listItem, $name ) ) {
2483 $whitelisted = true;
2489 if ( !$whitelisted ) {
2490 # If the title is not whitelisted, give extensions a chance to do so...
2491 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2492 if ( !$whitelisted ) {
2493 $errors[] = $this->missingPermissionError( $action, $short );
2501 * Get a description array when the user doesn't have the right to perform
2502 * $action (i.e. when User::isAllowed() returns false)
2504 * @param string $action The action to check
2505 * @param bool $short Short circuit on first error
2506 * @return array Array containing an error message key and any parameters
2508 private function missingPermissionError( $action, $short ) {
2509 // We avoid expensive display logic for quickUserCan's and such
2511 return [ 'badaccess-group0' ];
2514 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2518 * Can $user perform $action on this page? This is an internal function,
2519 * with multiple levels of checks depending on performance needs; see $rigor below.
2520 * It does not check wfReadOnly().
2522 * @param string $action Action that permission needs to be checked for
2523 * @param User $user User to check
2524 * @param string $rigor One of (quick,full,secure)
2525 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2526 * - full : does cheap and expensive checks possibly from a replica DB
2527 * - secure : does cheap and expensive checks, using the master as needed
2528 * @param bool $short Set this to true to stop after the first permission error.
2529 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2531 protected function getUserPermissionsErrorsInternal(
2532 $action, $user, $rigor = 'secure', $short = false
2534 if ( $rigor === true ) {
2535 $rigor = 'secure'; // b/c
2536 } elseif ( $rigor === false ) {
2537 $rigor = 'quick'; // b/c
2538 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2539 throw new Exception( "Invalid rigor parameter '$rigor'." );
2542 # Read has special handling
2543 if ( $action == 'read' ) {
2545 'checkPermissionHooks',
2546 'checkReadPermissions',
2547 'checkUserBlock', // for wgBlockDisablesLogin
2549 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2550 # here as it will lead to duplicate error messages. This is okay to do
2551 # since anywhere that checks for create will also check for edit, and
2552 # those checks are called for edit.
2553 } elseif ( $action == 'create' ) {
2555 'checkQuickPermissions',
2556 'checkPermissionHooks',
2557 'checkPageRestrictions',
2558 'checkCascadingSourcesRestrictions',
2559 'checkActionPermissions',
2564 'checkQuickPermissions',
2565 'checkPermissionHooks',
2566 'checkSpecialsAndNSPermissions',
2567 'checkCSSandJSPermissions',
2568 'checkPageRestrictions',
2569 'checkCascadingSourcesRestrictions',
2570 'checkActionPermissions',
2576 while ( count( $checks ) > 0 &&
2577 !( $short && count( $errors ) > 0 ) ) {
2578 $method = array_shift( $checks );
2579 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2586 * Get a filtered list of all restriction types supported by this wiki.
2587 * @param bool $exists True to get all restriction types that apply to
2588 * titles that do exist, False for all restriction types that apply to
2589 * titles that do not exist
2592 public static function getFilteredRestrictionTypes( $exists = true ) {
2593 global $wgRestrictionTypes;
2594 $types = $wgRestrictionTypes;
2596 # Remove the create restriction for existing titles
2597 $types = array_diff( $types, [ 'create' ] );
2599 # Only the create and upload restrictions apply to non-existing titles
2600 $types = array_intersect( $types, [ 'create', 'upload' ] );
2606 * Returns restriction types for the current Title
2608 * @return array Applicable restriction types
2610 public function getRestrictionTypes() {
2611 if ( $this->isSpecialPage() ) {
2615 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2617 if ( $this->getNamespace() != NS_FILE
) {
2618 # Remove the upload restriction for non-file titles
2619 $types = array_diff( $types, [ 'upload' ] );
2622 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2624 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2625 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2631 * Is this title subject to title protection?
2632 * Title protection is the one applied against creation of such title.
2634 * @return array|bool An associative array representing any existent title
2635 * protection, or false if there's none.
2637 public function getTitleProtection() {
2638 $protection = $this->getTitleProtectionInternal();
2639 if ( $protection ) {
2640 if ( $protection['permission'] == 'sysop' ) {
2641 $protection['permission'] = 'editprotected'; // B/C
2643 if ( $protection['permission'] == 'autoconfirmed' ) {
2644 $protection['permission'] = 'editsemiprotected'; // B/C
2651 * Fetch title protection settings
2653 * To work correctly, $this->loadRestrictions() needs to have access to the
2654 * actual protections in the database without munging 'sysop' =>
2655 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2656 * callers probably want $this->getTitleProtection() instead.
2658 * @return array|bool
2660 protected function getTitleProtectionInternal() {
2661 // Can't protect pages in special namespaces
2662 if ( $this->getNamespace() < 0 ) {
2666 // Can't protect pages that exist.
2667 if ( $this->exists() ) {
2671 if ( $this->mTitleProtection
=== null ) {
2672 $dbr = wfGetDB( DB_REPLICA
);
2673 $res = $dbr->select(
2676 'user' => 'pt_user',
2677 'reason' => 'pt_reason',
2678 'expiry' => 'pt_expiry',
2679 'permission' => 'pt_create_perm'
2681 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2685 // fetchRow returns false if there are no rows.
2686 $row = $dbr->fetchRow( $res );
2688 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2690 $this->mTitleProtection
= $row;
2692 return $this->mTitleProtection
;
2696 * Remove any title protection due to page existing
2698 public function deleteTitleProtection() {
2699 $dbw = wfGetDB( DB_MASTER
);
2703 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2706 $this->mTitleProtection
= false;
2710 * Is this page "semi-protected" - the *only* protection levels are listed
2711 * in $wgSemiprotectedRestrictionLevels?
2713 * @param string $action Action to check (default: edit)
2716 public function isSemiProtected( $action = 'edit' ) {
2717 global $wgSemiprotectedRestrictionLevels;
2719 $restrictions = $this->getRestrictions( $action );
2720 $semi = $wgSemiprotectedRestrictionLevels;
2721 if ( !$restrictions ||
!$semi ) {
2722 // Not protected, or all protection is full protection
2726 // Remap autoconfirmed to editsemiprotected for BC
2727 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2728 $semi[$key] = 'editsemiprotected';
2730 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2731 $restrictions[$key] = 'editsemiprotected';
2734 return !array_diff( $restrictions, $semi );
2738 * Does the title correspond to a protected article?
2740 * @param string $action The action the page is protected from,
2741 * by default checks all actions.
2744 public function isProtected( $action = '' ) {
2745 global $wgRestrictionLevels;
2747 $restrictionTypes = $this->getRestrictionTypes();
2749 # Special pages have inherent protection
2750 if ( $this->isSpecialPage() ) {
2754 # Check regular protection levels
2755 foreach ( $restrictionTypes as $type ) {
2756 if ( $action == $type ||
$action == '' ) {
2757 $r = $this->getRestrictions( $type );
2758 foreach ( $wgRestrictionLevels as $level ) {
2759 if ( in_array( $level, $r ) && $level != '' ) {
2770 * Determines if $user is unable to edit this page because it has been protected
2771 * by $wgNamespaceProtection.
2773 * @param User $user User object to check permissions
2776 public function isNamespaceProtected( User
$user ) {
2777 global $wgNamespaceProtection;
2779 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2780 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2781 if ( $right != '' && !$user->isAllowed( $right ) ) {
2790 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2792 * @return bool If the page is subject to cascading restrictions.
2794 public function isCascadeProtected() {
2795 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2796 return ( $sources > 0 );
2800 * Determines whether cascading protection sources have already been loaded from
2803 * @param bool $getPages True to check if the pages are loaded, or false to check
2804 * if the status is loaded.
2805 * @return bool Whether or not the specified information has been loaded
2808 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2809 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2813 * Cascading protection: Get the source of any cascading restrictions on this page.
2815 * @param bool $getPages Whether or not to retrieve the actual pages
2816 * that the restrictions have come from and the actual restrictions
2818 * @return array Two elements: First is an array of Title objects of the
2819 * pages from which cascading restrictions have come, false for
2820 * none, or true if such restrictions exist but $getPages was not
2821 * set. Second is an array like that returned by
2822 * Title::getAllRestrictions(), or an empty array if $getPages is
2825 public function getCascadeProtectionSources( $getPages = true ) {
2826 $pagerestrictions = [];
2828 if ( $this->mCascadeSources
!== null && $getPages ) {
2829 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2830 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2831 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2834 $dbr = wfGetDB( DB_REPLICA
);
2836 if ( $this->getNamespace() == NS_FILE
) {
2837 $tables = [ 'imagelinks', 'page_restrictions' ];
2839 'il_to' => $this->getDBkey(),
2844 $tables = [ 'templatelinks', 'page_restrictions' ];
2846 'tl_namespace' => $this->getNamespace(),
2847 'tl_title' => $this->getDBkey(),
2854 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2855 'pr_expiry', 'pr_type', 'pr_level' ];
2856 $where_clauses[] = 'page_id=pr_page';
2859 $cols = [ 'pr_expiry' ];
2862 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2864 $sources = $getPages ?
[] : false;
2865 $now = wfTimestampNow();
2867 foreach ( $res as $row ) {
2868 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2869 if ( $expiry > $now ) {
2871 $page_id = $row->pr_page
;
2872 $page_ns = $row->page_namespace
;
2873 $page_title = $row->page_title
;
2874 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2875 # Add groups needed for each restriction type if its not already there
2876 # Make sure this restriction type still exists
2878 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2879 $pagerestrictions[$row->pr_type
] = [];
2883 isset( $pagerestrictions[$row->pr_type
] )
2884 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2886 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2895 $this->mCascadeSources
= $sources;
2896 $this->mCascadingRestrictions
= $pagerestrictions;
2898 $this->mHasCascadingRestrictions
= $sources;
2901 return [ $sources, $pagerestrictions ];
2905 * Accessor for mRestrictionsLoaded
2907 * @return bool Whether or not the page's restrictions have already been
2908 * loaded from the database
2911 public function areRestrictionsLoaded() {
2912 return $this->mRestrictionsLoaded
;
2916 * Accessor/initialisation for mRestrictions
2918 * @param string $action Action that permission needs to be checked for
2919 * @return array Restriction levels needed to take the action. All levels are
2920 * required. Note that restriction levels are normally user rights, but 'sysop'
2921 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2922 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2924 public function getRestrictions( $action ) {
2925 if ( !$this->mRestrictionsLoaded
) {
2926 $this->loadRestrictions();
2928 return isset( $this->mRestrictions
[$action] )
2929 ?
$this->mRestrictions
[$action]
2934 * Accessor/initialisation for mRestrictions
2936 * @return array Keys are actions, values are arrays as returned by
2937 * Title::getRestrictions()
2940 public function getAllRestrictions() {
2941 if ( !$this->mRestrictionsLoaded
) {
2942 $this->loadRestrictions();
2944 return $this->mRestrictions
;
2948 * Get the expiry time for the restriction against a given action
2950 * @param string $action
2951 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2952 * or not protected at all, or false if the action is not recognised.
2954 public function getRestrictionExpiry( $action ) {
2955 if ( !$this->mRestrictionsLoaded
) {
2956 $this->loadRestrictions();
2958 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2962 * Returns cascading restrictions for the current article
2966 function areRestrictionsCascading() {
2967 if ( !$this->mRestrictionsLoaded
) {
2968 $this->loadRestrictions();
2971 return $this->mCascadeRestriction
;
2975 * Compiles list of active page restrictions from both page table (pre 1.10)
2976 * and page_restrictions table for this existing page.
2977 * Public for usage by LiquidThreads.
2979 * @param array $rows Array of db result objects
2980 * @param string $oldFashionedRestrictions Comma-separated list of page
2981 * restrictions from page table (pre 1.10)
2983 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2984 $dbr = wfGetDB( DB_REPLICA
);
2986 $restrictionTypes = $this->getRestrictionTypes();
2988 foreach ( $restrictionTypes as $type ) {
2989 $this->mRestrictions
[$type] = [];
2990 $this->mRestrictionsExpiry
[$type] = 'infinity';
2993 $this->mCascadeRestriction
= false;
2995 # Backwards-compatibility: also load the restrictions from the page record (old format).
2996 if ( $oldFashionedRestrictions !== null ) {
2997 $this->mOldRestrictions
= $oldFashionedRestrictions;
3000 if ( $this->mOldRestrictions
=== false ) {
3001 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3002 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3005 if ( $this->mOldRestrictions
!= '' ) {
3006 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3007 $temp = explode( '=', trim( $restrict ) );
3008 if ( count( $temp ) == 1 ) {
3009 // old old format should be treated as edit/move restriction
3010 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3011 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3013 $restriction = trim( $temp[1] );
3014 if ( $restriction != '' ) { // some old entries are empty
3015 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3021 if ( count( $rows ) ) {
3022 # Current system - load second to make them override.
3023 $now = wfTimestampNow();
3025 # Cycle through all the restrictions.
3026 foreach ( $rows as $row ) {
3027 // Don't take care of restrictions types that aren't allowed
3028 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3032 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3034 // Only apply the restrictions if they haven't expired!
3035 if ( !$expiry ||
$expiry > $now ) {
3036 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3037 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3039 $this->mCascadeRestriction |
= $row->pr_cascade
;
3044 $this->mRestrictionsLoaded
= true;
3048 * Load restrictions from the page_restrictions table
3050 * @param string $oldFashionedRestrictions Comma-separated list of page
3051 * restrictions from page table (pre 1.10)
3053 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3054 if ( $this->mRestrictionsLoaded
) {
3058 $id = $this->getArticleID();
3060 $cache = ObjectCache
::getMainWANInstance();
3061 $rows = $cache->getWithSetCallback(
3062 // Page protections always leave a new null revision
3063 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3065 function ( $curValue, &$ttl, array &$setOpts ) {
3066 $dbr = wfGetDB( DB_REPLICA
);
3068 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3070 return iterator_to_array(
3072 'page_restrictions',
3073 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3074 [ 'pr_page' => $this->getArticleID() ],
3081 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3083 $title_protection = $this->getTitleProtectionInternal();
3085 if ( $title_protection ) {
3086 $now = wfTimestampNow();
3087 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3089 if ( !$expiry ||
$expiry > $now ) {
3090 // Apply the restrictions
3091 $this->mRestrictionsExpiry
['create'] = $expiry;
3092 $this->mRestrictions
['create'] =
3093 explode( ',', trim( $title_protection['permission'] ) );
3094 } else { // Get rid of the old restrictions
3095 $this->mTitleProtection
= false;
3098 $this->mRestrictionsExpiry
['create'] = 'infinity';
3100 $this->mRestrictionsLoaded
= true;
3105 * Flush the protection cache in this object and force reload from the database.
3106 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3108 public function flushRestrictions() {
3109 $this->mRestrictionsLoaded
= false;
3110 $this->mTitleProtection
= null;
3114 * Purge expired restrictions from the page_restrictions table
3116 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3118 static function purgeExpiredRestrictions() {
3119 if ( wfReadOnly() ) {
3123 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3124 wfGetDB( DB_MASTER
),
3126 function ( IDatabase