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 MapCacheLRU */
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 = [];
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
117 protected $mOldRestrictions = false;
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
137 /** @var string Text form including namespace/interwiki, initialised on demand */
138 protected $mPrefixedText = null;
140 /** @var mixed Cached value for getTitleProtection (create protection) */
141 public $mTitleProtection;
144 * @var int Namespace index when there is no namespace. Don't change the
145 * following default, NS_MAIN is hardcoded in several places. See T2696.
146 * Zero except in {{transclusion}} tags.
148 public $mDefaultNamespace = NS_MAIN
;
150 /** @var int The page length, 0 for special pages */
151 protected $mLength = -1;
153 /** @var null Is the article at this title a redirect? */
154 public $mRedirect = null;
156 /** @var array Associative array of user ID -> timestamp/false */
157 private $mNotificationTimestamp = [];
159 /** @var bool Whether a page has any subpages */
160 private $mHasSubpages;
162 /** @var bool The (string) language code of the page's language and content code. */
163 private $mPageLanguage = false;
165 /** @var string|bool|null The page language code from the database, null if not saved in
166 * the database or false if not loaded, yet. */
167 private $mDbPageLanguage = false;
169 /** @var TitleValue A corresponding TitleValue object */
170 private $mTitleValue = null;
172 /** @var bool Would deleting this page be a big deletion? */
173 private $mIsBigDeletion = null;
177 * B/C kludge: provide a TitleParser for use by Title.
178 * Ideally, Title would have no methods that need this.
179 * Avoid usage of this singleton by using TitleValue
180 * and the associated services when possible.
182 * @return TitleFormatter
184 private static function getTitleFormatter() {
185 return MediaWikiServices
::getInstance()->getTitleFormatter();
189 * B/C kludge: provide an InterwikiLookup for use by Title.
190 * Ideally, Title would have no methods that need this.
191 * Avoid usage of this singleton by using TitleValue
192 * and the associated services when possible.
194 * @return InterwikiLookup
196 private static function getInterwikiLookup() {
197 return MediaWikiServices
::getInstance()->getInterwikiLookup();
203 function __construct() {
207 * Create a new Title from a prefixed DB key
209 * @param string $key The database key, which has underscores
210 * instead of spaces, possibly including namespace and
212 * @return Title|null Title, or null on an error
214 public static function newFromDBkey( $key ) {
216 $t->mDbkeyform
= $key;
219 $t->secureAndSplit();
221 } catch ( MalformedTitleException
$ex ) {
227 * Create a new Title from a TitleValue
229 * @param TitleValue $titleValue Assumed to be safe.
233 public static function newFromTitleValue( TitleValue
$titleValue ) {
234 return self
::newFromLinkTarget( $titleValue );
238 * Create a new Title from a LinkTarget
240 * @param LinkTarget $linkTarget Assumed to be safe.
244 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
245 if ( $linkTarget instanceof Title
) {
246 // Special case if it's already a Title object
249 return self
::makeTitle(
250 $linkTarget->getNamespace(),
251 $linkTarget->getText(),
252 $linkTarget->getFragment(),
253 $linkTarget->getInterwiki()
258 * Create a new Title from text, such as what one would find in a link. De-
259 * codes any HTML entities in the text.
261 * Title objects returned by this method are guaranteed to be valid, and
262 * thus return true from the isValid() method.
264 * @param string|int|null $text The link text; spaces, prefixes, and an
265 * initial ':' indicating the main namespace are accepted.
266 * @param int $defaultNamespace The namespace to use if none is specified
267 * by a prefix. If you want to force a specific namespace even if
268 * $text might begin with a namespace prefix, use makeTitle() or
270 * @throws InvalidArgumentException
271 * @return Title|null Title or null on an error.
273 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
274 // DWIM: Integers can be passed in here when page titles are used as array keys.
275 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
276 throw new InvalidArgumentException( '$text must be a string.' );
278 if ( $text === null ) {
283 return self
::newFromTextThrow( strval( $text ), $defaultNamespace );
284 } catch ( MalformedTitleException
$ex ) {
290 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
291 * rather than returning null.
293 * The exception subclasses encode detailed information about why the title is invalid.
295 * Title objects returned by this method are guaranteed to be valid, and
296 * thus return true from the isValid() method.
298 * @see Title::newFromText
301 * @param string $text Title text to check
302 * @param int $defaultNamespace
303 * @throws MalformedTitleException If the title is invalid
306 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
307 if ( is_object( $text ) ) {
308 throw new MWException( '$text must be a string, given an object' );
309 } elseif ( $text === null ) {
310 // Legacy code relies on MalformedTitleException being thrown in this case
311 // (happens when URL with no title in it is parsed). TODO fix
312 throw new MalformedTitleException( 'title-invalid-empty' );
315 $titleCache = self
::getTitleCache();
317 // Wiki pages often contain multiple links to the same page.
318 // Title normalization and parsing can become expensive on pages with many
319 // links, so we can save a little time by caching them.
320 // In theory these are value objects and won't get changed...
321 if ( $defaultNamespace == NS_MAIN
) {
322 $t = $titleCache->get( $text );
328 // Convert things like é ā or 〗 into normalized (T16952) text
329 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
332 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
333 $t->mDefaultNamespace
= intval( $defaultNamespace );
335 $t->secureAndSplit();
336 if ( $defaultNamespace == NS_MAIN
) {
337 $titleCache->set( $text, $t );
343 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
345 * Example of wrong and broken code:
346 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
348 * Example of right code:
349 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
351 * Create a new Title from URL-encoded text. Ensures that
352 * the given title's length does not exceed the maximum.
354 * @param string $url The title, as might be taken from a URL
355 * @return Title|null The new object, or null on an error
357 public static function newFromURL( $url ) {
360 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
361 # but some URLs used it as a space replacement and they still come
362 # from some external search tools.
363 if ( strpos( self
::legalChars(), '+' ) === false ) {
364 $url = strtr( $url, '+', ' ' );
367 $t->mDbkeyform
= strtr( $url, ' ', '_' );
370 $t->secureAndSplit();
372 } catch ( MalformedTitleException
$ex ) {
378 * @return MapCacheLRU
380 private static function getTitleCache() {
381 if ( self
::$titleCache == null ) {
382 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
384 return self
::$titleCache;
388 * Returns a list of fields that are to be selected for initializing Title
389 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
390 * whether to include page_content_model.
394 protected static function getSelectFields() {
395 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
398 'page_namespace', 'page_title', 'page_id',
399 'page_len', 'page_is_redirect', 'page_latest',
402 if ( $wgContentHandlerUseDB ) {
403 $fields[] = 'page_content_model';
406 if ( $wgPageLanguageUseDB ) {
407 $fields[] = 'page_lang';
414 * Create a new Title from an article ID
416 * @param int $id The page_id corresponding to the Title to create
417 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
418 * @return Title|null The new object, or null on an error
420 public static function newFromID( $id, $flags = 0 ) {
421 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
422 $row = $db->selectRow(
424 self
::getSelectFields(),
425 [ 'page_id' => $id ],
428 if ( $row !== false ) {
429 $title = self
::newFromRow( $row );
437 * Make an array of titles from an array of IDs
439 * @param int[] $ids Array of IDs
440 * @return Title[] Array of Titles
442 public static function newFromIDs( $ids ) {
443 if ( !count( $ids ) ) {
446 $dbr = wfGetDB( DB_REPLICA
);
450 self
::getSelectFields(),
451 [ 'page_id' => $ids ],
456 foreach ( $res as $row ) {
457 $titles[] = self
::newFromRow( $row );
463 * Make a Title object from a DB row
465 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
466 * @return Title Corresponding Title
468 public static function newFromRow( $row ) {
469 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
470 $t->loadFromRow( $row );
475 * Load Title object fields from a DB row.
476 * If false is given, the title will be treated as non-existing.
478 * @param stdClass|bool $row Database row
480 public function loadFromRow( $row ) {
481 if ( $row ) { // page found
482 if ( isset( $row->page_id
) ) {
483 $this->mArticleID
= (int)$row->page_id
;
485 if ( isset( $row->page_len
) ) {
486 $this->mLength
= (int)$row->page_len
;
488 if ( isset( $row->page_is_redirect
) ) {
489 $this->mRedirect
= (bool)$row->page_is_redirect
;
491 if ( isset( $row->page_latest
) ) {
492 $this->mLatestID
= (int)$row->page_latest
;
494 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
495 $this->mContentModel
= strval( $row->page_content_model
);
496 } elseif ( !$this->mForcedContentModel
) {
497 $this->mContentModel
= false; # initialized lazily in getContentModel()
499 if ( isset( $row->page_lang
) ) {
500 $this->mDbPageLanguage
= (string)$row->page_lang
;
502 if ( isset( $row->page_restrictions
) ) {
503 $this->mOldRestrictions
= $row->page_restrictions
;
505 } else { // page not found
506 $this->mArticleID
= 0;
508 $this->mRedirect
= false;
509 $this->mLatestID
= 0;
510 if ( !$this->mForcedContentModel
) {
511 $this->mContentModel
= false; # initialized lazily in getContentModel()
517 * Create a new Title from a namespace index and a DB key.
519 * It's assumed that $ns and $title are safe, for instance when
520 * they came directly from the database or a special page name,
521 * not from user input.
523 * No validation is applied. For convenience, spaces are normalized
524 * to underscores, so that e.g. user_text fields can be used directly.
526 * @note This method may return Title objects that are "invalid"
527 * according to the isValid() method. This is usually caused by
528 * configuration changes: e.g. a namespace that was once defined is
529 * no longer configured, or a character that was once allowed in
530 * titles is now forbidden.
532 * @param int $ns The namespace of the article
533 * @param string $title The unprefixed database key form
534 * @param string $fragment The link fragment (after the "#")
535 * @param string $interwiki The interwiki prefix
536 * @return Title The new object
538 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
540 $t->mInterwiki
= $interwiki;
541 $t->mFragment
= $fragment;
542 $t->mNamespace
= $ns = intval( $ns );
543 $t->mDbkeyform
= strtr( $title, ' ', '_' );
544 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
545 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
546 $t->mTextform
= strtr( $title, '_', ' ' );
547 $t->mContentModel
= false; # initialized lazily in getContentModel()
552 * Create a new Title from a namespace index and a DB key.
553 * The parameters will be checked for validity, which is a bit slower
554 * than makeTitle() but safer for user-provided data.
556 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
557 * that is, they return true from the isValid() method. If no valid Title
558 * can be constructed from the input, this method returns null.
560 * @param int $ns The namespace of the article
561 * @param string $title Database key form
562 * @param string $fragment The link fragment (after the "#")
563 * @param string $interwiki Interwiki prefix
564 * @return Title|null The new object, or null on an error
566 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
567 // NOTE: ideally, this would just call makeTitle() and then isValid(),
568 // but presently, that means more overhead on a potential performance hotspot.
570 if ( !MWNamespace
::exists( $ns ) ) {
575 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
578 $t->secureAndSplit();
580 } catch ( MalformedTitleException
$ex ) {
586 * Create a new Title for the Main Page
588 * @return Title The new object
590 public static function newMainPage() {
591 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
592 // Don't give fatal errors if the message is broken
594 $title = self
::newFromText( 'Main Page' );
600 * Get the prefixed DB key associated with an ID
602 * @param int $id The page_id of the article
603 * @return Title|null An object representing the article, or null if no such article was found
605 public static function nameOf( $id ) {
606 $dbr = wfGetDB( DB_REPLICA
);
608 $s = $dbr->selectRow(
610 [ 'page_namespace', 'page_title' ],
611 [ 'page_id' => $id ],
614 if ( $s === false ) {
618 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
623 * Get a regex character class describing the legal characters in a link
625 * @return string The list of characters, not delimited
627 public static function legalChars() {
628 global $wgLegalTitleChars;
629 return $wgLegalTitleChars;
633 * Utility method for converting a character sequence from bytes to Unicode.
635 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
636 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
638 * @param string $byteClass
641 public static function convertByteClassToUnicodeClass( $byteClass ) {
642 $length = strlen( $byteClass );
644 $x0 = $x1 = $x2 = '';
646 $d0 = $d1 = $d2 = '';
647 // Decoded integer codepoints
648 $ord0 = $ord1 = $ord2 = 0;
650 $r0 = $r1 = $r2 = '';
654 $allowUnicode = false;
655 for ( $pos = 0; $pos < $length; $pos++
) {
656 // Shift the queues down
665 // Load the current input token and decoded values
666 $inChar = $byteClass[$pos];
667 if ( $inChar == '\\' ) {
668 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
669 $x0 = $inChar . $m[0];
670 $d0 = chr( hexdec( $m[1] ) );
671 $pos +
= strlen( $m[0] );
672 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
673 $x0 = $inChar . $m[0];
674 $d0 = chr( octdec( $m[0] ) );
675 $pos +
= strlen( $m[0] );
676 } elseif ( $pos +
1 >= $length ) {
679 $d0 = $byteClass[$pos +
1];
687 // Load the current re-encoded value
688 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
689 $r0 = sprintf( '\x%02x', $ord0 );
690 } elseif ( $ord0 >= 0x80 ) {
691 // Allow unicode if a single high-bit character appears
692 $r0 = sprintf( '\x%02x', $ord0 );
693 $allowUnicode = true;
694 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
700 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
702 if ( $ord2 > $ord0 ) {
704 } elseif ( $ord0 >= 0x80 ) {
706 $allowUnicode = true;
707 if ( $ord2 < 0x80 ) {
708 // Keep the non-unicode section of the range
715 // Reset state to the initial value
716 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
717 } elseif ( $ord2 < 0x80 ) {
722 if ( $ord1 < 0x80 ) {
725 if ( $ord0 < 0x80 ) {
728 if ( $allowUnicode ) {
729 $out .= '\u0080-\uFFFF';
735 * Make a prefixed DB key from a DB key and a namespace index
737 * @param int $ns Numerical representation of the namespace
738 * @param string $title The DB key form the title
739 * @param string $fragment The link fragment (after the "#")
740 * @param string $interwiki The interwiki prefix
741 * @param bool $canonicalNamespace If true, use the canonical name for
742 * $ns instead of the localized version.
743 * @return string The prefixed form of the title
745 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
746 $canonicalNamespace = false
750 if ( $canonicalNamespace ) {
751 $namespace = MWNamespace
::getCanonicalName( $ns );
753 $namespace = $wgContLang->getNsText( $ns );
755 $name = $namespace == '' ?
$title : "$namespace:$title";
756 if ( strval( $interwiki ) != '' ) {
757 $name = "$interwiki:$name";
759 if ( strval( $fragment ) != '' ) {
760 $name .= '#' . $fragment;
766 * Escape a text fragment, say from a link, for a URL
768 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
770 * @param string $fragment Containing a URL or link fragment (after the "#")
771 * @return string Escaped string
773 static function escapeFragmentForURL( $fragment ) {
774 wfDeprecated( __METHOD__
, '1.30' );
775 # Note that we don't urlencode the fragment. urlencoded Unicode
776 # fragments appear not to work in IE (at least up to 7) or in at least
777 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
778 # to care if they aren't encoded.
779 return Sanitizer
::escapeId( $fragment, 'noninitial' );
783 * Callback for usort() to do title sorts by (namespace, title)
785 * @param LinkTarget $a
786 * @param LinkTarget $b
788 * @return int Result of string comparison, or namespace comparison
790 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
791 return $a->getNamespace() <=> $b->getNamespace()
792 ?
: strcmp( $a->getText(), $b->getText() );
796 * Returns true if the title is valid, false if it is invalid.
798 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
799 * Invalid titles may get returned from makeTitle(), and it may be useful to
800 * allow them to exist, e.g. in order to process log entries about pages in
801 * namespaces that belong to extensions that are no longer installed.
803 * @note This method is relatively expensive. When constructing Title
804 * objects that need to be valid, use an instantiator method that is guaranteed
805 * to return valid titles, such as makeTitleSafe() or newFromText().
809 public function isValid() {
810 $ns = $this->getNamespace();
812 if ( !MWNamespace
::exists( $ns ) ) {
817 $parser = MediaWikiServices
::getInstance()->getTitleParser();
818 $parser->parseTitle( $this->getDBkey(), $ns );
820 } catch ( MalformedTitleException
$ex ) {
826 * Determine whether the object refers to a page within
827 * this project (either this wiki or a wiki with a local
828 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
830 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
832 public function isLocal() {
833 if ( $this->isExternal() ) {
834 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
836 return $iw->isLocal();
843 * Is this Title interwiki?
847 public function isExternal() {
848 return $this->mInterwiki
!== '';
852 * Get the interwiki prefix
854 * Use Title::isExternal to check if a interwiki is set
856 * @return string Interwiki prefix
858 public function getInterwiki() {
859 return $this->mInterwiki
;
863 * Was this a local interwiki link?
867 public function wasLocalInterwiki() {
868 return $this->mLocalInterwiki
;
872 * Determine whether the object refers to a page within
873 * this project and is transcludable.
875 * @return bool True if this is transcludable
877 public function isTrans() {
878 if ( !$this->isExternal() ) {
882 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
886 * Returns the DB name of the distant wiki which owns the object.
888 * @return string|false The DB name
890 public function getTransWikiID() {
891 if ( !$this->isExternal() ) {
895 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
899 * Get a TitleValue object representing this Title.
901 * @note Not all valid Titles have a corresponding valid TitleValue
902 * (e.g. TitleValues cannot represent page-local links that have a
903 * fragment but no title text).
905 * @return TitleValue|null
907 public function getTitleValue() {
908 if ( $this->mTitleValue
=== null ) {
910 $this->mTitleValue
= new TitleValue(
911 $this->getNamespace(),
913 $this->getFragment(),
914 $this->getInterwiki()
916 } catch ( InvalidArgumentException
$ex ) {
917 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
918 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
922 return $this->mTitleValue
;
926 * Get the text form (spaces not underscores) of the main part
928 * @return string Main part of the title
930 public function getText() {
931 return $this->mTextform
;
935 * Get the URL-encoded form of the main part
937 * @return string Main part of the title, URL-encoded
939 public function getPartialURL() {
940 return $this->mUrlform
;
944 * Get the main part with underscores
946 * @return string Main part of the title, with underscores
948 public function getDBkey() {
949 return $this->mDbkeyform
;
953 * Get the DB key with the initial letter case as specified by the user
955 * @return string DB key
957 function getUserCaseDBKey() {
958 if ( !is_null( $this->mUserCaseDBKey
) ) {
959 return $this->mUserCaseDBKey
;
961 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
962 return $this->mDbkeyform
;
967 * Get the namespace index, i.e. one of the NS_xxxx constants.
969 * @return int Namespace index
971 public function getNamespace() {
972 return $this->mNamespace
;
976 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
978 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
979 * @return string Content model id
981 public function getContentModel( $flags = 0 ) {
982 if ( !$this->mForcedContentModel
983 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
984 && $this->getArticleID( $flags )
986 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
987 $linkCache->addLinkObj( $this ); # in case we already had an article ID
988 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
991 if ( !$this->mContentModel
) {
992 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
995 return $this->mContentModel
;
999 * Convenience method for checking a title's content model name
1001 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1002 * @return bool True if $this->getContentModel() == $id
1004 public function hasContentModel( $id ) {
1005 return $this->getContentModel() == $id;
1009 * Set a proposed content model for the page for permissions
1010 * checking. This does not actually change the content model
1013 * Additionally, you should make sure you've checked
1014 * ContentHandler::canBeUsedOn() first.
1017 * @param string $model CONTENT_MODEL_XXX constant
1019 public function setContentModel( $model ) {
1020 $this->mContentModel
= $model;
1021 $this->mForcedContentModel
= true;
1025 * Get the namespace text
1027 * @return string|false Namespace text
1029 public function getNsText() {
1030 if ( $this->isExternal() ) {
1031 // This probably shouldn't even happen, except for interwiki transclusion.
1032 // If possible, use the canonical name for the foreign namespace.
1033 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1034 if ( $nsText !== false ) {
1040 $formatter = self
::getTitleFormatter();
1041 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1042 } catch ( InvalidArgumentException
$ex ) {
1043 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1049 * Get the namespace text of the subject (rather than talk) page
1051 * @return string Namespace text
1053 public function getSubjectNsText() {
1055 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1059 * Get the namespace text of the talk page
1061 * @return string Namespace text
1063 public function getTalkNsText() {
1065 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1069 * Can this title have a corresponding talk page?
1071 * @deprecated since 1.30, use canHaveTalkPage() instead.
1073 * @return bool True if this title either is a talk page or can have a talk page associated.
1075 public function canTalk() {
1076 return $this->canHaveTalkPage();
1080 * Can this title have a corresponding talk page?
1082 * @see MWNamespace::hasTalkNamespace
1085 * @return bool True if this title either is a talk page or can have a talk page associated.
1087 public function canHaveTalkPage() {
1088 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1092 * Is this in a namespace that allows actual pages?
1096 public function canExist() {
1097 return $this->mNamespace
>= NS_MAIN
;
1101 * Can this title be added to a user's watchlist?
1105 public function isWatchable() {
1106 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1110 * Returns true if this is a special page.
1114 public function isSpecialPage() {
1115 return $this->getNamespace() == NS_SPECIAL
;
1119 * Returns true if this title resolves to the named special page
1121 * @param string $name The special page name
1124 public function isSpecial( $name ) {
1125 if ( $this->isSpecialPage() ) {
1126 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1127 if ( $name == $thisName ) {
1135 * If the Title refers to a special page alias which is not the local default, resolve
1136 * the alias, and localise the name as necessary. Otherwise, return $this
1140 public function fixSpecialName() {
1141 if ( $this->isSpecialPage() ) {
1142 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1143 if ( $canonicalName ) {
1144 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1145 if ( $localName != $this->mDbkeyform
) {
1146 return self
::makeTitle( NS_SPECIAL
, $localName );
1154 * Returns true if the title is inside the specified namespace.
1156 * Please make use of this instead of comparing to getNamespace()
1157 * This function is much more resistant to changes we may make
1158 * to namespaces than code that makes direct comparisons.
1159 * @param int $ns The namespace
1163 public function inNamespace( $ns ) {
1164 return MWNamespace
::equals( $this->getNamespace(), $ns );
1168 * Returns true if the title is inside one of the specified namespaces.
1170 * @param int|int[] $namespaces,... The namespaces to check for
1174 public function inNamespaces( /* ... */ ) {
1175 $namespaces = func_get_args();
1176 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1177 $namespaces = $namespaces[0];
1180 foreach ( $namespaces as $ns ) {
1181 if ( $this->inNamespace( $ns ) ) {
1190 * Returns true if the title has the same subject namespace as the
1191 * namespace specified.
1192 * For example this method will take NS_USER and return true if namespace
1193 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1194 * as their subject namespace.
1196 * This is MUCH simpler than individually testing for equivalence
1197 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1202 public function hasSubjectNamespace( $ns ) {
1203 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1207 * Is this Title in a namespace which contains content?
1208 * In other words, is this a content page, for the purposes of calculating
1213 public function isContentPage() {
1214 return MWNamespace
::isContent( $this->getNamespace() );
1218 * Would anybody with sufficient privileges be able to move this page?
1219 * Some pages just aren't movable.
1223 public function isMovable() {
1224 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1225 // Interwiki title or immovable namespace. Hooks don't get to override here
1230 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1235 * Is this the mainpage?
1236 * @note Title::newFromText seems to be sufficiently optimized by the title
1237 * cache that we don't need to over-optimize by doing direct comparisons and
1238 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1239 * ends up reporting something differently than $title->isMainPage();
1244 public function isMainPage() {
1245 return $this->equals( self
::newMainPage() );
1249 * Is this a subpage?
1253 public function isSubpage() {
1254 return MWNamespace
::hasSubpages( $this->mNamespace
)
1255 ?
strpos( $this->getText(), '/' ) !== false
1260 * Is this a conversion table for the LanguageConverter?
1264 public function isConversionTable() {
1265 // @todo ConversionTable should become a separate content model.
1267 return $this->getNamespace() == NS_MEDIAWIKI
&&
1268 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1272 * Does that page contain wikitext, or it is JS, CSS or whatever?
1276 public function isWikitextPage() {
1277 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1281 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1282 * global UI. This is generally true for pages in the MediaWiki namespace having
1283 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1285 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1288 * Note that this method should not return true for pages that contain and show
1289 * "inactive" CSS, JSON, or JS.
1294 public function isSiteConfigPage() {
1296 $this->isSiteCssConfigPage()
1297 ||
$this->isSiteJsonConfigPage()
1298 ||
$this->isSiteJsConfigPage()
1304 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1306 public function isCssOrJsPage() {
1307 wfDeprecated( __METHOD__
, '1.31' );
1308 return ( NS_MEDIAWIKI
== $this->mNamespace
1309 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1310 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1314 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1319 public function isUserConfigPage() {
1321 $this->isUserCssConfigPage()
1322 ||
$this->isUserJsonConfigPage()
1323 ||
$this->isUserJsConfigPage()
1329 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1331 public function isCssJsSubpage() {
1332 wfDeprecated( __METHOD__
, '1.31' );
1333 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1334 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1335 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1339 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1341 * @return string Containing skin name from .css, .json, or .js subpage title
1344 public function getSkinFromConfigSubpage() {
1345 $subpage = explode( '/', $this->mTextform
);
1346 $subpage = $subpage[count( $subpage ) - 1];
1347 $lastdot = strrpos( $subpage, '.' );
1348 if ( $lastdot === false ) {
1349 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1351 return substr( $subpage, 0, $lastdot );
1355 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1356 * @return string Containing skin name from .css, .json, or .js subpage title
1358 public function getSkinFromCssJsSubpage() {
1359 wfDeprecated( __METHOD__
, '1.31' );
1360 return $this->getSkinFromConfigSubpage();
1364 * Is this a CSS "config" sub-page of a user page?
1369 public function isUserCssConfigPage() {
1371 NS_USER
== $this->mNamespace
1372 && $this->isSubpage()
1373 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1378 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1381 public function isCssSubpage() {
1382 wfDeprecated( __METHOD__
, '1.31' );
1383 return $this->isUserCssConfigPage();
1387 * Is this a JSON "config" sub-page of a user page?
1392 public function isUserJsonConfigPage() {
1394 NS_USER
== $this->mNamespace
1395 && $this->isSubpage()
1396 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1401 * Is this a JS "config" sub-page of a user page?
1406 public function isUserJsConfigPage() {
1408 NS_USER
== $this->mNamespace
1409 && $this->isSubpage()
1410 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1415 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1418 public function isJsSubpage() {
1419 wfDeprecated( __METHOD__
, '1.31' );
1420 return $this->isUserJsConfigPage();
1424 * Is this a sitewide CSS "config" page?
1429 public function isSiteCssConfigPage() {
1431 NS_MEDIAWIKI
== $this->mNamespace
1433 $this->hasContentModel( CONTENT_MODEL_CSS
)
1434 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1435 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1436 ||
substr( $this->getDBkey(), -4 ) === '.css'
1442 * Is this a sitewide JSON "config" page?
1447 public function isSiteJsonConfigPage() {
1449 NS_MEDIAWIKI
== $this->mNamespace
1451 $this->hasContentModel( CONTENT_MODEL_JSON
)
1452 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1453 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1454 ||
substr( $this->getDBkey(), -5 ) === '.json'
1460 * Is this a sitewide JS "config" page?
1465 public function isSiteJsConfigPage() {
1467 NS_MEDIAWIKI
== $this->mNamespace
1469 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1470 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1471 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1472 ||
substr( $this->getDBkey(), -3 ) === '.js'
1478 * Is this a talk page of some sort?
1482 public function isTalkPage() {
1483 return MWNamespace
::isTalk( $this->getNamespace() );
1487 * Get a Title object associated with the talk page of this article
1489 * @return Title The object for the talk page
1491 public function getTalkPage() {
1492 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1496 * Get a Title object associated with the talk page of this article,
1497 * if such a talk page can exist.
1501 * @return Title|null The object for the talk page,
1502 * or null if no associated talk page can exist, according to canHaveTalkPage().
1504 public function getTalkPageIfDefined() {
1505 if ( !$this->canHaveTalkPage() ) {
1509 return $this->getTalkPage();
1513 * Get a title object associated with the subject page of this
1516 * @return Title The object for the subject page
1518 public function getSubjectPage() {
1519 // Is this the same title?
1520 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1521 if ( $this->getNamespace() == $subjectNS ) {
1524 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1528 * Get the other title for this page, if this is a subject page
1529 * get the talk page, if it is a subject page get the talk page
1532 * @throws MWException If the page doesn't have an other page
1535 public function getOtherPage() {
1536 if ( $this->isSpecialPage() ) {
1537 throw new MWException( 'Special pages cannot have other pages' );
1539 if ( $this->isTalkPage() ) {
1540 return $this->getSubjectPage();
1542 if ( !$this->canHaveTalkPage() ) {
1543 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1545 return $this->getTalkPage();
1550 * Get the default namespace index, for when there is no namespace
1552 * @return int Default namespace index
1554 public function getDefaultNamespace() {
1555 return $this->mDefaultNamespace
;
1559 * Get the Title fragment (i.e.\ the bit after the #) in text form
1561 * Use Title::hasFragment to check for a fragment
1563 * @return string Title fragment
1565 public function getFragment() {
1566 return $this->mFragment
;
1570 * Check if a Title fragment is set
1575 public function hasFragment() {
1576 return $this->mFragment
!== '';
1580 * Get the fragment in URL form, including the "#" character if there is one
1582 * @return string Fragment in URL form
1584 public function getFragmentForURL() {
1585 if ( !$this->hasFragment() ) {
1587 } elseif ( $this->isExternal()
1588 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1590 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1592 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1596 * Set the fragment for this title. Removes the first character from the
1597 * specified fragment before setting, so it assumes you're passing it with
1600 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1601 * or Title::createFragmentTarget().
1602 * Still in active use privately.
1605 * @param string $fragment Text
1607 public function setFragment( $fragment ) {
1608 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1612 * Creates a new Title for a different fragment of the same page.
1615 * @param string $fragment
1618 public function createFragmentTarget( $fragment ) {
1619 return self
::makeTitle(
1620 $this->getNamespace(),
1623 $this->getInterwiki()
1628 * Prefix some arbitrary text with the namespace or interwiki prefix
1631 * @param string $name The text
1632 * @return string The prefixed text
1634 private function prefix( $name ) {
1638 if ( $this->isExternal() ) {
1639 $p = $this->mInterwiki
. ':';
1642 if ( 0 != $this->mNamespace
) {
1643 $nsText = $this->getNsText();
1645 if ( $nsText === false ) {
1646 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1647 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1650 $p .= $nsText . ':';
1656 * Get the prefixed database key form
1658 * @return string The prefixed title, with underscores and
1659 * any interwiki and namespace prefixes
1661 public function getPrefixedDBkey() {
1662 $s = $this->prefix( $this->mDbkeyform
);
1663 $s = strtr( $s, ' ', '_' );
1668 * Get the prefixed title with spaces.
1669 * This is the form usually used for display
1671 * @return string The prefixed title, with spaces
1673 public function getPrefixedText() {
1674 if ( $this->mPrefixedText
=== null ) {
1675 $s = $this->prefix( $this->mTextform
);
1676 $s = strtr( $s, '_', ' ' );
1677 $this->mPrefixedText
= $s;
1679 return $this->mPrefixedText
;
1683 * Return a string representation of this title
1685 * @return string Representation of this title
1687 public function __toString() {
1688 return $this->getPrefixedText();
1692 * Get the prefixed title with spaces, plus any fragment
1693 * (part beginning with '#')
1695 * @return string The prefixed title, with spaces and the fragment, including '#'
1697 public function getFullText() {
1698 $text = $this->getPrefixedText();
1699 if ( $this->hasFragment() ) {
1700 $text .= '#' . $this->getFragment();
1706 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1710 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1714 * @return string Root name
1717 public function getRootText() {
1718 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1719 return $this->getText();
1722 return strtok( $this->getText(), '/' );
1726 * Get the root page name title, i.e. the leftmost part before any slashes
1730 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1731 * # returns: Title{User:Foo}
1734 * @return Title Root title
1737 public function getRootTitle() {
1738 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1742 * Get the base page name without a namespace, i.e. the part before the subpage name
1746 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1747 * # returns: 'Foo/Bar'
1750 * @return string Base name
1752 public function getBaseText() {
1753 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1754 return $this->getText();
1757 $parts = explode( '/', $this->getText() );
1758 # Don't discard the real title if there's no subpage involved
1759 if ( count( $parts ) > 1 ) {
1760 unset( $parts[count( $parts ) - 1] );
1762 return implode( '/', $parts );
1766 * Get the base page name title, i.e. the part before the subpage name
1770 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1771 * # returns: Title{User:Foo/Bar}
1774 * @return Title Base title
1777 public function getBaseTitle() {
1778 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1782 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1786 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1790 * @return string Subpage name
1792 public function getSubpageText() {
1793 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1794 return $this->mTextform
;
1796 $parts = explode( '/', $this->mTextform
);
1797 return $parts[count( $parts ) - 1];
1801 * Get the title for a subpage of the current page
1805 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1806 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1809 * @param string $text The subpage name to add to the title
1810 * @return Title Subpage title
1813 public function getSubpage( $text ) {
1814 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1818 * Get a URL-encoded form of the subpage text
1820 * @return string URL-encoded subpage name
1822 public function getSubpageUrlForm() {
1823 $text = $this->getSubpageText();
1824 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1829 * Get a URL-encoded title (not an actual URL) including interwiki
1831 * @return string The URL-encoded form
1833 public function getPrefixedURL() {
1834 $s = $this->prefix( $this->mDbkeyform
);
1835 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1840 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1841 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1842 * second argument named variant. This was deprecated in favor
1843 * of passing an array of option with a "variant" key
1844 * Once $query2 is removed for good, this helper can be dropped
1845 * and the wfArrayToCgi moved to getLocalURL();
1847 * @since 1.19 (r105919)
1848 * @param array|string $query
1849 * @param string|string[]|bool $query2
1852 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1853 if ( $query2 !== false ) {
1854 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1855 "method called with a second parameter is deprecated. Add your " .
1856 "parameter to an array passed as the first parameter.", "1.19" );
1858 if ( is_array( $query ) ) {
1859 $query = wfArrayToCgi( $query );
1862 if ( is_string( $query2 ) ) {
1863 // $query2 is a string, we will consider this to be
1864 // a deprecated $variant argument and add it to the query
1865 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1867 $query2 = wfArrayToCgi( $query2 );
1869 // If we have $query content add a & to it first
1873 // Now append the queries together
1880 * Get a real URL referring to this title, with interwiki link and
1883 * @see self::getLocalURL for the arguments.
1885 * @param string|string[] $query
1886 * @param string|string[]|bool $query2
1887 * @param string|int|null $proto Protocol type to use in URL
1888 * @return string The URL
1890 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1891 $query = self
::fixUrlQueryArgs( $query, $query2 );
1893 # Hand off all the decisions on urls to getLocalURL
1894 $url = $this->getLocalURL( $query );
1896 # Expand the url to make it a full url. Note that getLocalURL has the
1897 # potential to output full urls for a variety of reasons, so we use
1898 # wfExpandUrl instead of simply prepending $wgServer
1899 $url = wfExpandUrl( $url, $proto );
1901 # Finally, add the fragment.
1902 $url .= $this->getFragmentForURL();
1903 // Avoid PHP 7.1 warning from passing $this by reference
1905 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1910 * Get a url appropriate for making redirects based on an untrusted url arg
1912 * This is basically the same as getFullUrl(), but in the case of external
1913 * interwikis, we send the user to a landing page, to prevent possible
1914 * phishing attacks and the like.
1916 * @note Uses current protocol by default, since technically relative urls
1917 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1918 * places where the url gets cached, as might pollute between
1919 * https and non-https users.
1920 * @see self::getLocalURL for the arguments.
1921 * @param array|string $query
1922 * @param string $proto Protocol type to use in URL
1923 * @return string A url suitable to use in an HTTP location header.
1925 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1927 if ( $this->isExternal() ) {
1928 $target = SpecialPage
::getTitleFor(
1930 $this->getPrefixedDBkey()
1933 return $target->getFullURL( $query, false, $proto );
1937 * Get a URL with no fragment or server name (relative URL) from a Title object.
1938 * If this page is generated with action=render, however,
1939 * $wgServer is prepended to make an absolute URL.
1941 * @see self::getFullURL to always get an absolute URL.
1942 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1943 * valid to link, locally, to the current Title.
1944 * @see self::newFromText to produce a Title object.
1946 * @param string|string[] $query An optional query string,
1947 * not used for interwiki links. Can be specified as an associative array as well,
1948 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1949 * Some query patterns will trigger various shorturl path replacements.
1950 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1951 * be an array. If a string is passed it will be interpreted as a deprecated
1952 * variant argument and urlencoded into a variant= argument.
1953 * This second query argument will be added to the $query
1954 * The second parameter is deprecated since 1.19. Pass it as a key,value
1955 * pair in the first parameter array instead.
1957 * @return string String of the URL.
1959 public function getLocalURL( $query = '', $query2 = false ) {
1960 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1962 $query = self
::fixUrlQueryArgs( $query, $query2 );
1964 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1966 $namespace = $this->getNsText();
1967 if ( $namespace != '' ) {
1968 # Can this actually happen? Interwikis shouldn't be parsed.
1969 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1972 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1973 $url = wfAppendQuery( $url, $query );
1975 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1976 if ( $query == '' ) {
1977 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1978 // Avoid PHP 7.1 warning from passing $this by reference
1980 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1982 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1986 if ( !empty( $wgActionPaths )
1987 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1989 $action = urldecode( $matches[2] );
1990 if ( isset( $wgActionPaths[$action] ) ) {
1991 $query = $matches[1];
1992 if ( isset( $matches[4] ) ) {
1993 $query .= $matches[4];
1995 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1996 if ( $query != '' ) {
1997 $url = wfAppendQuery( $url, $query );
2003 && $wgVariantArticlePath
2004 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2005 && $this->getPageLanguage()->equals( $wgContLang )
2006 && $this->getPageLanguage()->hasVariants()
2008 $variant = urldecode( $matches[1] );
2009 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2010 // Only do the variant replacement if the given variant is a valid
2011 // variant for the page's language.
2012 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2013 $url = str_replace( '$1', $dbkey, $url );
2017 if ( $url === false ) {
2018 if ( $query == '-' ) {
2021 $url = "{$wgScript}?title={$dbkey}&{$query}";
2024 // Avoid PHP 7.1 warning from passing $this by reference
2026 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2028 // @todo FIXME: This causes breakage in various places when we
2029 // actually expected a local URL and end up with dupe prefixes.
2030 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2031 $url = $wgServer . $url;
2034 // Avoid PHP 7.1 warning from passing $this by reference
2036 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2041 * Get a URL that's the simplest URL that will be valid to link, locally,
2042 * to the current Title. It includes the fragment, but does not include
2043 * the server unless action=render is used (or the link is external). If
2044 * there's a fragment but the prefixed text is empty, we just return a link
2047 * The result obviously should not be URL-escaped, but does need to be
2048 * HTML-escaped if it's being output in HTML.
2050 * @param string|string[] $query
2051 * @param bool $query2
2052 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2053 * or false (default) for no expansion
2054 * @see self::getLocalURL for the arguments.
2055 * @return string The URL
2057 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2058 if ( $this->isExternal() ||
$proto !== false ) {
2059 $ret = $this->getFullURL( $query, $query2, $proto );
2060 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2061 $ret = $this->getFragmentForURL();
2063 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2069 * Get the URL form for an internal link.
2070 * - Used in various CDN-related code, in case we have a different
2071 * internal hostname for the server from the exposed one.
2073 * This uses $wgInternalServer to qualify the path, or $wgServer
2074 * if $wgInternalServer is not set. If the server variable used is
2075 * protocol-relative, the URL will be expanded to http://
2077 * @see self::getLocalURL for the arguments.
2078 * @param string $query
2079 * @param string|bool $query2
2080 * @return string The URL
2082 public function getInternalURL( $query = '', $query2 = false ) {
2083 global $wgInternalServer, $wgServer;
2084 $query = self
::fixUrlQueryArgs( $query, $query2 );
2085 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2086 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2087 // Avoid PHP 7.1 warning from passing $this by reference
2089 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2094 * Get the URL for a canonical link, for use in things like IRC and
2095 * e-mail notifications. Uses $wgCanonicalServer and the
2096 * GetCanonicalURL hook.
2098 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2100 * @see self::getLocalURL for the arguments.
2101 * @param string $query
2102 * @param string|bool $query2
2103 * @return string The URL
2106 public function getCanonicalURL( $query = '', $query2 = false ) {
2107 $query = self
::fixUrlQueryArgs( $query, $query2 );
2108 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2109 // Avoid PHP 7.1 warning from passing $this by reference
2111 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2116 * Get the edit URL for this Title
2118 * @return string The URL, or a null string if this is an interwiki link
2120 public function getEditURL() {
2121 if ( $this->isExternal() ) {
2124 $s = $this->getLocalURL( 'action=edit' );
2130 * Can $user perform $action on this page?
2131 * This skips potentially expensive cascading permission checks
2132 * as well as avoids expensive error formatting
2134 * Suitable for use for nonessential UI controls in common cases, but
2135 * _not_ for functional access control.
2137 * May provide false positives, but should never provide a false negative.
2139 * @param string $action Action that permission needs to be checked for
2140 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2143 public function quickUserCan( $action, $user = null ) {
2144 return $this->userCan( $action, $user, false );
2148 * Can $user perform $action on this page?
2150 * @param string $action Action that permission needs to be checked for
2151 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2153 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2156 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2157 if ( !$user instanceof User
) {
2162 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2166 * Can $user perform $action on this page?
2168 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2170 * @param string $action Action that permission needs to be checked for
2171 * @param User $user User to check
2172 * @param string $rigor One of (quick,full,secure)
2173 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2174 * - full : does cheap and expensive checks possibly from a replica DB
2175 * - secure : does cheap and expensive checks, using the master as needed
2176 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2177 * whose corresponding errors may be ignored.
2178 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2180 public function getUserPermissionsErrors(
2181 $action, $user, $rigor = 'secure', $ignoreErrors = []
2183 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2185 // Remove the errors being ignored.
2186 foreach ( $errors as $index => $error ) {
2187 $errKey = is_array( $error ) ?
$error[0] : $error;
2189 if ( in_array( $errKey, $ignoreErrors ) ) {
2190 unset( $errors[$index] );
2192 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2193 unset( $errors[$index] );
2201 * Permissions checks that fail most often, and which are easiest to test.
2203 * @param string $action The action to check
2204 * @param User $user User to check
2205 * @param array $errors List of current errors
2206 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2207 * @param bool $short Short circuit on first error
2209 * @return array List of errors
2211 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2212 if ( !Hooks
::run( 'TitleQuickPermissions',
2213 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2218 if ( $action == 'create' ) {
2220 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2221 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2223 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2225 } elseif ( $action == 'move' ) {
2226 if ( !$user->isAllowed( 'move-rootuserpages' )
2227 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2228 // Show user page-specific message only if the user can move other pages
2229 $errors[] = [ 'cant-move-user-page' ];
2232 // Check if user is allowed to move files if it's a file
2233 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2234 $errors[] = [ 'movenotallowedfile' ];
2237 // Check if user is allowed to move category pages if it's a category page
2238 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2239 $errors[] = [ 'cant-move-category-page' ];
2242 if ( !$user->isAllowed( 'move' ) ) {
2243 // User can't move anything
2244 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2245 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2246 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2247 // custom message if logged-in users without any special rights can move
2248 $errors[] = [ 'movenologintext' ];
2250 $errors[] = [ 'movenotallowed' ];
2253 } elseif ( $action == 'move-target' ) {
2254 if ( !$user->isAllowed( 'move' ) ) {
2255 // User can't move anything
2256 $errors[] = [ 'movenotallowed' ];
2257 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2258 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2259 // Show user page-specific message only if the user can move other pages
2260 $errors[] = [ 'cant-move-to-user-page' ];
2261 } elseif ( !$user->isAllowed( 'move-categorypages' )
2262 && $this->mNamespace
== NS_CATEGORY
) {
2263 // Show category page-specific message only if the user can move other pages
2264 $errors[] = [ 'cant-move-to-category-page' ];
2266 } elseif ( !$user->isAllowed( $action ) ) {
2267 $errors[] = $this->missingPermissionError( $action, $short );
2274 * Add the resulting error code to the errors array
2276 * @param array $errors List of current errors
2277 * @param array $result Result of errors
2279 * @return array List of errors
2281 private function resultToError( $errors, $result ) {
2282 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2283 // A single array representing an error
2284 $errors[] = $result;
2285 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2286 // A nested array representing multiple errors
2287 $errors = array_merge( $errors, $result );
2288 } elseif ( $result !== '' && is_string( $result ) ) {
2289 // A string representing a message-id
2290 $errors[] = [ $result ];
2291 } elseif ( $result instanceof MessageSpecifier
) {
2292 // A message specifier representing an error
2293 $errors[] = [ $result ];
2294 } elseif ( $result === false ) {
2295 // a generic "We don't want them to do that"
2296 $errors[] = [ 'badaccess-group0' ];
2302 * Check various permission hooks
2304 * @param string $action The action to check
2305 * @param User $user User to check
2306 * @param array $errors List of current errors
2307 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2308 * @param bool $short Short circuit on first error
2310 * @return array List of errors
2312 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2313 // Use getUserPermissionsErrors instead
2315 // Avoid PHP 7.1 warning from passing $this by reference
2317 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2318 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2320 // Check getUserPermissionsErrors hook
2321 // Avoid PHP 7.1 warning from passing $this by reference
2323 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2324 $errors = $this->resultToError( $errors, $result );
2326 // Check getUserPermissionsErrorsExpensive hook
2329 && !( $short && count( $errors ) > 0 )
2330 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2332 $errors = $this->resultToError( $errors, $result );
2339 * Check permissions on special pages & namespaces
2341 * @param string $action The action to check
2342 * @param User $user User to check
2343 * @param array $errors List of current errors
2344 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2345 * @param bool $short Short circuit on first error
2347 * @return array List of errors
2349 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2350 # Only 'createaccount' can be performed on special pages,
2351 # which don't actually exist in the DB.
2352 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2353 $errors[] = [ 'ns-specialprotected' ];
2356 # Check $wgNamespaceProtection for restricted namespaces
2357 if ( $this->isNamespaceProtected( $user ) ) {
2358 $ns = $this->mNamespace
== NS_MAIN ?
2359 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2360 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2361 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2368 * Check sitewide CSS/JSON/JS permissions
2370 * @param string $action The action to check
2371 * @param User $user User to check
2372 * @param array $errors List of current errors
2373 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2374 * @param bool $short Short circuit on first error
2376 * @return array List of errors
2378 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2379 if ( $action != 'patrol' ) {
2381 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2382 // editinterface right. That's implemented as a restriction so no check needed here.
2383 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2384 $error = [ 'sitecssprotected', $action ];
2385 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2386 $error = [ 'sitejsonprotected', $action ];
2387 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2388 $error = [ 'sitejsprotected', $action ];
2392 if ( $user->isAllowed( 'editinterface' ) ) {
2393 // Most users / site admins will probably find out about the new, more restrictive
2394 // permissions by failing to edit something. Give them more info.
2395 // TODO remove this a few release cycles after 1.32
2396 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2406 * Check CSS/JSON/JS sub-page permissions
2408 * @param string $action The action to check
2409 * @param User $user User to check
2410 * @param array $errors List of current errors
2411 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2412 * @param bool $short Short circuit on first error
2414 * @return array List of errors
2416 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2417 # Protect css/json/js subpages of user pages
2418 # XXX: this might be better using restrictions
2420 if ( $action != 'patrol' ) {
2421 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2423 $this->isUserCssConfigPage()
2424 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2426 $errors[] = [ 'mycustomcssprotected', $action ];
2428 $this->isUserJsonConfigPage()
2429 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2431 $errors[] = [ 'mycustomjsonprotected', $action ];
2433 $this->isUserJsConfigPage()
2434 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2436 $errors[] = [ 'mycustomjsprotected', $action ];
2440 $this->isUserCssConfigPage()
2441 && !$user->isAllowed( 'editusercss' )
2443 $errors[] = [ 'customcssprotected', $action ];
2445 $this->isUserJsonConfigPage()
2446 && !$user->isAllowed( 'edituserjson' )
2448 $errors[] = [ 'customjsonprotected', $action ];
2450 $this->isUserJsConfigPage()
2451 && !$user->isAllowed( 'edituserjs' )
2453 $errors[] = [ 'customjsprotected', $action ];
2462 * Check against page_restrictions table requirements on this
2463 * page. The user must possess all required rights for this
2466 * @param string $action The action to check
2467 * @param User $user User to check
2468 * @param array $errors List of current errors
2469 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2470 * @param bool $short Short circuit on first error
2472 * @return array List of errors
2474 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2475 foreach ( $this->getRestrictions( $action ) as $right ) {
2476 // Backwards compatibility, rewrite sysop -> editprotected
2477 if ( $right == 'sysop' ) {
2478 $right = 'editprotected';
2480 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2481 if ( $right == 'autoconfirmed' ) {
2482 $right = 'editsemiprotected';
2484 if ( $right == '' ) {
2487 if ( !$user->isAllowed( $right ) ) {
2488 $errors[] = [ 'protectedpagetext', $right, $action ];
2489 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2490 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2498 * Check restrictions on cascading pages.
2500 * @param string $action The action to check
2501 * @param User $user User to check
2502 * @param array $errors List of current errors
2503 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2504 * @param bool $short Short circuit on first error
2506 * @return array List of errors
2508 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2509 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2510 # We /could/ use the protection level on the source page, but it's
2511 # fairly ugly as we have to establish a precedence hierarchy for pages
2512 # included by multiple cascade-protected pages. So just restrict
2513 # it to people with 'protect' permission, as they could remove the
2514 # protection anyway.
2515 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2516 # Cascading protection depends on more than this page...
2517 # Several cascading protected pages may include this page...
2518 # Check each cascading level
2519 # This is only for protection restrictions, not for all actions
2520 if ( isset( $restrictions[$action] ) ) {
2521 foreach ( $restrictions[$action] as $right ) {
2522 // Backwards compatibility, rewrite sysop -> editprotected
2523 if ( $right == 'sysop' ) {
2524 $right = 'editprotected';
2526 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2527 if ( $right == 'autoconfirmed' ) {
2528 $right = 'editsemiprotected';
2530 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2532 foreach ( $cascadingSources as $page ) {
2533 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2535 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2545 * Check action permissions not already checked in checkQuickPermissions
2547 * @param string $action The action to check
2548 * @param User $user User to check
2549 * @param array $errors List of current errors
2550 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2551 * @param bool $short Short circuit on first error
2553 * @return array List of errors
2555 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2556 global $wgDeleteRevisionsLimit, $wgLang;
2558 if ( $action == 'protect' ) {
2559 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2560 // If they can't edit, they shouldn't protect.
2561 $errors[] = [ 'protect-cantedit' ];
2563 } elseif ( $action == 'create' ) {
2564 $title_protection = $this->getTitleProtection();
2565 if ( $title_protection ) {
2566 if ( $title_protection['permission'] == ''
2567 ||
!$user->isAllowed( $title_protection['permission'] )
2571 User
::whoIs( $title_protection['user'] ),
2572 $title_protection['reason']
2576 } elseif ( $action == 'move' ) {
2577 // Check for immobile pages
2578 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2579 // Specific message for this case
2580 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2581 } elseif ( !$this->isMovable() ) {
2582 // Less specific message for rarer cases
2583 $errors[] = [ 'immobile-source-page' ];
2585 } elseif ( $action == 'move-target' ) {
2586 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2587 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2588 } elseif ( !$this->isMovable() ) {
2589 $errors[] = [ 'immobile-target-page' ];
2591 } elseif ( $action == 'delete' ) {
2592 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2593 if ( !$tempErrors ) {
2594 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2595 $user, $tempErrors, $rigor, true );
2597 if ( $tempErrors ) {
2598 // If protection keeps them from editing, they shouldn't be able to delete.
2599 $errors[] = [ 'deleteprotected' ];
2601 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2602 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2604 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2606 } elseif ( $action === 'undelete' ) {
2607 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2608 // Undeleting implies editing
2609 $errors[] = [ 'undelete-cantedit' ];
2611 if ( !$this->exists()
2612 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2614 // Undeleting where nothing currently exists implies creating
2615 $errors[] = [ 'undelete-cantcreate' ];
2622 * Check that the user isn't blocked from editing.
2624 * @param string $action The action to check
2625 * @param User $user User to check
2626 * @param array $errors List of current errors
2627 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2628 * @param bool $short Short circuit on first error
2630 * @return array List of errors
2632 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2633 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2634 // Account creation blocks handled at userlogin.
2635 // Unblocking handled in SpecialUnblock
2636 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2640 // Optimize for a very common case
2641 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2645 if ( $wgEmailConfirmToEdit
2646 && !$user->isEmailConfirmed()
2647 && $action === 'edit'
2649 $errors[] = [ 'confirmedittext' ];
2652 $useSlave = ( $rigor !== 'secure' );
2653 if ( ( $action == 'edit' ||
$action == 'create' )
2654 && !$user->isBlockedFrom( $this, $useSlave )
2656 // Don't block the user from editing their own talk page unless they've been
2657 // explicitly blocked from that too.
2658 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2659 // @todo FIXME: Pass the relevant context into this function.
2660 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2667 * Check that the user is allowed to read this page.
2669 * @param string $action The action to check
2670 * @param User $user User to check
2671 * @param array $errors List of current errors
2672 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2673 * @param bool $short Short circuit on first error
2675 * @return array List of errors
2677 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2678 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2680 $whitelisted = false;
2681 if ( User
::isEveryoneAllowed( 'read' ) ) {
2682 # Shortcut for public wikis, allows skipping quite a bit of code
2683 $whitelisted = true;
2684 } elseif ( $user->isAllowed( 'read' ) ) {
2685 # If the user is allowed to read pages, he is allowed to read all pages
2686 $whitelisted = true;
2687 } elseif ( $this->isSpecial( 'Userlogin' )
2688 ||
$this->isSpecial( 'PasswordReset' )
2689 ||
$this->isSpecial( 'Userlogout' )
2691 # Always grant access to the login page.
2692 # Even anons need to be able to log in.
2693 $whitelisted = true;
2694 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2695 # Time to check the whitelist
2696 # Only do these checks is there's something to check against
2697 $name = $this->getPrefixedText();
2698 $dbName = $this->getPrefixedDBkey();
2700 // Check for explicit whitelisting with and without underscores
2701 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2702 $whitelisted = true;
2703 } elseif ( $this->getNamespace() == NS_MAIN
) {
2704 # Old settings might have the title prefixed with
2705 # a colon for main-namespace pages
2706 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2707 $whitelisted = true;
2709 } elseif ( $this->isSpecialPage() ) {
2710 # If it's a special page, ditch the subpage bit and check again
2711 $name = $this->getDBkey();
2712 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2714 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2715 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2716 $whitelisted = true;
2722 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2723 $name = $this->getPrefixedText();
2724 // Check for regex whitelisting
2725 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2726 if ( preg_match( $listItem, $name ) ) {
2727 $whitelisted = true;
2733 if ( !$whitelisted ) {
2734 # If the title is not whitelisted, give extensions a chance to do so...
2735 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2736 if ( !$whitelisted ) {
2737 $errors[] = $this->missingPermissionError( $action, $short );
2745 * Get a description array when the user doesn't have the right to perform
2746 * $action (i.e. when User::isAllowed() returns false)
2748 * @param string $action The action to check
2749 * @param bool $short Short circuit on first error
2750 * @return array Array containing an error message key and any parameters
2752 private function missingPermissionError( $action, $short ) {
2753 // We avoid expensive display logic for quickUserCan's and such
2755 return [ 'badaccess-group0' ];
2758 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2762 * Can $user perform $action on this page? This is an internal function,
2763 * with multiple levels of checks depending on performance needs; see $rigor below.
2764 * It does not check wfReadOnly().
2766 * @param string $action Action that permission needs to be checked for
2767 * @param User $user User to check
2768 * @param string $rigor One of (quick,full,secure)
2769 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2770 * - full : does cheap and expensive checks possibly from a replica DB
2771 * - secure : does cheap and expensive checks, using the master as needed
2772 * @param bool $short Set this to true to stop after the first permission error.
2773 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2775 protected function getUserPermissionsErrorsInternal(
2776 $action, $user, $rigor = 'secure', $short = false
2778 if ( $rigor === true ) {
2779 $rigor = 'secure'; // b/c
2780 } elseif ( $rigor === false ) {
2781 $rigor = 'quick'; // b/c
2782 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2783 throw new Exception( "Invalid rigor parameter '$rigor'." );
2786 # Read has special handling
2787 if ( $action == 'read' ) {
2789 'checkPermissionHooks',
2790 'checkReadPermissions',
2791 'checkUserBlock', // for wgBlockDisablesLogin
2793 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2794 # or checkUserConfigPermissions here as it will lead to duplicate
2795 # error messages. This is okay to do since anywhere that checks for
2796 # create will also check for edit, and those checks are called for edit.
2797 } elseif ( $action == 'create' ) {
2799 'checkQuickPermissions',
2800 'checkPermissionHooks',
2801 'checkPageRestrictions',
2802 'checkCascadingSourcesRestrictions',
2803 'checkActionPermissions',
2808 'checkQuickPermissions',
2809 'checkPermissionHooks',
2810 'checkSpecialsAndNSPermissions',
2811 'checkSiteConfigPermissions',
2812 'checkUserConfigPermissions',
2813 'checkPageRestrictions',
2814 'checkCascadingSourcesRestrictions',
2815 'checkActionPermissions',
2821 while ( count( $checks ) > 0 &&
2822 !( $short && count( $errors ) > 0 ) ) {
2823 $method = array_shift( $checks );
2824 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2831 * Get a filtered list of all restriction types supported by this wiki.
2832 * @param bool $exists True to get all restriction types that apply to
2833 * titles that do exist, False for all restriction types that apply to
2834 * titles that do not exist
2837 public static function getFilteredRestrictionTypes( $exists = true ) {
2838 global $wgRestrictionTypes;
2839 $types = $wgRestrictionTypes;
2841 # Remove the create restriction for existing titles
2842 $types = array_diff( $types, [ 'create' ] );
2844 # Only the create and upload restrictions apply to non-existing titles
2845 $types = array_intersect( $types, [ 'create', 'upload' ] );
2851 * Returns restriction types for the current Title
2853 * @return array Applicable restriction types
2855 public function getRestrictionTypes() {
2856 if ( $this->isSpecialPage() ) {
2860 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2862 if ( $this->getNamespace() != NS_FILE
) {
2863 # Remove the upload restriction for non-file titles
2864 $types = array_diff( $types, [ 'upload' ] );
2867 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2869 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2870 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2876 * Is this title subject to title protection?
2877 * Title protection is the one applied against creation of such title.
2879 * @return array|bool An associative array representing any existent title
2880 * protection, or false if there's none.
2882 public function getTitleProtection() {
2883 $protection = $this->getTitleProtectionInternal();
2884 if ( $protection ) {
2885 if ( $protection['permission'] == 'sysop' ) {
2886 $protection['permission'] = 'editprotected'; // B/C
2888 if ( $protection['permission'] == 'autoconfirmed' ) {
2889 $protection['permission'] = 'editsemiprotected'; // B/C
2896 * Fetch title protection settings
2898 * To work correctly, $this->loadRestrictions() needs to have access to the
2899 * actual protections in the database without munging 'sysop' =>
2900 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2901 * callers probably want $this->getTitleProtection() instead.
2903 * @return array|bool
2905 protected function getTitleProtectionInternal() {
2906 // Can't protect pages in special namespaces
2907 if ( $this->getNamespace() < 0 ) {
2911 // Can't protect pages that exist.
2912 if ( $this->exists() ) {
2916 if ( $this->mTitleProtection
=== null ) {
2917 $dbr = wfGetDB( DB_REPLICA
);
2918 $commentStore = CommentStore
::getStore();
2919 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2920 $res = $dbr->select(
2921 [ 'protected_titles' ] +
$commentQuery['tables'],
2923 'user' => 'pt_user',
2924 'expiry' => 'pt_expiry',
2925 'permission' => 'pt_create_perm'
2926 ] +
$commentQuery['fields'],
2927 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2930 $commentQuery['joins']
2933 // fetchRow returns false if there are no rows.
2934 $row = $dbr->fetchRow( $res );
2936 $this->mTitleProtection
= [
2937 'user' => $row['user'],
2938 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2939 'permission' => $row['permission'],
2940 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2943 $this->mTitleProtection
= false;
2946 return $this->mTitleProtection
;
2950 * Remove any title protection due to page existing
2952 public function deleteTitleProtection() {
2953 $dbw = wfGetDB( DB_MASTER
);
2957 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2960 $this->mTitleProtection
= false;
2964 * Is this page "semi-protected" - the *only* protection levels are listed
2965 * in $wgSemiprotectedRestrictionLevels?
2967 * @param string $action Action to check (default: edit)
2970 public function isSemiProtected( $action = 'edit' ) {
2971 global $wgSemiprotectedRestrictionLevels;
2973 $restrictions = $this->getRestrictions( $action );
2974 $semi = $wgSemiprotectedRestrictionLevels;
2975 if ( !$restrictions ||
!$semi ) {
2976 // Not protected, or all protection is full protection
2980 // Remap autoconfirmed to editsemiprotected for BC
2981 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2982 $semi[$key] = 'editsemiprotected';
2984 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2985 $restrictions[$key] = 'editsemiprotected';
2988 return !array_diff( $restrictions, $semi );
2992 * Does the title correspond to a protected article?
2994 * @param string $action The action the page is protected from,
2995 * by default checks all actions.
2998 public function isProtected( $action = '' ) {
2999 global $wgRestrictionLevels;
3001 $restrictionTypes = $this->getRestrictionTypes();
3003 # Special pages have inherent protection
3004 if ( $this->isSpecialPage() ) {
3008 # Check regular protection levels
3009 foreach ( $restrictionTypes as $type ) {
3010 if ( $action == $type ||
$action == '' ) {
3011 $r = $this->getRestrictions( $type );
3012 foreach ( $wgRestrictionLevels as $level ) {
3013 if ( in_array( $level, $r ) && $level != '' ) {
3024 * Determines if $user is unable to edit this page because it has been protected
3025 * by $wgNamespaceProtection.
3027 * @param User $user User object to check permissions
3030 public function isNamespaceProtected( User
$user ) {
3031 global $wgNamespaceProtection;
3033 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3034 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3035 if ( $right != '' && !$user->isAllowed( $right ) ) {
3044 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3046 * @return bool If the page is subject to cascading restrictions.
3048 public function isCascadeProtected() {
3049 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3050 return ( $sources > 0 );
3054 * Determines whether cascading protection sources have already been loaded from
3057 * @param bool $getPages True to check if the pages are loaded, or false to check
3058 * if the status is loaded.
3059 * @return bool Whether or not the specified information has been loaded
3062 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3063 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3067 * Cascading protection: Get the source of any cascading restrictions on this page.
3069 * @param bool $getPages Whether or not to retrieve the actual pages
3070 * that the restrictions have come from and the actual restrictions
3072 * @return array Two elements: First is an array of Title objects of the
3073 * pages from which cascading restrictions have come, false for
3074 * none, or true if such restrictions exist but $getPages was not
3075 * set. Second is an array like that returned by
3076 * Title::getAllRestrictions(), or an empty array if $getPages is
3079 public function getCascadeProtectionSources( $getPages = true ) {
3080 $pagerestrictions = [];
3082 if ( $this->mCascadeSources
!== null && $getPages ) {
3083 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3084 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3085 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3088 $dbr = wfGetDB( DB_REPLICA
);
3090 if ( $this->getNamespace() == NS_FILE
) {
3091 $tables = [ 'imagelinks', 'page_restrictions' ];
3093 'il_to' => $this->getDBkey(),
3098 $tables = [ 'templatelinks', 'page_restrictions' ];
3100 'tl_namespace' => $this->getNamespace(),
3101 'tl_title' => $this->getDBkey(),
3108 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3109 'pr_expiry', 'pr_type', 'pr_level' ];
3110 $where_clauses[] = 'page_id=pr_page';
3113 $cols = [ 'pr_expiry' ];
3116 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3118 $sources = $getPages ?
[] : false;
3119 $now = wfTimestampNow();
3121 foreach ( $res as $row ) {
3122 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3123 if ( $expiry > $now ) {
3125 $page_id = $row->pr_page
;
3126 $page_ns = $row->page_namespace
;
3127 $page_title = $row->page_title
;
3128 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3129 # Add groups needed for each restriction type if its not already there
3130 # Make sure this restriction type still exists
3132 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3133 $pagerestrictions[$row->pr_type
] = [];
3137 isset( $pagerestrictions[$row->pr_type
] )
3138 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3140 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3149 $this->mCascadeSources
= $sources;
3150 $this->mCascadingRestrictions
= $pagerestrictions;
3152 $this->mHasCascadingRestrictions
= $sources;
3155 return [ $sources, $pagerestrictions ];
3159 * Accessor for mRestrictionsLoaded
3161 * @return bool Whether or not the page's restrictions have already been
3162 * loaded from the database
3165 public function areRestrictionsLoaded() {
3166 return $this->mRestrictionsLoaded
;
3170 * Accessor/initialisation for mRestrictions
3172 * @param string $action Action that permission needs to be checked for
3173 * @return array Restriction levels needed to take the action. All levels are
3174 * required. Note that restriction levels are normally user rights, but 'sysop'
3175 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3176 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3178 public function getRestrictions( $action ) {
3179 if ( !$this->mRestrictionsLoaded
) {
3180 $this->loadRestrictions();
3182 return $this->mRestrictions
[$action] ??
[];
3186 * Accessor/initialisation for mRestrictions
3188 * @return array Keys are actions, values are arrays as returned by
3189 * Title::getRestrictions()
3192 public function getAllRestrictions() {
3193 if ( !$this->mRestrictionsLoaded
) {
3194 $this->loadRestrictions();
3196 return $this->mRestrictions
;
3200 * Get the expiry time for the restriction against a given action
3202 * @param string $action
3203 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3204 * or not protected at all, or false if the action is not recognised.
3206 public function getRestrictionExpiry( $action ) {
3207 if ( !$this->mRestrictionsLoaded
) {
3208 $this->loadRestrictions();
3210 return $this->mRestrictionsExpiry
[$action] ??
false;
3214 * Returns cascading restrictions for the current article
3218 function areRestrictionsCascading() {
3219 if ( !$this->mRestrictionsLoaded
) {
3220 $this->loadRestrictions();
3223 return $this->mCascadeRestriction
;
3227 * Compiles list of active page restrictions from both page table (pre 1.10)
3228 * and page_restrictions table for this existing page.
3229 * Public for usage by LiquidThreads.
3231 * @param array $rows Array of db result objects
3232 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3233 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3234 * Edit and move sections are separated by a colon
3235 * Example: "edit=autoconfirmed,sysop:move=sysop"
3237 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3238 $dbr = wfGetDB( DB_REPLICA
);
3240 $restrictionTypes = $this->getRestrictionTypes();
3242 foreach ( $restrictionTypes as $type ) {
3243 $this->mRestrictions
[$type] = [];
3244 $this->mRestrictionsExpiry
[$type] = 'infinity';
3247 $this->mCascadeRestriction
= false;
3249 # Backwards-compatibility: also load the restrictions from the page record (old format).
3250 if ( $oldFashionedRestrictions !== null ) {
3251 $this->mOldRestrictions
= $oldFashionedRestrictions;
3254 if ( $this->mOldRestrictions
=== false ) {
3255 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3256 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3259 if ( $this->mOldRestrictions
!= '' ) {
3260 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3261 $temp = explode( '=', trim( $restrict ) );
3262 if ( count( $temp ) == 1 ) {
3263 // old old format should be treated as edit/move restriction
3264 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3265 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3267 $restriction = trim( $temp[1] );
3268 if ( $restriction != '' ) { // some old entries are empty
3269 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3275 if ( count( $rows ) ) {
3276 # Current system - load second to make them override.
3277 $now = wfTimestampNow();
3279 # Cycle through all the restrictions.
3280 foreach ( $rows as $row ) {
3281 // Don't take care of restrictions types that aren't allowed
3282 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3286 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3288 // Only apply the restrictions if they haven't expired!
3289 if ( !$expiry ||
$expiry > $now ) {
3290 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3291 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3293 $this->mCascadeRestriction |
= $row->pr_cascade
;
3298 $this->mRestrictionsLoaded
= true;
3302 * Load restrictions from the page_restrictions table
3304 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3305 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3306 * Edit and move sections are separated by a colon
3307 * Example: "edit=autoconfirmed,sysop:move=sysop"
3309 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3310 if ( $this->mRestrictionsLoaded
) {
3314 $id = $this->getArticleID();
3316 $cache = ObjectCache
::getMainWANInstance();
3317 $rows = $cache->getWithSetCallback(
3318 // Page protections always leave a new null revision
3319 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3321 function ( $curValue, &$ttl, array &$setOpts ) {
3322 $dbr = wfGetDB( DB_REPLICA
);
3324 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3326 return iterator_to_array(
3328 'page_restrictions',
3329 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3330 [ 'pr_page' => $this->getArticleID() ],
3337 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3339 $title_protection = $this->getTitleProtectionInternal();
3341 if ( $title_protection ) {
3342 $now = wfTimestampNow();
3343 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3345 if ( !$expiry ||
$expiry > $now ) {
3346 // Apply the restrictions
3347 $this->mRestrictionsExpiry
['create'] = $expiry;
3348 $this->mRestrictions
['create'] =
3349 explode( ',', trim( $title_protection['permission'] ) );
3350 } else { // Get rid of the old restrictions
3351 $this->mTitleProtection
= false;
3354 $this->mRestrictionsExpiry
['create'] = 'infinity';
3356 $this->mRestrictionsLoaded
= true;
3361 * Flush the protection cache in this object and force reload from the database.
3362 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3364 public function flushRestrictions() {
3365 $this->mRestrictionsLoaded
= false;
3366 $this->mTitleProtection
= null;
3370 * Purge expired restrictions from the page_restrictions table
3372 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3374 static function purgeExpiredRestrictions() {
3375 if ( wfReadOnly() ) {
3379 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3380 wfGetDB( DB_MASTER
),
3382 function ( IDatabase
$dbw, $fname ) {
3383 $config = MediaWikiServices
::getInstance()->getMainConfig();
3384 $ids = $dbw->selectFieldValues(
3385 'page_restrictions',
3387 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3389 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3392 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3397 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3398 wfGetDB( DB_MASTER
),
3400 function ( IDatabase
$dbw, $fname ) {
3403 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3411 * Does this have subpages? (Warning, usually requires an extra DB query.)
3415 public function hasSubpages() {
3416 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3421 # We dynamically add a member variable for the purpose of this method
3422 # alone to cache the result. There's no point in having it hanging
3423 # around uninitialized in every Title object; therefore we only add it
3424 # if needed and don't declare it statically.
3425 if ( $this->mHasSubpages
=== null ) {
3426 $this->mHasSubpages
= false;
3427 $subpages = $this->getSubpages( 1 );
3428 if ( $subpages instanceof TitleArray
) {
3429 $this->mHasSubpages
= (bool)$subpages->count();
3433 return $this->mHasSubpages
;
3437 * Get all subpages of this page.
3439 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3440 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3441 * doesn't allow subpages
3443 public function getSubpages( $limit = -1 ) {
3444 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3448 $dbr = wfGetDB( DB_REPLICA
);
3449 $conds['page_namespace'] = $this->getNamespace();
3450 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3452 if ( $limit > -1 ) {
3453 $options['LIMIT'] = $limit;
3455 return TitleArray
::newFromResult(
3456 $dbr->select( 'page',
3457 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3466 * Is there a version of this page in the deletion archive?
3468 * @return int The number of archived revisions
3470 public function isDeleted() {
3471 if ( $this->getNamespace() < 0 ) {
3474 $dbr = wfGetDB( DB_REPLICA
);
3476 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3477 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3480 if ( $this->getNamespace() == NS_FILE
) {
3481 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3482 [ 'fa_name' => $this->getDBkey() ],
3491 * Is there a version of this page in the deletion archive?
3495 public function isDeletedQuick() {
3496 if ( $this->getNamespace() < 0 ) {
3499 $dbr = wfGetDB( DB_REPLICA
);
3500 $deleted = (bool)$dbr->selectField( 'archive', '1',
3501 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3504 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3505 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3506 [ 'fa_name' => $this->getDBkey() ],
3514 * Get the article ID for this Title from the link cache,
3515 * adding it if necessary
3517 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3519 * @return int The ID
3521 public function getArticleID( $flags = 0 ) {
3522 if ( $this->getNamespace() < 0 ) {
3523 $this->mArticleID
= 0;
3524 return $this->mArticleID
;
3526 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3527 if ( $flags & self
::GAID_FOR_UPDATE
) {
3528 $oldUpdate = $linkCache->forUpdate( true );
3529 $linkCache->clearLink( $this );
3530 $this->mArticleID
= $linkCache->addLinkObj( $this );
3531 $linkCache->forUpdate( $oldUpdate );
3533 if ( -1 == $this->mArticleID
) {
3534 $this->mArticleID
= $linkCache->addLinkObj( $this );
3537 return $this->mArticleID
;
3541 * Is this an article that is a redirect page?
3542 * Uses link cache, adding it if necessary
3544 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3547 public function isRedirect( $flags = 0 ) {
3548 if ( !is_null( $this->mRedirect
) ) {
3549 return $this->mRedirect
;
3551 if ( !$this->getArticleID( $flags ) ) {
3552 $this->mRedirect
= false;
3553 return $this->mRedirect
;
3556 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3557 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3558 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3559 if ( $cached === null ) {
3560 # Trust LinkCache's state over our own
3561 # LinkCache is telling us that the page doesn't exist, despite there being cached
3562 # data relating to an existing page in $this->mArticleID. Updaters should clear
3563 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3564 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3565 # LinkCache to refresh its data from the master.
3566 $this->mRedirect
= false;
3567 return $this->mRedirect
;
3570 $this->mRedirect
= (bool)$cached;
3572 return $this->mRedirect
;
3576 * What is the length of this page?
3577 * Uses link cache, adding it if necessary
3579 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3582 public function getLength( $flags = 0 ) {
3583 if ( $this->mLength
!= -1 ) {
3584 return $this->mLength
;
3586 if ( !$this->getArticleID( $flags ) ) {
3588 return $this->mLength
;
3590 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3591 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3592 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3593 if ( $cached === null ) {
3594 # Trust LinkCache's state over our own, as for isRedirect()
3596 return $this->mLength
;
3599 $this->mLength
= intval( $cached );
3601 return $this->mLength
;
3605 * What is the page_latest field for this page?
3607 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3608 * @return int Int or 0 if the page doesn't exist
3610 public function getLatestRevID( $flags = 0 ) {
3611 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3612 return intval( $this->mLatestID
);
3614 if ( !$this->getArticleID( $flags ) ) {
3615 $this->mLatestID
= 0;
3616 return $this->mLatestID
;
3618 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3619 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3620 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3621 if ( $cached === null ) {
3622 # Trust LinkCache's state over our own, as for isRedirect()
3623 $this->mLatestID
= 0;
3624 return $this->mLatestID
;
3627 $this->mLatestID
= intval( $cached );
3629 return $this->mLatestID
;
3633 * This clears some fields in this object, and clears any associated
3634 * keys in the "bad links" section of the link cache.
3636 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3637 * loading of the new page_id. It's also called from
3638 * WikiPage::doDeleteArticleReal()
3640 * @param int $newid The new Article ID
3642 public function resetArticleID( $newid ) {
3643 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3644 $linkCache->clearLink( $this );
3646 if ( $newid === false ) {
3647 $this->mArticleID
= -1;
3649 $this->mArticleID
= intval( $newid );
3651 $this->mRestrictionsLoaded
= false;
3652 $this->mRestrictions
= [];
3653 $this->mOldRestrictions
= false;
3654 $this->mRedirect
= null;
3655 $this->mLength
= -1;
3656 $this->mLatestID
= false;
3657 $this->mContentModel
= false;
3658 $this->mEstimateRevisions
= null;
3659 $this->mPageLanguage
= false;
3660 $this->mDbPageLanguage
= false;
3661 $this->mIsBigDeletion
= null;
3664 public static function clearCaches() {
3665 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3666 $linkCache->clear();
3668 $titleCache = self
::getTitleCache();
3669 $titleCache->clear();
3673 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3675 * @param string $text Containing title to capitalize
3676 * @param int $ns Namespace index, defaults to NS_MAIN
3677 * @return string Containing capitalized title
3679 public static function capitalize( $text, $ns = NS_MAIN
) {
3682 if ( MWNamespace
::isCapitalized( $ns ) ) {
3683 return $wgContLang->ucfirst( $text );
3690 * Secure and split - main initialisation function for this object
3692 * Assumes that mDbkeyform has been set, and is urldecoded
3693 * and uses underscores, but not otherwise munged. This function
3694 * removes illegal characters, splits off the interwiki and
3695 * namespace prefixes, sets the other forms, and canonicalizes
3698 * @throws MalformedTitleException On invalid titles
3699 * @return bool True on success
3701 private function secureAndSplit() {
3703 $this->mInterwiki
= '';
3704 $this->mFragment
= '';
3705 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3707 $dbkey = $this->mDbkeyform
;
3709 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3710 // the parsing code with Title, while avoiding massive refactoring.
3711 // @todo: get rid of secureAndSplit, refactor parsing code.
3712 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3713 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3714 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3715 // MalformedTitleException can be thrown here
3716 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3719 $this->setFragment( '#' . $parts['fragment'] );
3720 $this->mInterwiki
= $parts['interwiki'];
3721 $this->mLocalInterwiki
= $parts['local_interwiki'];
3722 $this->mNamespace
= $parts['namespace'];
3723 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3725 $this->mDbkeyform
= $parts['dbkey'];
3726 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3727 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3729 # We already know that some pages won't be in the database!
3730 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3731 $this->mArticleID
= 0;
3738 * Get an array of Title objects linking to this Title
3739 * Also stores the IDs in the link cache.
3741 * WARNING: do not use this function on arbitrary user-supplied titles!
3742 * On heavily-used templates it will max out the memory.
3744 * @param array $options May be FOR UPDATE
3745 * @param string $table Table name
3746 * @param string $prefix Fields prefix
3747 * @return Title[] Array of Title objects linking here
3749 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3750 if ( count( $options ) > 0 ) {
3751 $db = wfGetDB( DB_MASTER
);
3753 $db = wfGetDB( DB_REPLICA
);
3758 self
::getSelectFields(),
3760 "{$prefix}_from=page_id",
3761 "{$prefix}_namespace" => $this->getNamespace(),
3762 "{$prefix}_title" => $this->getDBkey() ],
3768 if ( $res->numRows() ) {
3769 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3770 foreach ( $res as $row ) {
3771 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3773 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3774 $retVal[] = $titleObj;
3782 * Get an array of Title objects using this Title as a template
3783 * Also stores the IDs in the link cache.
3785 * WARNING: do not use this function on arbitrary user-supplied titles!
3786 * On heavily-used templates it will max out the memory.
3788 * @param array $options Query option to Database::select()
3789 * @return Title[] Array of Title the Title objects linking here
3791 public function getTemplateLinksTo( $options = [] ) {
3792 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3796 * Get an array of Title objects linked from this Title
3797 * Also stores the IDs in the link cache.
3799 * WARNING: do not use this function on arbitrary user-supplied titles!
3800 * On heavily-used templates it will max out the memory.
3802 * @param array $options Query option to Database::select()
3803 * @param string $table Table name
3804 * @param string $prefix Fields prefix
3805 * @return array Array of Title objects linking here
3807 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3808 $id = $this->getArticleID();
3810 # If the page doesn't exist; there can't be any link from this page
3815 $db = wfGetDB( DB_REPLICA
);
3817 $blNamespace = "{$prefix}_namespace";
3818 $blTitle = "{$prefix}_title";
3820 $pageQuery = WikiPage
::getQueryInfo();
3822 [ $table, 'nestpage' => $pageQuery['tables'] ],
3824 [ $blNamespace, $blTitle ],
3825 $pageQuery['fields']
3827 [ "{$prefix}_from" => $id ],
3832 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3833 ] ] +
$pageQuery['joins']
3837 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3838 foreach ( $res as $row ) {
3839 if ( $row->page_id
) {
3840 $titleObj = self
::newFromRow( $row );
3842 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3843 $linkCache->addBadLinkObj( $titleObj );
3845 $retVal[] = $titleObj;
3852 * Get an array of Title objects used on this Title as a template
3853 * Also stores the IDs in the link cache.
3855 * WARNING: do not use this function on arbitrary user-supplied titles!
3856 * On heavily-used templates it will max out the memory.
3858 * @param array $options May be FOR UPDATE
3859 * @return Title[] Array of Title the Title objects used here
3861 public function getTemplateLinksFrom( $options = [] ) {
3862 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3866 * Get an array of Title objects referring to non-existent articles linked
3869 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3870 * should use redirect table in this case).
3871 * @return Title[] Array of Title the Title objects
3873 public function getBrokenLinksFrom() {
3874 if ( $this->getArticleID() == 0 ) {
3875 # All links from article ID 0 are false positives
3879 $dbr = wfGetDB( DB_REPLICA
);
3880 $res = $dbr->select(
3881 [ 'page', 'pagelinks' ],
3882 [ 'pl_namespace', 'pl_title' ],
3884 'pl_from' => $this->getArticleID(),
3885 'page_namespace IS NULL'
3891 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3897 foreach ( $res as $row ) {
3898 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3904 * Get a list of URLs to purge from the CDN cache when this
3907 * @return string[] Array of String the URLs
3909 public function getCdnUrls() {
3911 $this->getInternalURL(),
3912 $this->getInternalURL( 'action=history' )
3915 $pageLang = $this->getPageLanguage();
3916 if ( $pageLang->hasVariants() ) {
3917 $variants = $pageLang->getVariants();
3918 foreach ( $variants as $vCode ) {
3919 $urls[] = $this->getInternalURL( $vCode );
3923 // If we are looking at a css/js user subpage, purge the action=raw.
3924 if ( $this->isUserJsConfigPage() ) {
3925 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3926 } elseif ( $this->isUserJsonConfigPage() ) {
3927 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3928 } elseif ( $this->isUserCssConfigPage() ) {
3929 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3932 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3937 * @deprecated since 1.27 use getCdnUrls()
3939 public function getSquidURLs() {
3940 return $this->getCdnUrls();
3944 * Purge all applicable CDN URLs
3946 public function purgeSquid() {
3947 DeferredUpdates
::addUpdate(
3948 new CdnCacheUpdate( $this->getCdnUrls() ),
3949 DeferredUpdates
::PRESEND
3954 * Check whether a given move operation would be valid.
3955 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3957 * @deprecated since 1.25, use MovePage's methods instead
3958 * @param Title &$nt The new title
3959 * @param bool $auth Whether to check user permissions (uses $wgUser)
3960 * @param string $reason Is the log summary of the move, used for spam checking
3961 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3963 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3966 if ( !( $nt instanceof Title
) ) {
3967 // Normally we'd add this to $errors, but we'll get
3968 // lots of syntax errors if $nt is not an object
3969 return [ [ 'badtitletext' ] ];
3972 $mp = new MovePage( $this, $nt );
3973 $errors = $mp->isValidMove()->getErrorsArray();
3975 $errors = wfMergeErrorArrays(
3977 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3981 return $errors ?
: true;
3985 * Check if the requested move target is a valid file move target
3986 * @todo move this to MovePage
3987 * @param Title $nt Target title
3988 * @return array List of errors
3990 protected function validateFileMoveOperation( $nt ) {
3995 $destFile = wfLocalFile( $nt );
3996 $destFile->load( File
::READ_LATEST
);
3997 if ( !$wgUser->isAllowed( 'reupload-shared' )
3998 && !$destFile->exists() && wfFindFile( $nt )
4000 $errors[] = [ 'file-exists-sharedrepo' ];
4007 * Move a title to a new location
4009 * @deprecated since 1.25, use the MovePage class instead
4010 * @param Title &$nt The new title
4011 * @param bool $auth Indicates whether $wgUser's permissions
4013 * @param string $reason The reason for the move
4014 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4015 * Ignored if the user doesn't have the suppressredirect right.
4016 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4017 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4019 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4020 array $changeTags = []
4023 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4024 if ( is_array( $err ) ) {
4025 // Auto-block user's IP if the account was "hard" blocked
4026 $wgUser->spreadAnyEditBlock();
4029 // Check suppressredirect permission
4030 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4031 $createRedirect = true;
4034 $mp = new MovePage( $this, $nt );
4035 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4036 if ( $status->isOK() ) {
4039 return $status->getErrorsArray();
4044 * Move this page's subpages to be subpages of $nt
4046 * @param Title $nt Move target
4047 * @param bool $auth Whether $wgUser's permissions should be checked
4048 * @param string $reason The reason for the move
4049 * @param bool $createRedirect Whether to create redirects from the old subpages to
4050 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4051 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4052 * @return array Array with old page titles as keys, and strings (new page titles) or
4053 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4054 * getUserPermissionsErrors()-like error array with numeric indices if
4055 * no pages were moved
4057 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4058 array $changeTags = []
4060 global $wgMaximumMovedPages;
4061 // Check permissions
4062 if ( !$this->userCan( 'move-subpages' ) ) {
4064 [ 'cant-move-subpages' ],
4067 // Do the source and target namespaces support subpages?
4068 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4070 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
4073 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4075 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4079 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4082 foreach ( $subpages as $oldSubpage ) {
4084 if ( $count > $wgMaximumMovedPages ) {
4085 $retval[$oldSubpage->getPrefixedText()] = [
4086 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4091 // We don't know whether this function was called before
4092 // or after moving the root page, so check both
4094 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4095 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4097 // When moving a page to a subpage of itself,
4098 // don't move it twice
4101 $newPageName = preg_replace(
4102 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4103 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4104 $oldSubpage->getDBkey() );
4105 if ( $oldSubpage->isTalkPage() ) {
4106 $newNs = $nt->getTalkPage()->getNamespace();
4108 $newNs = $nt->getSubjectPage()->getNamespace();
4110 # T16385: we need makeTitleSafe because the new page names may
4111 # be longer than 255 characters.
4112 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4114 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4115 if ( $success === true ) {
4116 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4118 $retval[$oldSubpage->getPrefixedText()] = $success;
4125 * Checks if this page is just a one-rev redirect.
4126 * Adds lock, so don't use just for light purposes.
4130 public function isSingleRevRedirect() {
4131 global $wgContentHandlerUseDB;
4133 $dbw = wfGetDB( DB_MASTER
);
4136 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4137 if ( $wgContentHandlerUseDB ) {
4138 $fields[] = 'page_content_model';
4141 $row = $dbw->selectRow( 'page',
4147 # Cache some fields we may want
4148 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4149 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4150 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4151 $this->mContentModel
= $row && isset( $row->page_content_model
)
4152 ?
strval( $row->page_content_model
)
4155 if ( !$this->mRedirect
) {
4158 # Does the article have a history?
4159 $row = $dbw->selectField( [ 'page', 'revision' ],
4161 [ 'page_namespace' => $this->getNamespace(),
4162 'page_title' => $this->getDBkey(),
4164 'page_latest != rev_id'
4169 # Return true if there was no history
4170 return ( $row === false );
4174 * Checks if $this can be moved to a given Title
4175 * - Selects for update, so don't call it unless you mean business
4177 * @deprecated since 1.25, use MovePage's methods instead
4178 * @param Title $nt The new title to check
4181 public function isValidMoveTarget( $nt ) {
4182 # Is it an existing file?
4183 if ( $nt->getNamespace() == NS_FILE
) {
4184 $file = wfLocalFile( $nt );
4185 $file->load( File
::READ_LATEST
);
4186 if ( $file->exists() ) {
4187 wfDebug( __METHOD__
. ": file exists\n" );
4191 # Is it a redirect with no history?
4192 if ( !$nt->isSingleRevRedirect() ) {
4193 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4196 # Get the article text
4197 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4198 if ( !is_object( $rev ) ) {
4201 $content = $rev->getContent();
4202 # Does the redirect point to the source?
4203 # Or is it a broken self-redirect, usually caused by namespace collisions?
4204 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4206 if ( $redirTitle ) {
4207 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4208 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4209 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4215 # Fail safe (not a redirect after all. strange.)
4216 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4217 " is a redirect, but it doesn't contain a valid redirect.\n" );
4223 * Get categories to which this Title belongs and return an array of
4224 * categories' names.
4226 * @return array Array of parents in the form:
4227 * $parent => $currentarticle
4229 public function getParentCategories() {
4234 $titleKey = $this->getArticleID();
4236 if ( $titleKey === 0 ) {
4240 $dbr = wfGetDB( DB_REPLICA
);
4242 $res = $dbr->select(
4245 [ 'cl_from' => $titleKey ],
4249 if ( $res->numRows() > 0 ) {
4250 foreach ( $res as $row ) {
4251 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4252 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4259 * Get a tree of parent categories
4261 * @param array $children Array with the children in the keys, to check for circular refs
4262 * @return array Tree of parent categories
4264 public function getParentCategoryTree( $children = [] ) {
4266 $parents = $this->getParentCategories();
4269 foreach ( $parents as $parent => $current ) {
4270 if ( array_key_exists( $parent, $children ) ) {
4271 # Circular reference
4272 $stack[$parent] = [];
4274 $nt = self
::newFromText( $parent );
4276 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4286 * Get an associative array for selecting this title from
4289 * @return array Array suitable for the $where parameter of DB::select()
4291 public function pageCond() {
4292 if ( $this->mArticleID
> 0 ) {
4293 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4294 return [ 'page_id' => $this->mArticleID
];
4296 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4301 * Get next/previous revision ID relative to another revision ID
4302 * @param int $revId Revision ID. Get the revision that was before this one.
4303 * @param int $flags Title::GAID_FOR_UPDATE
4304 * @param string $dir 'next' or 'prev'
4305 * @return int|bool New revision ID, or false if none exists
4307 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4308 $revId = (int)$revId;
4309 if ( $dir === 'next' ) {
4312 } elseif ( $dir === 'prev' ) {
4316 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4319 if ( $flags & self
::GAID_FOR_UPDATE
) {
4320 $db = wfGetDB( DB_MASTER
);
4322 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4325 // Intentionally not caring if the specified revision belongs to this
4326 // page. We only care about the timestamp.
4327 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4328 if ( $ts === false ) {
4329 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4330 if ( $ts === false ) {
4331 // Or should this throw an InvalidArgumentException or something?
4335 $ts = $db->addQuotes( $ts );
4337 $revId = $db->selectField( 'revision', 'rev_id',
4339 'rev_page' => $this->getArticleID( $flags ),
4340 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4344 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4345 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4349 if ( $revId === false ) {
4352 return intval( $revId );
4357 * Get the revision ID of the previous revision
4359 * @param int $revId Revision ID. Get the revision that was before this one.
4360 * @param int $flags Title::GAID_FOR_UPDATE
4361 * @return int|bool Old revision ID, or false if none exists
4363 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4364 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4368 * Get the revision ID of the next revision
4370 * @param int $revId Revision ID. Get the revision that was after this one.
4371 * @param int $flags Title::GAID_FOR_UPDATE
4372 * @return int|bool Next revision ID, or false if none exists
4374 public function getNextRevisionID( $revId, $flags = 0 ) {
4375 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4379 * Get the first revision of the page
4381 * @param int $flags Title::GAID_FOR_UPDATE
4382 * @return Revision|null If page doesn't exist
4384 public function getFirstRevision( $flags = 0 ) {
4385 $pageId = $this->getArticleID( $flags );
4387 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4388 $revQuery = Revision
::getQueryInfo();
4389 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4390 [ 'rev_page' => $pageId ],
4393 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4394 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4399 return new Revision( $row );
4406 * Get the oldest revision timestamp of this page
4408 * @param int $flags Title::GAID_FOR_UPDATE
4409 * @return string MW timestamp
4411 public function getEarliestRevTime( $flags = 0 ) {
4412 $rev = $this->getFirstRevision( $flags );
4413 return $rev ?
$rev->getTimestamp() : null;
4417 * Check if this is a new page
4421 public function isNewPage() {
4422 $dbr = wfGetDB( DB_REPLICA
);
4423 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4427 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4431 public function isBigDeletion() {
4432 global $wgDeleteRevisionsLimit;
4434 if ( !$wgDeleteRevisionsLimit ) {
4438 if ( $this->mIsBigDeletion
=== null ) {
4439 $dbr = wfGetDB( DB_REPLICA
);
4441 $revCount = $dbr->selectRowCount(
4444 [ 'rev_page' => $this->getArticleID() ],
4446 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4449 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4452 return $this->mIsBigDeletion
;
4456 * Get the approximate revision count of this page.
4460 public function estimateRevisionCount() {
4461 if ( !$this->exists() ) {
4465 if ( $this->mEstimateRevisions
=== null ) {
4466 $dbr = wfGetDB( DB_REPLICA
);
4467 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4468 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4471 return $this->mEstimateRevisions
;
4475 * Get the number of revisions between the given revision.
4476 * Used for diffs and other things that really need it.
4478 * @param int|Revision $old Old revision or rev ID (first before range)
4479 * @param int|Revision $new New revision or rev ID (first after range)
4480 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4481 * @return int Number of revisions between these revisions.
4483 public function countRevisionsBetween( $old, $new, $max = null ) {
4484 if ( !( $old instanceof Revision
) ) {
4485 $old = Revision
::newFromTitle( $this, (int)$old );
4487 if ( !( $new instanceof Revision
) ) {
4488 $new = Revision
::newFromTitle( $this, (int)$new );
4490 if ( !$old ||
!$new ) {
4491 return 0; // nothing to compare
4493 $dbr = wfGetDB( DB_REPLICA
);
4495 'rev_page' => $this->getArticleID(),
4496 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4497 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4499 if ( $max !== null ) {
4500 return $dbr->selectRowCount( 'revision', '1',
4503 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4506 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4511 * Get the authors between the given revisions or revision IDs.
4512 * Used for diffs and other things that really need it.
4516 * @param int|Revision $old Old revision or rev ID (first before range by default)
4517 * @param int|Revision $new New revision or rev ID (first after range by default)
4518 * @param int $limit Maximum number of authors
4519 * @param string|array $options (Optional): Single option, or an array of options:
4520 * 'include_old' Include $old in the range; $new is excluded.
4521 * 'include_new' Include $new in the range; $old is excluded.
4522 * 'include_both' Include both $old and $new in the range.
4523 * Unknown option values are ignored.
4524 * @return array|null Names of revision authors in the range; null if not both revisions exist
4526 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4527 if ( !( $old instanceof Revision
) ) {
4528 $old = Revision
::newFromTitle( $this, (int)$old );
4530 if ( !( $new instanceof Revision
) ) {
4531 $new = Revision
::newFromTitle( $this, (int)$new );
4533 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4534 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4535 // in the sanity check below?
4536 if ( !$old ||
!$new ) {
4537 return null; // nothing to compare
4542 $options = (array)$options;
4543 if ( in_array( 'include_old', $options ) ) {
4546 if ( in_array( 'include_new', $options ) ) {
4549 if ( in_array( 'include_both', $options ) ) {
4553 // No DB query needed if $old and $new are the same or successive revisions:
4554 if ( $old->getId() === $new->getId() ) {
4555 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4557 [ $old->getUserText( Revision
::RAW
) ];
4558 } elseif ( $old->getId() === $new->getParentId() ) {
4559 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4560 $authors[] = $old->getUserText( Revision
::RAW
);
4561 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4562 $authors[] = $new->getUserText( Revision
::RAW
);
4564 } elseif ( $old_cmp === '>=' ) {
4565 $authors[] = $old->getUserText( Revision
::RAW
);
4566 } elseif ( $new_cmp === '<=' ) {
4567 $authors[] = $new->getUserText( Revision
::RAW
);
4571 $dbr = wfGetDB( DB_REPLICA
);
4572 $revQuery = Revision
::getQueryInfo();
4573 $authors = $dbr->selectFieldValues(
4574 $revQuery['tables'],
4575 $revQuery['fields']['rev_user_text'],
4577 'rev_page' => $this->getArticleID(),
4578 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4579 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4581 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4588 * Get the number of authors between the given revisions or revision IDs.
4589 * Used for diffs and other things that really need it.
4591 * @param int|Revision $old Old revision or rev ID (first before range by default)
4592 * @param int|Revision $new New revision or rev ID (first after range by default)
4593 * @param int $limit Maximum number of authors
4594 * @param string|array $options (Optional): Single option, or an array of options:
4595 * 'include_old' Include $old in the range; $new is excluded.
4596 * 'include_new' Include $new in the range; $old is excluded.
4597 * 'include_both' Include both $old and $new in the range.
4598 * Unknown option values are ignored.
4599 * @return int Number of revision authors in the range; zero if not both revisions exist
4601 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4602 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4603 return $authors ?
count( $authors ) : 0;
4607 * Compare with another title.
4609 * @param Title $title
4612 public function equals( Title
$title ) {
4613 // Note: === is necessary for proper matching of number-like titles.
4614 return $this->getInterwiki() === $title->getInterwiki()
4615 && $this->getNamespace() == $title->getNamespace()
4616 && $this->getDBkey() === $title->getDBkey();
4620 * Check if this title is a subpage of another title
4622 * @param Title $title
4625 public function isSubpageOf( Title
$title ) {
4626 return $this->getInterwiki() === $title->getInterwiki()
4627 && $this->getNamespace() == $title->getNamespace()
4628 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4632 * Check if page exists. For historical reasons, this function simply
4633 * checks for the existence of the title in the page table, and will
4634 * thus return false for interwiki links, special pages and the like.
4635 * If you want to know if a title can be meaningfully viewed, you should
4636 * probably call the isKnown() method instead.
4638 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4639 * from master/for update
4642 public function exists( $flags = 0 ) {
4643 $exists = $this->getArticleID( $flags ) != 0;
4644 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4649 * Should links to this title be shown as potentially viewable (i.e. as
4650 * "bluelinks"), even if there's no record by this title in the page
4653 * This function is semi-deprecated for public use, as well as somewhat
4654 * misleadingly named. You probably just want to call isKnown(), which
4655 * calls this function internally.
4657 * (ISSUE: Most of these checks are cheap, but the file existence check
4658 * can potentially be quite expensive. Including it here fixes a lot of
4659 * existing code, but we might want to add an optional parameter to skip
4660 * it and any other expensive checks.)
4664 public function isAlwaysKnown() {
4668 * Allows overriding default behavior for determining if a page exists.
4669 * If $isKnown is kept as null, regular checks happen. If it's
4670 * a boolean, this value is returned by the isKnown method.
4674 * @param Title $title
4675 * @param bool|null $isKnown
4677 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4679 if ( !is_null( $isKnown ) ) {
4683 if ( $this->isExternal() ) {
4684 return true; // any interwiki link might be viewable, for all we know
4687 switch ( $this->mNamespace
) {
4690 // file exists, possibly in a foreign repo
4691 return (bool)wfFindFile( $this );
4693 // valid special page
4694 return SpecialPageFactory
::exists( $this->getDBkey() );
4696 // selflink, possibly with fragment
4697 return $this->mDbkeyform
== '';
4699 // known system message
4700 return $this->hasSourceText() !== false;
4707 * Does this title refer to a page that can (or might) be meaningfully
4708 * viewed? In particular, this function may be used to determine if
4709 * links to the title should be rendered as "bluelinks" (as opposed to
4710 * "redlinks" to non-existent pages).
4711 * Adding something else to this function will cause inconsistency
4712 * since LinkHolderArray calls isAlwaysKnown() and does its own
4713 * page existence check.
4717 public function isKnown() {
4718 return $this->isAlwaysKnown() ||
$this->exists();
4722 * Does this page have source text?
4726 public function hasSourceText() {
4727 if ( $this->exists() ) {
4731 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4732 // If the page doesn't exist but is a known system message, default
4733 // message content will be displayed, same for language subpages-
4734 // Use always content language to avoid loading hundreds of languages
4735 // to get the link color.
4737 list( $name, ) = MessageCache
::singleton()->figureMessage(
4738 $wgContLang->lcfirst( $this->getText() )
4740 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4741 return $message->exists();
4748 * Get the default message text or false if the message doesn't exist
4750 * @return string|bool
4752 public function getDefaultMessageText() {
4755 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4759 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4760 $wgContLang->lcfirst( $this->getText() )
4762 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4764 if ( $message->exists() ) {
4765 return $message->plain();
4772 * Updates page_touched for this page; called from LinksUpdate.php
4774 * @param string|null $purgeTime [optional] TS_MW timestamp
4775 * @return bool True if the update succeeded
4777 public function invalidateCache( $purgeTime = null ) {
4778 if ( wfReadOnly() ) {
4780 } elseif ( $this->mArticleID
=== 0 ) {
4781 return true; // avoid gap locking if we know it's not there
4784 $dbw = wfGetDB( DB_MASTER
);
4785 $dbw->onTransactionPreCommitOrIdle(
4787 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4792 $conds = $this->pageCond();
4793 DeferredUpdates
::addUpdate(
4794 new AutoCommitUpdate(
4797 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4798 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4801 [ 'page_touched' => $dbTimestamp ],
4802 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4805 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4808 DeferredUpdates
::PRESEND
4815 * Update page_touched timestamps and send CDN purge messages for
4816 * pages linking to this title. May be sent to the job queue depending
4817 * on the number of links. Typically called on create and delete.
4819 public function touchLinks() {
4820 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4821 if ( $this->getNamespace() == NS_CATEGORY
) {
4822 DeferredUpdates
::addUpdate(
4823 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4829 * Get the last touched timestamp
4831 * @param IDatabase|null $db
4832 * @return string|false Last-touched timestamp
4834 public function getTouched( $db = null ) {
4835 if ( $db === null ) {
4836 $db = wfGetDB( DB_REPLICA
);
4838 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4843 * Get the timestamp when this page was updated since the user last saw it.
4845 * @param User|null $user
4846 * @return string|null
4848 public function getNotificationTimestamp( $user = null ) {
4851 // Assume current user if none given
4855 // Check cache first
4856 $uid = $user->getId();
4860 // avoid isset here, as it'll return false for null entries
4861 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4862 return $this->mNotificationTimestamp
[$uid];
4864 // Don't cache too much!
4865 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4866 $this->mNotificationTimestamp
= [];
4869 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4870 $watchedItem = $store->getWatchedItem( $user, $this );
4871 if ( $watchedItem ) {
4872 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4874 $this->mNotificationTimestamp
[$uid] = false;
4877 return $this->mNotificationTimestamp
[$uid];
4881 * Generate strings used for xml 'id' names in monobook tabs
4883 * @param string $prepend Defaults to 'nstab-'
4884 * @return string XML 'id' name
4886 public function getNamespaceKey( $prepend = 'nstab-' ) {
4888 // Gets the subject namespace of this title
4889 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
4890 // Prefer canonical namespace name for HTML IDs
4891 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4892 if ( $namespaceKey === false ) {
4893 // Fallback to localised text
4894 $namespaceKey = $this->getSubjectNsText();
4896 // Makes namespace key lowercase
4897 $namespaceKey = $wgContLang->lc( $namespaceKey );
4899 if ( $namespaceKey == '' ) {
4900 $namespaceKey = 'main';
4902 // Changes file to image for backwards compatibility
4903 if ( $namespaceKey == 'file' ) {
4904 $namespaceKey = 'image';
4906 return $prepend . $namespaceKey;
4910 * Get all extant redirects to this Title
4912 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4913 * @return Title[] Array of Title redirects to this title
4915 public function getRedirectsHere( $ns = null ) {
4918 $dbr = wfGetDB( DB_REPLICA
);
4920 'rd_namespace' => $this->getNamespace(),
4921 'rd_title' => $this->getDBkey(),
4924 if ( $this->isExternal() ) {
4925 $where['rd_interwiki'] = $this->getInterwiki();
4927 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4929 if ( !is_null( $ns ) ) {
4930 $where['page_namespace'] = $ns;
4933 $res = $dbr->select(
4934 [ 'redirect', 'page' ],
4935 [ 'page_namespace', 'page_title' ],
4940 foreach ( $res as $row ) {
4941 $redirs[] = self
::newFromRow( $row );
4947 * Check if this Title is a valid redirect target
4951 public function isValidRedirectTarget() {
4952 global $wgInvalidRedirectTargets;
4954 if ( $this->isSpecialPage() ) {
4955 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4956 if ( $this->isSpecial( 'Userlogout' ) ) {
4960 foreach ( $wgInvalidRedirectTargets as $target ) {
4961 if ( $this->isSpecial( $target ) ) {
4971 * Get a backlink cache object
4973 * @return BacklinkCache
4975 public function getBacklinkCache() {
4976 return BacklinkCache
::get( $this );
4980 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4984 public function canUseNoindex() {
4985 global $wgExemptFromUserRobotsControl;
4987 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4988 ? MWNamespace
::getContentNamespaces()
4989 : $wgExemptFromUserRobotsControl;
4991 return !in_array( $this->mNamespace
, $bannedNamespaces );
4995 * Returns the raw sort key to be used for categories, with the specified
4996 * prefix. This will be fed to Collation::getSortKey() to get a
4997 * binary sortkey that can be used for actual sorting.
4999 * @param string $prefix The prefix to be used, specified using
5000 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5004 public function getCategorySortkey( $prefix = '' ) {
5005 $unprefixed = $this->getText();
5007 // Anything that uses this hook should only depend
5008 // on the Title object passed in, and should probably
5009 // tell the users to run updateCollations.php --force
5010 // in order to re-sort existing category relations.
5011 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5012 if ( $prefix !== '' ) {
5013 # Separate with a line feed, so the unprefixed part is only used as
5014 # a tiebreaker when two pages have the exact same prefix.
5015 # In UCA, tab is the only character that can sort above LF
5016 # so we strip both of them from the original prefix.
5017 $prefix = strtr( $prefix, "\n\t", ' ' );
5018 return "$prefix\n$unprefixed";
5024 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5025 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5026 * the db, it will return NULL.
5028 * @return string|null|bool
5030 private function getDbPageLanguageCode() {
5031 global $wgPageLanguageUseDB;
5033 // check, if the page language could be saved in the database, and if so and
5034 // the value is not requested already, lookup the page language using LinkCache
5035 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5036 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5037 $linkCache->addLinkObj( $this );
5038 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5041 return $this->mDbPageLanguage
;
5045 * Get the language in which the content of this page is written in
5046 * wikitext. Defaults to $wgContLang, but in certain cases it can be
5047 * e.g. $wgLang (such as special pages, which are in the user language).
5052 public function getPageLanguage() {
5053 global $wgLang, $wgLanguageCode;
5054 if ( $this->isSpecialPage() ) {
5055 // special pages are in the user language
5059 // Checking if DB language is set
5060 $dbPageLanguage = $this->getDbPageLanguageCode();
5061 if ( $dbPageLanguage ) {
5062 return wfGetLangObj( $dbPageLanguage );
5065 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5066 // Note that this may depend on user settings, so the cache should
5067 // be only per-request.
5068 // NOTE: ContentHandler::getPageLanguage() may need to load the
5069 // content to determine the page language!
5070 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5072 $contentHandler = ContentHandler
::getForTitle( $this );
5073 $langObj = $contentHandler->getPageLanguage( $this );
5074 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5076 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5083 * Get the language in which the content of this page is written when
5084 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
5085 * e.g. $wgLang (such as special pages, which are in the user language).
5090 public function getPageViewLanguage() {
5093 if ( $this->isSpecialPage() ) {
5094 // If the user chooses a variant, the content is actually
5095 // in a language whose code is the variant code.
5096 $variant = $wgLang->getPreferredVariant();
5097 if ( $wgLang->getCode() !== $variant ) {
5098 return Language
::factory( $variant );
5104 // Checking if DB language is set
5105 $dbPageLanguage = $this->getDbPageLanguageCode();
5106 if ( $dbPageLanguage ) {
5107 $pageLang = wfGetLangObj( $dbPageLanguage );
5108 $variant = $pageLang->getPreferredVariant();
5109 if ( $pageLang->getCode() !== $variant ) {
5110 $pageLang = Language
::factory( $variant );
5116 // @note Can't be cached persistently, depends on user settings.
5117 // @note ContentHandler::getPageViewLanguage() may need to load the
5118 // content to determine the page language!
5119 $contentHandler = ContentHandler
::getForTitle( $this );
5120 $pageLang = $contentHandler->getPageViewLanguage( $this );
5125 * Get a list of rendered edit notices for this page.
5127 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5128 * they will already be wrapped in paragraphs.
5131 * @param int $oldid Revision ID that's being edited
5134 public function getEditNotices( $oldid = 0 ) {
5137 // Optional notice for the entire namespace
5138 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5139 $msg = wfMessage( $editnotice_ns );
5140 if ( $msg->exists() ) {
5141 $html = $msg->parseAsBlock();
5142 // Edit notices may have complex logic, but output nothing (T91715)
5143 if ( trim( $html ) !== '' ) {
5144 $notices[$editnotice_ns] = Html
::rawElement(
5148 'mw-editnotice-namespace',
5149 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5156 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5157 // Optional notice for page itself and any parent page
5158 $parts = explode( '/', $this->getDBkey() );
5159 $editnotice_base = $editnotice_ns;
5160 while ( count( $parts ) > 0 ) {
5161 $editnotice_base .= '-' . array_shift( $parts );
5162 $msg = wfMessage( $editnotice_base );
5163 if ( $msg->exists() ) {
5164 $html = $msg->parseAsBlock();
5165 if ( trim( $html ) !== '' ) {
5166 $notices[$editnotice_base] = Html
::rawElement(
5170 'mw-editnotice-base',
5171 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5179 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5180 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
5181 $msg = wfMessage( $editnoticeText );
5182 if ( $msg->exists() ) {
5183 $html = $msg->parseAsBlock();
5184 if ( trim( $html ) !== '' ) {
5185 $notices[$editnoticeText] = Html
::rawElement(
5189 'mw-editnotice-page',
5190 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5198 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5205 public function __sleep() {
5213 'mDefaultNamespace',
5217 public function __wakeup() {
5218 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5219 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5220 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );