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 * @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 === self
::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 self
::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( self
::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 self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1320 * Get a Title object associated with the talk page of this article,
1321 * if such a talk page can exist.
1323 * @return Title The object for the talk page,
1324 * or null if no associated talk page can exist, according to canHaveTalkPage().
1326 public function getTalkPageIfDefined() {
1327 if ( !$this->canHaveTalkPage() ) {
1331 return $this->getTalkPage();
1335 * Get a title object associated with the subject page of this
1338 * @return Title The object for the subject page
1340 public function getSubjectPage() {
1341 // Is this the same title?
1342 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1343 if ( $this->getNamespace() == $subjectNS ) {
1346 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1350 * Get the other title for this page, if this is a subject page
1351 * get the talk page, if it is a subject page get the talk page
1354 * @throws MWException
1357 public function getOtherPage() {
1358 if ( $this->isSpecialPage() ) {
1359 throw new MWException( 'Special pages cannot have other pages' );
1361 if ( $this->isTalkPage() ) {
1362 return $this->getSubjectPage();
1364 return $this->getTalkPage();
1369 * Get the default namespace index, for when there is no namespace
1371 * @return int Default namespace index
1373 public function getDefaultNamespace() {
1374 return $this->mDefaultNamespace
;
1378 * Get the Title fragment (i.e.\ the bit after the #) in text form
1380 * Use Title::hasFragment to check for a fragment
1382 * @return string Title fragment
1384 public function getFragment() {
1385 return $this->mFragment
;
1389 * Check if a Title fragment is set
1394 public function hasFragment() {
1395 return $this->mFragment
!== '';
1399 * Get the fragment in URL form, including the "#" character if there is one
1400 * @return string Fragment in URL form
1402 public function getFragmentForURL() {
1403 if ( !$this->hasFragment() ) {
1406 return '#' . self
::escapeFragmentForURL( $this->getFragment() );
1411 * Set the fragment for this title. Removes the first character from the
1412 * specified fragment before setting, so it assumes you're passing it with
1415 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1416 * or Title::createFragmentTarget().
1417 * Still in active use privately.
1420 * @param string $fragment Text
1422 public function setFragment( $fragment ) {
1423 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1427 * Creates a new Title for a different fragment of the same page.
1430 * @param string $fragment
1433 public function createFragmentTarget( $fragment ) {
1434 return self
::makeTitle(
1435 $this->getNamespace(),
1438 $this->getInterwiki()
1443 * Prefix some arbitrary text with the namespace or interwiki prefix
1446 * @param string $name The text
1447 * @return string The prefixed text
1449 private function prefix( $name ) {
1453 if ( $this->isExternal() ) {
1454 $p = $this->mInterwiki
. ':';
1457 if ( 0 != $this->mNamespace
) {
1458 $nsText = $this->getNsText();
1460 if ( $nsText === false ) {
1461 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1462 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1465 $p .= $nsText . ':';
1471 * Get the prefixed database key form
1473 * @return string The prefixed title, with underscores and
1474 * any interwiki and namespace prefixes
1476 public function getPrefixedDBkey() {
1477 $s = $this->prefix( $this->mDbkeyform
);
1478 $s = strtr( $s, ' ', '_' );
1483 * Get the prefixed title with spaces.
1484 * This is the form usually used for display
1486 * @return string The prefixed title, with spaces
1488 public function getPrefixedText() {
1489 if ( $this->mPrefixedText
=== null ) {
1490 $s = $this->prefix( $this->mTextform
);
1491 $s = strtr( $s, '_', ' ' );
1492 $this->mPrefixedText
= $s;
1494 return $this->mPrefixedText
;
1498 * Return a string representation of this title
1500 * @return string Representation of this title
1502 public function __toString() {
1503 return $this->getPrefixedText();
1507 * Get the prefixed title with spaces, plus any fragment
1508 * (part beginning with '#')
1510 * @return string The prefixed title, with spaces and the fragment, including '#'
1512 public function getFullText() {
1513 $text = $this->getPrefixedText();
1514 if ( $this->hasFragment() ) {
1515 $text .= '#' . $this->getFragment();
1521 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1525 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1529 * @return string Root name
1532 public function getRootText() {
1533 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1534 return $this->getText();
1537 return strtok( $this->getText(), '/' );
1541 * Get the root page name title, i.e. the leftmost part before any slashes
1545 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1546 * # returns: Title{User:Foo}
1549 * @return Title Root title
1552 public function getRootTitle() {
1553 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1557 * Get the base page name without a namespace, i.e. the part before the subpage name
1561 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1562 * # returns: 'Foo/Bar'
1565 * @return string Base name
1567 public function getBaseText() {
1568 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1569 return $this->getText();
1572 $parts = explode( '/', $this->getText() );
1573 # Don't discard the real title if there's no subpage involved
1574 if ( count( $parts ) > 1 ) {
1575 unset( $parts[count( $parts ) - 1] );
1577 return implode( '/', $parts );
1581 * Get the base page name title, i.e. the part before the subpage name
1585 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1586 * # returns: Title{User:Foo/Bar}
1589 * @return Title Base title
1592 public function getBaseTitle() {
1593 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1597 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1601 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1605 * @return string Subpage name
1607 public function getSubpageText() {
1608 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1609 return $this->mTextform
;
1611 $parts = explode( '/', $this->mTextform
);
1612 return $parts[count( $parts ) - 1];
1616 * Get the title for a subpage of the current page
1620 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1621 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1624 * @param string $text The subpage name to add to the title
1625 * @return Title Subpage title
1628 public function getSubpage( $text ) {
1629 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1633 * Get a URL-encoded form of the subpage text
1635 * @return string URL-encoded subpage name
1637 public function getSubpageUrlForm() {
1638 $text = $this->getSubpageText();
1639 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1644 * Get a URL-encoded title (not an actual URL) including interwiki
1646 * @return string The URL-encoded form
1648 public function getPrefixedURL() {
1649 $s = $this->prefix( $this->mDbkeyform
);
1650 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1655 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1656 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1657 * second argument named variant. This was deprecated in favor
1658 * of passing an array of option with a "variant" key
1659 * Once $query2 is removed for good, this helper can be dropped
1660 * and the wfArrayToCgi moved to getLocalURL();
1662 * @since 1.19 (r105919)
1663 * @param array|string $query
1664 * @param string|string[]|bool $query2
1667 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1668 if ( $query2 !== false ) {
1669 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1670 "method called with a second parameter is deprecated. Add your " .
1671 "parameter to an array passed as the first parameter.", "1.19" );
1673 if ( is_array( $query ) ) {
1674 $query = wfArrayToCgi( $query );
1677 if ( is_string( $query2 ) ) {
1678 // $query2 is a string, we will consider this to be
1679 // a deprecated $variant argument and add it to the query
1680 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1682 $query2 = wfArrayToCgi( $query2 );
1684 // If we have $query content add a & to it first
1688 // Now append the queries together
1695 * Get a real URL referring to this title, with interwiki link and
1698 * @see self::getLocalURL for the arguments.
1700 * @param string|string[] $query
1701 * @param string|string[]|bool $query2
1702 * @param string $proto Protocol type to use in URL
1703 * @return string The URL
1705 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1706 $query = self
::fixUrlQueryArgs( $query, $query2 );
1708 # Hand off all the decisions on urls to getLocalURL
1709 $url = $this->getLocalURL( $query );
1711 # Expand the url to make it a full url. Note that getLocalURL has the
1712 # potential to output full urls for a variety of reasons, so we use
1713 # wfExpandUrl instead of simply prepending $wgServer
1714 $url = wfExpandUrl( $url, $proto );
1716 # Finally, add the fragment.
1717 $url .= $this->getFragmentForURL();
1718 // Avoid PHP 7.1 warning from passing $this by reference
1720 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1725 * Get a url appropriate for making redirects based on an untrusted url arg
1727 * This is basically the same as getFullUrl(), but in the case of external
1728 * interwikis, we send the user to a landing page, to prevent possible
1729 * phishing attacks and the like.
1731 * @note Uses current protocol by default, since technically relative urls
1732 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1733 * places where the url gets cached, as might pollute between
1734 * https and non-https users.
1735 * @see self::getLocalURL for the arguments.
1736 * @param array|string $query
1737 * @param string $proto Protocol type to use in URL
1738 * @return String. A url suitable to use in an HTTP location header.
1740 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1742 if ( $this->isExternal() ) {
1743 $target = SpecialPage
::getTitleFor(
1745 $this->getPrefixedDBKey()
1748 return $target->getFullUrl( $query, false, $proto );
1752 * Get a URL with no fragment or server name (relative URL) from a Title object.
1753 * If this page is generated with action=render, however,
1754 * $wgServer is prepended to make an absolute URL.
1756 * @see self::getFullURL to always get an absolute URL.
1757 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1758 * valid to link, locally, to the current Title.
1759 * @see self::newFromText to produce a Title object.
1761 * @param string|string[] $query An optional query string,
1762 * not used for interwiki links. Can be specified as an associative array as well,
1763 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1764 * Some query patterns will trigger various shorturl path replacements.
1765 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1766 * be an array. If a string is passed it will be interpreted as a deprecated
1767 * variant argument and urlencoded into a variant= argument.
1768 * This second query argument will be added to the $query
1769 * The second parameter is deprecated since 1.19. Pass it as a key,value
1770 * pair in the first parameter array instead.
1772 * @return string String of the URL.
1774 public function getLocalURL( $query = '', $query2 = false ) {
1775 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1777 $query = self
::fixUrlQueryArgs( $query, $query2 );
1779 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1781 $namespace = $this->getNsText();
1782 if ( $namespace != '' ) {
1783 # Can this actually happen? Interwikis shouldn't be parsed.
1784 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1787 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1788 $url = wfAppendQuery( $url, $query );
1790 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1791 if ( $query == '' ) {
1792 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1793 // Avoid PHP 7.1 warning from passing $this by reference
1795 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1797 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1801 if ( !empty( $wgActionPaths )
1802 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1804 $action = urldecode( $matches[2] );
1805 if ( isset( $wgActionPaths[$action] ) ) {
1806 $query = $matches[1];
1807 if ( isset( $matches[4] ) ) {
1808 $query .= $matches[4];
1810 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1811 if ( $query != '' ) {
1812 $url = wfAppendQuery( $url, $query );
1818 && $wgVariantArticlePath
1819 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1820 && $this->getPageLanguage()->equals( $wgContLang )
1821 && $this->getPageLanguage()->hasVariants()
1823 $variant = urldecode( $matches[1] );
1824 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1825 // Only do the variant replacement if the given variant is a valid
1826 // variant for the page's language.
1827 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1828 $url = str_replace( '$1', $dbkey, $url );
1832 if ( $url === false ) {
1833 if ( $query == '-' ) {
1836 $url = "{$wgScript}?title={$dbkey}&{$query}";
1839 // Avoid PHP 7.1 warning from passing $this by reference
1841 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1843 // @todo FIXME: This causes breakage in various places when we
1844 // actually expected a local URL and end up with dupe prefixes.
1845 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1846 $url = $wgServer . $url;
1849 // Avoid PHP 7.1 warning from passing $this by reference
1851 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1856 * Get a URL that's the simplest URL that will be valid to link, locally,
1857 * to the current Title. It includes the fragment, but does not include
1858 * the server unless action=render is used (or the link is external). If
1859 * there's a fragment but the prefixed text is empty, we just return a link
1862 * The result obviously should not be URL-escaped, but does need to be
1863 * HTML-escaped if it's being output in HTML.
1865 * @param string|string[] $query
1866 * @param bool $query2
1867 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1868 * or false (default) for no expansion
1869 * @see self::getLocalURL for the arguments.
1870 * @return string The URL
1872 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1873 if ( $this->isExternal() ||
$proto !== false ) {
1874 $ret = $this->getFullURL( $query, $query2, $proto );
1875 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1876 $ret = $this->getFragmentForURL();
1878 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1884 * Get the URL form for an internal link.
1885 * - Used in various CDN-related code, in case we have a different
1886 * internal hostname for the server from the exposed one.
1888 * This uses $wgInternalServer to qualify the path, or $wgServer
1889 * if $wgInternalServer is not set. If the server variable used is
1890 * protocol-relative, the URL will be expanded to http://
1892 * @see self::getLocalURL for the arguments.
1893 * @return string The URL
1895 public function getInternalURL( $query = '', $query2 = false ) {
1896 global $wgInternalServer, $wgServer;
1897 $query = self
::fixUrlQueryArgs( $query, $query2 );
1898 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1899 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1900 // Avoid PHP 7.1 warning from passing $this by reference
1902 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1907 * Get the URL for a canonical link, for use in things like IRC and
1908 * e-mail notifications. Uses $wgCanonicalServer and the
1909 * GetCanonicalURL hook.
1911 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1913 * @see self::getLocalURL for the arguments.
1914 * @return string The URL
1917 public function getCanonicalURL( $query = '', $query2 = false ) {
1918 $query = self
::fixUrlQueryArgs( $query, $query2 );
1919 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1920 // Avoid PHP 7.1 warning from passing $this by reference
1922 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1927 * Get the edit URL for this Title
1929 * @return string The URL, or a null string if this is an interwiki link
1931 public function getEditURL() {
1932 if ( $this->isExternal() ) {
1935 $s = $this->getLocalURL( 'action=edit' );
1941 * Can $user perform $action on this page?
1942 * This skips potentially expensive cascading permission checks
1943 * as well as avoids expensive error formatting
1945 * Suitable for use for nonessential UI controls in common cases, but
1946 * _not_ for functional access control.
1948 * May provide false positives, but should never provide a false negative.
1950 * @param string $action Action that permission needs to be checked for
1951 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1954 public function quickUserCan( $action, $user = null ) {
1955 return $this->userCan( $action, $user, false );
1959 * Can $user perform $action on this page?
1961 * @param string $action Action that permission needs to be checked for
1962 * @param User $user User to check (since 1.19); $wgUser will be used if not
1964 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1967 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1968 if ( !$user instanceof User
) {
1973 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1977 * Can $user perform $action on this page?
1979 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1981 * @param string $action Action that permission needs to be checked for
1982 * @param User $user User to check
1983 * @param string $rigor One of (quick,full,secure)
1984 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1985 * - full : does cheap and expensive checks possibly from a replica DB
1986 * - secure : does cheap and expensive checks, using the master as needed
1987 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1988 * whose corresponding errors may be ignored.
1989 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1991 public function getUserPermissionsErrors(
1992 $action, $user, $rigor = 'secure', $ignoreErrors = []
1994 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1996 // Remove the errors being ignored.
1997 foreach ( $errors as $index => $error ) {
1998 $errKey = is_array( $error ) ?
$error[0] : $error;
2000 if ( in_array( $errKey, $ignoreErrors ) ) {
2001 unset( $errors[$index] );
2003 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2004 unset( $errors[$index] );
2012 * Permissions checks that fail most often, and which are easiest to test.
2014 * @param string $action The action to check
2015 * @param User $user User to check
2016 * @param array $errors List of current errors
2017 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2018 * @param bool $short Short circuit on first error
2020 * @return array List of errors
2022 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2023 if ( !Hooks
::run( 'TitleQuickPermissions',
2024 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2029 if ( $action == 'create' ) {
2031 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2032 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2034 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2036 } elseif ( $action == 'move' ) {
2037 if ( !$user->isAllowed( 'move-rootuserpages' )
2038 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2039 // Show user page-specific message only if the user can move other pages
2040 $errors[] = [ 'cant-move-user-page' ];
2043 // Check if user is allowed to move files if it's a file
2044 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2045 $errors[] = [ 'movenotallowedfile' ];
2048 // Check if user is allowed to move category pages if it's a category page
2049 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2050 $errors[] = [ 'cant-move-category-page' ];
2053 if ( !$user->isAllowed( 'move' ) ) {
2054 // User can't move anything
2055 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2056 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2057 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2058 // custom message if logged-in users without any special rights can move
2059 $errors[] = [ 'movenologintext' ];
2061 $errors[] = [ 'movenotallowed' ];
2064 } elseif ( $action == 'move-target' ) {
2065 if ( !$user->isAllowed( 'move' ) ) {
2066 // User can't move anything
2067 $errors[] = [ 'movenotallowed' ];
2068 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2069 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2070 // Show user page-specific message only if the user can move other pages
2071 $errors[] = [ 'cant-move-to-user-page' ];
2072 } elseif ( !$user->isAllowed( 'move-categorypages' )
2073 && $this->mNamespace
== NS_CATEGORY
) {
2074 // Show category page-specific message only if the user can move other pages
2075 $errors[] = [ 'cant-move-to-category-page' ];
2077 } elseif ( !$user->isAllowed( $action ) ) {
2078 $errors[] = $this->missingPermissionError( $action, $short );
2085 * Add the resulting error code to the errors array
2087 * @param array $errors List of current errors
2088 * @param array $result Result of errors
2090 * @return array List of errors
2092 private function resultToError( $errors, $result ) {
2093 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2094 // A single array representing an error
2095 $errors[] = $result;
2096 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2097 // A nested array representing multiple errors
2098 $errors = array_merge( $errors, $result );
2099 } elseif ( $result !== '' && is_string( $result ) ) {
2100 // A string representing a message-id
2101 $errors[] = [ $result ];
2102 } elseif ( $result instanceof MessageSpecifier
) {
2103 // A message specifier representing an error
2104 $errors[] = [ $result ];
2105 } elseif ( $result === false ) {
2106 // a generic "We don't want them to do that"
2107 $errors[] = [ 'badaccess-group0' ];
2113 * Check various permission hooks
2115 * @param string $action The action to check
2116 * @param User $user User to check
2117 * @param array $errors List of current errors
2118 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2119 * @param bool $short Short circuit on first error
2121 * @return array List of errors
2123 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2124 // Use getUserPermissionsErrors instead
2126 // Avoid PHP 7.1 warning from passing $this by reference
2128 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2129 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2131 // Check getUserPermissionsErrors hook
2132 // Avoid PHP 7.1 warning from passing $this by reference
2134 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2135 $errors = $this->resultToError( $errors, $result );
2137 // Check getUserPermissionsErrorsExpensive hook
2140 && !( $short && count( $errors ) > 0 )
2141 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2143 $errors = $this->resultToError( $errors, $result );
2150 * Check permissions on special pages & namespaces
2152 * @param string $action The action to check
2153 * @param User $user User to check
2154 * @param array $errors List of current errors
2155 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2156 * @param bool $short Short circuit on first error
2158 * @return array List of errors
2160 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2161 # Only 'createaccount' can be performed on special pages,
2162 # which don't actually exist in the DB.
2163 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2164 $errors[] = [ 'ns-specialprotected' ];
2167 # Check $wgNamespaceProtection for restricted namespaces
2168 if ( $this->isNamespaceProtected( $user ) ) {
2169 $ns = $this->mNamespace
== NS_MAIN ?
2170 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2171 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2172 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2179 * Check CSS/JS sub-page permissions
2181 * @param string $action The action to check
2182 * @param User $user User to check
2183 * @param array $errors List of current errors
2184 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2185 * @param bool $short Short circuit on first error
2187 * @return array List of errors
2189 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2190 # Protect css/js subpages of user pages
2191 # XXX: this might be better using restrictions
2192 if ( $action != 'patrol' ) {
2193 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2194 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2195 $errors[] = [ 'mycustomcssprotected', $action ];
2196 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2197 $errors[] = [ 'mycustomjsprotected', $action ];
2200 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2201 $errors[] = [ 'customcssprotected', $action ];
2202 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2203 $errors[] = [ 'customjsprotected', $action ];
2212 * Check against page_restrictions table requirements on this
2213 * page. The user must possess all required rights for this
2216 * @param string $action The action to check
2217 * @param User $user User to check
2218 * @param array $errors List of current errors
2219 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2220 * @param bool $short Short circuit on first error
2222 * @return array List of errors
2224 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2225 foreach ( $this->getRestrictions( $action ) as $right ) {
2226 // Backwards compatibility, rewrite sysop -> editprotected
2227 if ( $right == 'sysop' ) {
2228 $right = 'editprotected';
2230 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2231 if ( $right == 'autoconfirmed' ) {
2232 $right = 'editsemiprotected';
2234 if ( $right == '' ) {
2237 if ( !$user->isAllowed( $right ) ) {
2238 $errors[] = [ 'protectedpagetext', $right, $action ];
2239 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2240 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2248 * Check restrictions on cascading pages.
2250 * @param string $action The action to check
2251 * @param User $user User to check
2252 * @param array $errors List of current errors
2253 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2254 * @param bool $short Short circuit on first error
2256 * @return array List of errors
2258 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2259 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2260 # We /could/ use the protection level on the source page, but it's
2261 # fairly ugly as we have to establish a precedence hierarchy for pages
2262 # included by multiple cascade-protected pages. So just restrict
2263 # it to people with 'protect' permission, as they could remove the
2264 # protection anyway.
2265 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2266 # Cascading protection depends on more than this page...
2267 # Several cascading protected pages may include this page...
2268 # Check each cascading level
2269 # This is only for protection restrictions, not for all actions
2270 if ( isset( $restrictions[$action] ) ) {
2271 foreach ( $restrictions[$action] as $right ) {
2272 // Backwards compatibility, rewrite sysop -> editprotected
2273 if ( $right == 'sysop' ) {
2274 $right = 'editprotected';
2276 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2277 if ( $right == 'autoconfirmed' ) {
2278 $right = 'editsemiprotected';
2280 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2282 foreach ( $cascadingSources as $page ) {
2283 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2285 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2295 * Check action permissions not already checked in checkQuickPermissions
2297 * @param string $action The action to check
2298 * @param User $user User to check
2299 * @param array $errors List of current errors
2300 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2301 * @param bool $short Short circuit on first error
2303 * @return array List of errors
2305 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2306 global $wgDeleteRevisionsLimit, $wgLang;
2308 if ( $action == 'protect' ) {
2309 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2310 // If they can't edit, they shouldn't protect.
2311 $errors[] = [ 'protect-cantedit' ];
2313 } elseif ( $action == 'create' ) {
2314 $title_protection = $this->getTitleProtection();
2315 if ( $title_protection ) {
2316 if ( $title_protection['permission'] == ''
2317 ||
!$user->isAllowed( $title_protection['permission'] )
2321 User
::whoIs( $title_protection['user'] ),
2322 $title_protection['reason']
2326 } elseif ( $action == 'move' ) {
2327 // Check for immobile pages
2328 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2329 // Specific message for this case
2330 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2331 } elseif ( !$this->isMovable() ) {
2332 // Less specific message for rarer cases
2333 $errors[] = [ 'immobile-source-page' ];
2335 } elseif ( $action == 'move-target' ) {
2336 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2337 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2338 } elseif ( !$this->isMovable() ) {
2339 $errors[] = [ 'immobile-target-page' ];
2341 } elseif ( $action == 'delete' ) {
2342 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2343 if ( !$tempErrors ) {
2344 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2345 $user, $tempErrors, $rigor, true );
2347 if ( $tempErrors ) {
2348 // If protection keeps them from editing, they shouldn't be able to delete.
2349 $errors[] = [ 'deleteprotected' ];
2351 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2352 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2354 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2356 } elseif ( $action === 'undelete' ) {
2357 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2358 // Undeleting implies editing
2359 $errors[] = [ 'undelete-cantedit' ];
2361 if ( !$this->exists()
2362 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2364 // Undeleting where nothing currently exists implies creating
2365 $errors[] = [ 'undelete-cantcreate' ];
2372 * Check that the user isn't blocked from editing.
2374 * @param string $action The action to check
2375 * @param User $user User to check
2376 * @param array $errors List of current errors
2377 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2378 * @param bool $short Short circuit on first error
2380 * @return array List of errors
2382 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2383 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2384 // Account creation blocks handled at userlogin.
2385 // Unblocking handled in SpecialUnblock
2386 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2390 // Optimize for a very common case
2391 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2395 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2396 $errors[] = [ 'confirmedittext' ];
2399 $useSlave = ( $rigor !== 'secure' );
2400 if ( ( $action == 'edit' ||
$action == 'create' )
2401 && !$user->isBlockedFrom( $this, $useSlave )
2403 // Don't block the user from editing their own talk page unless they've been
2404 // explicitly blocked from that too.
2405 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2406 // @todo FIXME: Pass the relevant context into this function.
2407 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2414 * Check that the user is allowed to read this page.
2416 * @param string $action The action to check
2417 * @param User $user User to check
2418 * @param array $errors List of current errors
2419 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2420 * @param bool $short Short circuit on first error
2422 * @return array List of errors
2424 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2425 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2427 $whitelisted = false;
2428 if ( User
::isEveryoneAllowed( 'read' ) ) {
2429 # Shortcut for public wikis, allows skipping quite a bit of code
2430 $whitelisted = true;
2431 } elseif ( $user->isAllowed( 'read' ) ) {
2432 # If the user is allowed to read pages, he is allowed to read all pages
2433 $whitelisted = true;
2434 } elseif ( $this->isSpecial( 'Userlogin' )
2435 ||
$this->isSpecial( 'PasswordReset' )
2436 ||
$this->isSpecial( 'Userlogout' )
2438 # Always grant access to the login page.
2439 # Even anons need to be able to log in.
2440 $whitelisted = true;
2441 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2442 # Time to check the whitelist
2443 # Only do these checks is there's something to check against
2444 $name = $this->getPrefixedText();
2445 $dbName = $this->getPrefixedDBkey();
2447 // Check for explicit whitelisting with and without underscores
2448 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2449 $whitelisted = true;
2450 } elseif ( $this->getNamespace() == NS_MAIN
) {
2451 # Old settings might have the title prefixed with
2452 # a colon for main-namespace pages
2453 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2454 $whitelisted = true;
2456 } elseif ( $this->isSpecialPage() ) {
2457 # If it's a special page, ditch the subpage bit and check again
2458 $name = $this->getDBkey();
2459 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2461 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2462 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2463 $whitelisted = true;
2469 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2470 $name = $this->getPrefixedText();
2471 // Check for regex whitelisting
2472 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2473 if ( preg_match( $listItem, $name ) ) {
2474 $whitelisted = true;
2480 if ( !$whitelisted ) {
2481 # If the title is not whitelisted, give extensions a chance to do so...
2482 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2483 if ( !$whitelisted ) {
2484 $errors[] = $this->missingPermissionError( $action, $short );
2492 * Get a description array when the user doesn't have the right to perform
2493 * $action (i.e. when User::isAllowed() returns false)
2495 * @param string $action The action to check
2496 * @param bool $short Short circuit on first error
2497 * @return array Array containing an error message key and any parameters
2499 private function missingPermissionError( $action, $short ) {
2500 // We avoid expensive display logic for quickUserCan's and such
2502 return [ 'badaccess-group0' ];
2505 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2509 * Can $user perform $action on this page? This is an internal function,
2510 * with multiple levels of checks depending on performance needs; see $rigor below.
2511 * It does not check wfReadOnly().
2513 * @param string $action Action that permission needs to be checked for
2514 * @param User $user User to check
2515 * @param string $rigor One of (quick,full,secure)
2516 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2517 * - full : does cheap and expensive checks possibly from a replica DB
2518 * - secure : does cheap and expensive checks, using the master as needed
2519 * @param bool $short Set this to true to stop after the first permission error.
2520 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2522 protected function getUserPermissionsErrorsInternal(
2523 $action, $user, $rigor = 'secure', $short = false
2525 if ( $rigor === true ) {
2526 $rigor = 'secure'; // b/c
2527 } elseif ( $rigor === false ) {
2528 $rigor = 'quick'; // b/c
2529 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2530 throw new Exception( "Invalid rigor parameter '$rigor'." );
2533 # Read has special handling
2534 if ( $action == 'read' ) {
2536 'checkPermissionHooks',
2537 'checkReadPermissions',
2538 'checkUserBlock', // for wgBlockDisablesLogin
2540 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2541 # here as it will lead to duplicate error messages. This is okay to do
2542 # since anywhere that checks for create will also check for edit, and
2543 # those checks are called for edit.
2544 } elseif ( $action == 'create' ) {
2546 'checkQuickPermissions',
2547 'checkPermissionHooks',
2548 'checkPageRestrictions',
2549 'checkCascadingSourcesRestrictions',
2550 'checkActionPermissions',
2555 'checkQuickPermissions',
2556 'checkPermissionHooks',
2557 'checkSpecialsAndNSPermissions',
2558 'checkCSSandJSPermissions',
2559 'checkPageRestrictions',
2560 'checkCascadingSourcesRestrictions',
2561 'checkActionPermissions',
2567 while ( count( $checks ) > 0 &&
2568 !( $short && count( $errors ) > 0 ) ) {
2569 $method = array_shift( $checks );
2570 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2577 * Get a filtered list of all restriction types supported by this wiki.
2578 * @param bool $exists True to get all restriction types that apply to
2579 * titles that do exist, False for all restriction types that apply to
2580 * titles that do not exist
2583 public static function getFilteredRestrictionTypes( $exists = true ) {
2584 global $wgRestrictionTypes;
2585 $types = $wgRestrictionTypes;
2587 # Remove the create restriction for existing titles
2588 $types = array_diff( $types, [ 'create' ] );
2590 # Only the create and upload restrictions apply to non-existing titles
2591 $types = array_intersect( $types, [ 'create', 'upload' ] );
2597 * Returns restriction types for the current Title
2599 * @return array Applicable restriction types
2601 public function getRestrictionTypes() {
2602 if ( $this->isSpecialPage() ) {
2606 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2608 if ( $this->getNamespace() != NS_FILE
) {
2609 # Remove the upload restriction for non-file titles
2610 $types = array_diff( $types, [ 'upload' ] );
2613 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2615 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2616 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2622 * Is this title subject to title protection?
2623 * Title protection is the one applied against creation of such title.
2625 * @return array|bool An associative array representing any existent title
2626 * protection, or false if there's none.
2628 public function getTitleProtection() {
2629 $protection = $this->getTitleProtectionInternal();
2630 if ( $protection ) {
2631 if ( $protection['permission'] == 'sysop' ) {
2632 $protection['permission'] = 'editprotected'; // B/C
2634 if ( $protection['permission'] == 'autoconfirmed' ) {
2635 $protection['permission'] = 'editsemiprotected'; // B/C
2642 * Fetch title protection settings
2644 * To work correctly, $this->loadRestrictions() needs to have access to the
2645 * actual protections in the database without munging 'sysop' =>
2646 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2647 * callers probably want $this->getTitleProtection() instead.
2649 * @return array|bool
2651 protected function getTitleProtectionInternal() {
2652 // Can't protect pages in special namespaces
2653 if ( $this->getNamespace() < 0 ) {
2657 // Can't protect pages that exist.
2658 if ( $this->exists() ) {
2662 if ( $this->mTitleProtection
=== null ) {
2663 $dbr = wfGetDB( DB_REPLICA
);
2664 $res = $dbr->select(
2667 'user' => 'pt_user',
2668 'reason' => 'pt_reason',
2669 'expiry' => 'pt_expiry',
2670 'permission' => 'pt_create_perm'
2672 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2676 // fetchRow returns false if there are no rows.
2677 $row = $dbr->fetchRow( $res );
2679 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2681 $this->mTitleProtection
= $row;
2683 return $this->mTitleProtection
;
2687 * Remove any title protection due to page existing
2689 public function deleteTitleProtection() {
2690 $dbw = wfGetDB( DB_MASTER
);
2694 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2697 $this->mTitleProtection
= false;
2701 * Is this page "semi-protected" - the *only* protection levels are listed
2702 * in $wgSemiprotectedRestrictionLevels?
2704 * @param string $action Action to check (default: edit)
2707 public function isSemiProtected( $action = 'edit' ) {
2708 global $wgSemiprotectedRestrictionLevels;
2710 $restrictions = $this->getRestrictions( $action );
2711 $semi = $wgSemiprotectedRestrictionLevels;
2712 if ( !$restrictions ||
!$semi ) {
2713 // Not protected, or all protection is full protection
2717 // Remap autoconfirmed to editsemiprotected for BC
2718 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2719 $semi[$key] = 'editsemiprotected';
2721 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2722 $restrictions[$key] = 'editsemiprotected';
2725 return !array_diff( $restrictions, $semi );
2729 * Does the title correspond to a protected article?
2731 * @param string $action The action the page is protected from,
2732 * by default checks all actions.
2735 public function isProtected( $action = '' ) {
2736 global $wgRestrictionLevels;
2738 $restrictionTypes = $this->getRestrictionTypes();
2740 # Special pages have inherent protection
2741 if ( $this->isSpecialPage() ) {
2745 # Check regular protection levels
2746 foreach ( $restrictionTypes as $type ) {
2747 if ( $action == $type ||
$action == '' ) {
2748 $r = $this->getRestrictions( $type );
2749 foreach ( $wgRestrictionLevels as $level ) {
2750 if ( in_array( $level, $r ) && $level != '' ) {
2761 * Determines if $user is unable to edit this page because it has been protected
2762 * by $wgNamespaceProtection.
2764 * @param User $user User object to check permissions
2767 public function isNamespaceProtected( User
$user ) {
2768 global $wgNamespaceProtection;
2770 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2771 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2772 if ( $right != '' && !$user->isAllowed( $right ) ) {
2781 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2783 * @return bool If the page is subject to cascading restrictions.
2785 public function isCascadeProtected() {
2786 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2787 return ( $sources > 0 );
2791 * Determines whether cascading protection sources have already been loaded from
2794 * @param bool $getPages True to check if the pages are loaded, or false to check
2795 * if the status is loaded.
2796 * @return bool Whether or not the specified information has been loaded
2799 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2800 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2804 * Cascading protection: Get the source of any cascading restrictions on this page.
2806 * @param bool $getPages Whether or not to retrieve the actual pages
2807 * that the restrictions have come from and the actual restrictions
2809 * @return array Two elements: First is an array of Title objects of the
2810 * pages from which cascading restrictions have come, false for
2811 * none, or true if such restrictions exist but $getPages was not
2812 * set. Second is an array like that returned by
2813 * Title::getAllRestrictions(), or an empty array if $getPages is
2816 public function getCascadeProtectionSources( $getPages = true ) {
2817 $pagerestrictions = [];
2819 if ( $this->mCascadeSources
!== null && $getPages ) {
2820 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2821 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2822 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2825 $dbr = wfGetDB( DB_REPLICA
);
2827 if ( $this->getNamespace() == NS_FILE
) {
2828 $tables = [ 'imagelinks', 'page_restrictions' ];
2830 'il_to' => $this->getDBkey(),
2835 $tables = [ 'templatelinks', 'page_restrictions' ];
2837 'tl_namespace' => $this->getNamespace(),
2838 'tl_title' => $this->getDBkey(),
2845 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2846 'pr_expiry', 'pr_type', 'pr_level' ];
2847 $where_clauses[] = 'page_id=pr_page';
2850 $cols = [ 'pr_expiry' ];
2853 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2855 $sources = $getPages ?
[] : false;
2856 $now = wfTimestampNow();
2858 foreach ( $res as $row ) {
2859 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2860 if ( $expiry > $now ) {
2862 $page_id = $row->pr_page
;
2863 $page_ns = $row->page_namespace
;
2864 $page_title = $row->page_title
;
2865 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2866 # Add groups needed for each restriction type if its not already there
2867 # Make sure this restriction type still exists
2869 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2870 $pagerestrictions[$row->pr_type
] = [];
2874 isset( $pagerestrictions[$row->pr_type
] )
2875 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2877 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2886 $this->mCascadeSources
= $sources;
2887 $this->mCascadingRestrictions
= $pagerestrictions;
2889 $this->mHasCascadingRestrictions
= $sources;
2892 return [ $sources, $pagerestrictions ];
2896 * Accessor for mRestrictionsLoaded
2898 * @return bool Whether or not the page's restrictions have already been
2899 * loaded from the database
2902 public function areRestrictionsLoaded() {
2903 return $this->mRestrictionsLoaded
;
2907 * Accessor/initialisation for mRestrictions
2909 * @param string $action Action that permission needs to be checked for
2910 * @return array Restriction levels needed to take the action. All levels are
2911 * required. Note that restriction levels are normally user rights, but 'sysop'
2912 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2913 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2915 public function getRestrictions( $action ) {
2916 if ( !$this->mRestrictionsLoaded
) {
2917 $this->loadRestrictions();
2919 return isset( $this->mRestrictions
[$action] )
2920 ?
$this->mRestrictions
[$action]
2925 * Accessor/initialisation for mRestrictions
2927 * @return array Keys are actions, values are arrays as returned by
2928 * Title::getRestrictions()
2931 public function getAllRestrictions() {
2932 if ( !$this->mRestrictionsLoaded
) {
2933 $this->loadRestrictions();
2935 return $this->mRestrictions
;
2939 * Get the expiry time for the restriction against a given action
2941 * @param string $action
2942 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2943 * or not protected at all, or false if the action is not recognised.
2945 public function getRestrictionExpiry( $action ) {
2946 if ( !$this->mRestrictionsLoaded
) {
2947 $this->loadRestrictions();
2949 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2953 * Returns cascading restrictions for the current article
2957 function areRestrictionsCascading() {
2958 if ( !$this->mRestrictionsLoaded
) {
2959 $this->loadRestrictions();
2962 return $this->mCascadeRestriction
;
2966 * Compiles list of active page restrictions from both page table (pre 1.10)
2967 * and page_restrictions table for this existing page.
2968 * Public for usage by LiquidThreads.
2970 * @param array $rows Array of db result objects
2971 * @param string $oldFashionedRestrictions Comma-separated list of page
2972 * restrictions from page table (pre 1.10)
2974 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2975 $dbr = wfGetDB( DB_REPLICA
);
2977 $restrictionTypes = $this->getRestrictionTypes();
2979 foreach ( $restrictionTypes as $type ) {
2980 $this->mRestrictions
[$type] = [];
2981 $this->mRestrictionsExpiry
[$type] = 'infinity';
2984 $this->mCascadeRestriction
= false;
2986 # Backwards-compatibility: also load the restrictions from the page record (old format).
2987 if ( $oldFashionedRestrictions !== null ) {
2988 $this->mOldRestrictions
= $oldFashionedRestrictions;
2991 if ( $this->mOldRestrictions
=== false ) {
2992 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2993 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2996 if ( $this->mOldRestrictions
!= '' ) {
2997 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2998 $temp = explode( '=', trim( $restrict ) );
2999 if ( count( $temp ) == 1 ) {
3000 // old old format should be treated as edit/move restriction
3001 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3002 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3004 $restriction = trim( $temp[1] );
3005 if ( $restriction != '' ) { // some old entries are empty
3006 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3012 if ( count( $rows ) ) {
3013 # Current system - load second to make them override.
3014 $now = wfTimestampNow();
3016 # Cycle through all the restrictions.
3017 foreach ( $rows as $row ) {
3018 // Don't take care of restrictions types that aren't allowed
3019 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3023 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3025 // Only apply the restrictions if they haven't expired!
3026 if ( !$expiry ||
$expiry > $now ) {
3027 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3028 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3030 $this->mCascadeRestriction |
= $row->pr_cascade
;
3035 $this->mRestrictionsLoaded
= true;
3039 * Load restrictions from the page_restrictions table
3041 * @param string $oldFashionedRestrictions Comma-separated list of page
3042 * restrictions from page table (pre 1.10)
3044 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3045 if ( $this->mRestrictionsLoaded
) {
3049 $id = $this->getArticleID();
3051 $cache = ObjectCache
::getMainWANInstance();
3052 $rows = $cache->getWithSetCallback(
3053 // Page protections always leave a new null revision
3054 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3056 function ( $curValue, &$ttl, array &$setOpts ) {
3057 $dbr = wfGetDB( DB_REPLICA
);
3059 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3061 return iterator_to_array(
3063 'page_restrictions',
3064 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3065 [ 'pr_page' => $this->getArticleID() ],
3072 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3074 $title_protection = $this->getTitleProtectionInternal();
3076 if ( $title_protection ) {
3077 $now = wfTimestampNow();
3078 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3080 if ( !$expiry ||
$expiry > $now ) {
3081 // Apply the restrictions
3082 $this->mRestrictionsExpiry
['create'] = $expiry;
3083 $this->mRestrictions
['create'] =
3084 explode( ',', trim( $title_protection['permission'] ) );
3085 } else { // Get rid of the old restrictions
3086 $this->mTitleProtection
= false;
3089 $this->mRestrictionsExpiry
['create'] = 'infinity';
3091 $this->mRestrictionsLoaded
= true;
3096 * Flush the protection cache in this object and force reload from the database.
3097 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3099 public function flushRestrictions() {
3100 $this->mRestrictionsLoaded
= false;
3101 $this->mTitleProtection
= null;
3105 * Purge expired restrictions from the page_restrictions table
3107 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3109 static function purgeExpiredRestrictions() {
3110 if ( wfReadOnly() ) {
3114 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3115 wfGetDB( DB_MASTER
),
3117 function ( IDatabase
$dbw, $fname ) {
3118 $config = MediaWikiServices
::getInstance()->getMainConfig();
3119 $ids = $dbw->selectFieldValues(
3120 'page_restrictions',
3122 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3124 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3127 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3132 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3133 wfGetDB( DB_MASTER
),
3135 function ( IDatabase
$dbw, $fname ) {
3138 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3146 * Does this have subpages? (Warning, usually requires an extra DB query.)
3150 public function hasSubpages() {
3151 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3156 # We dynamically add a member variable for the purpose of this method
3157 # alone to cache the result. There's no point in having it hanging
3158 # around uninitialized in every Title object; therefore we only add it
3159 # if needed and don't declare it statically.
3160 if ( $this->mHasSubpages
=== null ) {
3161 $this->mHasSubpages
= false;
3162 $subpages = $this->getSubpages( 1 );
3163 if ( $subpages instanceof TitleArray
) {
3164 $this->mHasSubpages
= (bool)$subpages->count();
3168 return $this->mHasSubpages
;
3172 * Get all subpages of this page.
3174 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3175 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3176 * doesn't allow subpages
3178 public function getSubpages( $limit = -1 ) {
3179 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3183 $dbr = wfGetDB( DB_REPLICA
);
3184 $conds['page_namespace'] = $this->getNamespace();
3185 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3187 if ( $limit > -1 ) {
3188 $options['LIMIT'] = $limit;
3190 return TitleArray
::newFromResult(
3191 $dbr->select( 'page',
3192 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3201 * Is there a version of this page in the deletion archive?
3203 * @return int The number of archived revisions
3205 public function isDeleted() {
3206 if ( $this->getNamespace() < 0 ) {
3209 $dbr = wfGetDB( DB_REPLICA
);
3211 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3212 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3215 if ( $this->getNamespace() == NS_FILE
) {
3216 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3217 [ 'fa_name' => $this->getDBkey() ],
3226 * Is there a version of this page in the deletion archive?
3230 public function isDeletedQuick() {
3231 if ( $this->getNamespace() < 0 ) {
3234 $dbr = wfGetDB( DB_REPLICA
);
3235 $deleted = (bool)$dbr->selectField( 'archive', '1',
3236 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3239 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3240 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3241 [ 'fa_name' => $this->getDBkey() ],
3249 * Get the article ID for this Title from the link cache,
3250 * adding it if necessary
3252 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3254 * @return int The ID
3256 public function getArticleID( $flags = 0 ) {
3257 if ( $this->getNamespace() < 0 ) {
3258 $this->mArticleID
= 0;
3259 return $this->mArticleID
;
3261 $linkCache = LinkCache
::singleton();
3262 if ( $flags & self
::GAID_FOR_UPDATE
) {
3263 $oldUpdate = $linkCache->forUpdate( true );
3264 $linkCache->clearLink( $this );
3265 $this->mArticleID
= $linkCache->addLinkObj( $this );
3266 $linkCache->forUpdate( $oldUpdate );
3268 if ( -1 == $this->mArticleID
) {
3269 $this->mArticleID
= $linkCache->addLinkObj( $this );
3272 return $this->mArticleID
;
3276 * Is this an article that is a redirect page?
3277 * Uses link cache, adding it if necessary
3279 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3282 public function isRedirect( $flags = 0 ) {
3283 if ( !is_null( $this->mRedirect
) ) {
3284 return $this->mRedirect
;
3286 if ( !$this->getArticleID( $flags ) ) {
3287 $this->mRedirect
= false;
3288 return $this->mRedirect
;
3291 $linkCache = LinkCache
::singleton();
3292 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3293 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3294 if ( $cached === null ) {
3295 # Trust LinkCache's state over our own
3296 # LinkCache is telling us that the page doesn't exist, despite there being cached
3297 # data relating to an existing page in $this->mArticleID. Updaters should clear
3298 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3299 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3300 # LinkCache to refresh its data from the master.
3301 $this->mRedirect
= false;
3302 return $this->mRedirect
;
3305 $this->mRedirect
= (bool)$cached;
3307 return $this->mRedirect
;
3311 * What is the length of this page?
3312 * Uses link cache, adding it if necessary
3314 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3317 public function getLength( $flags = 0 ) {
3318 if ( $this->mLength
!= -1 ) {
3319 return $this->mLength
;
3321 if ( !$this->getArticleID( $flags ) ) {
3323 return $this->mLength
;
3325 $linkCache = LinkCache
::singleton();
3326 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3327 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3328 if ( $cached === null ) {
3329 # Trust LinkCache's state over our own, as for isRedirect()
3331 return $this->mLength
;
3334 $this->mLength
= intval( $cached );
3336 return $this->mLength
;
3340 * What is the page_latest field for this page?
3342 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3343 * @return int Int or 0 if the page doesn't exist
3345 public function getLatestRevID( $flags = 0 ) {
3346 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3347 return intval( $this->mLatestID
);
3349 if ( !$this->getArticleID( $flags ) ) {
3350 $this->mLatestID
= 0;
3351 return $this->mLatestID
;
3353 $linkCache = LinkCache
::singleton();
3354 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3355 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3356 if ( $cached === null ) {
3357 # Trust LinkCache's state over our own, as for isRedirect()
3358 $this->mLatestID
= 0;
3359 return $this->mLatestID
;
3362 $this->mLatestID
= intval( $cached );
3364 return $this->mLatestID
;
3368 * This clears some fields in this object, and clears any associated
3369 * keys in the "bad links" section of the link cache.
3371 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3372 * loading of the new page_id. It's also called from
3373 * WikiPage::doDeleteArticleReal()
3375 * @param int $newid The new Article ID
3377 public function resetArticleID( $newid ) {
3378 $linkCache = LinkCache
::singleton();
3379 $linkCache->clearLink( $this );
3381 if ( $newid === false ) {
3382 $this->mArticleID
= -1;
3384 $this->mArticleID
= intval( $newid );
3386 $this->mRestrictionsLoaded
= false;
3387 $this->mRestrictions
= [];
3388 $this->mOldRestrictions
= false;
3389 $this->mRedirect
= null;
3390 $this->mLength
= -1;
3391 $this->mLatestID
= false;
3392 $this->mContentModel
= false;
3393 $this->mEstimateRevisions
= null;
3394 $this->mPageLanguage
= false;
3395 $this->mDbPageLanguage
= false;
3396 $this->mIsBigDeletion
= null;
3399 public static function clearCaches() {
3400 $linkCache = LinkCache
::singleton();
3401 $linkCache->clear();
3403 $titleCache = self
::getTitleCache();
3404 $titleCache->clear();
3408 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3410 * @param string $text Containing title to capitalize
3411 * @param int $ns Namespace index, defaults to NS_MAIN
3412 * @return string Containing capitalized title
3414 public static function capitalize( $text, $ns = NS_MAIN
) {
3417 if ( MWNamespace
::isCapitalized( $ns ) ) {
3418 return $wgContLang->ucfirst( $text );
3425 * Secure and split - main initialisation function for this object
3427 * Assumes that mDbkeyform has been set, and is urldecoded
3428 * and uses underscores, but not otherwise munged. This function
3429 * removes illegal characters, splits off the interwiki and
3430 * namespace prefixes, sets the other forms, and canonicalizes
3433 * @throws MalformedTitleException On invalid titles
3434 * @return bool True on success
3436 private function secureAndSplit() {
3438 $this->mInterwiki
= '';
3439 $this->mFragment
= '';
3440 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3442 $dbkey = $this->mDbkeyform
;
3444 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3445 // the parsing code with Title, while avoiding massive refactoring.
3446 // @todo: get rid of secureAndSplit, refactor parsing code.
3447 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3448 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3449 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3450 // MalformedTitleException can be thrown here
3451 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3454 $this->setFragment( '#' . $parts['fragment'] );
3455 $this->mInterwiki
= $parts['interwiki'];
3456 $this->mLocalInterwiki
= $parts['local_interwiki'];
3457 $this->mNamespace
= $parts['namespace'];
3458 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3460 $this->mDbkeyform
= $parts['dbkey'];
3461 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3462 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3464 # We already know that some pages won't be in the database!
3465 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3466 $this->mArticleID
= 0;
3473 * Get an array of Title objects linking to this Title
3474 * Also stores the IDs in the link cache.
3476 * WARNING: do not use this function on arbitrary user-supplied titles!
3477 * On heavily-used templates it will max out the memory.
3479 * @param array $options May be FOR UPDATE
3480 * @param string $table Table name
3481 * @param string $prefix Fields prefix
3482 * @return Title[] Array of Title objects linking here
3484 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3485 if ( count( $options ) > 0 ) {
3486 $db = wfGetDB( DB_MASTER
);
3488 $db = wfGetDB( DB_REPLICA
);
3493 self
::getSelectFields(),
3495 "{$prefix}_from=page_id",
3496 "{$prefix}_namespace" => $this->getNamespace(),
3497 "{$prefix}_title" => $this->getDBkey() ],
3503 if ( $res->numRows() ) {
3504 $linkCache = LinkCache
::singleton();
3505 foreach ( $res as $row ) {
3506 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3508 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3509 $retVal[] = $titleObj;
3517 * Get an array of Title objects using this Title as a template
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 * @return Title[] Array of Title the Title objects linking here
3526 public function getTemplateLinksTo( $options = [] ) {
3527 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3531 * Get an array of Title objects linked from this Title
3532 * Also stores the IDs in the link cache.
3534 * WARNING: do not use this function on arbitrary user-supplied titles!
3535 * On heavily-used templates it will max out the memory.
3537 * @param array $options Query option to Database::select()
3538 * @param string $table Table name
3539 * @param string $prefix Fields prefix
3540 * @return array Array of Title objects linking here
3542 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3543 $id = $this->getArticleID();
3545 # If the page doesn't exist; there can't be any link from this page
3550 $db = wfGetDB( DB_REPLICA
);
3552 $blNamespace = "{$prefix}_namespace";
3553 $blTitle = "{$prefix}_title";
3558 [ $blNamespace, $blTitle ],
3559 WikiPage
::selectFields()
3561 [ "{$prefix}_from" => $id ],
3566 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3571 $linkCache = LinkCache
::singleton();
3572 foreach ( $res as $row ) {
3573 if ( $row->page_id
) {
3574 $titleObj = self
::newFromRow( $row );
3576 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3577 $linkCache->addBadLinkObj( $titleObj );
3579 $retVal[] = $titleObj;
3586 * Get an array of Title objects used on this Title as a template
3587 * Also stores the IDs in the link cache.
3589 * WARNING: do not use this function on arbitrary user-supplied titles!
3590 * On heavily-used templates it will max out the memory.
3592 * @param array $options May be FOR UPDATE
3593 * @return Title[] Array of Title the Title objects used here
3595 public function getTemplateLinksFrom( $options = [] ) {
3596 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3600 * Get an array of Title objects referring to non-existent articles linked
3603 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3604 * should use redirect table in this case).
3605 * @return Title[] Array of Title the Title objects
3607 public function getBrokenLinksFrom() {
3608 if ( $this->getArticleID() == 0 ) {
3609 # All links from article ID 0 are false positives
3613 $dbr = wfGetDB( DB_REPLICA
);
3614 $res = $dbr->select(
3615 [ 'page', 'pagelinks' ],
3616 [ 'pl_namespace', 'pl_title' ],
3618 'pl_from' => $this->getArticleID(),
3619 'page_namespace IS NULL'
3625 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3631 foreach ( $res as $row ) {
3632 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3638 * Get a list of URLs to purge from the CDN cache when this
3641 * @return string[] Array of String the URLs
3643 public function getCdnUrls() {
3645 $this->getInternalURL(),
3646 $this->getInternalURL( 'action=history' )
3649 $pageLang = $this->getPageLanguage();
3650 if ( $pageLang->hasVariants() ) {
3651 $variants = $pageLang->getVariants();
3652 foreach ( $variants as $vCode ) {
3653 $urls[] = $this->getInternalURL( $vCode );
3657 // If we are looking at a css/js user subpage, purge the action=raw.
3658 if ( $this->isJsSubpage() ) {
3659 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3660 } elseif ( $this->isCssSubpage() ) {
3661 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3664 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3669 * @deprecated since 1.27 use getCdnUrls()
3671 public function getSquidURLs() {
3672 return $this->getCdnUrls();
3676 * Purge all applicable CDN URLs
3678 public function purgeSquid() {
3679 DeferredUpdates
::addUpdate(
3680 new CdnCacheUpdate( $this->getCdnUrls() ),
3681 DeferredUpdates
::PRESEND
3686 * Check whether a given move operation would be valid.
3687 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3689 * @deprecated since 1.25, use MovePage's methods instead
3690 * @param Title $nt The new title
3691 * @param bool $auth Whether to check user permissions (uses $wgUser)
3692 * @param string $reason Is the log summary of the move, used for spam checking
3693 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3695 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3698 if ( !( $nt instanceof Title
) ) {
3699 // Normally we'd add this to $errors, but we'll get
3700 // lots of syntax errors if $nt is not an object
3701 return [ [ 'badtitletext' ] ];
3704 $mp = new MovePage( $this, $nt );
3705 $errors = $mp->isValidMove()->getErrorsArray();
3707 $errors = wfMergeErrorArrays(
3709 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3713 return $errors ?
: true;
3717 * Check if the requested move target is a valid file move target
3718 * @todo move this to MovePage
3719 * @param Title $nt Target title
3720 * @return array List of errors
3722 protected function validateFileMoveOperation( $nt ) {
3727 $destFile = wfLocalFile( $nt );
3728 $destFile->load( File
::READ_LATEST
);
3729 if ( !$wgUser->isAllowed( 'reupload-shared' )
3730 && !$destFile->exists() && wfFindFile( $nt )
3732 $errors[] = [ 'file-exists-sharedrepo' ];
3739 * Move a title to a new location
3741 * @deprecated since 1.25, use the MovePage class instead
3742 * @param Title $nt The new title
3743 * @param bool $auth Indicates whether $wgUser's permissions
3745 * @param string $reason The reason for the move
3746 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3747 * Ignored if the user doesn't have the suppressredirect right.
3748 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3749 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3751 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3752 array $changeTags = []
3755 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3756 if ( is_array( $err ) ) {
3757 // Auto-block user's IP if the account was "hard" blocked
3758 $wgUser->spreadAnyEditBlock();
3761 // Check suppressredirect permission
3762 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3763 $createRedirect = true;
3766 $mp = new MovePage( $this, $nt );
3767 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3768 if ( $status->isOK() ) {
3771 return $status->getErrorsArray();
3776 * Move this page's subpages to be subpages of $nt
3778 * @param Title $nt Move target
3779 * @param bool $auth Whether $wgUser's permissions should be checked
3780 * @param string $reason The reason for the move
3781 * @param bool $createRedirect Whether to create redirects from the old subpages to
3782 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3783 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3784 * @return array Array with old page titles as keys, and strings (new page titles) or
3785 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3786 * getUserPermissionsErrors()-like error array with numeric indices if
3787 * no pages were moved
3789 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3790 array $changeTags = []
3792 global $wgMaximumMovedPages;
3793 // Check permissions
3794 if ( !$this->userCan( 'move-subpages' ) ) {
3796 [ 'cant-move-subpages' ],
3799 // Do the source and target namespaces support subpages?
3800 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3802 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3805 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3807 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3811 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3814 foreach ( $subpages as $oldSubpage ) {
3816 if ( $count > $wgMaximumMovedPages ) {
3817 $retval[$oldSubpage->getPrefixedText()] = [
3818 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3823 // We don't know whether this function was called before
3824 // or after moving the root page, so check both
3826 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3827 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3829 // When moving a page to a subpage of itself,
3830 // don't move it twice
3833 $newPageName = preg_replace(
3834 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3835 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3836 $oldSubpage->getDBkey() );
3837 if ( $oldSubpage->isTalkPage() ) {
3838 $newNs = $nt->getTalkPage()->getNamespace();
3840 $newNs = $nt->getSubjectPage()->getNamespace();
3842 # T16385: we need makeTitleSafe because the new page names may
3843 # be longer than 255 characters.
3844 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3846 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3847 if ( $success === true ) {
3848 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3850 $retval[$oldSubpage->getPrefixedText()] = $success;
3857 * Checks if this page is just a one-rev redirect.
3858 * Adds lock, so don't use just for light purposes.
3862 public function isSingleRevRedirect() {
3863 global $wgContentHandlerUseDB;
3865 $dbw = wfGetDB( DB_MASTER
);
3868 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3869 if ( $wgContentHandlerUseDB ) {
3870 $fields[] = 'page_content_model';
3873 $row = $dbw->selectRow( 'page',
3879 # Cache some fields we may want
3880 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3881 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3882 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3883 $this->mContentModel
= $row && isset( $row->page_content_model
)
3884 ?
strval( $row->page_content_model
)
3887 if ( !$this->mRedirect
) {
3890 # Does the article have a history?
3891 $row = $dbw->selectField( [ 'page', 'revision' ],
3893 [ 'page_namespace' => $this->getNamespace(),
3894 'page_title' => $this->getDBkey(),
3896 'page_latest != rev_id'
3901 # Return true if there was no history
3902 return ( $row === false );
3906 * Checks if $this can be moved to a given Title
3907 * - Selects for update, so don't call it unless you mean business
3909 * @deprecated since 1.25, use MovePage's methods instead
3910 * @param Title $nt The new title to check
3913 public function isValidMoveTarget( $nt ) {
3914 # Is it an existing file?
3915 if ( $nt->getNamespace() == NS_FILE
) {
3916 $file = wfLocalFile( $nt );
3917 $file->load( File
::READ_LATEST
);
3918 if ( $file->exists() ) {
3919 wfDebug( __METHOD__
. ": file exists\n" );
3923 # Is it a redirect with no history?
3924 if ( !$nt->isSingleRevRedirect() ) {
3925 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3928 # Get the article text
3929 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3930 if ( !is_object( $rev ) ) {
3933 $content = $rev->getContent();
3934 # Does the redirect point to the source?
3935 # Or is it a broken self-redirect, usually caused by namespace collisions?
3936 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3938 if ( $redirTitle ) {
3939 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3940 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3941 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3947 # Fail safe (not a redirect after all. strange.)
3948 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3949 " is a redirect, but it doesn't contain a valid redirect.\n" );
3955 * Get categories to which this Title belongs and return an array of
3956 * categories' names.
3958 * @return array Array of parents in the form:
3959 * $parent => $currentarticle
3961 public function getParentCategories() {
3966 $titleKey = $this->getArticleID();
3968 if ( $titleKey === 0 ) {
3972 $dbr = wfGetDB( DB_REPLICA
);
3974 $res = $dbr->select(
3977 [ 'cl_from' => $titleKey ],
3981 if ( $res->numRows() > 0 ) {
3982 foreach ( $res as $row ) {
3983 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3984 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3991 * Get a tree of parent categories
3993 * @param array $children Array with the children in the keys, to check for circular refs
3994 * @return array Tree of parent categories
3996 public function getParentCategoryTree( $children = [] ) {
3998 $parents = $this->getParentCategories();
4001 foreach ( $parents as $parent => $current ) {
4002 if ( array_key_exists( $parent, $children ) ) {
4003 # Circular reference
4004 $stack[$parent] = [];
4006 $nt = self
::newFromText( $parent );
4008 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4018 * Get an associative array for selecting this title from
4021 * @return array Array suitable for the $where parameter of DB::select()
4023 public function pageCond() {
4024 if ( $this->mArticleID
> 0 ) {
4025 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4026 return [ 'page_id' => $this->mArticleID
];
4028 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4033 * Get next/previous revision ID relative to another revision ID
4034 * @param int $revId Revision ID. Get the revision that was before this one.
4035 * @param int $flags Title::GAID_FOR_UPDATE
4036 * @param string $dir 'next' or 'prev'
4037 * @return int|bool New revision ID, or false if none exists
4039 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4040 $revId = (int)$revId;
4041 if ( $dir === 'next' ) {
4044 } elseif ( $dir === 'prev' ) {
4048 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4051 if ( $flags & self
::GAID_FOR_UPDATE
) {
4052 $db = wfGetDB( DB_MASTER
);
4054 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4057 // Intentionally not caring if the specified revision belongs to this
4058 // page. We only care about the timestamp.
4059 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4060 if ( $ts === false ) {
4061 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4062 if ( $ts === false ) {
4063 // Or should this throw an InvalidArgumentException or something?
4067 $ts = $db->addQuotes( $ts );
4069 $revId = $db->selectField( 'revision', 'rev_id',
4071 'rev_page' => $this->getArticleID( $flags ),
4072 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4076 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4077 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4081 if ( $revId === false ) {
4084 return intval( $revId );
4089 * Get the revision ID of the previous revision
4091 * @param int $revId Revision ID. Get the revision that was before this one.
4092 * @param int $flags Title::GAID_FOR_UPDATE
4093 * @return int|bool Old revision ID, or false if none exists
4095 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4096 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4100 * Get the revision ID of the next revision
4102 * @param int $revId Revision ID. Get the revision that was after this one.
4103 * @param int $flags Title::GAID_FOR_UPDATE
4104 * @return int|bool Next revision ID, or false if none exists
4106 public function getNextRevisionID( $revId, $flags = 0 ) {
4107 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4111 * Get the first revision of the page
4113 * @param int $flags Title::GAID_FOR_UPDATE
4114 * @return Revision|null If page doesn't exist
4116 public function getFirstRevision( $flags = 0 ) {
4117 $pageId = $this->getArticleID( $flags );
4119 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4120 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4121 [ 'rev_page' => $pageId ],
4124 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4125 'IGNORE INDEX' => 'rev_timestamp', // See T159319
4129 return new Revision( $row );
4136 * Get the oldest revision timestamp of this page
4138 * @param int $flags Title::GAID_FOR_UPDATE
4139 * @return string MW timestamp
4141 public function getEarliestRevTime( $flags = 0 ) {
4142 $rev = $this->getFirstRevision( $flags );
4143 return $rev ?
$rev->getTimestamp() : null;
4147 * Check if this is a new page
4151 public function isNewPage() {
4152 $dbr = wfGetDB( DB_REPLICA
);
4153 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4157 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4161 public function isBigDeletion() {
4162 global $wgDeleteRevisionsLimit;
4164 if ( !$wgDeleteRevisionsLimit ) {
4168 if ( $this->mIsBigDeletion
=== null ) {
4169 $dbr = wfGetDB( DB_REPLICA
);
4171 $revCount = $dbr->selectRowCount(
4174 [ 'rev_page' => $this->getArticleID() ],
4176 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4179 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4182 return $this->mIsBigDeletion
;
4186 * Get the approximate revision count of this page.
4190 public function estimateRevisionCount() {
4191 if ( !$this->exists() ) {
4195 if ( $this->mEstimateRevisions
=== null ) {
4196 $dbr = wfGetDB( DB_REPLICA
);
4197 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4198 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4201 return $this->mEstimateRevisions
;
4205 * Get the number of revisions between the given revision.
4206 * Used for diffs and other things that really need it.
4208 * @param int|Revision $old Old revision or rev ID (first before range)
4209 * @param int|Revision $new New revision or rev ID (first after range)
4210 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4211 * @return int Number of revisions between these revisions.
4213 public function countRevisionsBetween( $old, $new, $max = null ) {
4214 if ( !( $old instanceof Revision
) ) {
4215 $old = Revision
::newFromTitle( $this, (int)$old );
4217 if ( !( $new instanceof Revision
) ) {
4218 $new = Revision
::newFromTitle( $this, (int)$new );
4220 if ( !$old ||
!$new ) {
4221 return 0; // nothing to compare
4223 $dbr = wfGetDB( DB_REPLICA
);
4225 'rev_page' => $this->getArticleID(),
4226 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4227 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4229 if ( $max !== null ) {
4230 return $dbr->selectRowCount( 'revision', '1',
4233 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4236 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4241 * Get the authors between the given revisions or revision IDs.
4242 * Used for diffs and other things that really need it.
4246 * @param int|Revision $old Old revision or rev ID (first before range by default)
4247 * @param int|Revision $new New revision or rev ID (first after range by default)
4248 * @param int $limit Maximum number of authors
4249 * @param string|array $options (Optional): Single option, or an array of options:
4250 * 'include_old' Include $old in the range; $new is excluded.
4251 * 'include_new' Include $new in the range; $old is excluded.
4252 * 'include_both' Include both $old and $new in the range.
4253 * Unknown option values are ignored.
4254 * @return array|null Names of revision authors in the range; null if not both revisions exist
4256 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4257 if ( !( $old instanceof Revision
) ) {
4258 $old = Revision
::newFromTitle( $this, (int)$old );
4260 if ( !( $new instanceof Revision
) ) {
4261 $new = Revision
::newFromTitle( $this, (int)$new );
4263 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4264 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4265 // in the sanity check below?
4266 if ( !$old ||
!$new ) {
4267 return null; // nothing to compare
4272 $options = (array)$options;
4273 if ( in_array( 'include_old', $options ) ) {
4276 if ( in_array( 'include_new', $options ) ) {
4279 if ( in_array( 'include_both', $options ) ) {
4283 // No DB query needed if $old and $new are the same or successive revisions:
4284 if ( $old->getId() === $new->getId() ) {
4285 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4287 [ $old->getUserText( Revision
::RAW
) ];
4288 } elseif ( $old->getId() === $new->getParentId() ) {
4289 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4290 $authors[] = $old->getUserText( Revision
::RAW
);
4291 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4292 $authors[] = $new->getUserText( Revision
::RAW
);
4294 } elseif ( $old_cmp === '>=' ) {
4295 $authors[] = $old->getUserText( Revision
::RAW
);
4296 } elseif ( $new_cmp === '<=' ) {
4297 $authors[] = $new->getUserText( Revision
::RAW
);
4301 $dbr = wfGetDB( DB_REPLICA
);
4302 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4304 'rev_page' => $this->getArticleID(),
4305 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4306 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4308 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4310 foreach ( $res as $row ) {
4311 $authors[] = $row->rev_user_text
;
4317 * Get the number of authors between the given revisions or revision IDs.
4318 * Used for diffs and other things that really need it.
4320 * @param int|Revision $old Old revision or rev ID (first before range by default)
4321 * @param int|Revision $new New revision or rev ID (first after range by default)
4322 * @param int $limit Maximum number of authors
4323 * @param string|array $options (Optional): Single option, or an array of options:
4324 * 'include_old' Include $old in the range; $new is excluded.
4325 * 'include_new' Include $new in the range; $old is excluded.
4326 * 'include_both' Include both $old and $new in the range.
4327 * Unknown option values are ignored.
4328 * @return int Number of revision authors in the range; zero if not both revisions exist
4330 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4331 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4332 return $authors ?
count( $authors ) : 0;
4336 * Compare with another title.
4338 * @param Title $title
4341 public function equals( Title
$title ) {
4342 // Note: === is necessary for proper matching of number-like titles.
4343 return $this->getInterwiki() === $title->getInterwiki()
4344 && $this->getNamespace() == $title->getNamespace()
4345 && $this->getDBkey() === $title->getDBkey();
4349 * Check if this title is a subpage of another title
4351 * @param Title $title
4354 public function isSubpageOf( Title
$title ) {
4355 return $this->getInterwiki() === $title->getInterwiki()
4356 && $this->getNamespace() == $title->getNamespace()
4357 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4361 * Check if page exists. For historical reasons, this function simply
4362 * checks for the existence of the title in the page table, and will
4363 * thus return false for interwiki links, special pages and the like.
4364 * If you want to know if a title can be meaningfully viewed, you should
4365 * probably call the isKnown() method instead.
4367 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4368 * from master/for update
4371 public function exists( $flags = 0 ) {
4372 $exists = $this->getArticleID( $flags ) != 0;
4373 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4378 * Should links to this title be shown as potentially viewable (i.e. as
4379 * "bluelinks"), even if there's no record by this title in the page
4382 * This function is semi-deprecated for public use, as well as somewhat
4383 * misleadingly named. You probably just want to call isKnown(), which
4384 * calls this function internally.
4386 * (ISSUE: Most of these checks are cheap, but the file existence check
4387 * can potentially be quite expensive. Including it here fixes a lot of
4388 * existing code, but we might want to add an optional parameter to skip
4389 * it and any other expensive checks.)
4393 public function isAlwaysKnown() {
4397 * Allows overriding default behavior for determining if a page exists.
4398 * If $isKnown is kept as null, regular checks happen. If it's
4399 * a boolean, this value is returned by the isKnown method.
4403 * @param Title $title
4404 * @param bool|null $isKnown
4406 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4408 if ( !is_null( $isKnown ) ) {
4412 if ( $this->isExternal() ) {
4413 return true; // any interwiki link might be viewable, for all we know
4416 switch ( $this->mNamespace
) {
4419 // file exists, possibly in a foreign repo
4420 return (bool)wfFindFile( $this );
4422 // valid special page
4423 return SpecialPageFactory
::exists( $this->getDBkey() );
4425 // selflink, possibly with fragment
4426 return $this->mDbkeyform
== '';
4428 // known system message
4429 return $this->hasSourceText() !== false;
4436 * Does this title refer to a page that can (or might) be meaningfully
4437 * viewed? In particular, this function may be used to determine if
4438 * links to the title should be rendered as "bluelinks" (as opposed to
4439 * "redlinks" to non-existent pages).
4440 * Adding something else to this function will cause inconsistency
4441 * since LinkHolderArray calls isAlwaysKnown() and does its own
4442 * page existence check.
4446 public function isKnown() {
4447 return $this->isAlwaysKnown() ||
$this->exists();
4451 * Does this page have source text?
4455 public function hasSourceText() {
4456 if ( $this->exists() ) {
4460 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4461 // If the page doesn't exist but is a known system message, default
4462 // message content will be displayed, same for language subpages-
4463 // Use always content language to avoid loading hundreds of languages
4464 // to get the link color.
4466 list( $name, ) = MessageCache
::singleton()->figureMessage(
4467 $wgContLang->lcfirst( $this->getText() )
4469 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4470 return $message->exists();
4477 * Get the default message text or false if the message doesn't exist
4479 * @return string|bool
4481 public function getDefaultMessageText() {
4484 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4488 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4489 $wgContLang->lcfirst( $this->getText() )
4491 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4493 if ( $message->exists() ) {
4494 return $message->plain();
4501 * Updates page_touched for this page; called from LinksUpdate.php
4503 * @param string $purgeTime [optional] TS_MW timestamp
4504 * @return bool True if the update succeeded
4506 public function invalidateCache( $purgeTime = null ) {
4507 if ( wfReadOnly() ) {
4509 } elseif ( $this->mArticleID
=== 0 ) {
4510 return true; // avoid gap locking if we know it's not there
4513 $dbw = wfGetDB( DB_MASTER
);
4514 $dbw->onTransactionPreCommitOrIdle( function () {
4515 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4518 $conds = $this->pageCond();
4519 DeferredUpdates
::addUpdate(
4520 new AutoCommitUpdate(
4523 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4524 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4527 [ 'page_touched' => $dbTimestamp ],
4528 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4531 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4534 DeferredUpdates
::PRESEND
4541 * Update page_touched timestamps and send CDN purge messages for
4542 * pages linking to this title. May be sent to the job queue depending
4543 * on the number of links. Typically called on create and delete.
4545 public function touchLinks() {
4546 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4547 if ( $this->getNamespace() == NS_CATEGORY
) {
4548 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4553 * Get the last touched timestamp
4555 * @param IDatabase $db Optional db
4556 * @return string|false Last-touched timestamp
4558 public function getTouched( $db = null ) {
4559 if ( $db === null ) {
4560 $db = wfGetDB( DB_REPLICA
);
4562 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4567 * Get the timestamp when this page was updated since the user last saw it.
4570 * @return string|null
4572 public function getNotificationTimestamp( $user = null ) {
4575 // Assume current user if none given
4579 // Check cache first
4580 $uid = $user->getId();
4584 // avoid isset here, as it'll return false for null entries
4585 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4586 return $this->mNotificationTimestamp
[$uid];
4588 // Don't cache too much!
4589 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4590 $this->mNotificationTimestamp
= [];
4593 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4594 $watchedItem = $store->getWatchedItem( $user, $this );
4595 if ( $watchedItem ) {
4596 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4598 $this->mNotificationTimestamp
[$uid] = false;
4601 return $this->mNotificationTimestamp
[$uid];
4605 * Generate strings used for xml 'id' names in monobook tabs
4607 * @param string $prepend Defaults to 'nstab-'
4608 * @return string XML 'id' name
4610 public function getNamespaceKey( $prepend = 'nstab-' ) {
4612 // Gets the subject namespace if this title
4613 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4614 // Checks if canonical namespace name exists for namespace
4615 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4616 // Uses canonical namespace name
4617 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4619 // Uses text of namespace
4620 $namespaceKey = $this->getSubjectNsText();
4622 // Makes namespace key lowercase
4623 $namespaceKey = $wgContLang->lc( $namespaceKey );
4625 if ( $namespaceKey == '' ) {
4626 $namespaceKey = 'main';
4628 // Changes file to image for backwards compatibility
4629 if ( $namespaceKey == 'file' ) {
4630 $namespaceKey = 'image';
4632 return $prepend . $namespaceKey;
4636 * Get all extant redirects to this Title
4638 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4639 * @return Title[] Array of Title redirects to this title
4641 public function getRedirectsHere( $ns = null ) {
4644 $dbr = wfGetDB( DB_REPLICA
);
4646 'rd_namespace' => $this->getNamespace(),
4647 'rd_title' => $this->getDBkey(),
4650 if ( $this->isExternal() ) {
4651 $where['rd_interwiki'] = $this->getInterwiki();
4653 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4655 if ( !is_null( $ns ) ) {
4656 $where['page_namespace'] = $ns;
4659 $res = $dbr->select(
4660 [ 'redirect', 'page' ],
4661 [ 'page_namespace', 'page_title' ],
4666 foreach ( $res as $row ) {
4667 $redirs[] = self
::newFromRow( $row );
4673 * Check if this Title is a valid redirect target
4677 public function isValidRedirectTarget() {
4678 global $wgInvalidRedirectTargets;
4680 if ( $this->isSpecialPage() ) {
4681 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4682 if ( $this->isSpecial( 'Userlogout' ) ) {
4686 foreach ( $wgInvalidRedirectTargets as $target ) {
4687 if ( $this->isSpecial( $target ) ) {
4697 * Get a backlink cache object
4699 * @return BacklinkCache
4701 public function getBacklinkCache() {
4702 return BacklinkCache
::get( $this );
4706 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4710 public function canUseNoindex() {
4711 global $wgExemptFromUserRobotsControl;
4713 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4714 ? MWNamespace
::getContentNamespaces()
4715 : $wgExemptFromUserRobotsControl;
4717 return !in_array( $this->mNamespace
, $bannedNamespaces );
4721 * Returns the raw sort key to be used for categories, with the specified
4722 * prefix. This will be fed to Collation::getSortKey() to get a
4723 * binary sortkey that can be used for actual sorting.
4725 * @param string $prefix The prefix to be used, specified using
4726 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4730 public function getCategorySortkey( $prefix = '' ) {
4731 $unprefixed = $this->getText();
4733 // Anything that uses this hook should only depend
4734 // on the Title object passed in, and should probably
4735 // tell the users to run updateCollations.php --force
4736 // in order to re-sort existing category relations.
4737 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4738 if ( $prefix !== '' ) {
4739 # Separate with a line feed, so the unprefixed part is only used as
4740 # a tiebreaker when two pages have the exact same prefix.
4741 # In UCA, tab is the only character that can sort above LF
4742 # so we strip both of them from the original prefix.
4743 $prefix = strtr( $prefix, "\n\t", ' ' );
4744 return "$prefix\n$unprefixed";
4750 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4751 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4752 * the db, it will return NULL.
4754 * @return string|null|bool
4756 private function getDbPageLanguageCode() {
4757 global $wgPageLanguageUseDB;
4759 // check, if the page language could be saved in the database, and if so and
4760 // the value is not requested already, lookup the page language using LinkCache
4761 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4762 $linkCache = LinkCache
::singleton();
4763 $linkCache->addLinkObj( $this );
4764 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4767 return $this->mDbPageLanguage
;
4771 * Get the language in which the content of this page is written in
4772 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4773 * e.g. $wgLang (such as special pages, which are in the user language).
4778 public function getPageLanguage() {
4779 global $wgLang, $wgLanguageCode;
4780 if ( $this->isSpecialPage() ) {
4781 // special pages are in the user language
4785 // Checking if DB language is set
4786 $dbPageLanguage = $this->getDbPageLanguageCode();
4787 if ( $dbPageLanguage ) {
4788 return wfGetLangObj( $dbPageLanguage );
4791 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4792 // Note that this may depend on user settings, so the cache should
4793 // be only per-request.
4794 // NOTE: ContentHandler::getPageLanguage() may need to load the
4795 // content to determine the page language!
4796 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4798 $contentHandler = ContentHandler
::getForTitle( $this );
4799 $langObj = $contentHandler->getPageLanguage( $this );
4800 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4802 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4809 * Get the language in which the content of this page is written when
4810 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4811 * e.g. $wgLang (such as special pages, which are in the user language).
4816 public function getPageViewLanguage() {
4819 if ( $this->isSpecialPage() ) {
4820 // If the user chooses a variant, the content is actually
4821 // in a language whose code is the variant code.
4822 $variant = $wgLang->getPreferredVariant();
4823 if ( $wgLang->getCode() !== $variant ) {
4824 return Language
::factory( $variant );
4830 // Checking if DB language is set
4831 $dbPageLanguage = $this->getDbPageLanguageCode();
4832 if ( $dbPageLanguage ) {
4833 $pageLang = wfGetLangObj( $dbPageLanguage );
4834 $variant = $pageLang->getPreferredVariant();
4835 if ( $pageLang->getCode() !== $variant ) {
4836 $pageLang = Language
::factory( $variant );
4842 // @note Can't be cached persistently, depends on user settings.
4843 // @note ContentHandler::getPageViewLanguage() may need to load the
4844 // content to determine the page language!
4845 $contentHandler = ContentHandler
::getForTitle( $this );
4846 $pageLang = $contentHandler->getPageViewLanguage( $this );
4851 * Get a list of rendered edit notices for this page.
4853 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4854 * they will already be wrapped in paragraphs.
4857 * @param int $oldid Revision ID that's being edited
4860 public function getEditNotices( $oldid = 0 ) {
4863 // Optional notice for the entire namespace
4864 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4865 $msg = wfMessage( $editnotice_ns );
4866 if ( $msg->exists() ) {
4867 $html = $msg->parseAsBlock();
4868 // Edit notices may have complex logic, but output nothing (T91715)
4869 if ( trim( $html ) !== '' ) {
4870 $notices[$editnotice_ns] = Html
::rawElement(
4874 'mw-editnotice-namespace',
4875 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4882 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4883 // Optional notice for page itself and any parent page
4884 $parts = explode( '/', $this->getDBkey() );
4885 $editnotice_base = $editnotice_ns;
4886 while ( count( $parts ) > 0 ) {
4887 $editnotice_base .= '-' . array_shift( $parts );
4888 $msg = wfMessage( $editnotice_base );
4889 if ( $msg->exists() ) {
4890 $html = $msg->parseAsBlock();
4891 if ( trim( $html ) !== '' ) {
4892 $notices[$editnotice_base] = Html
::rawElement(
4896 'mw-editnotice-base',
4897 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4905 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4906 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4907 $msg = wfMessage( $editnoticeText );
4908 if ( $msg->exists() ) {
4909 $html = $msg->parseAsBlock();
4910 if ( trim( $html ) !== '' ) {
4911 $notices[$editnoticeText] = Html
::rawElement(
4915 'mw-editnotice-page',
4916 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4924 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4931 public function __sleep() {
4939 'mDefaultNamespace',
4943 public function __wakeup() {
4944 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4945 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4946 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );