3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
{
40 /** @var HashBagOStuff */
41 static private $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
111 /** @var string|bool */
112 protected $mOldRestrictions = false;
114 /** @var bool Cascade restrictions on this page to included templates and images? */
115 public $mCascadeRestriction;
117 /** Caching the results of getCascadeProtectionSources */
118 public $mCascadingRestrictions;
120 /** @var array When do the restrictions on this page expire? */
121 protected $mRestrictionsExpiry = [];
123 /** @var bool Are cascading restrictions in effect on this page? */
124 protected $mHasCascadingRestrictions;
126 /** @var array Where are the cascading restrictions coming from on this page? */
127 public $mCascadeSources;
129 /** @var bool Boolean for initialisation on demand */
130 public $mRestrictionsLoaded = false;
132 /** @var string Text form including namespace/interwiki, initialised on demand */
133 protected $mPrefixedText = null;
135 /** @var mixed Cached value for getTitleProtection (create protection) */
136 public $mTitleProtection;
139 * @var int Namespace index when there is no namespace. Don't change the
140 * following default, NS_MAIN is hardcoded in several places. See T2696.
141 * Zero except in {{transclusion}} tags.
143 public $mDefaultNamespace = NS_MAIN
;
145 /** @var int The page length, 0 for special pages */
146 protected $mLength = -1;
148 /** @var null Is the article at this title a redirect? */
149 public $mRedirect = null;
151 /** @var array Associative array of user ID -> timestamp/false */
152 private $mNotificationTimestamp = [];
154 /** @var bool Whether a page has any subpages */
155 private $mHasSubpages;
157 /** @var bool The (string) language code of the page's language and content code. */
158 private $mPageLanguage = false;
160 /** @var string|bool|null The page language code from the database, null if not saved in
161 * the database or false if not loaded, yet. */
162 private $mDbPageLanguage = false;
164 /** @var TitleValue A corresponding TitleValue object */
165 private $mTitleValue = null;
167 /** @var bool Would deleting this page be a big deletion? */
168 private $mIsBigDeletion = null;
172 * B/C kludge: provide a TitleParser for use by Title.
173 * Ideally, Title would have no methods that need this.
174 * Avoid usage of this singleton by using TitleValue
175 * and the associated services when possible.
177 * @return TitleFormatter
179 private static function getTitleFormatter() {
180 return MediaWikiServices
::getInstance()->getTitleFormatter();
184 * B/C kludge: provide an InterwikiLookup for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
189 * @return InterwikiLookup
191 private static function getInterwikiLookup() {
192 return MediaWikiServices
::getInstance()->getInterwikiLookup();
198 function __construct() {
202 * Create a new Title from a prefixed DB key
204 * @param string $key The database key, which has underscores
205 * instead of spaces, possibly including namespace and
207 * @return Title|null Title, or null on an error
209 public static function newFromDBkey( $key ) {
211 $t->mDbkeyform
= $key;
214 $t->secureAndSplit();
216 } catch ( MalformedTitleException
$ex ) {
222 * Create a new Title from a TitleValue
224 * @param TitleValue $titleValue Assumed to be safe.
228 public static function newFromTitleValue( TitleValue
$titleValue ) {
229 return self
::newFromLinkTarget( $titleValue );
233 * Create a new Title from a LinkTarget
235 * @param LinkTarget $linkTarget Assumed to be safe.
239 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
240 if ( $linkTarget instanceof Title
) {
241 // Special case if it's already a Title object
244 return self
::makeTitle(
245 $linkTarget->getNamespace(),
246 $linkTarget->getText(),
247 $linkTarget->getFragment(),
248 $linkTarget->getInterwiki()
253 * Create a new Title from text, such as what one would find in a link. De-
254 * codes any HTML entities in the text.
256 * @param string|int|null $text The link text; spaces, prefixes, and an
257 * initial ':' indicating the main namespace are accepted.
258 * @param int $defaultNamespace The namespace to use if none is specified
259 * by a prefix. If you want to force a specific namespace even if
260 * $text might begin with a namespace prefix, use makeTitle() or
262 * @throws InvalidArgumentException
263 * @return Title|null Title or null on an error.
265 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
266 // DWIM: Integers can be passed in here when page titles are used as array keys.
267 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
268 throw new InvalidArgumentException( '$text must be a string.' );
270 if ( $text === null ) {
275 return self
::newFromTextThrow( strval( $text ), $defaultNamespace );
276 } catch ( MalformedTitleException
$ex ) {
282 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
283 * rather than returning null.
285 * The exception subclasses encode detailed information about why the title is invalid.
287 * @see Title::newFromText
290 * @param string $text Title text to check
291 * @param int $defaultNamespace
292 * @throws MalformedTitleException If the title is invalid
295 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
296 if ( is_object( $text ) ) {
297 throw new MWException( '$text must be a string, given an object' );
300 $titleCache = self
::getTitleCache();
302 // Wiki pages often contain multiple links to the same page.
303 // Title normalization and parsing can become expensive on pages with many
304 // links, so we can save a little time by caching them.
305 // In theory these are value objects and won't get changed...
306 if ( $defaultNamespace == NS_MAIN
) {
307 $t = $titleCache->get( $text );
313 // Convert things like é ā or 〗 into normalized (T16952) text
314 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
317 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
318 $t->mDefaultNamespace
= intval( $defaultNamespace );
320 $t->secureAndSplit();
321 if ( $defaultNamespace == NS_MAIN
) {
322 $titleCache->set( $text, $t );
328 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
330 * Example of wrong and broken code:
331 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
333 * Example of right code:
334 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
336 * Create a new Title from URL-encoded text. Ensures that
337 * the given title's length does not exceed the maximum.
339 * @param string $url The title, as might be taken from a URL
340 * @return Title|null The new object, or null on an error
342 public static function newFromURL( $url ) {
345 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
346 # but some URLs used it as a space replacement and they still come
347 # from some external search tools.
348 if ( strpos( self
::legalChars(), '+' ) === false ) {
349 $url = strtr( $url, '+', ' ' );
352 $t->mDbkeyform
= strtr( $url, ' ', '_' );
355 $t->secureAndSplit();
357 } catch ( MalformedTitleException
$ex ) {
363 * @return HashBagOStuff
365 private static function getTitleCache() {
366 if ( self
::$titleCache == null ) {
367 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
369 return self
::$titleCache;
373 * Returns a list of fields that are to be selected for initializing Title
374 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
375 * whether to include page_content_model.
379 protected static function getSelectFields() {
380 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
383 'page_namespace', 'page_title', 'page_id',
384 'page_len', 'page_is_redirect', 'page_latest',
387 if ( $wgContentHandlerUseDB ) {
388 $fields[] = 'page_content_model';
391 if ( $wgPageLanguageUseDB ) {
392 $fields[] = 'page_lang';
399 * Create a new Title from an article ID
401 * @param int $id The page_id corresponding to the Title to create
402 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
403 * @return Title|null The new object, or null on an error
405 public static function newFromID( $id, $flags = 0 ) {
406 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
407 $row = $db->selectRow(
409 self
::getSelectFields(),
410 [ 'page_id' => $id ],
413 if ( $row !== false ) {
414 $title = self
::newFromRow( $row );
422 * Make an array of titles from an array of IDs
424 * @param int[] $ids Array of IDs
425 * @return Title[] Array of Titles
427 public static function newFromIDs( $ids ) {
428 if ( !count( $ids ) ) {
431 $dbr = wfGetDB( DB_REPLICA
);
435 self
::getSelectFields(),
436 [ 'page_id' => $ids ],
441 foreach ( $res as $row ) {
442 $titles[] = self
::newFromRow( $row );
448 * Make a Title object from a DB row
450 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
451 * @return Title Corresponding Title
453 public static function newFromRow( $row ) {
454 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
455 $t->loadFromRow( $row );
460 * Load Title object fields from a DB row.
461 * If false is given, the title will be treated as non-existing.
463 * @param stdClass|bool $row Database row
465 public function loadFromRow( $row ) {
466 if ( $row ) { // page found
467 if ( isset( $row->page_id
) ) {
468 $this->mArticleID
= (int)$row->page_id
;
470 if ( isset( $row->page_len
) ) {
471 $this->mLength
= (int)$row->page_len
;
473 if ( isset( $row->page_is_redirect
) ) {
474 $this->mRedirect
= (bool)$row->page_is_redirect
;
476 if ( isset( $row->page_latest
) ) {
477 $this->mLatestID
= (int)$row->page_latest
;
479 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
480 $this->mContentModel
= strval( $row->page_content_model
);
481 } elseif ( !$this->mForcedContentModel
) {
482 $this->mContentModel
= false; # initialized lazily in getContentModel()
484 if ( isset( $row->page_lang
) ) {
485 $this->mDbPageLanguage
= (string)$row->page_lang
;
487 if ( isset( $row->page_restrictions
) ) {
488 $this->mOldRestrictions
= $row->page_restrictions
;
490 } else { // page not found
491 $this->mArticleID
= 0;
493 $this->mRedirect
= false;
494 $this->mLatestID
= 0;
495 if ( !$this->mForcedContentModel
) {
496 $this->mContentModel
= false; # initialized lazily in getContentModel()
502 * Create a new Title from a namespace index and a DB key.
503 * It's assumed that $ns and $title are *valid*, for instance when
504 * they came directly from the database or a special page name.
505 * For convenience, spaces are converted to underscores so that
506 * eg user_text fields can be used directly.
508 * @param int $ns The namespace of the article
509 * @param string $title The unprefixed database key form
510 * @param string $fragment The link fragment (after the "#")
511 * @param string $interwiki The interwiki prefix
512 * @return Title The new object
514 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
516 $t->mInterwiki
= $interwiki;
517 $t->mFragment
= $fragment;
518 $t->mNamespace
= $ns = intval( $ns );
519 $t->mDbkeyform
= strtr( $title, ' ', '_' );
520 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
521 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
522 $t->mTextform
= strtr( $title, '_', ' ' );
523 $t->mContentModel
= false; # initialized lazily in getContentModel()
528 * Create a new Title from a namespace index and a DB key.
529 * The parameters will be checked for validity, which is a bit slower
530 * than makeTitle() but safer for user-provided data.
532 * @param int $ns The namespace of the article
533 * @param string $title Database key form
534 * @param string $fragment The link fragment (after the "#")
535 * @param string $interwiki Interwiki prefix
536 * @return Title|null The new object, or null on an error
538 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
539 if ( !MWNamespace
::exists( $ns ) ) {
544 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
547 $t->secureAndSplit();
549 } catch ( MalformedTitleException
$ex ) {
555 * Create a new Title for the Main Page
557 * @return Title The new object
559 public static function newMainPage() {
560 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
561 // Don't give fatal errors if the message is broken
563 $title = self
::newFromText( 'Main Page' );
569 * Get the prefixed DB key associated with an ID
571 * @param int $id The page_id of the article
572 * @return Title|null An object representing the article, or null if no such article was found
574 public static function nameOf( $id ) {
575 $dbr = wfGetDB( DB_REPLICA
);
577 $s = $dbr->selectRow(
579 [ 'page_namespace', 'page_title' ],
580 [ 'page_id' => $id ],
583 if ( $s === false ) {
587 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
592 * Get a regex character class describing the legal characters in a link
594 * @return string The list of characters, not delimited
596 public static function legalChars() {
597 global $wgLegalTitleChars;
598 return $wgLegalTitleChars;
602 * Returns a simple regex that will match on characters and sequences invalid in titles.
603 * Note that this doesn't pick up many things that could be wrong with titles, but that
604 * replacing this regex with something valid will make many titles valid.
606 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
608 * @return string Regex string
610 static function getTitleInvalidRegex() {
611 wfDeprecated( __METHOD__
, '1.25' );
612 return MediaWikiTitleCodec
::getTitleInvalidRegex();
616 * Utility method for converting a character sequence from bytes to Unicode.
618 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
619 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
621 * @param string $byteClass
624 public static function convertByteClassToUnicodeClass( $byteClass ) {
625 $length = strlen( $byteClass );
627 $x0 = $x1 = $x2 = '';
629 $d0 = $d1 = $d2 = '';
630 // Decoded integer codepoints
631 $ord0 = $ord1 = $ord2 = 0;
633 $r0 = $r1 = $r2 = '';
637 $allowUnicode = false;
638 for ( $pos = 0; $pos < $length; $pos++
) {
639 // Shift the queues down
648 // Load the current input token and decoded values
649 $inChar = $byteClass[$pos];
650 if ( $inChar == '\\' ) {
651 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
652 $x0 = $inChar . $m[0];
653 $d0 = chr( hexdec( $m[1] ) );
654 $pos +
= strlen( $m[0] );
655 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
656 $x0 = $inChar . $m[0];
657 $d0 = chr( octdec( $m[0] ) );
658 $pos +
= strlen( $m[0] );
659 } elseif ( $pos +
1 >= $length ) {
662 $d0 = $byteClass[$pos +
1];
670 // Load the current re-encoded value
671 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
672 $r0 = sprintf( '\x%02x', $ord0 );
673 } elseif ( $ord0 >= 0x80 ) {
674 // Allow unicode if a single high-bit character appears
675 $r0 = sprintf( '\x%02x', $ord0 );
676 $allowUnicode = true;
677 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
683 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
685 if ( $ord2 > $ord0 ) {
687 } elseif ( $ord0 >= 0x80 ) {
689 $allowUnicode = true;
690 if ( $ord2 < 0x80 ) {
691 // Keep the non-unicode section of the range
698 // Reset state to the initial value
699 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
700 } elseif ( $ord2 < 0x80 ) {
705 if ( $ord1 < 0x80 ) {
708 if ( $ord0 < 0x80 ) {
711 if ( $allowUnicode ) {
712 $out .= '\u0080-\uFFFF';
718 * Make a prefixed DB key from a DB key and a namespace index
720 * @param int $ns Numerical representation of the namespace
721 * @param string $title The DB key form the title
722 * @param string $fragment The link fragment (after the "#")
723 * @param string $interwiki The interwiki prefix
724 * @param bool $canonicalNamespace If true, use the canonical name for
725 * $ns instead of the localized version.
726 * @return string The prefixed form of the title
728 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
729 $canonicalNamespace = false
733 if ( $canonicalNamespace ) {
734 $namespace = MWNamespace
::getCanonicalName( $ns );
736 $namespace = $wgContLang->getNsText( $ns );
738 $name = $namespace == '' ?
$title : "$namespace:$title";
739 if ( strval( $interwiki ) != '' ) {
740 $name = "$interwiki:$name";
742 if ( strval( $fragment ) != '' ) {
743 $name .= '#' . $fragment;
749 * Escape a text fragment, say from a link, for a URL
751 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
753 * @param string $fragment Containing a URL or link fragment (after the "#")
754 * @return string Escaped string
756 static function escapeFragmentForURL( $fragment ) {
757 # Note that we don't urlencode the fragment. urlencoded Unicode
758 # fragments appear not to work in IE (at least up to 7) or in at least
759 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
760 # to care if they aren't encoded.
761 return Sanitizer
::escapeId( $fragment, 'noninitial' );
765 * Callback for usort() to do title sorts by (namespace, title)
767 * @param LinkTarget $a
768 * @param LinkTarget $b
770 * @return int Result of string comparison, or namespace comparison
772 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
773 if ( $a->getNamespace() == $b->getNamespace() ) {
774 return strcmp( $a->getText(), $b->getText() );
776 return $a->getNamespace() - $b->getNamespace();
781 * Determine whether the object refers to a page within
782 * this project (either this wiki or a wiki with a local
783 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
785 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
787 public function isLocal() {
788 if ( $this->isExternal() ) {
789 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
791 return $iw->isLocal();
798 * Is this Title interwiki?
802 public function isExternal() {
803 return $this->mInterwiki
!== '';
807 * Get the interwiki prefix
809 * Use Title::isExternal to check if a interwiki is set
811 * @return string Interwiki prefix
813 public function getInterwiki() {
814 return $this->mInterwiki
;
818 * Was this a local interwiki link?
822 public function wasLocalInterwiki() {
823 return $this->mLocalInterwiki
;
827 * Determine whether the object refers to a page within
828 * this project and is transcludable.
830 * @return bool True if this is transcludable
832 public function isTrans() {
833 if ( !$this->isExternal() ) {
837 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
841 * Returns the DB name of the distant wiki which owns the object.
843 * @return string|false The DB name
845 public function getTransWikiID() {
846 if ( !$this->isExternal() ) {
850 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
854 * Get a TitleValue object representing this Title.
856 * @note Not all valid Titles have a corresponding valid TitleValue
857 * (e.g. TitleValues cannot represent page-local links that have a
858 * fragment but no title text).
860 * @return TitleValue|null
862 public function getTitleValue() {
863 if ( $this->mTitleValue
=== null ) {
865 $this->mTitleValue
= new TitleValue(
866 $this->getNamespace(),
868 $this->getFragment(),
869 $this->getInterwiki()
871 } catch ( InvalidArgumentException
$ex ) {
872 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
873 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
877 return $this->mTitleValue
;
881 * Get the text form (spaces not underscores) of the main part
883 * @return string Main part of the title
885 public function getText() {
886 return $this->mTextform
;
890 * Get the URL-encoded form of the main part
892 * @return string Main part of the title, URL-encoded
894 public function getPartialURL() {
895 return $this->mUrlform
;
899 * Get the main part with underscores
901 * @return string Main part of the title, with underscores
903 public function getDBkey() {
904 return $this->mDbkeyform
;
908 * Get the DB key with the initial letter case as specified by the user
910 * @return string DB key
912 function getUserCaseDBKey() {
913 if ( !is_null( $this->mUserCaseDBKey
) ) {
914 return $this->mUserCaseDBKey
;
916 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
917 return $this->mDbkeyform
;
922 * Get the namespace index, i.e. one of the NS_xxxx constants.
924 * @return int Namespace index
926 public function getNamespace() {
927 return $this->mNamespace
;
931 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
933 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
934 * @return string Content model id
936 public function getContentModel( $flags = 0 ) {
937 if ( !$this->mForcedContentModel
938 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
939 && $this->getArticleID( $flags )
941 $linkCache = LinkCache
::singleton();
942 $linkCache->addLinkObj( $this ); # in case we already had an article ID
943 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
946 if ( !$this->mContentModel
) {
947 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
950 return $this->mContentModel
;
954 * Convenience method for checking a title's content model name
956 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
957 * @return bool True if $this->getContentModel() == $id
959 public function hasContentModel( $id ) {
960 return $this->getContentModel() == $id;
964 * Set a proposed content model for the page for permissions
965 * checking. This does not actually change the content model
968 * Additionally, you should make sure you've checked
969 * ContentHandler::canBeUsedOn() first.
972 * @param string $model CONTENT_MODEL_XXX constant
974 public function setContentModel( $model ) {
975 $this->mContentModel
= $model;
976 $this->mForcedContentModel
= true;
980 * Get the namespace text
982 * @return string|false Namespace text
984 public function getNsText() {
985 if ( $this->isExternal() ) {
986 // This probably shouldn't even happen,
987 // but for interwiki transclusion it sometimes does.
988 // Use the canonical namespaces if possible to try to
989 // resolve a foreign namespace.
990 if ( MWNamespace
::exists( $this->mNamespace
) ) {
991 return MWNamespace
::getCanonicalName( $this->mNamespace
);
996 $formatter = self
::getTitleFormatter();
997 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
998 } catch ( InvalidArgumentException
$ex ) {
999 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1005 * Get the namespace text of the subject (rather than talk) page
1007 * @return string Namespace text
1009 public function getSubjectNsText() {
1011 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1015 * Get the namespace text of the talk page
1017 * @return string Namespace text
1019 public function getTalkNsText() {
1021 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1025 * Can this title have a corresponding talk page?
1027 * @deprecated since 1.30, use canHaveTalkPage() instead.
1029 * @return bool True if this title either is a talk page or can have a talk page associated.
1031 public function canTalk() {
1032 return $this->canHaveTalkPage();
1036 * Can this title have a corresponding talk page?
1038 * @see MWNamespace::hasTalkNamespace
1040 * @return bool True if this title either is a talk page or can have a talk page associated.
1042 public function canHaveTalkPage() {
1043 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1047 * Is this in a namespace that allows actual pages?
1051 public function canExist() {
1052 return $this->mNamespace
>= NS_MAIN
;
1056 * Can this title be added to a user's watchlist?
1060 public function isWatchable() {
1061 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1065 * Returns true if this is a special page.
1069 public function isSpecialPage() {
1070 return $this->getNamespace() == NS_SPECIAL
;
1074 * Returns true if this title resolves to the named special page
1076 * @param string $name The special page name
1079 public function isSpecial( $name ) {
1080 if ( $this->isSpecialPage() ) {
1081 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1082 if ( $name == $thisName ) {
1090 * If the Title refers to a special page alias which is not the local default, resolve
1091 * the alias, and localise the name as necessary. Otherwise, return $this
1095 public function fixSpecialName() {
1096 if ( $this->isSpecialPage() ) {
1097 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1098 if ( $canonicalName ) {
1099 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1100 if ( $localName != $this->mDbkeyform
) {
1101 return self
::makeTitle( NS_SPECIAL
, $localName );
1109 * Returns true if the title is inside the specified namespace.
1111 * Please make use of this instead of comparing to getNamespace()
1112 * This function is much more resistant to changes we may make
1113 * to namespaces than code that makes direct comparisons.
1114 * @param int $ns The namespace
1118 public function inNamespace( $ns ) {
1119 return MWNamespace
::equals( $this->getNamespace(), $ns );
1123 * Returns true if the title is inside one of the specified namespaces.
1125 * @param int|int[] $namespaces,... The namespaces to check for
1129 public function inNamespaces( /* ... */ ) {
1130 $namespaces = func_get_args();
1131 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1132 $namespaces = $namespaces[0];
1135 foreach ( $namespaces as $ns ) {
1136 if ( $this->inNamespace( $ns ) ) {
1145 * Returns true if the title has the same subject namespace as the
1146 * namespace specified.
1147 * For example this method will take NS_USER and return true if namespace
1148 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1149 * as their subject namespace.
1151 * This is MUCH simpler than individually testing for equivalence
1152 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1157 public function hasSubjectNamespace( $ns ) {
1158 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1162 * Is this Title in a namespace which contains content?
1163 * In other words, is this a content page, for the purposes of calculating
1168 public function isContentPage() {
1169 return MWNamespace
::isContent( $this->getNamespace() );
1173 * Would anybody with sufficient privileges be able to move this page?
1174 * Some pages just aren't movable.
1178 public function isMovable() {
1179 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1180 // Interwiki title or immovable namespace. Hooks don't get to override here
1185 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1190 * Is this the mainpage?
1191 * @note Title::newFromText seems to be sufficiently optimized by the title
1192 * cache that we don't need to over-optimize by doing direct comparisons and
1193 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1194 * ends up reporting something differently than $title->isMainPage();
1199 public function isMainPage() {
1200 return $this->equals( self
::newMainPage() );
1204 * Is this a subpage?
1208 public function isSubpage() {
1209 return MWNamespace
::hasSubpages( $this->mNamespace
)
1210 ?
strpos( $this->getText(), '/' ) !== false
1215 * Is this a conversion table for the LanguageConverter?
1219 public function isConversionTable() {
1220 // @todo ConversionTable should become a separate content model.
1222 return $this->getNamespace() == NS_MEDIAWIKI
&&
1223 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1227 * Does that page contain wikitext, or it is JS, CSS or whatever?
1231 public function isWikitextPage() {
1232 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1236 * Could this page contain custom CSS or JavaScript for the global UI.
1237 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1238 * or CONTENT_MODEL_JAVASCRIPT.
1240 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1243 * Note that this method should not return true for pages that contain and
1244 * show "inactive" CSS or JS.
1247 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1249 public function isCssOrJsPage() {
1250 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1251 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1252 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1254 return $isCssOrJsPage;
1258 * Is this a .css or .js subpage of a user page?
1260 * @todo FIXME: Rename to isUserConfigPage()
1262 public function isCssJsSubpage() {
1263 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1264 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1265 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1269 * Trim down a .css or .js subpage title to get the corresponding skin name
1271 * @return string Containing skin name from .css or .js subpage title
1273 public function getSkinFromCssJsSubpage() {
1274 $subpage = explode( '/', $this->mTextform
);
1275 $subpage = $subpage[count( $subpage ) - 1];
1276 $lastdot = strrpos( $subpage, '.' );
1277 if ( $lastdot === false ) {
1278 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1280 return substr( $subpage, 0, $lastdot );
1284 * Is this a .css subpage of a user page?
1288 public function isCssSubpage() {
1289 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1290 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1294 * Is this a .js subpage of a user page?
1298 public function isJsSubpage() {
1299 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1300 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1304 * Is this a talk page of some sort?
1308 public function isTalkPage() {
1309 return MWNamespace
::isTalk( $this->getNamespace() );
1313 * Get a Title object associated with the talk page of this article
1315 * @return Title The object for the talk page
1317 public function getTalkPage() {
1318 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1322 * Get a Title object associated with the talk page of this article,
1323 * if such a talk page can exist.
1327 * @return Title|null The object for the talk page,
1328 * or null if no associated talk page can exist, according to canHaveTalkPage().
1330 public function getTalkPageIfDefined() {
1331 if ( !$this->canHaveTalkPage() ) {
1335 return $this->getTalkPage();
1339 * Get a title object associated with the subject page of this
1342 * @return Title The object for the subject page
1344 public function getSubjectPage() {
1345 // Is this the same title?
1346 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1347 if ( $this->getNamespace() == $subjectNS ) {
1350 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1354 * Get the other title for this page, if this is a subject page
1355 * get the talk page, if it is a subject page get the talk page
1358 * @throws MWException If the page doesn't have an other page
1361 public function getOtherPage() {
1362 if ( $this->isSpecialPage() ) {
1363 throw new MWException( 'Special pages cannot have other pages' );
1365 if ( $this->isTalkPage() ) {
1366 return $this->getSubjectPage();
1368 if ( !$this->canHaveTalkPage() ) {
1369 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1371 return $this->getTalkPage();
1376 * Get the default namespace index, for when there is no namespace
1378 * @return int Default namespace index
1380 public function getDefaultNamespace() {
1381 return $this->mDefaultNamespace
;
1385 * Get the Title fragment (i.e.\ the bit after the #) in text form
1387 * Use Title::hasFragment to check for a fragment
1389 * @return string Title fragment
1391 public function getFragment() {
1392 return $this->mFragment
;
1396 * Check if a Title fragment is set
1401 public function hasFragment() {
1402 return $this->mFragment
!== '';
1406 * Get the fragment in URL form, including the "#" character if there is one
1408 * @return string Fragment in URL form
1410 public function getFragmentForURL() {
1411 if ( !$this->hasFragment() ) {
1413 } elseif ( $this->isExternal() && !$this->getTransWikiID() ) {
1414 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1416 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1420 * Set the fragment for this title. Removes the first character from the
1421 * specified fragment before setting, so it assumes you're passing it with
1424 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1425 * or Title::createFragmentTarget().
1426 * Still in active use privately.
1429 * @param string $fragment Text
1431 public function setFragment( $fragment ) {
1432 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1436 * Creates a new Title for a different fragment of the same page.
1439 * @param string $fragment
1442 public function createFragmentTarget( $fragment ) {
1443 return self
::makeTitle(
1444 $this->getNamespace(),
1447 $this->getInterwiki()
1452 * Prefix some arbitrary text with the namespace or interwiki prefix
1455 * @param string $name The text
1456 * @return string The prefixed text
1458 private function prefix( $name ) {
1462 if ( $this->isExternal() ) {
1463 $p = $this->mInterwiki
. ':';
1466 if ( 0 != $this->mNamespace
) {
1467 $nsText = $this->getNsText();
1469 if ( $nsText === false ) {
1470 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1471 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1474 $p .= $nsText . ':';
1480 * Get the prefixed database key form
1482 * @return string The prefixed title, with underscores and
1483 * any interwiki and namespace prefixes
1485 public function getPrefixedDBkey() {
1486 $s = $this->prefix( $this->mDbkeyform
);
1487 $s = strtr( $s, ' ', '_' );
1492 * Get the prefixed title with spaces.
1493 * This is the form usually used for display
1495 * @return string The prefixed title, with spaces
1497 public function getPrefixedText() {
1498 if ( $this->mPrefixedText
=== null ) {
1499 $s = $this->prefix( $this->mTextform
);
1500 $s = strtr( $s, '_', ' ' );
1501 $this->mPrefixedText
= $s;
1503 return $this->mPrefixedText
;
1507 * Return a string representation of this title
1509 * @return string Representation of this title
1511 public function __toString() {
1512 return $this->getPrefixedText();
1516 * Get the prefixed title with spaces, plus any fragment
1517 * (part beginning with '#')
1519 * @return string The prefixed title, with spaces and the fragment, including '#'
1521 public function getFullText() {
1522 $text = $this->getPrefixedText();
1523 if ( $this->hasFragment() ) {
1524 $text .= '#' . $this->getFragment();
1530 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1534 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1538 * @return string Root name
1541 public function getRootText() {
1542 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1543 return $this->getText();
1546 return strtok( $this->getText(), '/' );
1550 * Get the root page name title, i.e. the leftmost part before any slashes
1554 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1555 * # returns: Title{User:Foo}
1558 * @return Title Root title
1561 public function getRootTitle() {
1562 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1566 * Get the base page name without a namespace, i.e. the part before the subpage name
1570 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1571 * # returns: 'Foo/Bar'
1574 * @return string Base name
1576 public function getBaseText() {
1577 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1578 return $this->getText();
1581 $parts = explode( '/', $this->getText() );
1582 # Don't discard the real title if there's no subpage involved
1583 if ( count( $parts ) > 1 ) {
1584 unset( $parts[count( $parts ) - 1] );
1586 return implode( '/', $parts );
1590 * Get the base page name title, i.e. the part before the subpage name
1594 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1595 * # returns: Title{User:Foo/Bar}
1598 * @return Title Base title
1601 public function getBaseTitle() {
1602 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1606 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1610 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1614 * @return string Subpage name
1616 public function getSubpageText() {
1617 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1618 return $this->mTextform
;
1620 $parts = explode( '/', $this->mTextform
);
1621 return $parts[count( $parts ) - 1];
1625 * Get the title for a subpage of the current page
1629 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1630 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1633 * @param string $text The subpage name to add to the title
1634 * @return Title Subpage title
1637 public function getSubpage( $text ) {
1638 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1642 * Get a URL-encoded form of the subpage text
1644 * @return string URL-encoded subpage name
1646 public function getSubpageUrlForm() {
1647 $text = $this->getSubpageText();
1648 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1653 * Get a URL-encoded title (not an actual URL) including interwiki
1655 * @return string The URL-encoded form
1657 public function getPrefixedURL() {
1658 $s = $this->prefix( $this->mDbkeyform
);
1659 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1664 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1665 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1666 * second argument named variant. This was deprecated in favor
1667 * of passing an array of option with a "variant" key
1668 * Once $query2 is removed for good, this helper can be dropped
1669 * and the wfArrayToCgi moved to getLocalURL();
1671 * @since 1.19 (r105919)
1672 * @param array|string $query
1673 * @param string|string[]|bool $query2
1676 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1677 if ( $query2 !== false ) {
1678 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1679 "method called with a second parameter is deprecated. Add your " .
1680 "parameter to an array passed as the first parameter.", "1.19" );
1682 if ( is_array( $query ) ) {
1683 $query = wfArrayToCgi( $query );
1686 if ( is_string( $query2 ) ) {
1687 // $query2 is a string, we will consider this to be
1688 // a deprecated $variant argument and add it to the query
1689 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1691 $query2 = wfArrayToCgi( $query2 );
1693 // If we have $query content add a & to it first
1697 // Now append the queries together
1704 * Get a real URL referring to this title, with interwiki link and
1707 * @see self::getLocalURL for the arguments.
1709 * @param string|string[] $query
1710 * @param string|string[]|bool $query2
1711 * @param string $proto Protocol type to use in URL
1712 * @return string The URL
1714 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1715 $query = self
::fixUrlQueryArgs( $query, $query2 );
1717 # Hand off all the decisions on urls to getLocalURL
1718 $url = $this->getLocalURL( $query );
1720 # Expand the url to make it a full url. Note that getLocalURL has the
1721 # potential to output full urls for a variety of reasons, so we use
1722 # wfExpandUrl instead of simply prepending $wgServer
1723 $url = wfExpandUrl( $url, $proto );
1725 # Finally, add the fragment.
1726 $url .= $this->getFragmentForURL();
1727 // Avoid PHP 7.1 warning from passing $this by reference
1729 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1734 * Get a url appropriate for making redirects based on an untrusted url arg
1736 * This is basically the same as getFullUrl(), but in the case of external
1737 * interwikis, we send the user to a landing page, to prevent possible
1738 * phishing attacks and the like.
1740 * @note Uses current protocol by default, since technically relative urls
1741 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1742 * places where the url gets cached, as might pollute between
1743 * https and non-https users.
1744 * @see self::getLocalURL for the arguments.
1745 * @param array|string $query
1746 * @param string $proto Protocol type to use in URL
1747 * @return String. A url suitable to use in an HTTP location header.
1749 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1751 if ( $this->isExternal() ) {
1752 $target = SpecialPage
::getTitleFor(
1754 $this->getPrefixedDBKey()
1757 return $target->getFullUrl( $query, false, $proto );
1761 * Get a URL with no fragment or server name (relative URL) from a Title object.
1762 * If this page is generated with action=render, however,
1763 * $wgServer is prepended to make an absolute URL.
1765 * @see self::getFullURL to always get an absolute URL.
1766 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1767 * valid to link, locally, to the current Title.
1768 * @see self::newFromText to produce a Title object.
1770 * @param string|string[] $query An optional query string,
1771 * not used for interwiki links. Can be specified as an associative array as well,
1772 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1773 * Some query patterns will trigger various shorturl path replacements.
1774 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1775 * be an array. If a string is passed it will be interpreted as a deprecated
1776 * variant argument and urlencoded into a variant= argument.
1777 * This second query argument will be added to the $query
1778 * The second parameter is deprecated since 1.19. Pass it as a key,value
1779 * pair in the first parameter array instead.
1781 * @return string String of the URL.
1783 public function getLocalURL( $query = '', $query2 = false ) {
1784 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1786 $query = self
::fixUrlQueryArgs( $query, $query2 );
1788 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1790 $namespace = $this->getNsText();
1791 if ( $namespace != '' ) {
1792 # Can this actually happen? Interwikis shouldn't be parsed.
1793 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1796 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1797 $url = wfAppendQuery( $url, $query );
1799 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1800 if ( $query == '' ) {
1801 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1802 // Avoid PHP 7.1 warning from passing $this by reference
1804 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1806 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1810 if ( !empty( $wgActionPaths )
1811 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1813 $action = urldecode( $matches[2] );
1814 if ( isset( $wgActionPaths[$action] ) ) {
1815 $query = $matches[1];
1816 if ( isset( $matches[4] ) ) {
1817 $query .= $matches[4];
1819 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1820 if ( $query != '' ) {
1821 $url = wfAppendQuery( $url, $query );
1827 && $wgVariantArticlePath
1828 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1829 && $this->getPageLanguage()->equals( $wgContLang )
1830 && $this->getPageLanguage()->hasVariants()
1832 $variant = urldecode( $matches[1] );
1833 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1834 // Only do the variant replacement if the given variant is a valid
1835 // variant for the page's language.
1836 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1837 $url = str_replace( '$1', $dbkey, $url );
1841 if ( $url === false ) {
1842 if ( $query == '-' ) {
1845 $url = "{$wgScript}?title={$dbkey}&{$query}";
1848 // Avoid PHP 7.1 warning from passing $this by reference
1850 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1852 // @todo FIXME: This causes breakage in various places when we
1853 // actually expected a local URL and end up with dupe prefixes.
1854 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1855 $url = $wgServer . $url;
1858 // Avoid PHP 7.1 warning from passing $this by reference
1860 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1865 * Get a URL that's the simplest URL that will be valid to link, locally,
1866 * to the current Title. It includes the fragment, but does not include
1867 * the server unless action=render is used (or the link is external). If
1868 * there's a fragment but the prefixed text is empty, we just return a link
1871 * The result obviously should not be URL-escaped, but does need to be
1872 * HTML-escaped if it's being output in HTML.
1874 * @param string|string[] $query
1875 * @param bool $query2
1876 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1877 * or false (default) for no expansion
1878 * @see self::getLocalURL for the arguments.
1879 * @return string The URL
1881 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1882 if ( $this->isExternal() ||
$proto !== false ) {
1883 $ret = $this->getFullURL( $query, $query2, $proto );
1884 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1885 $ret = $this->getFragmentForURL();
1887 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1893 * Get the URL form for an internal link.
1894 * - Used in various CDN-related code, in case we have a different
1895 * internal hostname for the server from the exposed one.
1897 * This uses $wgInternalServer to qualify the path, or $wgServer
1898 * if $wgInternalServer is not set. If the server variable used is
1899 * protocol-relative, the URL will be expanded to http://
1901 * @see self::getLocalURL for the arguments.
1902 * @param string $query
1903 * @param string|bool $query2
1904 * @return string The URL
1906 public function getInternalURL( $query = '', $query2 = false ) {
1907 global $wgInternalServer, $wgServer;
1908 $query = self
::fixUrlQueryArgs( $query, $query2 );
1909 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1910 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1911 // Avoid PHP 7.1 warning from passing $this by reference
1913 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1918 * Get the URL for a canonical link, for use in things like IRC and
1919 * e-mail notifications. Uses $wgCanonicalServer and the
1920 * GetCanonicalURL hook.
1922 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1924 * @see self::getLocalURL for the arguments.
1925 * @return string The URL
1928 public function getCanonicalURL( $query = '', $query2 = false ) {
1929 $query = self
::fixUrlQueryArgs( $query, $query2 );
1930 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1931 // Avoid PHP 7.1 warning from passing $this by reference
1933 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1938 * Get the edit URL for this Title
1940 * @return string The URL, or a null string if this is an interwiki link
1942 public function getEditURL() {
1943 if ( $this->isExternal() ) {
1946 $s = $this->getLocalURL( 'action=edit' );
1952 * Can $user perform $action on this page?
1953 * This skips potentially expensive cascading permission checks
1954 * as well as avoids expensive error formatting
1956 * Suitable for use for nonessential UI controls in common cases, but
1957 * _not_ for functional access control.
1959 * May provide false positives, but should never provide a false negative.
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 provided.
1965 public function quickUserCan( $action, $user = null ) {
1966 return $this->userCan( $action, $user, false );
1970 * Can $user perform $action on this page?
1972 * @param string $action Action that permission needs to be checked for
1973 * @param User $user User to check (since 1.19); $wgUser will be used if not
1975 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1978 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1979 if ( !$user instanceof User
) {
1984 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1988 * Can $user perform $action on this page?
1990 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1992 * @param string $action Action that permission needs to be checked for
1993 * @param User $user User to check
1994 * @param string $rigor One of (quick,full,secure)
1995 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1996 * - full : does cheap and expensive checks possibly from a replica DB
1997 * - secure : does cheap and expensive checks, using the master as needed
1998 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1999 * whose corresponding errors may be ignored.
2000 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2002 public function getUserPermissionsErrors(
2003 $action, $user, $rigor = 'secure', $ignoreErrors = []
2005 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2007 // Remove the errors being ignored.
2008 foreach ( $errors as $index => $error ) {
2009 $errKey = is_array( $error ) ?
$error[0] : $error;
2011 if ( in_array( $errKey, $ignoreErrors ) ) {
2012 unset( $errors[$index] );
2014 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2015 unset( $errors[$index] );
2023 * Permissions checks that fail most often, and which are easiest to test.
2025 * @param string $action The action to check
2026 * @param User $user User to check
2027 * @param array $errors List of current errors
2028 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2029 * @param bool $short Short circuit on first error
2031 * @return array List of errors
2033 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2034 if ( !Hooks
::run( 'TitleQuickPermissions',
2035 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2040 if ( $action == 'create' ) {
2042 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2043 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2045 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2047 } elseif ( $action == 'move' ) {
2048 if ( !$user->isAllowed( 'move-rootuserpages' )
2049 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2050 // Show user page-specific message only if the user can move other pages
2051 $errors[] = [ 'cant-move-user-page' ];
2054 // Check if user is allowed to move files if it's a file
2055 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2056 $errors[] = [ 'movenotallowedfile' ];
2059 // Check if user is allowed to move category pages if it's a category page
2060 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2061 $errors[] = [ 'cant-move-category-page' ];
2064 if ( !$user->isAllowed( 'move' ) ) {
2065 // User can't move anything
2066 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2067 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2068 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2069 // custom message if logged-in users without any special rights can move
2070 $errors[] = [ 'movenologintext' ];
2072 $errors[] = [ 'movenotallowed' ];
2075 } elseif ( $action == 'move-target' ) {
2076 if ( !$user->isAllowed( 'move' ) ) {
2077 // User can't move anything
2078 $errors[] = [ 'movenotallowed' ];
2079 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2080 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2081 // Show user page-specific message only if the user can move other pages
2082 $errors[] = [ 'cant-move-to-user-page' ];
2083 } elseif ( !$user->isAllowed( 'move-categorypages' )
2084 && $this->mNamespace
== NS_CATEGORY
) {
2085 // Show category page-specific message only if the user can move other pages
2086 $errors[] = [ 'cant-move-to-category-page' ];
2088 } elseif ( !$user->isAllowed( $action ) ) {
2089 $errors[] = $this->missingPermissionError( $action, $short );
2096 * Add the resulting error code to the errors array
2098 * @param array $errors List of current errors
2099 * @param array $result Result of errors
2101 * @return array List of errors
2103 private function resultToError( $errors, $result ) {
2104 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2105 // A single array representing an error
2106 $errors[] = $result;
2107 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2108 // A nested array representing multiple errors
2109 $errors = array_merge( $errors, $result );
2110 } elseif ( $result !== '' && is_string( $result ) ) {
2111 // A string representing a message-id
2112 $errors[] = [ $result ];
2113 } elseif ( $result instanceof MessageSpecifier
) {
2114 // A message specifier representing an error
2115 $errors[] = [ $result ];
2116 } elseif ( $result === false ) {
2117 // a generic "We don't want them to do that"
2118 $errors[] = [ 'badaccess-group0' ];
2124 * Check various permission hooks
2126 * @param string $action The action to check
2127 * @param User $user User to check
2128 * @param array $errors List of current errors
2129 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2130 * @param bool $short Short circuit on first error
2132 * @return array List of errors
2134 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2135 // Use getUserPermissionsErrors instead
2137 // Avoid PHP 7.1 warning from passing $this by reference
2139 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2140 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2142 // Check getUserPermissionsErrors hook
2143 // Avoid PHP 7.1 warning from passing $this by reference
2145 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2146 $errors = $this->resultToError( $errors, $result );
2148 // Check getUserPermissionsErrorsExpensive hook
2151 && !( $short && count( $errors ) > 0 )
2152 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2154 $errors = $this->resultToError( $errors, $result );
2161 * Check permissions on special pages & namespaces
2163 * @param string $action The action to check
2164 * @param User $user User to check
2165 * @param array $errors List of current errors
2166 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2167 * @param bool $short Short circuit on first error
2169 * @return array List of errors
2171 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2172 # Only 'createaccount' can be performed on special pages,
2173 # which don't actually exist in the DB.
2174 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2175 $errors[] = [ 'ns-specialprotected' ];
2178 # Check $wgNamespaceProtection for restricted namespaces
2179 if ( $this->isNamespaceProtected( $user ) ) {
2180 $ns = $this->mNamespace
== NS_MAIN ?
2181 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2182 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2183 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2190 * Check CSS/JS sub-page permissions
2192 * @param string $action The action to check
2193 * @param User $user User to check
2194 * @param array $errors List of current errors
2195 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2196 * @param bool $short Short circuit on first error
2198 * @return array List of errors
2200 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2201 # Protect css/js subpages of user pages
2202 # XXX: this might be better using restrictions
2203 if ( $action != 'patrol' ) {
2204 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2205 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2206 $errors[] = [ 'mycustomcssprotected', $action ];
2207 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2208 $errors[] = [ 'mycustomjsprotected', $action ];
2211 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2212 $errors[] = [ 'customcssprotected', $action ];
2213 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2214 $errors[] = [ 'customjsprotected', $action ];
2223 * Check against page_restrictions table requirements on this
2224 * page. The user must possess all required rights for this
2227 * @param string $action The action to check
2228 * @param User $user User to check
2229 * @param array $errors List of current errors
2230 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2231 * @param bool $short Short circuit on first error
2233 * @return array List of errors
2235 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2236 foreach ( $this->getRestrictions( $action ) as $right ) {
2237 // Backwards compatibility, rewrite sysop -> editprotected
2238 if ( $right == 'sysop' ) {
2239 $right = 'editprotected';
2241 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2242 if ( $right == 'autoconfirmed' ) {
2243 $right = 'editsemiprotected';
2245 if ( $right == '' ) {
2248 if ( !$user->isAllowed( $right ) ) {
2249 $errors[] = [ 'protectedpagetext', $right, $action ];
2250 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2251 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2259 * Check restrictions on cascading pages.
2261 * @param string $action The action to check
2262 * @param User $user User to check
2263 * @param array $errors List of current errors
2264 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2265 * @param bool $short Short circuit on first error
2267 * @return array List of errors
2269 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2270 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2271 # We /could/ use the protection level on the source page, but it's
2272 # fairly ugly as we have to establish a precedence hierarchy for pages
2273 # included by multiple cascade-protected pages. So just restrict
2274 # it to people with 'protect' permission, as they could remove the
2275 # protection anyway.
2276 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2277 # Cascading protection depends on more than this page...
2278 # Several cascading protected pages may include this page...
2279 # Check each cascading level
2280 # This is only for protection restrictions, not for all actions
2281 if ( isset( $restrictions[$action] ) ) {
2282 foreach ( $restrictions[$action] as $right ) {
2283 // Backwards compatibility, rewrite sysop -> editprotected
2284 if ( $right == 'sysop' ) {
2285 $right = 'editprotected';
2287 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2288 if ( $right == 'autoconfirmed' ) {
2289 $right = 'editsemiprotected';
2291 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2293 foreach ( $cascadingSources as $page ) {
2294 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2296 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2306 * Check action permissions not already checked in checkQuickPermissions
2308 * @param string $action The action to check
2309 * @param User $user User to check
2310 * @param array $errors List of current errors
2311 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2312 * @param bool $short Short circuit on first error
2314 * @return array List of errors
2316 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2317 global $wgDeleteRevisionsLimit, $wgLang;
2319 if ( $action == 'protect' ) {
2320 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2321 // If they can't edit, they shouldn't protect.
2322 $errors[] = [ 'protect-cantedit' ];
2324 } elseif ( $action == 'create' ) {
2325 $title_protection = $this->getTitleProtection();
2326 if ( $title_protection ) {
2327 if ( $title_protection['permission'] == ''
2328 ||
!$user->isAllowed( $title_protection['permission'] )
2332 User
::whoIs( $title_protection['user'] ),
2333 $title_protection['reason']
2337 } elseif ( $action == 'move' ) {
2338 // Check for immobile pages
2339 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2340 // Specific message for this case
2341 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2342 } elseif ( !$this->isMovable() ) {
2343 // Less specific message for rarer cases
2344 $errors[] = [ 'immobile-source-page' ];
2346 } elseif ( $action == 'move-target' ) {
2347 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2348 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2349 } elseif ( !$this->isMovable() ) {
2350 $errors[] = [ 'immobile-target-page' ];
2352 } elseif ( $action == 'delete' ) {
2353 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2354 if ( !$tempErrors ) {
2355 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2356 $user, $tempErrors, $rigor, true );
2358 if ( $tempErrors ) {
2359 // If protection keeps them from editing, they shouldn't be able to delete.
2360 $errors[] = [ 'deleteprotected' ];
2362 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2363 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2365 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2367 } elseif ( $action === 'undelete' ) {
2368 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2369 // Undeleting implies editing
2370 $errors[] = [ 'undelete-cantedit' ];
2372 if ( !$this->exists()
2373 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2375 // Undeleting where nothing currently exists implies creating
2376 $errors[] = [ 'undelete-cantcreate' ];
2383 * Check that the user isn't blocked from editing.
2385 * @param string $action The action to check
2386 * @param User $user User to check
2387 * @param array $errors List of current errors
2388 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2389 * @param bool $short Short circuit on first error
2391 * @return array List of errors
2393 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2394 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2395 // Account creation blocks handled at userlogin.
2396 // Unblocking handled in SpecialUnblock
2397 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2401 // Optimize for a very common case
2402 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2406 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2407 $errors[] = [ 'confirmedittext' ];
2410 $useSlave = ( $rigor !== 'secure' );
2411 if ( ( $action == 'edit' ||
$action == 'create' )
2412 && !$user->isBlockedFrom( $this, $useSlave )
2414 // Don't block the user from editing their own talk page unless they've been
2415 // explicitly blocked from that too.
2416 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2417 // @todo FIXME: Pass the relevant context into this function.
2418 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2425 * Check that the user is allowed to read this page.
2427 * @param string $action The action to check
2428 * @param User $user User to check
2429 * @param array $errors List of current errors
2430 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2431 * @param bool $short Short circuit on first error
2433 * @return array List of errors
2435 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2436 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2438 $whitelisted = false;
2439 if ( User
::isEveryoneAllowed( 'read' ) ) {
2440 # Shortcut for public wikis, allows skipping quite a bit of code
2441 $whitelisted = true;
2442 } elseif ( $user->isAllowed( 'read' ) ) {
2443 # If the user is allowed to read pages, he is allowed to read all pages
2444 $whitelisted = true;
2445 } elseif ( $this->isSpecial( 'Userlogin' )
2446 ||
$this->isSpecial( 'PasswordReset' )
2447 ||
$this->isSpecial( 'Userlogout' )
2449 # Always grant access to the login page.
2450 # Even anons need to be able to log in.
2451 $whitelisted = true;
2452 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2453 # Time to check the whitelist
2454 # Only do these checks is there's something to check against
2455 $name = $this->getPrefixedText();
2456 $dbName = $this->getPrefixedDBkey();
2458 // Check for explicit whitelisting with and without underscores
2459 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2460 $whitelisted = true;
2461 } elseif ( $this->getNamespace() == NS_MAIN
) {
2462 # Old settings might have the title prefixed with
2463 # a colon for main-namespace pages
2464 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2465 $whitelisted = true;
2467 } elseif ( $this->isSpecialPage() ) {
2468 # If it's a special page, ditch the subpage bit and check again
2469 $name = $this->getDBkey();
2470 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2472 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2473 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2474 $whitelisted = true;
2480 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2481 $name = $this->getPrefixedText();
2482 // Check for regex whitelisting
2483 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2484 if ( preg_match( $listItem, $name ) ) {
2485 $whitelisted = true;
2491 if ( !$whitelisted ) {
2492 # If the title is not whitelisted, give extensions a chance to do so...
2493 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2494 if ( !$whitelisted ) {
2495 $errors[] = $this->missingPermissionError( $action, $short );
2503 * Get a description array when the user doesn't have the right to perform
2504 * $action (i.e. when User::isAllowed() returns false)
2506 * @param string $action The action to check
2507 * @param bool $short Short circuit on first error
2508 * @return array Array containing an error message key and any parameters
2510 private function missingPermissionError( $action, $short ) {
2511 // We avoid expensive display logic for quickUserCan's and such
2513 return [ 'badaccess-group0' ];
2516 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2520 * Can $user perform $action on this page? This is an internal function,
2521 * with multiple levels of checks depending on performance needs; see $rigor below.
2522 * It does not check wfReadOnly().
2524 * @param string $action Action that permission needs to be checked for
2525 * @param User $user User to check
2526 * @param string $rigor One of (quick,full,secure)
2527 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2528 * - full : does cheap and expensive checks possibly from a replica DB
2529 * - secure : does cheap and expensive checks, using the master as needed
2530 * @param bool $short Set this to true to stop after the first permission error.
2531 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2533 protected function getUserPermissionsErrorsInternal(
2534 $action, $user, $rigor = 'secure', $short = false
2536 if ( $rigor === true ) {
2537 $rigor = 'secure'; // b/c
2538 } elseif ( $rigor === false ) {
2539 $rigor = 'quick'; // b/c
2540 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2541 throw new Exception( "Invalid rigor parameter '$rigor'." );
2544 # Read has special handling
2545 if ( $action == 'read' ) {
2547 'checkPermissionHooks',
2548 'checkReadPermissions',
2549 'checkUserBlock', // for wgBlockDisablesLogin
2551 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2552 # here as it will lead to duplicate error messages. This is okay to do
2553 # since anywhere that checks for create will also check for edit, and
2554 # those checks are called for edit.
2555 } elseif ( $action == 'create' ) {
2557 'checkQuickPermissions',
2558 'checkPermissionHooks',
2559 'checkPageRestrictions',
2560 'checkCascadingSourcesRestrictions',
2561 'checkActionPermissions',
2566 'checkQuickPermissions',
2567 'checkPermissionHooks',
2568 'checkSpecialsAndNSPermissions',
2569 'checkCSSandJSPermissions',
2570 'checkPageRestrictions',
2571 'checkCascadingSourcesRestrictions',
2572 'checkActionPermissions',
2578 while ( count( $checks ) > 0 &&
2579 !( $short && count( $errors ) > 0 ) ) {
2580 $method = array_shift( $checks );
2581 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2588 * Get a filtered list of all restriction types supported by this wiki.
2589 * @param bool $exists True to get all restriction types that apply to
2590 * titles that do exist, False for all restriction types that apply to
2591 * titles that do not exist
2594 public static function getFilteredRestrictionTypes( $exists = true ) {
2595 global $wgRestrictionTypes;
2596 $types = $wgRestrictionTypes;
2598 # Remove the create restriction for existing titles
2599 $types = array_diff( $types, [ 'create' ] );
2601 # Only the create and upload restrictions apply to non-existing titles
2602 $types = array_intersect( $types, [ 'create', 'upload' ] );
2608 * Returns restriction types for the current Title
2610 * @return array Applicable restriction types
2612 public function getRestrictionTypes() {
2613 if ( $this->isSpecialPage() ) {
2617 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2619 if ( $this->getNamespace() != NS_FILE
) {
2620 # Remove the upload restriction for non-file titles
2621 $types = array_diff( $types, [ 'upload' ] );
2624 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2626 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2627 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2633 * Is this title subject to title protection?
2634 * Title protection is the one applied against creation of such title.
2636 * @return array|bool An associative array representing any existent title
2637 * protection, or false if there's none.
2639 public function getTitleProtection() {
2640 $protection = $this->getTitleProtectionInternal();
2641 if ( $protection ) {
2642 if ( $protection['permission'] == 'sysop' ) {
2643 $protection['permission'] = 'editprotected'; // B/C
2645 if ( $protection['permission'] == 'autoconfirmed' ) {
2646 $protection['permission'] = 'editsemiprotected'; // B/C
2653 * Fetch title protection settings
2655 * To work correctly, $this->loadRestrictions() needs to have access to the
2656 * actual protections in the database without munging 'sysop' =>
2657 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2658 * callers probably want $this->getTitleProtection() instead.
2660 * @return array|bool
2662 protected function getTitleProtectionInternal() {
2663 // Can't protect pages in special namespaces
2664 if ( $this->getNamespace() < 0 ) {
2668 // Can't protect pages that exist.
2669 if ( $this->exists() ) {
2673 if ( $this->mTitleProtection
=== null ) {
2674 $dbr = wfGetDB( DB_REPLICA
);
2675 $res = $dbr->select(
2678 'user' => 'pt_user',
2679 'reason' => 'pt_reason',
2680 'expiry' => 'pt_expiry',
2681 'permission' => 'pt_create_perm'
2683 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2687 // fetchRow returns false if there are no rows.
2688 $row = $dbr->fetchRow( $res );
2690 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2692 $this->mTitleProtection
= $row;
2694 return $this->mTitleProtection
;
2698 * Remove any title protection due to page existing
2700 public function deleteTitleProtection() {
2701 $dbw = wfGetDB( DB_MASTER
);
2705 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2708 $this->mTitleProtection
= false;
2712 * Is this page "semi-protected" - the *only* protection levels are listed
2713 * in $wgSemiprotectedRestrictionLevels?
2715 * @param string $action Action to check (default: edit)
2718 public function isSemiProtected( $action = 'edit' ) {
2719 global $wgSemiprotectedRestrictionLevels;
2721 $restrictions = $this->getRestrictions( $action );
2722 $semi = $wgSemiprotectedRestrictionLevels;
2723 if ( !$restrictions ||
!$semi ) {
2724 // Not protected, or all protection is full protection
2728 // Remap autoconfirmed to editsemiprotected for BC
2729 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2730 $semi[$key] = 'editsemiprotected';
2732 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2733 $restrictions[$key] = 'editsemiprotected';
2736 return !array_diff( $restrictions, $semi );
2740 * Does the title correspond to a protected article?
2742 * @param string $action The action the page is protected from,
2743 * by default checks all actions.
2746 public function isProtected( $action = '' ) {
2747 global $wgRestrictionLevels;
2749 $restrictionTypes = $this->getRestrictionTypes();
2751 # Special pages have inherent protection
2752 if ( $this->isSpecialPage() ) {
2756 # Check regular protection levels
2757 foreach ( $restrictionTypes as $type ) {
2758 if ( $action == $type ||
$action == '' ) {
2759 $r = $this->getRestrictions( $type );
2760 foreach ( $wgRestrictionLevels as $level ) {
2761 if ( in_array( $level, $r ) && $level != '' ) {
2772 * Determines if $user is unable to edit this page because it has been protected
2773 * by $wgNamespaceProtection.
2775 * @param User $user User object to check permissions
2778 public function isNamespaceProtected( User
$user ) {
2779 global $wgNamespaceProtection;
2781 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2782 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2783 if ( $right != '' && !$user->isAllowed( $right ) ) {
2792 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2794 * @return bool If the page is subject to cascading restrictions.
2796 public function isCascadeProtected() {
2797 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2798 return ( $sources > 0 );
2802 * Determines whether cascading protection sources have already been loaded from
2805 * @param bool $getPages True to check if the pages are loaded, or false to check
2806 * if the status is loaded.
2807 * @return bool Whether or not the specified information has been loaded
2810 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2811 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2815 * Cascading protection: Get the source of any cascading restrictions on this page.
2817 * @param bool $getPages Whether or not to retrieve the actual pages
2818 * that the restrictions have come from and the actual restrictions
2820 * @return array Two elements: First is an array of Title objects of the
2821 * pages from which cascading restrictions have come, false for
2822 * none, or true if such restrictions exist but $getPages was not
2823 * set. Second is an array like that returned by
2824 * Title::getAllRestrictions(), or an empty array if $getPages is
2827 public function getCascadeProtectionSources( $getPages = true ) {
2828 $pagerestrictions = [];
2830 if ( $this->mCascadeSources
!== null && $getPages ) {
2831 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2832 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2833 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2836 $dbr = wfGetDB( DB_REPLICA
);
2838 if ( $this->getNamespace() == NS_FILE
) {
2839 $tables = [ 'imagelinks', 'page_restrictions' ];
2841 'il_to' => $this->getDBkey(),
2846 $tables = [ 'templatelinks', 'page_restrictions' ];
2848 'tl_namespace' => $this->getNamespace(),
2849 'tl_title' => $this->getDBkey(),
2856 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2857 'pr_expiry', 'pr_type', 'pr_level' ];
2858 $where_clauses[] = 'page_id=pr_page';
2861 $cols = [ 'pr_expiry' ];
2864 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2866 $sources = $getPages ?
[] : false;
2867 $now = wfTimestampNow();
2869 foreach ( $res as $row ) {
2870 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2871 if ( $expiry > $now ) {
2873 $page_id = $row->pr_page
;
2874 $page_ns = $row->page_namespace
;
2875 $page_title = $row->page_title
;
2876 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2877 # Add groups needed for each restriction type if its not already there
2878 # Make sure this restriction type still exists
2880 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2881 $pagerestrictions[$row->pr_type
] = [];
2885 isset( $pagerestrictions[$row->pr_type
] )
2886 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2888 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2897 $this->mCascadeSources
= $sources;
2898 $this->mCascadingRestrictions
= $pagerestrictions;
2900 $this->mHasCascadingRestrictions
= $sources;
2903 return [ $sources, $pagerestrictions ];
2907 * Accessor for mRestrictionsLoaded
2909 * @return bool Whether or not the page's restrictions have already been
2910 * loaded from the database
2913 public function areRestrictionsLoaded() {
2914 return $this->mRestrictionsLoaded
;
2918 * Accessor/initialisation for mRestrictions
2920 * @param string $action Action that permission needs to be checked for
2921 * @return array Restriction levels needed to take the action. All levels are
2922 * required. Note that restriction levels are normally user rights, but 'sysop'
2923 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2924 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2926 public function getRestrictions( $action ) {
2927 if ( !$this->mRestrictionsLoaded
) {
2928 $this->loadRestrictions();
2930 return isset( $this->mRestrictions
[$action] )
2931 ?
$this->mRestrictions
[$action]
2936 * Accessor/initialisation for mRestrictions
2938 * @return array Keys are actions, values are arrays as returned by
2939 * Title::getRestrictions()
2942 public function getAllRestrictions() {
2943 if ( !$this->mRestrictionsLoaded
) {
2944 $this->loadRestrictions();
2946 return $this->mRestrictions
;
2950 * Get the expiry time for the restriction against a given action
2952 * @param string $action
2953 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2954 * or not protected at all, or false if the action is not recognised.
2956 public function getRestrictionExpiry( $action ) {
2957 if ( !$this->mRestrictionsLoaded
) {
2958 $this->loadRestrictions();
2960 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2964 * Returns cascading restrictions for the current article
2968 function areRestrictionsCascading() {
2969 if ( !$this->mRestrictionsLoaded
) {
2970 $this->loadRestrictions();
2973 return $this->mCascadeRestriction
;
2977 * Compiles list of active page restrictions from both page table (pre 1.10)
2978 * and page_restrictions table for this existing page.
2979 * Public for usage by LiquidThreads.
2981 * @param array $rows Array of db result objects
2982 * @param string $oldFashionedRestrictions Comma-separated list of page
2983 * restrictions from page table (pre 1.10)
2985 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2986 $dbr = wfGetDB( DB_REPLICA
);
2988 $restrictionTypes = $this->getRestrictionTypes();
2990 foreach ( $restrictionTypes as $type ) {
2991 $this->mRestrictions
[$type] = [];
2992 $this->mRestrictionsExpiry
[$type] = 'infinity';
2995 $this->mCascadeRestriction
= false;
2997 # Backwards-compatibility: also load the restrictions from the page record (old format).
2998 if ( $oldFashionedRestrictions !== null ) {
2999 $this->mOldRestrictions
= $oldFashionedRestrictions;
3002 if ( $this->mOldRestrictions
=== false ) {
3003 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3004 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3007 if ( $this->mOldRestrictions
!= '' ) {
3008 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3009 $temp = explode( '=', trim( $restrict ) );
3010 if ( count( $temp ) == 1 ) {
3011 // old old format should be treated as edit/move restriction
3012 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3013 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3015 $restriction = trim( $temp[1] );
3016 if ( $restriction != '' ) { // some old entries are empty
3017 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3023 if ( count( $rows ) ) {
3024 # Current system - load second to make them override.
3025 $now = wfTimestampNow();
3027 # Cycle through all the restrictions.
3028 foreach ( $rows as $row ) {
3029 // Don't take care of restrictions types that aren't allowed
3030 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3034 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3036 // Only apply the restrictions if they haven't expired!
3037 if ( !$expiry ||
$expiry > $now ) {
3038 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3039 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3041 $this->mCascadeRestriction |
= $row->pr_cascade
;
3046 $this->mRestrictionsLoaded
= true;
3050 * Load restrictions from the page_restrictions table
3052 * @param string $oldFashionedRestrictions Comma-separated list of page
3053 * restrictions from page table (pre 1.10)
3055 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3056 if ( $this->mRestrictionsLoaded
) {
3060 $id = $this->getArticleID();
3062 $cache = ObjectCache
::getMainWANInstance();
3063 $rows = $cache->getWithSetCallback(
3064 // Page protections always leave a new null revision
3065 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3067 function ( $curValue, &$ttl, array &$setOpts ) {
3068 $dbr = wfGetDB( DB_REPLICA
);
3070 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3072 return iterator_to_array(
3074 'page_restrictions',
3075 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3076 [ 'pr_page' => $this->getArticleID() ],
3083 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3085 $title_protection = $this->getTitleProtectionInternal();
3087 if ( $title_protection ) {
3088 $now = wfTimestampNow();
3089 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3091 if ( !$expiry ||
$expiry > $now ) {
3092 // Apply the restrictions
3093 $this->mRestrictionsExpiry
['create'] = $expiry;
3094 $this->mRestrictions
['create'] =
3095 explode( ',', trim( $title_protection['permission'] ) );
3096 } else { // Get rid of the old restrictions
3097 $this->mTitleProtection
= false;
3100 $this->mRestrictionsExpiry
['create'] = 'infinity';
3102 $this->mRestrictionsLoaded
= true;
3107 * Flush the protection cache in this object and force reload from the database.
3108 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3110 public function flushRestrictions() {
3111 $this->mRestrictionsLoaded
= false;
3112 $this->mTitleProtection
= null;
3116 * Purge expired restrictions from the page_restrictions table
3118 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3120 static function purgeExpiredRestrictions() {
3121 if ( wfReadOnly() ) {
3125 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3126 wfGetDB( DB_MASTER
),
3128 function ( IDatabase
$dbw, $fname ) {
3129 $config = MediaWikiServices
::getInstance()->getMainConfig();
3130 $ids = $dbw->selectFieldValues(
3131 'page_restrictions',
3133 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3135 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3138 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3143 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3144 wfGetDB( DB_MASTER
),
3146 function ( IDatabase
$dbw, $fname ) {
3149 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3157 * Does this have subpages? (Warning, usually requires an extra DB query.)
3161 public function hasSubpages() {
3162 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3167 # We dynamically add a member variable for the purpose of this method
3168 # alone to cache the result. There's no point in having it hanging
3169 # around uninitialized in every Title object; therefore we only add it
3170 # if needed and don't declare it statically.
3171 if ( $this->mHasSubpages
=== null ) {
3172 $this->mHasSubpages
= false;
3173 $subpages = $this->getSubpages( 1 );
3174 if ( $subpages instanceof TitleArray
) {
3175 $this->mHasSubpages
= (bool)$subpages->count();
3179 return $this->mHasSubpages
;
3183 * Get all subpages of this page.
3185 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3186 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3187 * doesn't allow subpages
3189 public function getSubpages( $limit = -1 ) {
3190 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3194 $dbr = wfGetDB( DB_REPLICA
);
3195 $conds['page_namespace'] = $this->getNamespace();
3196 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3198 if ( $limit > -1 ) {
3199 $options['LIMIT'] = $limit;
3201 return TitleArray
::newFromResult(
3202 $dbr->select( 'page',
3203 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3212 * Is there a version of this page in the deletion archive?
3214 * @return int The number of archived revisions
3216 public function isDeleted() {
3217 if ( $this->getNamespace() < 0 ) {
3220 $dbr = wfGetDB( DB_REPLICA
);
3222 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3223 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3226 if ( $this->getNamespace() == NS_FILE
) {
3227 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3228 [ 'fa_name' => $this->getDBkey() ],
3237 * Is there a version of this page in the deletion archive?
3241 public function isDeletedQuick() {
3242 if ( $this->getNamespace() < 0 ) {
3245 $dbr = wfGetDB( DB_REPLICA
);
3246 $deleted = (bool)$dbr->selectField( 'archive', '1',
3247 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3250 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3251 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3252 [ 'fa_name' => $this->getDBkey() ],
3260 * Get the article ID for this Title from the link cache,
3261 * adding it if necessary
3263 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3265 * @return int The ID
3267 public function getArticleID( $flags = 0 ) {
3268 if ( $this->getNamespace() < 0 ) {
3269 $this->mArticleID
= 0;
3270 return $this->mArticleID
;
3272 $linkCache = LinkCache
::singleton();
3273 if ( $flags & self
::GAID_FOR_UPDATE
) {
3274 $oldUpdate = $linkCache->forUpdate( true );
3275 $linkCache->clearLink( $this );
3276 $this->mArticleID
= $linkCache->addLinkObj( $this );
3277 $linkCache->forUpdate( $oldUpdate );
3279 if ( -1 == $this->mArticleID
) {
3280 $this->mArticleID
= $linkCache->addLinkObj( $this );
3283 return $this->mArticleID
;
3287 * Is this an article that is a redirect page?
3288 * Uses link cache, adding it if necessary
3290 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3293 public function isRedirect( $flags = 0 ) {
3294 if ( !is_null( $this->mRedirect
) ) {
3295 return $this->mRedirect
;
3297 if ( !$this->getArticleID( $flags ) ) {
3298 $this->mRedirect
= false;
3299 return $this->mRedirect
;
3302 $linkCache = LinkCache
::singleton();
3303 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3304 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3305 if ( $cached === null ) {
3306 # Trust LinkCache's state over our own
3307 # LinkCache is telling us that the page doesn't exist, despite there being cached
3308 # data relating to an existing page in $this->mArticleID. Updaters should clear
3309 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3310 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3311 # LinkCache to refresh its data from the master.
3312 $this->mRedirect
= false;
3313 return $this->mRedirect
;
3316 $this->mRedirect
= (bool)$cached;
3318 return $this->mRedirect
;
3322 * What is the length of this page?
3323 * Uses link cache, adding it if necessary
3325 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3328 public function getLength( $flags = 0 ) {
3329 if ( $this->mLength
!= -1 ) {
3330 return $this->mLength
;
3332 if ( !$this->getArticleID( $flags ) ) {
3334 return $this->mLength
;
3336 $linkCache = LinkCache
::singleton();
3337 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3338 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3339 if ( $cached === null ) {
3340 # Trust LinkCache's state over our own, as for isRedirect()
3342 return $this->mLength
;
3345 $this->mLength
= intval( $cached );
3347 return $this->mLength
;
3351 * What is the page_latest field for this page?
3353 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3354 * @return int Int or 0 if the page doesn't exist
3356 public function getLatestRevID( $flags = 0 ) {
3357 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3358 return intval( $this->mLatestID
);
3360 if ( !$this->getArticleID( $flags ) ) {
3361 $this->mLatestID
= 0;
3362 return $this->mLatestID
;
3364 $linkCache = LinkCache
::singleton();
3365 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3366 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3367 if ( $cached === null ) {
3368 # Trust LinkCache's state over our own, as for isRedirect()
3369 $this->mLatestID
= 0;
3370 return $this->mLatestID
;
3373 $this->mLatestID
= intval( $cached );
3375 return $this->mLatestID
;
3379 * This clears some fields in this object, and clears any associated
3380 * keys in the "bad links" section of the link cache.
3382 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3383 * loading of the new page_id. It's also called from
3384 * WikiPage::doDeleteArticleReal()
3386 * @param int $newid The new Article ID
3388 public function resetArticleID( $newid ) {
3389 $linkCache = LinkCache
::singleton();
3390 $linkCache->clearLink( $this );
3392 if ( $newid === false ) {
3393 $this->mArticleID
= -1;
3395 $this->mArticleID
= intval( $newid );
3397 $this->mRestrictionsLoaded
= false;
3398 $this->mRestrictions
= [];
3399 $this->mOldRestrictions
= false;
3400 $this->mRedirect
= null;
3401 $this->mLength
= -1;
3402 $this->mLatestID
= false;
3403 $this->mContentModel
= false;
3404 $this->mEstimateRevisions
= null;
3405 $this->mPageLanguage
= false;
3406 $this->mDbPageLanguage
= false;
3407 $this->mIsBigDeletion
= null;
3410 public static function clearCaches() {
3411 $linkCache = LinkCache
::singleton();
3412 $linkCache->clear();
3414 $titleCache = self
::getTitleCache();
3415 $titleCache->clear();
3419 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3421 * @param string $text Containing title to capitalize
3422 * @param int $ns Namespace index, defaults to NS_MAIN
3423 * @return string Containing capitalized title
3425 public static function capitalize( $text, $ns = NS_MAIN
) {
3428 if ( MWNamespace
::isCapitalized( $ns ) ) {
3429 return $wgContLang->ucfirst( $text );
3436 * Secure and split - main initialisation function for this object
3438 * Assumes that mDbkeyform has been set, and is urldecoded
3439 * and uses underscores, but not otherwise munged. This function
3440 * removes illegal characters, splits off the interwiki and
3441 * namespace prefixes, sets the other forms, and canonicalizes
3444 * @throws MalformedTitleException On invalid titles
3445 * @return bool True on success
3447 private function secureAndSplit() {
3449 $this->mInterwiki
= '';
3450 $this->mFragment
= '';
3451 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3453 $dbkey = $this->mDbkeyform
;
3455 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3456 // the parsing code with Title, while avoiding massive refactoring.
3457 // @todo: get rid of secureAndSplit, refactor parsing code.
3458 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3459 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3460 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3461 // MalformedTitleException can be thrown here
3462 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3465 $this->setFragment( '#' . $parts['fragment'] );
3466 $this->mInterwiki
= $parts['interwiki'];
3467 $this->mLocalInterwiki
= $parts['local_interwiki'];
3468 $this->mNamespace
= $parts['namespace'];
3469 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3471 $this->mDbkeyform
= $parts['dbkey'];
3472 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3473 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3475 # We already know that some pages won't be in the database!
3476 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3477 $this->mArticleID
= 0;
3484 * Get an array of Title objects linking to this Title
3485 * Also stores the IDs in the link cache.
3487 * WARNING: do not use this function on arbitrary user-supplied titles!
3488 * On heavily-used templates it will max out the memory.
3490 * @param array $options May be FOR UPDATE
3491 * @param string $table Table name
3492 * @param string $prefix Fields prefix
3493 * @return Title[] Array of Title objects linking here
3495 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3496 if ( count( $options ) > 0 ) {
3497 $db = wfGetDB( DB_MASTER
);
3499 $db = wfGetDB( DB_REPLICA
);
3504 self
::getSelectFields(),
3506 "{$prefix}_from=page_id",
3507 "{$prefix}_namespace" => $this->getNamespace(),
3508 "{$prefix}_title" => $this->getDBkey() ],
3514 if ( $res->numRows() ) {
3515 $linkCache = LinkCache
::singleton();
3516 foreach ( $res as $row ) {
3517 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3519 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3520 $retVal[] = $titleObj;
3528 * Get an array of Title objects using this Title as a template
3529 * Also stores the IDs in the link cache.
3531 * WARNING: do not use this function on arbitrary user-supplied titles!
3532 * On heavily-used templates it will max out the memory.
3534 * @param array $options Query option to Database::select()
3535 * @return Title[] Array of Title the Title objects linking here
3537 public function getTemplateLinksTo( $options = [] ) {
3538 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3542 * Get an array of Title objects linked from this Title
3543 * Also stores the IDs in the link cache.
3545 * WARNING: do not use this function on arbitrary user-supplied titles!
3546 * On heavily-used templates it will max out the memory.
3548 * @param array $options Query option to Database::select()
3549 * @param string $table Table name
3550 * @param string $prefix Fields prefix
3551 * @return array Array of Title objects linking here
3553 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3554 $id = $this->getArticleID();
3556 # If the page doesn't exist; there can't be any link from this page
3561 $db = wfGetDB( DB_REPLICA
);
3563 $blNamespace = "{$prefix}_namespace";
3564 $blTitle = "{$prefix}_title";
3569 [ $blNamespace, $blTitle ],
3570 WikiPage
::selectFields()
3572 [ "{$prefix}_from" => $id ],
3577 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3582 $linkCache = LinkCache
::singleton();
3583 foreach ( $res as $row ) {
3584 if ( $row->page_id
) {
3585 $titleObj = self
::newFromRow( $row );
3587 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3588 $linkCache->addBadLinkObj( $titleObj );
3590 $retVal[] = $titleObj;
3597 * Get an array of Title objects used on this Title as a template
3598 * Also stores the IDs in the link cache.
3600 * WARNING: do not use this function on arbitrary user-supplied titles!
3601 * On heavily-used templates it will max out the memory.
3603 * @param array $options May be FOR UPDATE
3604 * @return Title[] Array of Title the Title objects used here
3606 public function getTemplateLinksFrom( $options = [] ) {
3607 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3611 * Get an array of Title objects referring to non-existent articles linked
3614 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3615 * should use redirect table in this case).
3616 * @return Title[] Array of Title the Title objects
3618 public function getBrokenLinksFrom() {
3619 if ( $this->getArticleID() == 0 ) {
3620 # All links from article ID 0 are false positives
3624 $dbr = wfGetDB( DB_REPLICA
);
3625 $res = $dbr->select(
3626 [ 'page', 'pagelinks' ],
3627 [ 'pl_namespace', 'pl_title' ],
3629 'pl_from' => $this->getArticleID(),
3630 'page_namespace IS NULL'
3636 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3642 foreach ( $res as $row ) {
3643 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3649 * Get a list of URLs to purge from the CDN cache when this
3652 * @return string[] Array of String the URLs
3654 public function getCdnUrls() {
3656 $this->getInternalURL(),
3657 $this->getInternalURL( 'action=history' )
3660 $pageLang = $this->getPageLanguage();
3661 if ( $pageLang->hasVariants() ) {
3662 $variants = $pageLang->getVariants();
3663 foreach ( $variants as $vCode ) {
3664 $urls[] = $this->getInternalURL( $vCode );
3668 // If we are looking at a css/js user subpage, purge the action=raw.
3669 if ( $this->isJsSubpage() ) {
3670 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3671 } elseif ( $this->isCssSubpage() ) {
3672 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3675 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3680 * @deprecated since 1.27 use getCdnUrls()
3682 public function getSquidURLs() {
3683 return $this->getCdnUrls();
3687 * Purge all applicable CDN URLs
3689 public function purgeSquid() {
3690 DeferredUpdates
::addUpdate(
3691 new CdnCacheUpdate( $this->getCdnUrls() ),
3692 DeferredUpdates
::PRESEND
3697 * Check whether a given move operation would be valid.
3698 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3700 * @deprecated since 1.25, use MovePage's methods instead
3701 * @param Title &$nt The new title
3702 * @param bool $auth Whether to check user permissions (uses $wgUser)
3703 * @param string $reason Is the log summary of the move, used for spam checking
3704 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3706 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3709 if ( !( $nt instanceof Title
) ) {
3710 // Normally we'd add this to $errors, but we'll get
3711 // lots of syntax errors if $nt is not an object
3712 return [ [ 'badtitletext' ] ];
3715 $mp = new MovePage( $this, $nt );
3716 $errors = $mp->isValidMove()->getErrorsArray();
3718 $errors = wfMergeErrorArrays(
3720 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3724 return $errors ?
: true;
3728 * Check if the requested move target is a valid file move target
3729 * @todo move this to MovePage
3730 * @param Title $nt Target title
3731 * @return array List of errors
3733 protected function validateFileMoveOperation( $nt ) {
3738 $destFile = wfLocalFile( $nt );
3739 $destFile->load( File
::READ_LATEST
);
3740 if ( !$wgUser->isAllowed( 'reupload-shared' )
3741 && !$destFile->exists() && wfFindFile( $nt )
3743 $errors[] = [ 'file-exists-sharedrepo' ];
3750 * Move a title to a new location
3752 * @deprecated since 1.25, use the MovePage class instead
3753 * @param Title &$nt The new title
3754 * @param bool $auth Indicates whether $wgUser's permissions
3756 * @param string $reason The reason for the move
3757 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3758 * Ignored if the user doesn't have the suppressredirect right.
3759 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3760 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3762 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3763 array $changeTags = []
3766 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3767 if ( is_array( $err ) ) {
3768 // Auto-block user's IP if the account was "hard" blocked
3769 $wgUser->spreadAnyEditBlock();
3772 // Check suppressredirect permission
3773 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3774 $createRedirect = true;
3777 $mp = new MovePage( $this, $nt );
3778 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3779 if ( $status->isOK() ) {
3782 return $status->getErrorsArray();
3787 * Move this page's subpages to be subpages of $nt
3789 * @param Title $nt Move target
3790 * @param bool $auth Whether $wgUser's permissions should be checked
3791 * @param string $reason The reason for the move
3792 * @param bool $createRedirect Whether to create redirects from the old subpages to
3793 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3794 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3795 * @return array Array with old page titles as keys, and strings (new page titles) or
3796 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3797 * getUserPermissionsErrors()-like error array with numeric indices if
3798 * no pages were moved
3800 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3801 array $changeTags = []
3803 global $wgMaximumMovedPages;
3804 // Check permissions
3805 if ( !$this->userCan( 'move-subpages' ) ) {
3807 [ 'cant-move-subpages' ],
3810 // Do the source and target namespaces support subpages?
3811 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3813 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3816 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3818 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3822 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3825 foreach ( $subpages as $oldSubpage ) {
3827 if ( $count > $wgMaximumMovedPages ) {
3828 $retval[$oldSubpage->getPrefixedText()] = [
3829 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3834 // We don't know whether this function was called before
3835 // or after moving the root page, so check both
3837 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3838 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3840 // When moving a page to a subpage of itself,
3841 // don't move it twice
3844 $newPageName = preg_replace(
3845 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3846 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3847 $oldSubpage->getDBkey() );
3848 if ( $oldSubpage->isTalkPage() ) {
3849 $newNs = $nt->getTalkPage()->getNamespace();
3851 $newNs = $nt->getSubjectPage()->getNamespace();
3853 # T16385: we need makeTitleSafe because the new page names may
3854 # be longer than 255 characters.
3855 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3857 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3858 if ( $success === true ) {
3859 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3861 $retval[$oldSubpage->getPrefixedText()] = $success;
3868 * Checks if this page is just a one-rev redirect.
3869 * Adds lock, so don't use just for light purposes.
3873 public function isSingleRevRedirect() {
3874 global $wgContentHandlerUseDB;
3876 $dbw = wfGetDB( DB_MASTER
);
3879 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3880 if ( $wgContentHandlerUseDB ) {
3881 $fields[] = 'page_content_model';
3884 $row = $dbw->selectRow( 'page',
3890 # Cache some fields we may want
3891 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3892 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3893 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3894 $this->mContentModel
= $row && isset( $row->page_content_model
)
3895 ?
strval( $row->page_content_model
)
3898 if ( !$this->mRedirect
) {
3901 # Does the article have a history?
3902 $row = $dbw->selectField( [ 'page', 'revision' ],
3904 [ 'page_namespace' => $this->getNamespace(),
3905 'page_title' => $this->getDBkey(),
3907 'page_latest != rev_id'
3912 # Return true if there was no history
3913 return ( $row === false );
3917 * Checks if $this can be moved to a given Title
3918 * - Selects for update, so don't call it unless you mean business
3920 * @deprecated since 1.25, use MovePage's methods instead
3921 * @param Title $nt The new title to check
3924 public function isValidMoveTarget( $nt ) {
3925 # Is it an existing file?
3926 if ( $nt->getNamespace() == NS_FILE
) {
3927 $file = wfLocalFile( $nt );
3928 $file->load( File
::READ_LATEST
);
3929 if ( $file->exists() ) {
3930 wfDebug( __METHOD__
. ": file exists\n" );
3934 # Is it a redirect with no history?
3935 if ( !$nt->isSingleRevRedirect() ) {
3936 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3939 # Get the article text
3940 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3941 if ( !is_object( $rev ) ) {
3944 $content = $rev->getContent();
3945 # Does the redirect point to the source?
3946 # Or is it a broken self-redirect, usually caused by namespace collisions?
3947 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3949 if ( $redirTitle ) {
3950 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3951 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3952 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3958 # Fail safe (not a redirect after all. strange.)
3959 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3960 " is a redirect, but it doesn't contain a valid redirect.\n" );
3966 * Get categories to which this Title belongs and return an array of
3967 * categories' names.
3969 * @return array Array of parents in the form:
3970 * $parent => $currentarticle
3972 public function getParentCategories() {
3977 $titleKey = $this->getArticleID();
3979 if ( $titleKey === 0 ) {
3983 $dbr = wfGetDB( DB_REPLICA
);
3985 $res = $dbr->select(
3988 [ 'cl_from' => $titleKey ],
3992 if ( $res->numRows() > 0 ) {
3993 foreach ( $res as $row ) {
3994 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3995 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4002 * Get a tree of parent categories
4004 * @param array $children Array with the children in the keys, to check for circular refs
4005 * @return array Tree of parent categories
4007 public function getParentCategoryTree( $children = [] ) {
4009 $parents = $this->getParentCategories();
4012 foreach ( $parents as $parent => $current ) {
4013 if ( array_key_exists( $parent, $children ) ) {
4014 # Circular reference
4015 $stack[$parent] = [];
4017 $nt = self
::newFromText( $parent );
4019 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4029 * Get an associative array for selecting this title from
4032 * @return array Array suitable for the $where parameter of DB::select()
4034 public function pageCond() {
4035 if ( $this->mArticleID
> 0 ) {
4036 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4037 return [ 'page_id' => $this->mArticleID
];
4039 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4044 * Get next/previous revision ID relative to another revision ID
4045 * @param int $revId Revision ID. Get the revision that was before this one.
4046 * @param int $flags Title::GAID_FOR_UPDATE
4047 * @param string $dir 'next' or 'prev'
4048 * @return int|bool New revision ID, or false if none exists
4050 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4051 $revId = (int)$revId;
4052 if ( $dir === 'next' ) {
4055 } elseif ( $dir === 'prev' ) {
4059 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4062 if ( $flags & self
::GAID_FOR_UPDATE
) {
4063 $db = wfGetDB( DB_MASTER
);
4065 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4068 // Intentionally not caring if the specified revision belongs to this
4069 // page. We only care about the timestamp.
4070 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4071 if ( $ts === false ) {
4072 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4073 if ( $ts === false ) {
4074 // Or should this throw an InvalidArgumentException or something?
4078 $ts = $db->addQuotes( $ts );
4080 $revId = $db->selectField( 'revision', 'rev_id',
4082 'rev_page' => $this->getArticleID( $flags ),
4083 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4087 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4088 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4092 if ( $revId === false ) {
4095 return intval( $revId );
4100 * Get the revision ID of the previous revision
4102 * @param int $revId Revision ID. Get the revision that was before this one.
4103 * @param int $flags Title::GAID_FOR_UPDATE
4104 * @return int|bool Old revision ID, or false if none exists
4106 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4107 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4111 * Get the revision ID of the next revision
4113 * @param int $revId Revision ID. Get the revision that was after this one.
4114 * @param int $flags Title::GAID_FOR_UPDATE
4115 * @return int|bool Next revision ID, or false if none exists
4117 public function getNextRevisionID( $revId, $flags = 0 ) {
4118 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4122 * Get the first revision of the page
4124 * @param int $flags Title::GAID_FOR_UPDATE
4125 * @return Revision|null If page doesn't exist
4127 public function getFirstRevision( $flags = 0 ) {
4128 $pageId = $this->getArticleID( $flags );
4130 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4131 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4132 [ 'rev_page' => $pageId ],
4135 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4136 'IGNORE INDEX' => 'rev_timestamp', // See T159319
4140 return new Revision( $row );
4147 * Get the oldest revision timestamp of this page
4149 * @param int $flags Title::GAID_FOR_UPDATE
4150 * @return string MW timestamp
4152 public function getEarliestRevTime( $flags = 0 ) {
4153 $rev = $this->getFirstRevision( $flags );
4154 return $rev ?
$rev->getTimestamp() : null;
4158 * Check if this is a new page
4162 public function isNewPage() {
4163 $dbr = wfGetDB( DB_REPLICA
);
4164 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4168 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4172 public function isBigDeletion() {
4173 global $wgDeleteRevisionsLimit;
4175 if ( !$wgDeleteRevisionsLimit ) {
4179 if ( $this->mIsBigDeletion
=== null ) {
4180 $dbr = wfGetDB( DB_REPLICA
);
4182 $revCount = $dbr->selectRowCount(
4185 [ 'rev_page' => $this->getArticleID() ],
4187 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4190 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4193 return $this->mIsBigDeletion
;
4197 * Get the approximate revision count of this page.
4201 public function estimateRevisionCount() {
4202 if ( !$this->exists() ) {
4206 if ( $this->mEstimateRevisions
=== null ) {
4207 $dbr = wfGetDB( DB_REPLICA
);
4208 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4209 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4212 return $this->mEstimateRevisions
;
4216 * Get the number of revisions between the given revision.
4217 * Used for diffs and other things that really need it.
4219 * @param int|Revision $old Old revision or rev ID (first before range)
4220 * @param int|Revision $new New revision or rev ID (first after range)
4221 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4222 * @return int Number of revisions between these revisions.
4224 public function countRevisionsBetween( $old, $new, $max = null ) {
4225 if ( !( $old instanceof Revision
) ) {
4226 $old = Revision
::newFromTitle( $this, (int)$old );
4228 if ( !( $new instanceof Revision
) ) {
4229 $new = Revision
::newFromTitle( $this, (int)$new );
4231 if ( !$old ||
!$new ) {
4232 return 0; // nothing to compare
4234 $dbr = wfGetDB( DB_REPLICA
);
4236 'rev_page' => $this->getArticleID(),
4237 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4238 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4240 if ( $max !== null ) {
4241 return $dbr->selectRowCount( 'revision', '1',
4244 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4247 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4252 * Get the authors between the given revisions or revision IDs.
4253 * Used for diffs and other things that really need it.
4257 * @param int|Revision $old Old revision or rev ID (first before range by default)
4258 * @param int|Revision $new New revision or rev ID (first after range by default)
4259 * @param int $limit Maximum number of authors
4260 * @param string|array $options (Optional): Single option, or an array of options:
4261 * 'include_old' Include $old in the range; $new is excluded.
4262 * 'include_new' Include $new in the range; $old is excluded.
4263 * 'include_both' Include both $old and $new in the range.
4264 * Unknown option values are ignored.
4265 * @return array|null Names of revision authors in the range; null if not both revisions exist
4267 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4268 if ( !( $old instanceof Revision
) ) {
4269 $old = Revision
::newFromTitle( $this, (int)$old );
4271 if ( !( $new instanceof Revision
) ) {
4272 $new = Revision
::newFromTitle( $this, (int)$new );
4274 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4275 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4276 // in the sanity check below?
4277 if ( !$old ||
!$new ) {
4278 return null; // nothing to compare
4283 $options = (array)$options;
4284 if ( in_array( 'include_old', $options ) ) {
4287 if ( in_array( 'include_new', $options ) ) {
4290 if ( in_array( 'include_both', $options ) ) {
4294 // No DB query needed if $old and $new are the same or successive revisions:
4295 if ( $old->getId() === $new->getId() ) {
4296 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4298 [ $old->getUserText( Revision
::RAW
) ];
4299 } elseif ( $old->getId() === $new->getParentId() ) {
4300 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4301 $authors[] = $old->getUserText( Revision
::RAW
);
4302 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4303 $authors[] = $new->getUserText( Revision
::RAW
);
4305 } elseif ( $old_cmp === '>=' ) {
4306 $authors[] = $old->getUserText( Revision
::RAW
);
4307 } elseif ( $new_cmp === '<=' ) {
4308 $authors[] = $new->getUserText( Revision
::RAW
);
4312 $dbr = wfGetDB( DB_REPLICA
);
4313 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4315 'rev_page' => $this->getArticleID(),
4316 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4317 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4319 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4321 foreach ( $res as $row ) {
4322 $authors[] = $row->rev_user_text
;
4328 * Get the number of authors between the given revisions or revision IDs.
4329 * Used for diffs and other things that really need it.
4331 * @param int|Revision $old Old revision or rev ID (first before range by default)
4332 * @param int|Revision $new New revision or rev ID (first after range by default)
4333 * @param int $limit Maximum number of authors
4334 * @param string|array $options (Optional): Single option, or an array of options:
4335 * 'include_old' Include $old in the range; $new is excluded.
4336 * 'include_new' Include $new in the range; $old is excluded.
4337 * 'include_both' Include both $old and $new in the range.
4338 * Unknown option values are ignored.
4339 * @return int Number of revision authors in the range; zero if not both revisions exist
4341 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4342 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4343 return $authors ?
count( $authors ) : 0;
4347 * Compare with another title.
4349 * @param Title $title
4352 public function equals( Title
$title ) {
4353 // Note: === is necessary for proper matching of number-like titles.
4354 return $this->getInterwiki() === $title->getInterwiki()
4355 && $this->getNamespace() == $title->getNamespace()
4356 && $this->getDBkey() === $title->getDBkey();
4360 * Check if this title is a subpage of another title
4362 * @param Title $title
4365 public function isSubpageOf( Title
$title ) {
4366 return $this->getInterwiki() === $title->getInterwiki()
4367 && $this->getNamespace() == $title->getNamespace()
4368 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4372 * Check if page exists. For historical reasons, this function simply
4373 * checks for the existence of the title in the page table, and will
4374 * thus return false for interwiki links, special pages and the like.
4375 * If you want to know if a title can be meaningfully viewed, you should
4376 * probably call the isKnown() method instead.
4378 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4379 * from master/for update
4382 public function exists( $flags = 0 ) {
4383 $exists = $this->getArticleID( $flags ) != 0;
4384 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4389 * Should links to this title be shown as potentially viewable (i.e. as
4390 * "bluelinks"), even if there's no record by this title in the page
4393 * This function is semi-deprecated for public use, as well as somewhat
4394 * misleadingly named. You probably just want to call isKnown(), which
4395 * calls this function internally.
4397 * (ISSUE: Most of these checks are cheap, but the file existence check
4398 * can potentially be quite expensive. Including it here fixes a lot of
4399 * existing code, but we might want to add an optional parameter to skip
4400 * it and any other expensive checks.)
4404 public function isAlwaysKnown() {
4408 * Allows overriding default behavior for determining if a page exists.
4409 * If $isKnown is kept as null, regular checks happen. If it's
4410 * a boolean, this value is returned by the isKnown method.
4414 * @param Title $title
4415 * @param bool|null $isKnown
4417 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4419 if ( !is_null( $isKnown ) ) {
4423 if ( $this->isExternal() ) {
4424 return true; // any interwiki link might be viewable, for all we know
4427 switch ( $this->mNamespace
) {
4430 // file exists, possibly in a foreign repo
4431 return (bool)wfFindFile( $this );
4433 // valid special page
4434 return SpecialPageFactory
::exists( $this->getDBkey() );
4436 // selflink, possibly with fragment
4437 return $this->mDbkeyform
== '';
4439 // known system message
4440 return $this->hasSourceText() !== false;
4447 * Does this title refer to a page that can (or might) be meaningfully
4448 * viewed? In particular, this function may be used to determine if
4449 * links to the title should be rendered as "bluelinks" (as opposed to
4450 * "redlinks" to non-existent pages).
4451 * Adding something else to this function will cause inconsistency
4452 * since LinkHolderArray calls isAlwaysKnown() and does its own
4453 * page existence check.
4457 public function isKnown() {
4458 return $this->isAlwaysKnown() ||
$this->exists();
4462 * Does this page have source text?
4466 public function hasSourceText() {
4467 if ( $this->exists() ) {
4471 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4472 // If the page doesn't exist but is a known system message, default
4473 // message content will be displayed, same for language subpages-
4474 // Use always content language to avoid loading hundreds of languages
4475 // to get the link color.
4477 list( $name, ) = MessageCache
::singleton()->figureMessage(
4478 $wgContLang->lcfirst( $this->getText() )
4480 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4481 return $message->exists();
4488 * Get the default message text or false if the message doesn't exist
4490 * @return string|bool
4492 public function getDefaultMessageText() {
4495 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4499 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4500 $wgContLang->lcfirst( $this->getText() )
4502 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4504 if ( $message->exists() ) {
4505 return $message->plain();
4512 * Updates page_touched for this page; called from LinksUpdate.php
4514 * @param string $purgeTime [optional] TS_MW timestamp
4515 * @return bool True if the update succeeded
4517 public function invalidateCache( $purgeTime = null ) {
4518 if ( wfReadOnly() ) {
4520 } elseif ( $this->mArticleID
=== 0 ) {
4521 return true; // avoid gap locking if we know it's not there
4524 $dbw = wfGetDB( DB_MASTER
);
4525 $dbw->onTransactionPreCommitOrIdle( function () {
4526 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4529 $conds = $this->pageCond();
4530 DeferredUpdates
::addUpdate(
4531 new AutoCommitUpdate(
4534 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4535 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4538 [ 'page_touched' => $dbTimestamp ],
4539 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4542 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4545 DeferredUpdates
::PRESEND
4552 * Update page_touched timestamps and send CDN purge messages for
4553 * pages linking to this title. May be sent to the job queue depending
4554 * on the number of links. Typically called on create and delete.
4556 public function touchLinks() {
4557 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4558 if ( $this->getNamespace() == NS_CATEGORY
) {
4559 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4564 * Get the last touched timestamp
4566 * @param IDatabase $db Optional db
4567 * @return string|false Last-touched timestamp
4569 public function getTouched( $db = null ) {
4570 if ( $db === null ) {
4571 $db = wfGetDB( DB_REPLICA
);
4573 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4578 * Get the timestamp when this page was updated since the user last saw it.
4581 * @return string|null
4583 public function getNotificationTimestamp( $user = null ) {
4586 // Assume current user if none given
4590 // Check cache first
4591 $uid = $user->getId();
4595 // avoid isset here, as it'll return false for null entries
4596 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4597 return $this->mNotificationTimestamp
[$uid];
4599 // Don't cache too much!
4600 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4601 $this->mNotificationTimestamp
= [];
4604 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4605 $watchedItem = $store->getWatchedItem( $user, $this );
4606 if ( $watchedItem ) {
4607 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4609 $this->mNotificationTimestamp
[$uid] = false;
4612 return $this->mNotificationTimestamp
[$uid];
4616 * Generate strings used for xml 'id' names in monobook tabs
4618 * @param string $prepend Defaults to 'nstab-'
4619 * @return string XML 'id' name
4621 public function getNamespaceKey( $prepend = 'nstab-' ) {
4623 // Gets the subject namespace if this title
4624 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4625 // Checks if canonical namespace name exists for namespace
4626 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4627 // Uses canonical namespace name
4628 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4630 // Uses text of namespace
4631 $namespaceKey = $this->getSubjectNsText();
4633 // Makes namespace key lowercase
4634 $namespaceKey = $wgContLang->lc( $namespaceKey );
4636 if ( $namespaceKey == '' ) {
4637 $namespaceKey = 'main';
4639 // Changes file to image for backwards compatibility
4640 if ( $namespaceKey == 'file' ) {
4641 $namespaceKey = 'image';
4643 return $prepend . $namespaceKey;
4647 * Get all extant redirects to this Title
4649 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4650 * @return Title[] Array of Title redirects to this title
4652 public function getRedirectsHere( $ns = null ) {
4655 $dbr = wfGetDB( DB_REPLICA
);
4657 'rd_namespace' => $this->getNamespace(),
4658 'rd_title' => $this->getDBkey(),
4661 if ( $this->isExternal() ) {
4662 $where['rd_interwiki'] = $this->getInterwiki();
4664 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4666 if ( !is_null( $ns ) ) {
4667 $where['page_namespace'] = $ns;
4670 $res = $dbr->select(
4671 [ 'redirect', 'page' ],
4672 [ 'page_namespace', 'page_title' ],
4677 foreach ( $res as $row ) {
4678 $redirs[] = self
::newFromRow( $row );
4684 * Check if this Title is a valid redirect target
4688 public function isValidRedirectTarget() {
4689 global $wgInvalidRedirectTargets;
4691 if ( $this->isSpecialPage() ) {
4692 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4693 if ( $this->isSpecial( 'Userlogout' ) ) {
4697 foreach ( $wgInvalidRedirectTargets as $target ) {
4698 if ( $this->isSpecial( $target ) ) {
4708 * Get a backlink cache object
4710 * @return BacklinkCache
4712 public function getBacklinkCache() {
4713 return BacklinkCache
::get( $this );
4717 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4721 public function canUseNoindex() {
4722 global $wgExemptFromUserRobotsControl;
4724 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4725 ? MWNamespace
::getContentNamespaces()
4726 : $wgExemptFromUserRobotsControl;
4728 return !in_array( $this->mNamespace
, $bannedNamespaces );
4732 * Returns the raw sort key to be used for categories, with the specified
4733 * prefix. This will be fed to Collation::getSortKey() to get a
4734 * binary sortkey that can be used for actual sorting.
4736 * @param string $prefix The prefix to be used, specified using
4737 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4741 public function getCategorySortkey( $prefix = '' ) {
4742 $unprefixed = $this->getText();
4744 // Anything that uses this hook should only depend
4745 // on the Title object passed in, and should probably
4746 // tell the users to run updateCollations.php --force
4747 // in order to re-sort existing category relations.
4748 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4749 if ( $prefix !== '' ) {
4750 # Separate with a line feed, so the unprefixed part is only used as
4751 # a tiebreaker when two pages have the exact same prefix.
4752 # In UCA, tab is the only character that can sort above LF
4753 # so we strip both of them from the original prefix.
4754 $prefix = strtr( $prefix, "\n\t", ' ' );
4755 return "$prefix\n$unprefixed";
4761 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4762 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4763 * the db, it will return NULL.
4765 * @return string|null|bool
4767 private function getDbPageLanguageCode() {
4768 global $wgPageLanguageUseDB;
4770 // check, if the page language could be saved in the database, and if so and
4771 // the value is not requested already, lookup the page language using LinkCache
4772 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4773 $linkCache = LinkCache
::singleton();
4774 $linkCache->addLinkObj( $this );
4775 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4778 return $this->mDbPageLanguage
;
4782 * Get the language in which the content of this page is written in
4783 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4784 * e.g. $wgLang (such as special pages, which are in the user language).
4789 public function getPageLanguage() {
4790 global $wgLang, $wgLanguageCode;
4791 if ( $this->isSpecialPage() ) {
4792 // special pages are in the user language
4796 // Checking if DB language is set
4797 $dbPageLanguage = $this->getDbPageLanguageCode();
4798 if ( $dbPageLanguage ) {
4799 return wfGetLangObj( $dbPageLanguage );
4802 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4803 // Note that this may depend on user settings, so the cache should
4804 // be only per-request.
4805 // NOTE: ContentHandler::getPageLanguage() may need to load the
4806 // content to determine the page language!
4807 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4809 $contentHandler = ContentHandler
::getForTitle( $this );
4810 $langObj = $contentHandler->getPageLanguage( $this );
4811 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4813 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4820 * Get the language in which the content of this page is written when
4821 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4822 * e.g. $wgLang (such as special pages, which are in the user language).
4827 public function getPageViewLanguage() {
4830 if ( $this->isSpecialPage() ) {
4831 // If the user chooses a variant, the content is actually
4832 // in a language whose code is the variant code.
4833 $variant = $wgLang->getPreferredVariant();
4834 if ( $wgLang->getCode() !== $variant ) {
4835 return Language
::factory( $variant );
4841 // Checking if DB language is set
4842 $dbPageLanguage = $this->getDbPageLanguageCode();
4843 if ( $dbPageLanguage ) {
4844 $pageLang = wfGetLangObj( $dbPageLanguage );
4845 $variant = $pageLang->getPreferredVariant();
4846 if ( $pageLang->getCode() !== $variant ) {
4847 $pageLang = Language
::factory( $variant );
4853 // @note Can't be cached persistently, depends on user settings.
4854 // @note ContentHandler::getPageViewLanguage() may need to load the
4855 // content to determine the page language!
4856 $contentHandler = ContentHandler
::getForTitle( $this );
4857 $pageLang = $contentHandler->getPageViewLanguage( $this );
4862 * Get a list of rendered edit notices for this page.
4864 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4865 * they will already be wrapped in paragraphs.
4868 * @param int $oldid Revision ID that's being edited
4871 public function getEditNotices( $oldid = 0 ) {
4874 // Optional notice for the entire namespace
4875 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4876 $msg = wfMessage( $editnotice_ns );
4877 if ( $msg->exists() ) {
4878 $html = $msg->parseAsBlock();
4879 // Edit notices may have complex logic, but output nothing (T91715)
4880 if ( trim( $html ) !== '' ) {
4881 $notices[$editnotice_ns] = Html
::rawElement(
4885 'mw-editnotice-namespace',
4886 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4893 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4894 // Optional notice for page itself and any parent page
4895 $parts = explode( '/', $this->getDBkey() );
4896 $editnotice_base = $editnotice_ns;
4897 while ( count( $parts ) > 0 ) {
4898 $editnotice_base .= '-' . array_shift( $parts );
4899 $msg = wfMessage( $editnotice_base );
4900 if ( $msg->exists() ) {
4901 $html = $msg->parseAsBlock();
4902 if ( trim( $html ) !== '' ) {
4903 $notices[$editnotice_base] = Html
::rawElement(
4907 'mw-editnotice-base',
4908 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4916 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4917 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4918 $msg = wfMessage( $editnoticeText );
4919 if ( $msg->exists() ) {
4920 $html = $msg->parseAsBlock();
4921 if ( trim( $html ) !== '' ) {
4922 $notices[$editnoticeText] = Html
::rawElement(
4926 'mw-editnotice-page',
4927 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4935 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4942 public function __sleep() {
4950 'mDefaultNamespace',
4954 public function __wakeup() {
4955 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4956 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4957 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );