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
748 if ( $canonicalNamespace ) {
749 $namespace = MWNamespace
::getCanonicalName( $ns );
751 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
753 $name = $namespace == '' ?
$title : "$namespace:$title";
754 if ( strval( $interwiki ) != '' ) {
755 $name = "$interwiki:$name";
757 if ( strval( $fragment ) != '' ) {
758 $name .= '#' . $fragment;
764 * Escape a text fragment, say from a link, for a URL
766 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
768 * @param string $fragment Containing a URL or link fragment (after the "#")
769 * @return string Escaped string
771 static function escapeFragmentForURL( $fragment ) {
772 wfDeprecated( __METHOD__
, '1.30' );
773 # Note that we don't urlencode the fragment. urlencoded Unicode
774 # fragments appear not to work in IE (at least up to 7) or in at least
775 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
776 # to care if they aren't encoded.
777 return Sanitizer
::escapeId( $fragment, 'noninitial' );
781 * Callback for usort() to do title sorts by (namespace, title)
783 * @param LinkTarget $a
784 * @param LinkTarget $b
786 * @return int Result of string comparison, or namespace comparison
788 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
789 return $a->getNamespace() <=> $b->getNamespace()
790 ?
: strcmp( $a->getText(), $b->getText() );
794 * Returns true if the title is valid, false if it is invalid.
796 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
797 * Invalid titles may get returned from makeTitle(), and it may be useful to
798 * allow them to exist, e.g. in order to process log entries about pages in
799 * namespaces that belong to extensions that are no longer installed.
801 * @note This method is relatively expensive. When constructing Title
802 * objects that need to be valid, use an instantiator method that is guaranteed
803 * to return valid titles, such as makeTitleSafe() or newFromText().
807 public function isValid() {
808 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
813 $parser = MediaWikiServices
::getInstance()->getTitleParser();
814 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
816 } catch ( MalformedTitleException
$ex ) {
822 * Determine whether the object refers to a page within
823 * this project (either this wiki or a wiki with a local
824 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
826 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
828 public function isLocal() {
829 if ( $this->isExternal() ) {
830 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
832 return $iw->isLocal();
839 * Is this Title interwiki?
843 public function isExternal() {
844 return $this->mInterwiki
!== '';
848 * Get the interwiki prefix
850 * Use Title::isExternal to check if a interwiki is set
852 * @return string Interwiki prefix
854 public function getInterwiki() {
855 return $this->mInterwiki
;
859 * Was this a local interwiki link?
863 public function wasLocalInterwiki() {
864 return $this->mLocalInterwiki
;
868 * Determine whether the object refers to a page within
869 * this project and is transcludable.
871 * @return bool True if this is transcludable
873 public function isTrans() {
874 if ( !$this->isExternal() ) {
878 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
882 * Returns the DB name of the distant wiki which owns the object.
884 * @return string|false The DB name
886 public function getTransWikiID() {
887 if ( !$this->isExternal() ) {
891 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
895 * Get a TitleValue object representing this Title.
897 * @note Not all valid Titles have a corresponding valid TitleValue
898 * (e.g. TitleValues cannot represent page-local links that have a
899 * fragment but no title text).
901 * @return TitleValue|null
903 public function getTitleValue() {
904 if ( $this->mTitleValue
=== null ) {
906 $this->mTitleValue
= new TitleValue(
912 } catch ( InvalidArgumentException
$ex ) {
913 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
914 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
918 return $this->mTitleValue
;
922 * Get the text form (spaces not underscores) of the main part
924 * @return string Main part of the title
926 public function getText() {
927 return $this->mTextform
;
931 * Get the URL-encoded form of the main part
933 * @return string Main part of the title, URL-encoded
935 public function getPartialURL() {
936 return $this->mUrlform
;
940 * Get the main part with underscores
942 * @return string Main part of the title, with underscores
944 public function getDBkey() {
945 return $this->mDbkeyform
;
949 * Get the DB key with the initial letter case as specified by the user
951 * @return string DB key
953 function getUserCaseDBKey() {
954 if ( !is_null( $this->mUserCaseDBKey
) ) {
955 return $this->mUserCaseDBKey
;
957 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
958 return $this->mDbkeyform
;
963 * Get the namespace index, i.e. one of the NS_xxxx constants.
965 * @return int Namespace index
967 public function getNamespace() {
968 return $this->mNamespace
;
972 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
974 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
975 * @return string Content model id
977 public function getContentModel( $flags = 0 ) {
978 if ( !$this->mForcedContentModel
979 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
980 && $this->getArticleID( $flags )
982 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
983 $linkCache->addLinkObj( $this ); # in case we already had an article ID
984 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
987 if ( !$this->mContentModel
) {
988 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
991 return $this->mContentModel
;
995 * Convenience method for checking a title's content model name
997 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
998 * @return bool True if $this->getContentModel() == $id
1000 public function hasContentModel( $id ) {
1001 return $this->getContentModel() == $id;
1005 * Set a proposed content model for the page for permissions
1006 * checking. This does not actually change the content model
1009 * Additionally, you should make sure you've checked
1010 * ContentHandler::canBeUsedOn() first.
1013 * @param string $model CONTENT_MODEL_XXX constant
1015 public function setContentModel( $model ) {
1016 $this->mContentModel
= $model;
1017 $this->mForcedContentModel
= true;
1021 * Get the namespace text
1023 * @return string|false Namespace text
1025 public function getNsText() {
1026 if ( $this->isExternal() ) {
1027 // This probably shouldn't even happen, except for interwiki transclusion.
1028 // If possible, use the canonical name for the foreign namespace.
1029 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1030 if ( $nsText !== false ) {
1036 $formatter = self
::getTitleFormatter();
1037 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1038 } catch ( InvalidArgumentException
$ex ) {
1039 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1045 * Get the namespace text of the subject (rather than talk) page
1047 * @return string Namespace text
1049 public function getSubjectNsText() {
1050 return MediaWikiServices
::getInstance()->getContentLanguage()->
1051 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1055 * Get the namespace text of the talk page
1057 * @return string Namespace text
1059 public function getTalkNsText() {
1060 return MediaWikiServices
::getInstance()->getContentLanguage()->
1061 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1065 * Can this title have a corresponding talk page?
1067 * @deprecated since 1.30, use canHaveTalkPage() instead.
1069 * @return bool True if this title either is a talk page or can have a talk page associated.
1071 public function canTalk() {
1072 return $this->canHaveTalkPage();
1076 * Can this title have a corresponding talk page?
1078 * @see MWNamespace::hasTalkNamespace
1081 * @return bool True if this title either is a talk page or can have a talk page associated.
1083 public function canHaveTalkPage() {
1084 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1088 * Is this in a namespace that allows actual pages?
1092 public function canExist() {
1093 return $this->mNamespace
>= NS_MAIN
;
1097 * Can this title be added to a user's watchlist?
1101 public function isWatchable() {
1102 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1106 * Returns true if this is a special page.
1110 public function isSpecialPage() {
1111 return $this->mNamespace
== NS_SPECIAL
;
1115 * Returns true if this title resolves to the named special page
1117 * @param string $name The special page name
1120 public function isSpecial( $name ) {
1121 if ( $this->isSpecialPage() ) {
1122 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1123 if ( $name == $thisName ) {
1131 * If the Title refers to a special page alias which is not the local default, resolve
1132 * the alias, and localise the name as necessary. Otherwise, return $this
1136 public function fixSpecialName() {
1137 if ( $this->isSpecialPage() ) {
1138 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1139 if ( $canonicalName ) {
1140 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1141 if ( $localName != $this->mDbkeyform
) {
1142 return self
::makeTitle( NS_SPECIAL
, $localName );
1150 * Returns true if the title is inside the specified namespace.
1152 * Please make use of this instead of comparing to getNamespace()
1153 * This function is much more resistant to changes we may make
1154 * to namespaces than code that makes direct comparisons.
1155 * @param int $ns The namespace
1159 public function inNamespace( $ns ) {
1160 return MWNamespace
::equals( $this->mNamespace
, $ns );
1164 * Returns true if the title is inside one of the specified namespaces.
1166 * @param int|int[] $namespaces,... The namespaces to check for
1170 public function inNamespaces( /* ... */ ) {
1171 $namespaces = func_get_args();
1172 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1173 $namespaces = $namespaces[0];
1176 foreach ( $namespaces as $ns ) {
1177 if ( $this->inNamespace( $ns ) ) {
1186 * Returns true if the title has the same subject namespace as the
1187 * namespace specified.
1188 * For example this method will take NS_USER and return true if namespace
1189 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1190 * as their subject namespace.
1192 * This is MUCH simpler than individually testing for equivalence
1193 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1198 public function hasSubjectNamespace( $ns ) {
1199 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1203 * Is this Title in a namespace which contains content?
1204 * In other words, is this a content page, for the purposes of calculating
1209 public function isContentPage() {
1210 return MWNamespace
::isContent( $this->mNamespace
);
1214 * Would anybody with sufficient privileges be able to move this page?
1215 * Some pages just aren't movable.
1219 public function isMovable() {
1220 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1221 // Interwiki title or immovable namespace. Hooks don't get to override here
1226 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1231 * Is this the mainpage?
1232 * @note Title::newFromText seems to be sufficiently optimized by the title
1233 * cache that we don't need to over-optimize by doing direct comparisons and
1234 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1235 * ends up reporting something differently than $title->isMainPage();
1240 public function isMainPage() {
1241 return $this->equals( self
::newMainPage() );
1245 * Is this a subpage?
1249 public function isSubpage() {
1250 return MWNamespace
::hasSubpages( $this->mNamespace
)
1251 ?
strpos( $this->getText(), '/' ) !== false
1256 * Is this a conversion table for the LanguageConverter?
1260 public function isConversionTable() {
1261 // @todo ConversionTable should become a separate content model.
1263 return $this->mNamespace
== NS_MEDIAWIKI
&&
1264 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1268 * Does that page contain wikitext, or it is JS, CSS or whatever?
1272 public function isWikitextPage() {
1273 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1277 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1278 * global UI. This is generally true for pages in the MediaWiki namespace having
1279 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1281 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1284 * Note that this method should not return true for pages that contain and show
1285 * "inactive" CSS, JSON, or JS.
1290 public function isSiteConfigPage() {
1292 $this->isSiteCssConfigPage()
1293 ||
$this->isSiteJsonConfigPage()
1294 ||
$this->isSiteJsConfigPage()
1300 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1302 public function isCssOrJsPage() {
1303 wfDeprecated( __METHOD__
, '1.31' );
1304 return ( NS_MEDIAWIKI
== $this->mNamespace
1305 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1306 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1310 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1315 public function isUserConfigPage() {
1317 $this->isUserCssConfigPage()
1318 ||
$this->isUserJsonConfigPage()
1319 ||
$this->isUserJsConfigPage()
1325 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1327 public function isCssJsSubpage() {
1328 wfDeprecated( __METHOD__
, '1.31' );
1329 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1330 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1331 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1335 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1337 * @return string Containing skin name from .css, .json, or .js subpage title
1340 public function getSkinFromConfigSubpage() {
1341 $subpage = explode( '/', $this->mTextform
);
1342 $subpage = $subpage[count( $subpage ) - 1];
1343 $lastdot = strrpos( $subpage, '.' );
1344 if ( $lastdot === false ) {
1345 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1347 return substr( $subpage, 0, $lastdot );
1351 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1352 * @return string Containing skin name from .css, .json, or .js subpage title
1354 public function getSkinFromCssJsSubpage() {
1355 wfDeprecated( __METHOD__
, '1.31' );
1356 return $this->getSkinFromConfigSubpage();
1360 * Is this a CSS "config" sub-page of a user page?
1365 public function isUserCssConfigPage() {
1367 NS_USER
== $this->mNamespace
1368 && $this->isSubpage()
1369 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1374 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1377 public function isCssSubpage() {
1378 wfDeprecated( __METHOD__
, '1.31' );
1379 return $this->isUserCssConfigPage();
1383 * Is this a JSON "config" sub-page of a user page?
1388 public function isUserJsonConfigPage() {
1390 NS_USER
== $this->mNamespace
1391 && $this->isSubpage()
1392 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1397 * Is this a JS "config" sub-page of a user page?
1402 public function isUserJsConfigPage() {
1404 NS_USER
== $this->mNamespace
1405 && $this->isSubpage()
1406 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1411 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1414 public function isJsSubpage() {
1415 wfDeprecated( __METHOD__
, '1.31' );
1416 return $this->isUserJsConfigPage();
1420 * Is this a sitewide CSS "config" page?
1425 public function isSiteCssConfigPage() {
1427 NS_MEDIAWIKI
== $this->mNamespace
1429 $this->hasContentModel( CONTENT_MODEL_CSS
)
1430 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1431 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1432 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1438 * Is this a sitewide JSON "config" page?
1443 public function isSiteJsonConfigPage() {
1445 NS_MEDIAWIKI
== $this->mNamespace
1447 $this->hasContentModel( CONTENT_MODEL_JSON
)
1448 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1449 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1450 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1456 * Is this a sitewide JS "config" page?
1461 public function isSiteJsConfigPage() {
1463 NS_MEDIAWIKI
== $this->mNamespace
1465 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1466 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1467 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1468 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1474 * Is this a talk page of some sort?
1478 public function isTalkPage() {
1479 return MWNamespace
::isTalk( $this->mNamespace
);
1483 * Get a Title object associated with the talk page of this article
1485 * @return Title The object for the talk page
1487 public function getTalkPage() {
1488 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1492 * Get a Title object associated with the talk page of this article,
1493 * if such a talk page can exist.
1497 * @return Title|null The object for the talk page,
1498 * or null if no associated talk page can exist, according to canHaveTalkPage().
1500 public function getTalkPageIfDefined() {
1501 if ( !$this->canHaveTalkPage() ) {
1505 return $this->getTalkPage();
1509 * Get a title object associated with the subject page of this
1512 * @return Title The object for the subject page
1514 public function getSubjectPage() {
1515 // Is this the same title?
1516 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1517 if ( $this->mNamespace
== $subjectNS ) {
1520 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1524 * Get the other title for this page, if this is a subject page
1525 * get the talk page, if it is a subject page get the talk page
1528 * @throws MWException If the page doesn't have an other page
1531 public function getOtherPage() {
1532 if ( $this->isSpecialPage() ) {
1533 throw new MWException( 'Special pages cannot have other pages' );
1535 if ( $this->isTalkPage() ) {
1536 return $this->getSubjectPage();
1538 if ( !$this->canHaveTalkPage() ) {
1539 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1541 return $this->getTalkPage();
1546 * Get the default namespace index, for when there is no namespace
1548 * @return int Default namespace index
1550 public function getDefaultNamespace() {
1551 return $this->mDefaultNamespace
;
1555 * Get the Title fragment (i.e.\ the bit after the #) in text form
1557 * Use Title::hasFragment to check for a fragment
1559 * @return string Title fragment
1561 public function getFragment() {
1562 return $this->mFragment
;
1566 * Check if a Title fragment is set
1571 public function hasFragment() {
1572 return $this->mFragment
!== '';
1576 * Get the fragment in URL form, including the "#" character if there is one
1578 * @return string Fragment in URL form
1580 public function getFragmentForURL() {
1581 if ( !$this->hasFragment() ) {
1583 } elseif ( $this->isExternal()
1584 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1586 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1588 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1592 * Set the fragment for this title. Removes the first character from the
1593 * specified fragment before setting, so it assumes you're passing it with
1596 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1597 * or Title::createFragmentTarget().
1598 * Still in active use privately.
1601 * @param string $fragment Text
1603 public function setFragment( $fragment ) {
1604 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1608 * Creates a new Title for a different fragment of the same page.
1611 * @param string $fragment
1614 public function createFragmentTarget( $fragment ) {
1615 return self
::makeTitle(
1624 * Prefix some arbitrary text with the namespace or interwiki prefix
1627 * @param string $name The text
1628 * @return string The prefixed text
1630 private function prefix( $name ) {
1632 if ( $this->isExternal() ) {
1633 $p = $this->mInterwiki
. ':';
1636 if ( 0 != $this->mNamespace
) {
1637 $nsText = $this->getNsText();
1639 if ( $nsText === false ) {
1640 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1641 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1642 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1645 $p .= $nsText . ':';
1651 * Get the prefixed database key form
1653 * @return string The prefixed title, with underscores and
1654 * any interwiki and namespace prefixes
1656 public function getPrefixedDBkey() {
1657 $s = $this->prefix( $this->mDbkeyform
);
1658 $s = strtr( $s, ' ', '_' );
1663 * Get the prefixed title with spaces.
1664 * This is the form usually used for display
1666 * @return string The prefixed title, with spaces
1668 public function getPrefixedText() {
1669 if ( $this->mPrefixedText
=== null ) {
1670 $s = $this->prefix( $this->mTextform
);
1671 $s = strtr( $s, '_', ' ' );
1672 $this->mPrefixedText
= $s;
1674 return $this->mPrefixedText
;
1678 * Return a string representation of this title
1680 * @return string Representation of this title
1682 public function __toString() {
1683 return $this->getPrefixedText();
1687 * Get the prefixed title with spaces, plus any fragment
1688 * (part beginning with '#')
1690 * @return string The prefixed title, with spaces and the fragment, including '#'
1692 public function getFullText() {
1693 $text = $this->getPrefixedText();
1694 if ( $this->hasFragment() ) {
1695 $text .= '#' . $this->mFragment
;
1701 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1705 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1709 * @return string Root name
1712 public function getRootText() {
1713 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1714 return $this->getText();
1717 return strtok( $this->getText(), '/' );
1721 * Get the root page name title, i.e. the leftmost part before any slashes
1725 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1726 * # returns: Title{User:Foo}
1729 * @return Title Root title
1732 public function getRootTitle() {
1733 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1737 * Get the base page name without a namespace, i.e. the part before the subpage name
1741 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1742 * # returns: 'Foo/Bar'
1745 * @return string Base name
1747 public function getBaseText() {
1748 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1749 return $this->getText();
1752 $parts = explode( '/', $this->getText() );
1753 # Don't discard the real title if there's no subpage involved
1754 if ( count( $parts ) > 1 ) {
1755 unset( $parts[count( $parts ) - 1] );
1757 return implode( '/', $parts );
1761 * Get the base page name title, i.e. the part before the subpage name
1765 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1766 * # returns: Title{User:Foo/Bar}
1769 * @return Title Base title
1772 public function getBaseTitle() {
1773 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1777 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1781 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1785 * @return string Subpage name
1787 public function getSubpageText() {
1788 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1789 return $this->mTextform
;
1791 $parts = explode( '/', $this->mTextform
);
1792 return $parts[count( $parts ) - 1];
1796 * Get the title for a subpage of the current page
1800 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1801 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1804 * @param string $text The subpage name to add to the title
1805 * @return Title Subpage title
1808 public function getSubpage( $text ) {
1809 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1813 * Get a URL-encoded form of the subpage text
1815 * @return string URL-encoded subpage name
1817 public function getSubpageUrlForm() {
1818 $text = $this->getSubpageText();
1819 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1824 * Get a URL-encoded title (not an actual URL) including interwiki
1826 * @return string The URL-encoded form
1828 public function getPrefixedURL() {
1829 $s = $this->prefix( $this->mDbkeyform
);
1830 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1835 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1836 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1837 * second argument named variant. This was deprecated in favor
1838 * of passing an array of option with a "variant" key
1839 * Once $query2 is removed for good, this helper can be dropped
1840 * and the wfArrayToCgi moved to getLocalURL();
1842 * @since 1.19 (r105919)
1843 * @param array|string $query
1844 * @param string|string[]|bool $query2
1847 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1848 if ( $query2 !== false ) {
1849 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1850 "method called with a second parameter is deprecated. Add your " .
1851 "parameter to an array passed as the first parameter.", "1.19" );
1853 if ( is_array( $query ) ) {
1854 $query = wfArrayToCgi( $query );
1857 if ( is_string( $query2 ) ) {
1858 // $query2 is a string, we will consider this to be
1859 // a deprecated $variant argument and add it to the query
1860 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1862 $query2 = wfArrayToCgi( $query2 );
1864 // If we have $query content add a & to it first
1868 // Now append the queries together
1875 * Get a real URL referring to this title, with interwiki link and
1878 * @see self::getLocalURL for the arguments.
1880 * @param string|string[] $query
1881 * @param string|string[]|bool $query2
1882 * @param string|int|null $proto Protocol type to use in URL
1883 * @return string The URL
1885 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1886 $query = self
::fixUrlQueryArgs( $query, $query2 );
1888 # Hand off all the decisions on urls to getLocalURL
1889 $url = $this->getLocalURL( $query );
1891 # Expand the url to make it a full url. Note that getLocalURL has the
1892 # potential to output full urls for a variety of reasons, so we use
1893 # wfExpandUrl instead of simply prepending $wgServer
1894 $url = wfExpandUrl( $url, $proto );
1896 # Finally, add the fragment.
1897 $url .= $this->getFragmentForURL();
1898 // Avoid PHP 7.1 warning from passing $this by reference
1900 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1905 * Get a url appropriate for making redirects based on an untrusted url arg
1907 * This is basically the same as getFullUrl(), but in the case of external
1908 * interwikis, we send the user to a landing page, to prevent possible
1909 * phishing attacks and the like.
1911 * @note Uses current protocol by default, since technically relative urls
1912 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1913 * places where the url gets cached, as might pollute between
1914 * https and non-https users.
1915 * @see self::getLocalURL for the arguments.
1916 * @param array|string $query
1917 * @param string $proto Protocol type to use in URL
1918 * @return string A url suitable to use in an HTTP location header.
1920 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1922 if ( $this->isExternal() ) {
1923 $target = SpecialPage
::getTitleFor(
1925 $this->getPrefixedDBkey()
1928 return $target->getFullURL( $query, false, $proto );
1932 * Get a URL with no fragment or server name (relative URL) from a Title object.
1933 * If this page is generated with action=render, however,
1934 * $wgServer is prepended to make an absolute URL.
1936 * @see self::getFullURL to always get an absolute URL.
1937 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1938 * valid to link, locally, to the current Title.
1939 * @see self::newFromText to produce a Title object.
1941 * @param string|string[] $query An optional query string,
1942 * not used for interwiki links. Can be specified as an associative array as well,
1943 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1944 * Some query patterns will trigger various shorturl path replacements.
1945 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1946 * be an array. If a string is passed it will be interpreted as a deprecated
1947 * variant argument and urlencoded into a variant= argument.
1948 * This second query argument will be added to the $query
1949 * The second parameter is deprecated since 1.19. Pass it as a key,value
1950 * pair in the first parameter array instead.
1952 * @return string String of the URL.
1954 public function getLocalURL( $query = '', $query2 = false ) {
1955 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1957 $query = self
::fixUrlQueryArgs( $query, $query2 );
1959 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1961 $namespace = $this->getNsText();
1962 if ( $namespace != '' ) {
1963 # Can this actually happen? Interwikis shouldn't be parsed.
1964 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1967 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1968 $url = wfAppendQuery( $url, $query );
1970 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1971 if ( $query == '' ) {
1972 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1973 // Avoid PHP 7.1 warning from passing $this by reference
1975 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1977 global $wgVariantArticlePath, $wgActionPaths;
1981 if ( !empty( $wgActionPaths )
1982 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1984 $action = urldecode( $matches[2] );
1985 if ( isset( $wgActionPaths[$action] ) ) {
1986 $query = $matches[1];
1987 if ( isset( $matches[4] ) ) {
1988 $query .= $matches[4];
1990 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1991 if ( $query != '' ) {
1992 $url = wfAppendQuery( $url, $query );
1998 && $wgVariantArticlePath
1999 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2000 && $this->getPageLanguage()->equals(
2001 MediaWikiServices
::getInstance()->getContentLanguage() )
2002 && $this->getPageLanguage()->hasVariants()
2004 $variant = urldecode( $matches[1] );
2005 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2006 // Only do the variant replacement if the given variant is a valid
2007 // variant for the page's language.
2008 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2009 $url = str_replace( '$1', $dbkey, $url );
2013 if ( $url === false ) {
2014 if ( $query == '-' ) {
2017 $url = "{$wgScript}?title={$dbkey}&{$query}";
2020 // Avoid PHP 7.1 warning from passing $this by reference
2022 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2024 // @todo FIXME: This causes breakage in various places when we
2025 // actually expected a local URL and end up with dupe prefixes.
2026 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2027 $url = $wgServer . $url;
2030 // Avoid PHP 7.1 warning from passing $this by reference
2032 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2037 * Get a URL that's the simplest URL that will be valid to link, locally,
2038 * to the current Title. It includes the fragment, but does not include
2039 * the server unless action=render is used (or the link is external). If
2040 * there's a fragment but the prefixed text is empty, we just return a link
2043 * The result obviously should not be URL-escaped, but does need to be
2044 * HTML-escaped if it's being output in HTML.
2046 * @param string|string[] $query
2047 * @param bool $query2
2048 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2049 * or false (default) for no expansion
2050 * @see self::getLocalURL for the arguments.
2051 * @return string The URL
2053 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2054 if ( $this->isExternal() ||
$proto !== false ) {
2055 $ret = $this->getFullURL( $query, $query2, $proto );
2056 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2057 $ret = $this->getFragmentForURL();
2059 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2065 * Get the URL form for an internal link.
2066 * - Used in various CDN-related code, in case we have a different
2067 * internal hostname for the server from the exposed one.
2069 * This uses $wgInternalServer to qualify the path, or $wgServer
2070 * if $wgInternalServer is not set. If the server variable used is
2071 * protocol-relative, the URL will be expanded to http://
2073 * @see self::getLocalURL for the arguments.
2074 * @param string $query
2075 * @param string|bool $query2
2076 * @return string The URL
2078 public function getInternalURL( $query = '', $query2 = false ) {
2079 global $wgInternalServer, $wgServer;
2080 $query = self
::fixUrlQueryArgs( $query, $query2 );
2081 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2082 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2083 // Avoid PHP 7.1 warning from passing $this by reference
2085 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2090 * Get the URL for a canonical link, for use in things like IRC and
2091 * e-mail notifications. Uses $wgCanonicalServer and the
2092 * GetCanonicalURL hook.
2094 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2096 * @see self::getLocalURL for the arguments.
2097 * @param string $query
2098 * @param string|bool $query2
2099 * @return string The URL
2102 public function getCanonicalURL( $query = '', $query2 = false ) {
2103 $query = self
::fixUrlQueryArgs( $query, $query2 );
2104 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2105 // Avoid PHP 7.1 warning from passing $this by reference
2107 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2112 * Get the edit URL for this Title
2114 * @return string The URL, or a null string if this is an interwiki link
2116 public function getEditURL() {
2117 if ( $this->isExternal() ) {
2120 $s = $this->getLocalURL( 'action=edit' );
2126 * Can $user perform $action on this page?
2127 * This skips potentially expensive cascading permission checks
2128 * as well as avoids expensive error formatting
2130 * Suitable for use for nonessential UI controls in common cases, but
2131 * _not_ for functional access control.
2133 * May provide false positives, but should never provide a false negative.
2135 * @param string $action Action that permission needs to be checked for
2136 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2139 public function quickUserCan( $action, $user = null ) {
2140 return $this->userCan( $action, $user, false );
2144 * Can $user perform $action on this page?
2146 * @param string $action Action that permission needs to be checked for
2147 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2149 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2152 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2153 if ( !$user instanceof User
) {
2158 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2162 * Can $user perform $action on this page?
2164 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2166 * @param string $action Action that permission needs to be checked for
2167 * @param User $user User to check
2168 * @param string $rigor One of (quick,full,secure)
2169 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2170 * - full : does cheap and expensive checks possibly from a replica DB
2171 * - secure : does cheap and expensive checks, using the master as needed
2172 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2173 * whose corresponding errors may be ignored.
2174 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2176 public function getUserPermissionsErrors(
2177 $action, $user, $rigor = 'secure', $ignoreErrors = []
2179 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2181 // Remove the errors being ignored.
2182 foreach ( $errors as $index => $error ) {
2183 $errKey = is_array( $error ) ?
$error[0] : $error;
2185 if ( in_array( $errKey, $ignoreErrors ) ) {
2186 unset( $errors[$index] );
2188 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2189 unset( $errors[$index] );
2197 * Permissions checks that fail most often, and which are easiest to test.
2199 * @param string $action The action to check
2200 * @param User $user User to check
2201 * @param array $errors List of current errors
2202 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2203 * @param bool $short Short circuit on first error
2205 * @return array List of errors
2207 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2208 if ( !Hooks
::run( 'TitleQuickPermissions',
2209 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2214 if ( $action == 'create' ) {
2216 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2217 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2219 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2221 } elseif ( $action == 'move' ) {
2222 if ( !$user->isAllowed( 'move-rootuserpages' )
2223 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2224 // Show user page-specific message only if the user can move other pages
2225 $errors[] = [ 'cant-move-user-page' ];
2228 // Check if user is allowed to move files if it's a file
2229 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2230 $errors[] = [ 'movenotallowedfile' ];
2233 // Check if user is allowed to move category pages if it's a category page
2234 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2235 $errors[] = [ 'cant-move-category-page' ];
2238 if ( !$user->isAllowed( 'move' ) ) {
2239 // User can't move anything
2240 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2241 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2242 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2243 // custom message if logged-in users without any special rights can move
2244 $errors[] = [ 'movenologintext' ];
2246 $errors[] = [ 'movenotallowed' ];
2249 } elseif ( $action == 'move-target' ) {
2250 if ( !$user->isAllowed( 'move' ) ) {
2251 // User can't move anything
2252 $errors[] = [ 'movenotallowed' ];
2253 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2254 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2255 // Show user page-specific message only if the user can move other pages
2256 $errors[] = [ 'cant-move-to-user-page' ];
2257 } elseif ( !$user->isAllowed( 'move-categorypages' )
2258 && $this->mNamespace
== NS_CATEGORY
) {
2259 // Show category page-specific message only if the user can move other pages
2260 $errors[] = [ 'cant-move-to-category-page' ];
2262 } elseif ( !$user->isAllowed( $action ) ) {
2263 $errors[] = $this->missingPermissionError( $action, $short );
2270 * Add the resulting error code to the errors array
2272 * @param array $errors List of current errors
2273 * @param array $result Result of errors
2275 * @return array List of errors
2277 private function resultToError( $errors, $result ) {
2278 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2279 // A single array representing an error
2280 $errors[] = $result;
2281 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2282 // A nested array representing multiple errors
2283 $errors = array_merge( $errors, $result );
2284 } elseif ( $result !== '' && is_string( $result ) ) {
2285 // A string representing a message-id
2286 $errors[] = [ $result ];
2287 } elseif ( $result instanceof MessageSpecifier
) {
2288 // A message specifier representing an error
2289 $errors[] = [ $result ];
2290 } elseif ( $result === false ) {
2291 // a generic "We don't want them to do that"
2292 $errors[] = [ 'badaccess-group0' ];
2298 * Check various permission hooks
2300 * @param string $action The action to check
2301 * @param User $user User to check
2302 * @param array $errors List of current errors
2303 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2304 * @param bool $short Short circuit on first error
2306 * @return array List of errors
2308 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2309 // Use getUserPermissionsErrors instead
2311 // Avoid PHP 7.1 warning from passing $this by reference
2313 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2314 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2316 // Check getUserPermissionsErrors hook
2317 // Avoid PHP 7.1 warning from passing $this by reference
2319 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2320 $errors = $this->resultToError( $errors, $result );
2322 // Check getUserPermissionsErrorsExpensive hook
2325 && !( $short && count( $errors ) > 0 )
2326 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2328 $errors = $this->resultToError( $errors, $result );
2335 * Check permissions on special pages & namespaces
2337 * @param string $action The action to check
2338 * @param User $user User to check
2339 * @param array $errors List of current errors
2340 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2341 * @param bool $short Short circuit on first error
2343 * @return array List of errors
2345 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2346 # Only 'createaccount' can be performed on special pages,
2347 # which don't actually exist in the DB.
2348 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2349 $errors[] = [ 'ns-specialprotected' ];
2352 # Check $wgNamespaceProtection for restricted namespaces
2353 if ( $this->isNamespaceProtected( $user ) ) {
2354 $ns = $this->mNamespace
== NS_MAIN ?
2355 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2356 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2357 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2364 * Check sitewide CSS/JSON/JS permissions
2366 * @param string $action The action to check
2367 * @param User $user User to check
2368 * @param array $errors List of current errors
2369 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2370 * @param bool $short Short circuit on first error
2372 * @return array List of errors
2374 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2375 if ( $action != 'patrol' ) {
2377 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2378 // editinterface right. That's implemented as a restriction so no check needed here.
2379 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2380 $error = [ 'sitecssprotected', $action ];
2381 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2382 $error = [ 'sitejsonprotected', $action ];
2383 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2384 $error = [ 'sitejsprotected', $action ];
2388 if ( $user->isAllowed( 'editinterface' ) ) {
2389 // Most users / site admins will probably find out about the new, more restrictive
2390 // permissions by failing to edit something. Give them more info.
2391 // TODO remove this a few release cycles after 1.32
2392 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2402 * Check CSS/JSON/JS sub-page permissions
2404 * @param string $action The action to check
2405 * @param User $user User to check
2406 * @param array $errors List of current errors
2407 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2408 * @param bool $short Short circuit on first error
2410 * @return array List of errors
2412 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2413 # Protect css/json/js subpages of user pages
2414 # XXX: this might be better using restrictions
2416 if ( $action != 'patrol' ) {
2417 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2419 $this->isUserCssConfigPage()
2420 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2422 $errors[] = [ 'mycustomcssprotected', $action ];
2424 $this->isUserJsonConfigPage()
2425 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2427 $errors[] = [ 'mycustomjsonprotected', $action ];
2429 $this->isUserJsConfigPage()
2430 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2432 $errors[] = [ 'mycustomjsprotected', $action ];
2436 $this->isUserCssConfigPage()
2437 && !$user->isAllowed( 'editusercss' )
2439 $errors[] = [ 'customcssprotected', $action ];
2441 $this->isUserJsonConfigPage()
2442 && !$user->isAllowed( 'edituserjson' )
2444 $errors[] = [ 'customjsonprotected', $action ];
2446 $this->isUserJsConfigPage()
2447 && !$user->isAllowed( 'edituserjs' )
2449 $errors[] = [ 'customjsprotected', $action ];
2458 * Check against page_restrictions table requirements on this
2459 * page. The user must possess all required rights for this
2462 * @param string $action The action to check
2463 * @param User $user User to check
2464 * @param array $errors List of current errors
2465 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2466 * @param bool $short Short circuit on first error
2468 * @return array List of errors
2470 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2471 foreach ( $this->getRestrictions( $action ) as $right ) {
2472 // Backwards compatibility, rewrite sysop -> editprotected
2473 if ( $right == 'sysop' ) {
2474 $right = 'editprotected';
2476 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2477 if ( $right == 'autoconfirmed' ) {
2478 $right = 'editsemiprotected';
2480 if ( $right == '' ) {
2483 if ( !$user->isAllowed( $right ) ) {
2484 $errors[] = [ 'protectedpagetext', $right, $action ];
2485 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2486 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2494 * Check restrictions on cascading pages.
2496 * @param string $action The action to check
2497 * @param User $user User to check
2498 * @param array $errors List of current errors
2499 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2500 * @param bool $short Short circuit on first error
2502 * @return array List of errors
2504 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2505 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2506 # We /could/ use the protection level on the source page, but it's
2507 # fairly ugly as we have to establish a precedence hierarchy for pages
2508 # included by multiple cascade-protected pages. So just restrict
2509 # it to people with 'protect' permission, as they could remove the
2510 # protection anyway.
2511 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2512 # Cascading protection depends on more than this page...
2513 # Several cascading protected pages may include this page...
2514 # Check each cascading level
2515 # This is only for protection restrictions, not for all actions
2516 if ( isset( $restrictions[$action] ) ) {
2517 foreach ( $restrictions[$action] as $right ) {
2518 // Backwards compatibility, rewrite sysop -> editprotected
2519 if ( $right == 'sysop' ) {
2520 $right = 'editprotected';
2522 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2523 if ( $right == 'autoconfirmed' ) {
2524 $right = 'editsemiprotected';
2526 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2528 foreach ( $cascadingSources as $page ) {
2529 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2531 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2541 * Check action permissions not already checked in checkQuickPermissions
2543 * @param string $action The action to check
2544 * @param User $user User to check
2545 * @param array $errors List of current errors
2546 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2547 * @param bool $short Short circuit on first error
2549 * @return array List of errors
2551 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2552 global $wgDeleteRevisionsLimit, $wgLang;
2554 if ( $action == 'protect' ) {
2555 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2556 // If they can't edit, they shouldn't protect.
2557 $errors[] = [ 'protect-cantedit' ];
2559 } elseif ( $action == 'create' ) {
2560 $title_protection = $this->getTitleProtection();
2561 if ( $title_protection ) {
2562 if ( $title_protection['permission'] == ''
2563 ||
!$user->isAllowed( $title_protection['permission'] )
2567 User
::whoIs( $title_protection['user'] ),
2568 $title_protection['reason']
2572 } elseif ( $action == 'move' ) {
2573 // Check for immobile pages
2574 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2575 // Specific message for this case
2576 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2577 } elseif ( !$this->isMovable() ) {
2578 // Less specific message for rarer cases
2579 $errors[] = [ 'immobile-source-page' ];
2581 } elseif ( $action == 'move-target' ) {
2582 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2583 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2584 } elseif ( !$this->isMovable() ) {
2585 $errors[] = [ 'immobile-target-page' ];
2587 } elseif ( $action == 'delete' ) {
2588 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2589 if ( !$tempErrors ) {
2590 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2591 $user, $tempErrors, $rigor, true );
2593 if ( $tempErrors ) {
2594 // If protection keeps them from editing, they shouldn't be able to delete.
2595 $errors[] = [ 'deleteprotected' ];
2597 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2598 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2600 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2602 } elseif ( $action === 'undelete' ) {
2603 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2604 // Undeleting implies editing
2605 $errors[] = [ 'undelete-cantedit' ];
2607 if ( !$this->exists()
2608 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2610 // Undeleting where nothing currently exists implies creating
2611 $errors[] = [ 'undelete-cantcreate' ];
2618 * Check that the user isn't blocked from editing.
2620 * @param string $action The action to check
2621 * @param User $user User to check
2622 * @param array $errors List of current errors
2623 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2624 * @param bool $short Short circuit on first error
2626 * @return array List of errors
2628 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2629 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2630 // Account creation blocks handled at userlogin.
2631 // Unblocking handled in SpecialUnblock
2632 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2636 // Optimize for a very common case
2637 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2641 if ( $wgEmailConfirmToEdit
2642 && !$user->isEmailConfirmed()
2643 && $action === 'edit'
2645 $errors[] = [ 'confirmedittext' ];
2648 $useSlave = ( $rigor !== 'secure' );
2649 if ( ( $action == 'edit' ||
$action == 'create' )
2650 && !$user->isBlockedFrom( $this, $useSlave )
2652 // Don't block the user from editing their own talk page unless they've been
2653 // explicitly blocked from that too.
2654 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2655 // @todo FIXME: Pass the relevant context into this function.
2656 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2663 * Check that the user is allowed to read this page.
2665 * @param string $action The action to check
2666 * @param User $user User to check
2667 * @param array $errors List of current errors
2668 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2669 * @param bool $short Short circuit on first error
2671 * @return array List of errors
2673 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2674 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2676 $whitelisted = false;
2677 if ( User
::isEveryoneAllowed( 'read' ) ) {
2678 # Shortcut for public wikis, allows skipping quite a bit of code
2679 $whitelisted = true;
2680 } elseif ( $user->isAllowed( 'read' ) ) {
2681 # If the user is allowed to read pages, he is allowed to read all pages
2682 $whitelisted = true;
2683 } elseif ( $this->isSpecial( 'Userlogin' )
2684 ||
$this->isSpecial( 'PasswordReset' )
2685 ||
$this->isSpecial( 'Userlogout' )
2687 # Always grant access to the login page.
2688 # Even anons need to be able to log in.
2689 $whitelisted = true;
2690 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2691 # Time to check the whitelist
2692 # Only do these checks is there's something to check against
2693 $name = $this->getPrefixedText();
2694 $dbName = $this->getPrefixedDBkey();
2696 // Check for explicit whitelisting with and without underscores
2697 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2698 $whitelisted = true;
2699 } elseif ( $this->mNamespace
== NS_MAIN
) {
2700 # Old settings might have the title prefixed with
2701 # a colon for main-namespace pages
2702 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2703 $whitelisted = true;
2705 } elseif ( $this->isSpecialPage() ) {
2706 # If it's a special page, ditch the subpage bit and check again
2707 $name = $this->mDbkeyform
;
2708 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2710 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2711 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2712 $whitelisted = true;
2718 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2719 $name = $this->getPrefixedText();
2720 // Check for regex whitelisting
2721 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2722 if ( preg_match( $listItem, $name ) ) {
2723 $whitelisted = true;
2729 if ( !$whitelisted ) {
2730 # If the title is not whitelisted, give extensions a chance to do so...
2731 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2732 if ( !$whitelisted ) {
2733 $errors[] = $this->missingPermissionError( $action, $short );
2741 * Get a description array when the user doesn't have the right to perform
2742 * $action (i.e. when User::isAllowed() returns false)
2744 * @param string $action The action to check
2745 * @param bool $short Short circuit on first error
2746 * @return array Array containing an error message key and any parameters
2748 private function missingPermissionError( $action, $short ) {
2749 // We avoid expensive display logic for quickUserCan's and such
2751 return [ 'badaccess-group0' ];
2754 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2758 * Can $user perform $action on this page? This is an internal function,
2759 * with multiple levels of checks depending on performance needs; see $rigor below.
2760 * It does not check wfReadOnly().
2762 * @param string $action Action that permission needs to be checked for
2763 * @param User $user User to check
2764 * @param string $rigor One of (quick,full,secure)
2765 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2766 * - full : does cheap and expensive checks possibly from a replica DB
2767 * - secure : does cheap and expensive checks, using the master as needed
2768 * @param bool $short Set this to true to stop after the first permission error.
2769 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2771 protected function getUserPermissionsErrorsInternal(
2772 $action, $user, $rigor = 'secure', $short = false
2774 if ( $rigor === true ) {
2775 $rigor = 'secure'; // b/c
2776 } elseif ( $rigor === false ) {
2777 $rigor = 'quick'; // b/c
2778 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2779 throw new Exception( "Invalid rigor parameter '$rigor'." );
2782 # Read has special handling
2783 if ( $action == 'read' ) {
2785 'checkPermissionHooks',
2786 'checkReadPermissions',
2787 'checkUserBlock', // for wgBlockDisablesLogin
2789 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2790 # or checkUserConfigPermissions here as it will lead to duplicate
2791 # error messages. This is okay to do since anywhere that checks for
2792 # create will also check for edit, and those checks are called for edit.
2793 } elseif ( $action == 'create' ) {
2795 'checkQuickPermissions',
2796 'checkPermissionHooks',
2797 'checkPageRestrictions',
2798 'checkCascadingSourcesRestrictions',
2799 'checkActionPermissions',
2804 'checkQuickPermissions',
2805 'checkPermissionHooks',
2806 'checkSpecialsAndNSPermissions',
2807 'checkSiteConfigPermissions',
2808 'checkUserConfigPermissions',
2809 'checkPageRestrictions',
2810 'checkCascadingSourcesRestrictions',
2811 'checkActionPermissions',
2817 while ( count( $checks ) > 0 &&
2818 !( $short && count( $errors ) > 0 ) ) {
2819 $method = array_shift( $checks );
2820 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2827 * Get a filtered list of all restriction types supported by this wiki.
2828 * @param bool $exists True to get all restriction types that apply to
2829 * titles that do exist, False for all restriction types that apply to
2830 * titles that do not exist
2833 public static function getFilteredRestrictionTypes( $exists = true ) {
2834 global $wgRestrictionTypes;
2835 $types = $wgRestrictionTypes;
2837 # Remove the create restriction for existing titles
2838 $types = array_diff( $types, [ 'create' ] );
2840 # Only the create and upload restrictions apply to non-existing titles
2841 $types = array_intersect( $types, [ 'create', 'upload' ] );
2847 * Returns restriction types for the current Title
2849 * @return array Applicable restriction types
2851 public function getRestrictionTypes() {
2852 if ( $this->isSpecialPage() ) {
2856 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2858 if ( $this->mNamespace
!= NS_FILE
) {
2859 # Remove the upload restriction for non-file titles
2860 $types = array_diff( $types, [ 'upload' ] );
2863 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2865 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2866 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2872 * Is this title subject to title protection?
2873 * Title protection is the one applied against creation of such title.
2875 * @return array|bool An associative array representing any existent title
2876 * protection, or false if there's none.
2878 public function getTitleProtection() {
2879 $protection = $this->getTitleProtectionInternal();
2880 if ( $protection ) {
2881 if ( $protection['permission'] == 'sysop' ) {
2882 $protection['permission'] = 'editprotected'; // B/C
2884 if ( $protection['permission'] == 'autoconfirmed' ) {
2885 $protection['permission'] = 'editsemiprotected'; // B/C
2892 * Fetch title protection settings
2894 * To work correctly, $this->loadRestrictions() needs to have access to the
2895 * actual protections in the database without munging 'sysop' =>
2896 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2897 * callers probably want $this->getTitleProtection() instead.
2899 * @return array|bool
2901 protected function getTitleProtectionInternal() {
2902 // Can't protect pages in special namespaces
2903 if ( $this->mNamespace
< 0 ) {
2907 // Can't protect pages that exist.
2908 if ( $this->exists() ) {
2912 if ( $this->mTitleProtection
=== null ) {
2913 $dbr = wfGetDB( DB_REPLICA
);
2914 $commentStore = CommentStore
::getStore();
2915 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2916 $res = $dbr->select(
2917 [ 'protected_titles' ] +
$commentQuery['tables'],
2919 'user' => 'pt_user',
2920 'expiry' => 'pt_expiry',
2921 'permission' => 'pt_create_perm'
2922 ] +
$commentQuery['fields'],
2923 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2926 $commentQuery['joins']
2929 // fetchRow returns false if there are no rows.
2930 $row = $dbr->fetchRow( $res );
2932 $this->mTitleProtection
= [
2933 'user' => $row['user'],
2934 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2935 'permission' => $row['permission'],
2936 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2939 $this->mTitleProtection
= false;
2942 return $this->mTitleProtection
;
2946 * Remove any title protection due to page existing
2948 public function deleteTitleProtection() {
2949 $dbw = wfGetDB( DB_MASTER
);
2953 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2956 $this->mTitleProtection
= false;
2960 * Is this page "semi-protected" - the *only* protection levels are listed
2961 * in $wgSemiprotectedRestrictionLevels?
2963 * @param string $action Action to check (default: edit)
2966 public function isSemiProtected( $action = 'edit' ) {
2967 global $wgSemiprotectedRestrictionLevels;
2969 $restrictions = $this->getRestrictions( $action );
2970 $semi = $wgSemiprotectedRestrictionLevels;
2971 if ( !$restrictions ||
!$semi ) {
2972 // Not protected, or all protection is full protection
2976 // Remap autoconfirmed to editsemiprotected for BC
2977 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2978 $semi[$key] = 'editsemiprotected';
2980 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2981 $restrictions[$key] = 'editsemiprotected';
2984 return !array_diff( $restrictions, $semi );
2988 * Does the title correspond to a protected article?
2990 * @param string $action The action the page is protected from,
2991 * by default checks all actions.
2994 public function isProtected( $action = '' ) {
2995 global $wgRestrictionLevels;
2997 $restrictionTypes = $this->getRestrictionTypes();
2999 # Special pages have inherent protection
3000 if ( $this->isSpecialPage() ) {
3004 # Check regular protection levels
3005 foreach ( $restrictionTypes as $type ) {
3006 if ( $action == $type ||
$action == '' ) {
3007 $r = $this->getRestrictions( $type );
3008 foreach ( $wgRestrictionLevels as $level ) {
3009 if ( in_array( $level, $r ) && $level != '' ) {
3020 * Determines if $user is unable to edit this page because it has been protected
3021 * by $wgNamespaceProtection.
3023 * @param User $user User object to check permissions
3026 public function isNamespaceProtected( User
$user ) {
3027 global $wgNamespaceProtection;
3029 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3030 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3031 if ( $right != '' && !$user->isAllowed( $right ) ) {
3040 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3042 * @return bool If the page is subject to cascading restrictions.
3044 public function isCascadeProtected() {
3045 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3046 return ( $sources > 0 );
3050 * Determines whether cascading protection sources have already been loaded from
3053 * @param bool $getPages True to check if the pages are loaded, or false to check
3054 * if the status is loaded.
3055 * @return bool Whether or not the specified information has been loaded
3058 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3059 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3063 * Cascading protection: Get the source of any cascading restrictions on this page.
3065 * @param bool $getPages Whether or not to retrieve the actual pages
3066 * that the restrictions have come from and the actual restrictions
3068 * @return array Two elements: First is an array of Title objects of the
3069 * pages from which cascading restrictions have come, false for
3070 * none, or true if such restrictions exist but $getPages was not
3071 * set. Second is an array like that returned by
3072 * Title::getAllRestrictions(), or an empty array if $getPages is
3075 public function getCascadeProtectionSources( $getPages = true ) {
3076 $pagerestrictions = [];
3078 if ( $this->mCascadeSources
!== null && $getPages ) {
3079 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3080 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3081 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3084 $dbr = wfGetDB( DB_REPLICA
);
3086 if ( $this->mNamespace
== NS_FILE
) {
3087 $tables = [ 'imagelinks', 'page_restrictions' ];
3089 'il_to' => $this->mDbkeyform
,
3094 $tables = [ 'templatelinks', 'page_restrictions' ];
3096 'tl_namespace' => $this->mNamespace
,
3097 'tl_title' => $this->mDbkeyform
,
3104 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3105 'pr_expiry', 'pr_type', 'pr_level' ];
3106 $where_clauses[] = 'page_id=pr_page';
3109 $cols = [ 'pr_expiry' ];
3112 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3114 $sources = $getPages ?
[] : false;
3115 $now = wfTimestampNow();
3117 foreach ( $res as $row ) {
3118 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3119 if ( $expiry > $now ) {
3121 $page_id = $row->pr_page
;
3122 $page_ns = $row->page_namespace
;
3123 $page_title = $row->page_title
;
3124 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3125 # Add groups needed for each restriction type if its not already there
3126 # Make sure this restriction type still exists
3128 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3129 $pagerestrictions[$row->pr_type
] = [];
3133 isset( $pagerestrictions[$row->pr_type
] )
3134 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3136 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3145 $this->mCascadeSources
= $sources;
3146 $this->mCascadingRestrictions
= $pagerestrictions;
3148 $this->mHasCascadingRestrictions
= $sources;
3151 return [ $sources, $pagerestrictions ];
3155 * Accessor for mRestrictionsLoaded
3157 * @return bool Whether or not the page's restrictions have already been
3158 * loaded from the database
3161 public function areRestrictionsLoaded() {
3162 return $this->mRestrictionsLoaded
;
3166 * Accessor/initialisation for mRestrictions
3168 * @param string $action Action that permission needs to be checked for
3169 * @return array Restriction levels needed to take the action. All levels are
3170 * required. Note that restriction levels are normally user rights, but 'sysop'
3171 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3172 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3174 public function getRestrictions( $action ) {
3175 if ( !$this->mRestrictionsLoaded
) {
3176 $this->loadRestrictions();
3178 return $this->mRestrictions
[$action] ??
[];
3182 * Accessor/initialisation for mRestrictions
3184 * @return array Keys are actions, values are arrays as returned by
3185 * Title::getRestrictions()
3188 public function getAllRestrictions() {
3189 if ( !$this->mRestrictionsLoaded
) {
3190 $this->loadRestrictions();
3192 return $this->mRestrictions
;
3196 * Get the expiry time for the restriction against a given action
3198 * @param string $action
3199 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3200 * or not protected at all, or false if the action is not recognised.
3202 public function getRestrictionExpiry( $action ) {
3203 if ( !$this->mRestrictionsLoaded
) {
3204 $this->loadRestrictions();
3206 return $this->mRestrictionsExpiry
[$action] ??
false;
3210 * Returns cascading restrictions for the current article
3214 function areRestrictionsCascading() {
3215 if ( !$this->mRestrictionsLoaded
) {
3216 $this->loadRestrictions();
3219 return $this->mCascadeRestriction
;
3223 * Compiles list of active page restrictions from both page table (pre 1.10)
3224 * and page_restrictions table for this existing page.
3225 * Public for usage by LiquidThreads.
3227 * @param array $rows Array of db result objects
3228 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3229 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3230 * Edit and move sections are separated by a colon
3231 * Example: "edit=autoconfirmed,sysop:move=sysop"
3233 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3234 $dbr = wfGetDB( DB_REPLICA
);
3236 $restrictionTypes = $this->getRestrictionTypes();
3238 foreach ( $restrictionTypes as $type ) {
3239 $this->mRestrictions
[$type] = [];
3240 $this->mRestrictionsExpiry
[$type] = 'infinity';
3243 $this->mCascadeRestriction
= false;
3245 # Backwards-compatibility: also load the restrictions from the page record (old format).
3246 if ( $oldFashionedRestrictions !== null ) {
3247 $this->mOldRestrictions
= $oldFashionedRestrictions;
3250 if ( $this->mOldRestrictions
=== false ) {
3251 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3252 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3255 if ( $this->mOldRestrictions
!= '' ) {
3256 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3257 $temp = explode( '=', trim( $restrict ) );
3258 if ( count( $temp ) == 1 ) {
3259 // old old format should be treated as edit/move restriction
3260 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3261 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3263 $restriction = trim( $temp[1] );
3264 if ( $restriction != '' ) { // some old entries are empty
3265 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3271 if ( count( $rows ) ) {
3272 # Current system - load second to make them override.
3273 $now = wfTimestampNow();
3275 # Cycle through all the restrictions.
3276 foreach ( $rows as $row ) {
3277 // Don't take care of restrictions types that aren't allowed
3278 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3282 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3284 // Only apply the restrictions if they haven't expired!
3285 if ( !$expiry ||
$expiry > $now ) {
3286 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3287 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3289 $this->mCascadeRestriction |
= $row->pr_cascade
;
3294 $this->mRestrictionsLoaded
= true;
3298 * Load restrictions from the page_restrictions table
3300 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3301 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3302 * Edit and move sections are separated by a colon
3303 * Example: "edit=autoconfirmed,sysop:move=sysop"
3305 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3306 if ( $this->mRestrictionsLoaded
) {
3310 $id = $this->getArticleID();
3312 $cache = ObjectCache
::getMainWANInstance();
3313 $rows = $cache->getWithSetCallback(
3314 // Page protections always leave a new null revision
3315 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3317 function ( $curValue, &$ttl, array &$setOpts ) {
3318 $dbr = wfGetDB( DB_REPLICA
);
3320 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3322 return iterator_to_array(
3324 'page_restrictions',
3325 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3326 [ 'pr_page' => $this->getArticleID() ],
3333 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3335 $title_protection = $this->getTitleProtectionInternal();
3337 if ( $title_protection ) {
3338 $now = wfTimestampNow();
3339 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3341 if ( !$expiry ||
$expiry > $now ) {
3342 // Apply the restrictions
3343 $this->mRestrictionsExpiry
['create'] = $expiry;
3344 $this->mRestrictions
['create'] =
3345 explode( ',', trim( $title_protection['permission'] ) );
3346 } else { // Get rid of the old restrictions
3347 $this->mTitleProtection
= false;
3350 $this->mRestrictionsExpiry
['create'] = 'infinity';
3352 $this->mRestrictionsLoaded
= true;
3357 * Flush the protection cache in this object and force reload from the database.
3358 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3360 public function flushRestrictions() {
3361 $this->mRestrictionsLoaded
= false;
3362 $this->mTitleProtection
= null;
3366 * Purge expired restrictions from the page_restrictions table
3368 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3370 static function purgeExpiredRestrictions() {
3371 if ( wfReadOnly() ) {
3375 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3376 wfGetDB( DB_MASTER
),
3378 function ( IDatabase
$dbw, $fname ) {
3379 $config = MediaWikiServices
::getInstance()->getMainConfig();
3380 $ids = $dbw->selectFieldValues(
3381 'page_restrictions',
3383 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3385 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3388 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3393 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3394 wfGetDB( DB_MASTER
),
3396 function ( IDatabase
$dbw, $fname ) {
3399 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3407 * Does this have subpages? (Warning, usually requires an extra DB query.)
3411 public function hasSubpages() {
3412 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3417 # We dynamically add a member variable for the purpose of this method
3418 # alone to cache the result. There's no point in having it hanging
3419 # around uninitialized in every Title object; therefore we only add it
3420 # if needed and don't declare it statically.
3421 if ( $this->mHasSubpages
=== null ) {
3422 $this->mHasSubpages
= false;
3423 $subpages = $this->getSubpages( 1 );
3424 if ( $subpages instanceof TitleArray
) {
3425 $this->mHasSubpages
= (bool)$subpages->count();
3429 return $this->mHasSubpages
;
3433 * Get all subpages of this page.
3435 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3436 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3437 * doesn't allow subpages
3439 public function getSubpages( $limit = -1 ) {
3440 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3444 $dbr = wfGetDB( DB_REPLICA
);
3445 $conds['page_namespace'] = $this->mNamespace
;
3446 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3448 if ( $limit > -1 ) {
3449 $options['LIMIT'] = $limit;
3451 return TitleArray
::newFromResult(
3452 $dbr->select( 'page',
3453 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3462 * Is there a version of this page in the deletion archive?
3464 * @return int The number of archived revisions
3466 public function isDeleted() {
3467 if ( $this->mNamespace
< 0 ) {
3470 $dbr = wfGetDB( DB_REPLICA
);
3472 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3473 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3476 if ( $this->mNamespace
== NS_FILE
) {
3477 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3478 [ 'fa_name' => $this->mDbkeyform
],
3487 * Is there a version of this page in the deletion archive?
3491 public function isDeletedQuick() {
3492 if ( $this->mNamespace
< 0 ) {
3495 $dbr = wfGetDB( DB_REPLICA
);
3496 $deleted = (bool)$dbr->selectField( 'archive', '1',
3497 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3500 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3501 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3502 [ 'fa_name' => $this->mDbkeyform
],
3510 * Get the article ID for this Title from the link cache,
3511 * adding it if necessary
3513 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3515 * @return int The ID
3517 public function getArticleID( $flags = 0 ) {
3518 if ( $this->mNamespace
< 0 ) {
3519 $this->mArticleID
= 0;
3520 return $this->mArticleID
;
3522 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3523 if ( $flags & self
::GAID_FOR_UPDATE
) {
3524 $oldUpdate = $linkCache->forUpdate( true );
3525 $linkCache->clearLink( $this );
3526 $this->mArticleID
= $linkCache->addLinkObj( $this );
3527 $linkCache->forUpdate( $oldUpdate );
3529 if ( -1 == $this->mArticleID
) {
3530 $this->mArticleID
= $linkCache->addLinkObj( $this );
3533 return $this->mArticleID
;
3537 * Is this an article that is a redirect page?
3538 * Uses link cache, adding it if necessary
3540 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3543 public function isRedirect( $flags = 0 ) {
3544 if ( !is_null( $this->mRedirect
) ) {
3545 return $this->mRedirect
;
3547 if ( !$this->getArticleID( $flags ) ) {
3548 $this->mRedirect
= false;
3549 return $this->mRedirect
;
3552 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3553 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3554 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3555 if ( $cached === null ) {
3556 # Trust LinkCache's state over our own
3557 # LinkCache is telling us that the page doesn't exist, despite there being cached
3558 # data relating to an existing page in $this->mArticleID. Updaters should clear
3559 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3560 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3561 # LinkCache to refresh its data from the master.
3562 $this->mRedirect
= false;
3563 return $this->mRedirect
;
3566 $this->mRedirect
= (bool)$cached;
3568 return $this->mRedirect
;
3572 * What is the length of this page?
3573 * Uses link cache, adding it if necessary
3575 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3578 public function getLength( $flags = 0 ) {
3579 if ( $this->mLength
!= -1 ) {
3580 return $this->mLength
;
3582 if ( !$this->getArticleID( $flags ) ) {
3584 return $this->mLength
;
3586 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3587 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3588 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3589 if ( $cached === null ) {
3590 # Trust LinkCache's state over our own, as for isRedirect()
3592 return $this->mLength
;
3595 $this->mLength
= intval( $cached );
3597 return $this->mLength
;
3601 * What is the page_latest field for this page?
3603 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3604 * @return int Int or 0 if the page doesn't exist
3606 public function getLatestRevID( $flags = 0 ) {
3607 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3608 return intval( $this->mLatestID
);
3610 if ( !$this->getArticleID( $flags ) ) {
3611 $this->mLatestID
= 0;
3612 return $this->mLatestID
;
3614 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3615 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3616 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3617 if ( $cached === null ) {
3618 # Trust LinkCache's state over our own, as for isRedirect()
3619 $this->mLatestID
= 0;
3620 return $this->mLatestID
;
3623 $this->mLatestID
= intval( $cached );
3625 return $this->mLatestID
;
3629 * This clears some fields in this object, and clears any associated
3630 * keys in the "bad links" section of the link cache.
3632 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3633 * loading of the new page_id. It's also called from
3634 * WikiPage::doDeleteArticleReal()
3636 * @param int $newid The new Article ID
3638 public function resetArticleID( $newid ) {
3639 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3640 $linkCache->clearLink( $this );
3642 if ( $newid === false ) {
3643 $this->mArticleID
= -1;
3645 $this->mArticleID
= intval( $newid );
3647 $this->mRestrictionsLoaded
= false;
3648 $this->mRestrictions
= [];
3649 $this->mOldRestrictions
= false;
3650 $this->mRedirect
= null;
3651 $this->mLength
= -1;
3652 $this->mLatestID
= false;
3653 $this->mContentModel
= false;
3654 $this->mEstimateRevisions
= null;
3655 $this->mPageLanguage
= false;
3656 $this->mDbPageLanguage
= false;
3657 $this->mIsBigDeletion
= null;
3660 public static function clearCaches() {
3661 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3662 $linkCache->clear();
3664 $titleCache = self
::getTitleCache();
3665 $titleCache->clear();
3669 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3671 * @param string $text Containing title to capitalize
3672 * @param int $ns Namespace index, defaults to NS_MAIN
3673 * @return string Containing capitalized title
3675 public static function capitalize( $text, $ns = NS_MAIN
) {
3676 if ( MWNamespace
::isCapitalized( $ns ) ) {
3677 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3684 * Secure and split - main initialisation function for this object
3686 * Assumes that mDbkeyform has been set, and is urldecoded
3687 * and uses underscores, but not otherwise munged. This function
3688 * removes illegal characters, splits off the interwiki and
3689 * namespace prefixes, sets the other forms, and canonicalizes
3692 * @throws MalformedTitleException On invalid titles
3693 * @return bool True on success
3695 private function secureAndSplit() {
3696 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3697 // the parsing code with Title, while avoiding massive refactoring.
3698 // @todo: get rid of secureAndSplit, refactor parsing code.
3699 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3700 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3701 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3702 // MalformedTitleException can be thrown here
3703 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3706 $this->setFragment( '#' . $parts['fragment'] );
3707 $this->mInterwiki
= $parts['interwiki'];
3708 $this->mLocalInterwiki
= $parts['local_interwiki'];
3709 $this->mNamespace
= $parts['namespace'];
3710 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3712 $this->mDbkeyform
= $parts['dbkey'];
3713 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3714 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3716 # We already know that some pages won't be in the database!
3717 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3718 $this->mArticleID
= 0;
3725 * Get an array of Title objects linking to this Title
3726 * Also stores the IDs in the link cache.
3728 * WARNING: do not use this function on arbitrary user-supplied titles!
3729 * On heavily-used templates it will max out the memory.
3731 * @param array $options May be FOR UPDATE
3732 * @param string $table Table name
3733 * @param string $prefix Fields prefix
3734 * @return Title[] Array of Title objects linking here
3736 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3737 if ( count( $options ) > 0 ) {
3738 $db = wfGetDB( DB_MASTER
);
3740 $db = wfGetDB( DB_REPLICA
);
3745 self
::getSelectFields(),
3747 "{$prefix}_from=page_id",
3748 "{$prefix}_namespace" => $this->mNamespace
,
3749 "{$prefix}_title" => $this->mDbkeyform
],
3755 if ( $res->numRows() ) {
3756 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3757 foreach ( $res as $row ) {
3758 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3760 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3761 $retVal[] = $titleObj;
3769 * Get an array of Title objects using this Title as a template
3770 * Also stores the IDs in the link cache.
3772 * WARNING: do not use this function on arbitrary user-supplied titles!
3773 * On heavily-used templates it will max out the memory.
3775 * @param array $options Query option to Database::select()
3776 * @return Title[] Array of Title the Title objects linking here
3778 public function getTemplateLinksTo( $options = [] ) {
3779 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3783 * Get an array of Title objects linked from this Title
3784 * Also stores the IDs in the link cache.
3786 * WARNING: do not use this function on arbitrary user-supplied titles!
3787 * On heavily-used templates it will max out the memory.
3789 * @param array $options Query option to Database::select()
3790 * @param string $table Table name
3791 * @param string $prefix Fields prefix
3792 * @return array Array of Title objects linking here
3794 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3795 $id = $this->getArticleID();
3797 # If the page doesn't exist; there can't be any link from this page
3802 $db = wfGetDB( DB_REPLICA
);
3804 $blNamespace = "{$prefix}_namespace";
3805 $blTitle = "{$prefix}_title";
3807 $pageQuery = WikiPage
::getQueryInfo();
3809 [ $table, 'nestpage' => $pageQuery['tables'] ],
3811 [ $blNamespace, $blTitle ],
3812 $pageQuery['fields']
3814 [ "{$prefix}_from" => $id ],
3819 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3820 ] ] +
$pageQuery['joins']
3824 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3825 foreach ( $res as $row ) {
3826 if ( $row->page_id
) {
3827 $titleObj = self
::newFromRow( $row );
3829 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3830 $linkCache->addBadLinkObj( $titleObj );
3832 $retVal[] = $titleObj;
3839 * Get an array of Title objects used on this Title as a template
3840 * Also stores the IDs in the link cache.
3842 * WARNING: do not use this function on arbitrary user-supplied titles!
3843 * On heavily-used templates it will max out the memory.
3845 * @param array $options May be FOR UPDATE
3846 * @return Title[] Array of Title the Title objects used here
3848 public function getTemplateLinksFrom( $options = [] ) {
3849 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3853 * Get an array of Title objects referring to non-existent articles linked
3856 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3857 * should use redirect table in this case).
3858 * @return Title[] Array of Title the Title objects
3860 public function getBrokenLinksFrom() {
3861 if ( $this->getArticleID() == 0 ) {
3862 # All links from article ID 0 are false positives
3866 $dbr = wfGetDB( DB_REPLICA
);
3867 $res = $dbr->select(
3868 [ 'page', 'pagelinks' ],
3869 [ 'pl_namespace', 'pl_title' ],
3871 'pl_from' => $this->getArticleID(),
3872 'page_namespace IS NULL'
3878 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3884 foreach ( $res as $row ) {
3885 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3891 * Get a list of URLs to purge from the CDN cache when this
3894 * @return string[] Array of String the URLs
3896 public function getCdnUrls() {
3898 $this->getInternalURL(),
3899 $this->getInternalURL( 'action=history' )
3902 $pageLang = $this->getPageLanguage();
3903 if ( $pageLang->hasVariants() ) {
3904 $variants = $pageLang->getVariants();
3905 foreach ( $variants as $vCode ) {
3906 $urls[] = $this->getInternalURL( $vCode );
3910 // If we are looking at a css/js user subpage, purge the action=raw.
3911 if ( $this->isUserJsConfigPage() ) {
3912 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3913 } elseif ( $this->isUserJsonConfigPage() ) {
3914 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3915 } elseif ( $this->isUserCssConfigPage() ) {
3916 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3919 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3924 * @deprecated since 1.27 use getCdnUrls()
3926 public function getSquidURLs() {
3927 return $this->getCdnUrls();
3931 * Purge all applicable CDN URLs
3933 public function purgeSquid() {
3934 DeferredUpdates
::addUpdate(
3935 new CdnCacheUpdate( $this->getCdnUrls() ),
3936 DeferredUpdates
::PRESEND
3941 * Check whether a given move operation would be valid.
3942 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3944 * @deprecated since 1.25, use MovePage's methods instead
3945 * @param Title &$nt The new title
3946 * @param bool $auth Whether to check user permissions (uses $wgUser)
3947 * @param string $reason Is the log summary of the move, used for spam checking
3948 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3950 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3953 if ( !( $nt instanceof Title
) ) {
3954 // Normally we'd add this to $errors, but we'll get
3955 // lots of syntax errors if $nt is not an object
3956 return [ [ 'badtitletext' ] ];
3959 $mp = new MovePage( $this, $nt );
3960 $errors = $mp->isValidMove()->getErrorsArray();
3962 $errors = wfMergeErrorArrays(
3964 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3968 return $errors ?
: true;
3972 * Check if the requested move target is a valid file move target
3973 * @todo move this to MovePage
3974 * @param Title $nt Target title
3975 * @return array List of errors
3977 protected function validateFileMoveOperation( $nt ) {
3982 $destFile = wfLocalFile( $nt );
3983 $destFile->load( File
::READ_LATEST
);
3984 if ( !$wgUser->isAllowed( 'reupload-shared' )
3985 && !$destFile->exists() && wfFindFile( $nt )
3987 $errors[] = [ 'file-exists-sharedrepo' ];
3994 * Move a title to a new location
3996 * @deprecated since 1.25, use the MovePage class instead
3997 * @param Title &$nt The new title
3998 * @param bool $auth Indicates whether $wgUser's permissions
4000 * @param string $reason The reason for the move
4001 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4002 * Ignored if the user doesn't have the suppressredirect right.
4003 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4004 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4006 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4007 array $changeTags = []
4010 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4011 if ( is_array( $err ) ) {
4012 // Auto-block user's IP if the account was "hard" blocked
4013 $wgUser->spreadAnyEditBlock();
4016 // Check suppressredirect permission
4017 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4018 $createRedirect = true;
4021 $mp = new MovePage( $this, $nt );
4022 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4023 if ( $status->isOK() ) {
4026 return $status->getErrorsArray();
4031 * Move this page's subpages to be subpages of $nt
4033 * @param Title $nt Move target
4034 * @param bool $auth Whether $wgUser's permissions should be checked
4035 * @param string $reason The reason for the move
4036 * @param bool $createRedirect Whether to create redirects from the old subpages to
4037 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4038 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4039 * @return array Array with old page titles as keys, and strings (new page titles) or
4040 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4041 * getUserPermissionsErrors()-like error array with numeric indices if
4042 * no pages were moved
4044 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4045 array $changeTags = []
4047 global $wgMaximumMovedPages;
4048 // Check permissions
4049 if ( !$this->userCan( 'move-subpages' ) ) {
4051 [ 'cant-move-subpages' ],
4054 // Do the source and target namespaces support subpages?
4055 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4057 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4060 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4062 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4066 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4069 foreach ( $subpages as $oldSubpage ) {
4071 if ( $count > $wgMaximumMovedPages ) {
4072 $retval[$oldSubpage->getPrefixedText()] = [
4073 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4078 // We don't know whether this function was called before
4079 // or after moving the root page, so check both
4081 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4082 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4084 // When moving a page to a subpage of itself,
4085 // don't move it twice
4088 $newPageName = preg_replace(
4089 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4090 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4091 $oldSubpage->getDBkey() );
4092 if ( $oldSubpage->isTalkPage() ) {
4093 $newNs = $nt->getTalkPage()->getNamespace();
4095 $newNs = $nt->getSubjectPage()->getNamespace();
4097 # T16385: we need makeTitleSafe because the new page names may
4098 # be longer than 255 characters.
4099 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4101 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4102 if ( $success === true ) {
4103 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4105 $retval[$oldSubpage->getPrefixedText()] = $success;
4112 * Checks if this page is just a one-rev redirect.
4113 * Adds lock, so don't use just for light purposes.
4117 public function isSingleRevRedirect() {
4118 global $wgContentHandlerUseDB;
4120 $dbw = wfGetDB( DB_MASTER
);
4123 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4124 if ( $wgContentHandlerUseDB ) {
4125 $fields[] = 'page_content_model';
4128 $row = $dbw->selectRow( 'page',
4134 # Cache some fields we may want
4135 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4136 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4137 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4138 $this->mContentModel
= $row && isset( $row->page_content_model
)
4139 ?
strval( $row->page_content_model
)
4142 if ( !$this->mRedirect
) {
4145 # Does the article have a history?
4146 $row = $dbw->selectField( [ 'page', 'revision' ],
4148 [ 'page_namespace' => $this->mNamespace
,
4149 'page_title' => $this->mDbkeyform
,
4151 'page_latest != rev_id'
4156 # Return true if there was no history
4157 return ( $row === false );
4161 * Checks if $this can be moved to a given Title
4162 * - Selects for update, so don't call it unless you mean business
4164 * @deprecated since 1.25, use MovePage's methods instead
4165 * @param Title $nt The new title to check
4168 public function isValidMoveTarget( $nt ) {
4169 # Is it an existing file?
4170 if ( $nt->getNamespace() == NS_FILE
) {
4171 $file = wfLocalFile( $nt );
4172 $file->load( File
::READ_LATEST
);
4173 if ( $file->exists() ) {
4174 wfDebug( __METHOD__
. ": file exists\n" );
4178 # Is it a redirect with no history?
4179 if ( !$nt->isSingleRevRedirect() ) {
4180 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4183 # Get the article text
4184 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4185 if ( !is_object( $rev ) ) {
4188 $content = $rev->getContent();
4189 # Does the redirect point to the source?
4190 # Or is it a broken self-redirect, usually caused by namespace collisions?
4191 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4193 if ( $redirTitle ) {
4194 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4195 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4196 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4202 # Fail safe (not a redirect after all. strange.)
4203 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4204 " is a redirect, but it doesn't contain a valid redirect.\n" );
4210 * Get categories to which this Title belongs and return an array of
4211 * categories' names.
4213 * @return array Array of parents in the form:
4214 * $parent => $currentarticle
4216 public function getParentCategories() {
4219 $titleKey = $this->getArticleID();
4221 if ( $titleKey === 0 ) {
4225 $dbr = wfGetDB( DB_REPLICA
);
4227 $res = $dbr->select(
4230 [ 'cl_from' => $titleKey ],
4234 if ( $res->numRows() > 0 ) {
4235 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4236 foreach ( $res as $row ) {
4237 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4238 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4239 $this->getFullText();
4246 * Get a tree of parent categories
4248 * @param array $children Array with the children in the keys, to check for circular refs
4249 * @return array Tree of parent categories
4251 public function getParentCategoryTree( $children = [] ) {
4253 $parents = $this->getParentCategories();
4256 foreach ( $parents as $parent => $current ) {
4257 if ( array_key_exists( $parent, $children ) ) {
4258 # Circular reference
4259 $stack[$parent] = [];
4261 $nt = self
::newFromText( $parent );
4263 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4273 * Get an associative array for selecting this title from
4276 * @return array Array suitable for the $where parameter of DB::select()
4278 public function pageCond() {
4279 if ( $this->mArticleID
> 0 ) {
4280 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4281 return [ 'page_id' => $this->mArticleID
];
4283 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4288 * Get next/previous revision ID relative to another revision ID
4289 * @param int $revId Revision ID. Get the revision that was before this one.
4290 * @param int $flags Title::GAID_FOR_UPDATE
4291 * @param string $dir 'next' or 'prev'
4292 * @return int|bool New revision ID, or false if none exists
4294 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4295 $revId = (int)$revId;
4296 if ( $dir === 'next' ) {
4299 } elseif ( $dir === 'prev' ) {
4303 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4306 if ( $flags & self
::GAID_FOR_UPDATE
) {
4307 $db = wfGetDB( DB_MASTER
);
4309 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4312 // Intentionally not caring if the specified revision belongs to this
4313 // page. We only care about the timestamp.
4314 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4315 if ( $ts === false ) {
4316 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4317 if ( $ts === false ) {
4318 // Or should this throw an InvalidArgumentException or something?
4322 $ts = $db->addQuotes( $ts );
4324 $revId = $db->selectField( 'revision', 'rev_id',
4326 'rev_page' => $this->getArticleID( $flags ),
4327 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4331 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4332 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4336 if ( $revId === false ) {
4339 return intval( $revId );
4344 * Get the revision ID of the previous revision
4346 * @param int $revId Revision ID. Get the revision that was before this one.
4347 * @param int $flags Title::GAID_FOR_UPDATE
4348 * @return int|bool Old revision ID, or false if none exists
4350 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4351 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4355 * Get the revision ID of the next revision
4357 * @param int $revId Revision ID. Get the revision that was after this one.
4358 * @param int $flags Title::GAID_FOR_UPDATE
4359 * @return int|bool Next revision ID, or false if none exists
4361 public function getNextRevisionID( $revId, $flags = 0 ) {
4362 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4366 * Get the first revision of the page
4368 * @param int $flags Title::GAID_FOR_UPDATE
4369 * @return Revision|null If page doesn't exist
4371 public function getFirstRevision( $flags = 0 ) {
4372 $pageId = $this->getArticleID( $flags );
4374 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4375 $revQuery = Revision
::getQueryInfo();
4376 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4377 [ 'rev_page' => $pageId ],
4380 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4381 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4386 return new Revision( $row );
4393 * Get the oldest revision timestamp of this page
4395 * @param int $flags Title::GAID_FOR_UPDATE
4396 * @return string MW timestamp
4398 public function getEarliestRevTime( $flags = 0 ) {
4399 $rev = $this->getFirstRevision( $flags );
4400 return $rev ?
$rev->getTimestamp() : null;
4404 * Check if this is a new page
4408 public function isNewPage() {
4409 $dbr = wfGetDB( DB_REPLICA
);
4410 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4414 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4418 public function isBigDeletion() {
4419 global $wgDeleteRevisionsLimit;
4421 if ( !$wgDeleteRevisionsLimit ) {
4425 if ( $this->mIsBigDeletion
=== null ) {
4426 $dbr = wfGetDB( DB_REPLICA
);
4428 $revCount = $dbr->selectRowCount(
4431 [ 'rev_page' => $this->getArticleID() ],
4433 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4436 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4439 return $this->mIsBigDeletion
;
4443 * Get the approximate revision count of this page.
4447 public function estimateRevisionCount() {
4448 if ( !$this->exists() ) {
4452 if ( $this->mEstimateRevisions
=== null ) {
4453 $dbr = wfGetDB( DB_REPLICA
);
4454 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4455 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4458 return $this->mEstimateRevisions
;
4462 * Get the number of revisions between the given revision.
4463 * Used for diffs and other things that really need it.
4465 * @param int|Revision $old Old revision or rev ID (first before range)
4466 * @param int|Revision $new New revision or rev ID (first after range)
4467 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4468 * @return int Number of revisions between these revisions.
4470 public function countRevisionsBetween( $old, $new, $max = null ) {
4471 if ( !( $old instanceof Revision
) ) {
4472 $old = Revision
::newFromTitle( $this, (int)$old );
4474 if ( !( $new instanceof Revision
) ) {
4475 $new = Revision
::newFromTitle( $this, (int)$new );
4477 if ( !$old ||
!$new ) {
4478 return 0; // nothing to compare
4480 $dbr = wfGetDB( DB_REPLICA
);
4482 'rev_page' => $this->getArticleID(),
4483 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4484 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4486 if ( $max !== null ) {
4487 return $dbr->selectRowCount( 'revision', '1',
4490 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4493 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4498 * Get the authors between the given revisions or revision IDs.
4499 * Used for diffs and other things that really need it.
4503 * @param int|Revision $old Old revision or rev ID (first before range by default)
4504 * @param int|Revision $new New revision or rev ID (first after range by default)
4505 * @param int $limit Maximum number of authors
4506 * @param string|array $options (Optional): Single option, or an array of options:
4507 * 'include_old' Include $old in the range; $new is excluded.
4508 * 'include_new' Include $new in the range; $old is excluded.
4509 * 'include_both' Include both $old and $new in the range.
4510 * Unknown option values are ignored.
4511 * @return array|null Names of revision authors in the range; null if not both revisions exist
4513 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4514 if ( !( $old instanceof Revision
) ) {
4515 $old = Revision
::newFromTitle( $this, (int)$old );
4517 if ( !( $new instanceof Revision
) ) {
4518 $new = Revision
::newFromTitle( $this, (int)$new );
4520 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4521 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4522 // in the sanity check below?
4523 if ( !$old ||
!$new ) {
4524 return null; // nothing to compare
4529 $options = (array)$options;
4530 if ( in_array( 'include_old', $options ) ) {
4533 if ( in_array( 'include_new', $options ) ) {
4536 if ( in_array( 'include_both', $options ) ) {
4540 // No DB query needed if $old and $new are the same or successive revisions:
4541 if ( $old->getId() === $new->getId() ) {
4542 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4544 [ $old->getUserText( Revision
::RAW
) ];
4545 } elseif ( $old->getId() === $new->getParentId() ) {
4546 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4547 $authors[] = $old->getUserText( Revision
::RAW
);
4548 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4549 $authors[] = $new->getUserText( Revision
::RAW
);
4551 } elseif ( $old_cmp === '>=' ) {
4552 $authors[] = $old->getUserText( Revision
::RAW
);
4553 } elseif ( $new_cmp === '<=' ) {
4554 $authors[] = $new->getUserText( Revision
::RAW
);
4558 $dbr = wfGetDB( DB_REPLICA
);
4559 $revQuery = Revision
::getQueryInfo();
4560 $authors = $dbr->selectFieldValues(
4561 $revQuery['tables'],
4562 $revQuery['fields']['rev_user_text'],
4564 'rev_page' => $this->getArticleID(),
4565 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4566 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4568 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4575 * Get the number of authors between the given revisions or revision IDs.
4576 * Used for diffs and other things that really need it.
4578 * @param int|Revision $old Old revision or rev ID (first before range by default)
4579 * @param int|Revision $new New revision or rev ID (first after range by default)
4580 * @param int $limit Maximum number of authors
4581 * @param string|array $options (Optional): Single option, or an array of options:
4582 * 'include_old' Include $old in the range; $new is excluded.
4583 * 'include_new' Include $new in the range; $old is excluded.
4584 * 'include_both' Include both $old and $new in the range.
4585 * Unknown option values are ignored.
4586 * @return int Number of revision authors in the range; zero if not both revisions exist
4588 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4589 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4590 return $authors ?
count( $authors ) : 0;
4594 * Compare with another title.
4596 * @param Title $title
4599 public function equals( Title
$title ) {
4600 // Note: === is necessary for proper matching of number-like titles.
4601 return $this->mInterwiki
=== $title->mInterwiki
4602 && $this->mNamespace
== $title->mNamespace
4603 && $this->mDbkeyform
=== $title->mDbkeyform
;
4607 * Check if this title is a subpage of another title
4609 * @param Title $title
4612 public function isSubpageOf( Title
$title ) {
4613 return $this->mInterwiki
=== $title->mInterwiki
4614 && $this->mNamespace
== $title->mNamespace
4615 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4619 * Check if page exists. For historical reasons, this function simply
4620 * checks for the existence of the title in the page table, and will
4621 * thus return false for interwiki links, special pages and the like.
4622 * If you want to know if a title can be meaningfully viewed, you should
4623 * probably call the isKnown() method instead.
4625 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4626 * from master/for update
4629 public function exists( $flags = 0 ) {
4630 $exists = $this->getArticleID( $flags ) != 0;
4631 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4636 * Should links to this title be shown as potentially viewable (i.e. as
4637 * "bluelinks"), even if there's no record by this title in the page
4640 * This function is semi-deprecated for public use, as well as somewhat
4641 * misleadingly named. You probably just want to call isKnown(), which
4642 * calls this function internally.
4644 * (ISSUE: Most of these checks are cheap, but the file existence check
4645 * can potentially be quite expensive. Including it here fixes a lot of
4646 * existing code, but we might want to add an optional parameter to skip
4647 * it and any other expensive checks.)
4651 public function isAlwaysKnown() {
4655 * Allows overriding default behavior for determining if a page exists.
4656 * If $isKnown is kept as null, regular checks happen. If it's
4657 * a boolean, this value is returned by the isKnown method.
4661 * @param Title $title
4662 * @param bool|null $isKnown
4664 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4666 if ( !is_null( $isKnown ) ) {
4670 if ( $this->isExternal() ) {
4671 return true; // any interwiki link might be viewable, for all we know
4674 switch ( $this->mNamespace
) {
4677 // file exists, possibly in a foreign repo
4678 return (bool)wfFindFile( $this );
4680 // valid special page
4681 return SpecialPageFactory
::exists( $this->mDbkeyform
);
4683 // selflink, possibly with fragment
4684 return $this->mDbkeyform
== '';
4686 // known system message
4687 return $this->hasSourceText() !== false;
4694 * Does this title refer to a page that can (or might) be meaningfully
4695 * viewed? In particular, this function may be used to determine if
4696 * links to the title should be rendered as "bluelinks" (as opposed to
4697 * "redlinks" to non-existent pages).
4698 * Adding something else to this function will cause inconsistency
4699 * since LinkHolderArray calls isAlwaysKnown() and does its own
4700 * page existence check.
4704 public function isKnown() {
4705 return $this->isAlwaysKnown() ||
$this->exists();
4709 * Does this page have source text?
4713 public function hasSourceText() {
4714 if ( $this->exists() ) {
4718 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4719 // If the page doesn't exist but is a known system message, default
4720 // message content will be displayed, same for language subpages-
4721 // Use always content language to avoid loading hundreds of languages
4722 // to get the link color.
4723 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4724 list( $name, ) = MessageCache
::singleton()->figureMessage(
4725 $contLang->lcfirst( $this->getText() )
4727 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4728 return $message->exists();
4735 * Get the default message text or false if the message doesn't exist
4737 * @return string|bool
4739 public function getDefaultMessageText() {
4740 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4744 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4745 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4747 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4749 if ( $message->exists() ) {
4750 return $message->plain();
4757 * Updates page_touched for this page; called from LinksUpdate.php
4759 * @param string|null $purgeTime [optional] TS_MW timestamp
4760 * @return bool True if the update succeeded
4762 public function invalidateCache( $purgeTime = null ) {
4763 if ( wfReadOnly() ) {
4765 } elseif ( $this->mArticleID
=== 0 ) {
4766 return true; // avoid gap locking if we know it's not there
4769 $dbw = wfGetDB( DB_MASTER
);
4770 $dbw->onTransactionPreCommitOrIdle(
4772 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4777 $conds = $this->pageCond();
4778 DeferredUpdates
::addUpdate(
4779 new AutoCommitUpdate(
4782 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4783 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4786 [ 'page_touched' => $dbTimestamp ],
4787 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4790 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4793 DeferredUpdates
::PRESEND
4800 * Update page_touched timestamps and send CDN purge messages for
4801 * pages linking to this title. May be sent to the job queue depending
4802 * on the number of links. Typically called on create and delete.
4804 public function touchLinks() {
4805 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4806 if ( $this->mNamespace
== NS_CATEGORY
) {
4807 DeferredUpdates
::addUpdate(
4808 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4814 * Get the last touched timestamp
4816 * @param IDatabase|null $db
4817 * @return string|false Last-touched timestamp
4819 public function getTouched( $db = null ) {
4820 if ( $db === null ) {
4821 $db = wfGetDB( DB_REPLICA
);
4823 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4828 * Get the timestamp when this page was updated since the user last saw it.
4830 * @param User|null $user
4831 * @return string|null
4833 public function getNotificationTimestamp( $user = null ) {
4836 // Assume current user if none given
4840 // Check cache first
4841 $uid = $user->getId();
4845 // avoid isset here, as it'll return false for null entries
4846 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4847 return $this->mNotificationTimestamp
[$uid];
4849 // Don't cache too much!
4850 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4851 $this->mNotificationTimestamp
= [];
4854 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4855 $watchedItem = $store->getWatchedItem( $user, $this );
4856 if ( $watchedItem ) {
4857 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4859 $this->mNotificationTimestamp
[$uid] = false;
4862 return $this->mNotificationTimestamp
[$uid];
4866 * Generate strings used for xml 'id' names in monobook tabs
4868 * @param string $prepend Defaults to 'nstab-'
4869 * @return string XML 'id' name
4871 public function getNamespaceKey( $prepend = 'nstab-' ) {
4872 // Gets the subject namespace of this title
4873 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4874 // Prefer canonical namespace name for HTML IDs
4875 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4876 if ( $namespaceKey === false ) {
4877 // Fallback to localised text
4878 $namespaceKey = $this->getSubjectNsText();
4880 // Makes namespace key lowercase
4881 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4883 if ( $namespaceKey == '' ) {
4884 $namespaceKey = 'main';
4886 // Changes file to image for backwards compatibility
4887 if ( $namespaceKey == 'file' ) {
4888 $namespaceKey = 'image';
4890 return $prepend . $namespaceKey;
4894 * Get all extant redirects to this Title
4896 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4897 * @return Title[] Array of Title redirects to this title
4899 public function getRedirectsHere( $ns = null ) {
4902 $dbr = wfGetDB( DB_REPLICA
);
4904 'rd_namespace' => $this->mNamespace
,
4905 'rd_title' => $this->mDbkeyform
,
4908 if ( $this->isExternal() ) {
4909 $where['rd_interwiki'] = $this->mInterwiki
;
4911 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4913 if ( !is_null( $ns ) ) {
4914 $where['page_namespace'] = $ns;
4917 $res = $dbr->select(
4918 [ 'redirect', 'page' ],
4919 [ 'page_namespace', 'page_title' ],
4924 foreach ( $res as $row ) {
4925 $redirs[] = self
::newFromRow( $row );
4931 * Check if this Title is a valid redirect target
4935 public function isValidRedirectTarget() {
4936 global $wgInvalidRedirectTargets;
4938 if ( $this->isSpecialPage() ) {
4939 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4940 if ( $this->isSpecial( 'Userlogout' ) ) {
4944 foreach ( $wgInvalidRedirectTargets as $target ) {
4945 if ( $this->isSpecial( $target ) ) {
4955 * Get a backlink cache object
4957 * @return BacklinkCache
4959 public function getBacklinkCache() {
4960 return BacklinkCache
::get( $this );
4964 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4968 public function canUseNoindex() {
4969 global $wgExemptFromUserRobotsControl;
4971 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4972 ? MWNamespace
::getContentNamespaces()
4973 : $wgExemptFromUserRobotsControl;
4975 return !in_array( $this->mNamespace
, $bannedNamespaces );
4979 * Returns the raw sort key to be used for categories, with the specified
4980 * prefix. This will be fed to Collation::getSortKey() to get a
4981 * binary sortkey that can be used for actual sorting.
4983 * @param string $prefix The prefix to be used, specified using
4984 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4988 public function getCategorySortkey( $prefix = '' ) {
4989 $unprefixed = $this->getText();
4991 // Anything that uses this hook should only depend
4992 // on the Title object passed in, and should probably
4993 // tell the users to run updateCollations.php --force
4994 // in order to re-sort existing category relations.
4995 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4996 if ( $prefix !== '' ) {
4997 # Separate with a line feed, so the unprefixed part is only used as
4998 # a tiebreaker when two pages have the exact same prefix.
4999 # In UCA, tab is the only character that can sort above LF
5000 # so we strip both of them from the original prefix.
5001 $prefix = strtr( $prefix, "\n\t", ' ' );
5002 return "$prefix\n$unprefixed";
5008 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5009 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5010 * the db, it will return NULL.
5012 * @return string|null|bool
5014 private function getDbPageLanguageCode() {
5015 global $wgPageLanguageUseDB;
5017 // check, if the page language could be saved in the database, and if so and
5018 // the value is not requested already, lookup the page language using LinkCache
5019 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5020 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5021 $linkCache->addLinkObj( $this );
5022 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5025 return $this->mDbPageLanguage
;
5029 * Get the language in which the content of this page is written in
5030 * wikitext. Defaults to content language, but in certain cases it can be
5031 * e.g. $wgLang (such as special pages, which are in the user language).
5036 public function getPageLanguage() {
5037 global $wgLang, $wgLanguageCode;
5038 if ( $this->isSpecialPage() ) {
5039 // special pages are in the user language
5043 // Checking if DB language is set
5044 $dbPageLanguage = $this->getDbPageLanguageCode();
5045 if ( $dbPageLanguage ) {
5046 return wfGetLangObj( $dbPageLanguage );
5049 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5050 // Note that this may depend on user settings, so the cache should
5051 // be only per-request.
5052 // NOTE: ContentHandler::getPageLanguage() may need to load the
5053 // content to determine the page language!
5054 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5056 $contentHandler = ContentHandler
::getForTitle( $this );
5057 $langObj = $contentHandler->getPageLanguage( $this );
5058 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5060 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5067 * Get the language in which the content of this page is written when
5068 * viewed by user. Defaults to content language, but in certain cases it can be
5069 * e.g. $wgLang (such as special pages, which are in the user language).
5074 public function getPageViewLanguage() {
5077 if ( $this->isSpecialPage() ) {
5078 // If the user chooses a variant, the content is actually
5079 // in a language whose code is the variant code.
5080 $variant = $wgLang->getPreferredVariant();
5081 if ( $wgLang->getCode() !== $variant ) {
5082 return Language
::factory( $variant );
5088 // Checking if DB language is set
5089 $dbPageLanguage = $this->getDbPageLanguageCode();
5090 if ( $dbPageLanguage ) {
5091 $pageLang = wfGetLangObj( $dbPageLanguage );
5092 $variant = $pageLang->getPreferredVariant();
5093 if ( $pageLang->getCode() !== $variant ) {
5094 $pageLang = Language
::factory( $variant );
5100 // @note Can't be cached persistently, depends on user settings.
5101 // @note ContentHandler::getPageViewLanguage() may need to load the
5102 // content to determine the page language!
5103 $contentHandler = ContentHandler
::getForTitle( $this );
5104 $pageLang = $contentHandler->getPageViewLanguage( $this );
5109 * Get a list of rendered edit notices for this page.
5111 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5112 * they will already be wrapped in paragraphs.
5115 * @param int $oldid Revision ID that's being edited
5118 public function getEditNotices( $oldid = 0 ) {
5121 // Optional notice for the entire namespace
5122 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5123 $msg = wfMessage( $editnotice_ns );
5124 if ( $msg->exists() ) {
5125 $html = $msg->parseAsBlock();
5126 // Edit notices may have complex logic, but output nothing (T91715)
5127 if ( trim( $html ) !== '' ) {
5128 $notices[$editnotice_ns] = Html
::rawElement(
5132 'mw-editnotice-namespace',
5133 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5140 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5141 // Optional notice for page itself and any parent page
5142 $parts = explode( '/', $this->mDbkeyform
);
5143 $editnotice_base = $editnotice_ns;
5144 while ( count( $parts ) > 0 ) {
5145 $editnotice_base .= '-' . array_shift( $parts );
5146 $msg = wfMessage( $editnotice_base );
5147 if ( $msg->exists() ) {
5148 $html = $msg->parseAsBlock();
5149 if ( trim( $html ) !== '' ) {
5150 $notices[$editnotice_base] = Html
::rawElement(
5154 'mw-editnotice-base',
5155 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5163 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5164 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5165 $msg = wfMessage( $editnoticeText );
5166 if ( $msg->exists() ) {
5167 $html = $msg->parseAsBlock();
5168 if ( trim( $html ) !== '' ) {
5169 $notices[$editnoticeText] = Html
::rawElement(
5173 'mw-editnotice-page',
5174 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5182 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5189 public function __sleep() {
5197 'mDefaultNamespace',
5201 public function __wakeup() {
5202 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5203 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5204 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );