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 $ns = $this->getNamespace();
810 if ( !MWNamespace
::exists( $ns ) ) {
815 $parser = MediaWikiServices
::getInstance()->getTitleParser();
816 $parser->parseTitle( $this->getDBkey(), $ns );
818 } catch ( MalformedTitleException
$ex ) {
824 * Determine whether the object refers to a page within
825 * this project (either this wiki or a wiki with a local
826 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
828 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
830 public function isLocal() {
831 if ( $this->isExternal() ) {
832 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
834 return $iw->isLocal();
841 * Is this Title interwiki?
845 public function isExternal() {
846 return $this->mInterwiki
!== '';
850 * Get the interwiki prefix
852 * Use Title::isExternal to check if a interwiki is set
854 * @return string Interwiki prefix
856 public function getInterwiki() {
857 return $this->mInterwiki
;
861 * Was this a local interwiki link?
865 public function wasLocalInterwiki() {
866 return $this->mLocalInterwiki
;
870 * Determine whether the object refers to a page within
871 * this project and is transcludable.
873 * @return bool True if this is transcludable
875 public function isTrans() {
876 if ( !$this->isExternal() ) {
880 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
884 * Returns the DB name of the distant wiki which owns the object.
886 * @return string|false The DB name
888 public function getTransWikiID() {
889 if ( !$this->isExternal() ) {
893 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
897 * Get a TitleValue object representing this Title.
899 * @note Not all valid Titles have a corresponding valid TitleValue
900 * (e.g. TitleValues cannot represent page-local links that have a
901 * fragment but no title text).
903 * @return TitleValue|null
905 public function getTitleValue() {
906 if ( $this->mTitleValue
=== null ) {
908 $this->mTitleValue
= new TitleValue(
909 $this->getNamespace(),
911 $this->getFragment(),
912 $this->getInterwiki()
914 } catch ( InvalidArgumentException
$ex ) {
915 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
916 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
920 return $this->mTitleValue
;
924 * Get the text form (spaces not underscores) of the main part
926 * @return string Main part of the title
928 public function getText() {
929 return $this->mTextform
;
933 * Get the URL-encoded form of the main part
935 * @return string Main part of the title, URL-encoded
937 public function getPartialURL() {
938 return $this->mUrlform
;
942 * Get the main part with underscores
944 * @return string Main part of the title, with underscores
946 public function getDBkey() {
947 return $this->mDbkeyform
;
951 * Get the DB key with the initial letter case as specified by the user
953 * @return string DB key
955 function getUserCaseDBKey() {
956 if ( !is_null( $this->mUserCaseDBKey
) ) {
957 return $this->mUserCaseDBKey
;
959 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
960 return $this->mDbkeyform
;
965 * Get the namespace index, i.e. one of the NS_xxxx constants.
967 * @return int Namespace index
969 public function getNamespace() {
970 return $this->mNamespace
;
974 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
976 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
977 * @return string Content model id
979 public function getContentModel( $flags = 0 ) {
980 if ( !$this->mForcedContentModel
981 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
982 && $this->getArticleID( $flags )
984 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
985 $linkCache->addLinkObj( $this ); # in case we already had an article ID
986 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
989 if ( !$this->mContentModel
) {
990 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
993 return $this->mContentModel
;
997 * Convenience method for checking a title's content model name
999 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1000 * @return bool True if $this->getContentModel() == $id
1002 public function hasContentModel( $id ) {
1003 return $this->getContentModel() == $id;
1007 * Set a proposed content model for the page for permissions
1008 * checking. This does not actually change the content model
1011 * Additionally, you should make sure you've checked
1012 * ContentHandler::canBeUsedOn() first.
1015 * @param string $model CONTENT_MODEL_XXX constant
1017 public function setContentModel( $model ) {
1018 $this->mContentModel
= $model;
1019 $this->mForcedContentModel
= true;
1023 * Get the namespace text
1025 * @return string|false Namespace text
1027 public function getNsText() {
1028 if ( $this->isExternal() ) {
1029 // This probably shouldn't even happen, except for interwiki transclusion.
1030 // If possible, use the canonical name for the foreign namespace.
1031 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1032 if ( $nsText !== false ) {
1038 $formatter = self
::getTitleFormatter();
1039 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1040 } catch ( InvalidArgumentException
$ex ) {
1041 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1047 * Get the namespace text of the subject (rather than talk) page
1049 * @return string Namespace text
1051 public function getSubjectNsText() {
1052 return MediaWikiServices
::getInstance()->getContentLanguage()->
1053 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1057 * Get the namespace text of the talk page
1059 * @return string Namespace text
1061 public function getTalkNsText() {
1062 return MediaWikiServices
::getInstance()->getContentLanguage()->
1063 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1067 * Can this title have a corresponding talk page?
1069 * @deprecated since 1.30, use canHaveTalkPage() instead.
1071 * @return bool True if this title either is a talk page or can have a talk page associated.
1073 public function canTalk() {
1074 return $this->canHaveTalkPage();
1078 * Can this title have a corresponding talk page?
1080 * @see MWNamespace::hasTalkNamespace
1083 * @return bool True if this title either is a talk page or can have a talk page associated.
1085 public function canHaveTalkPage() {
1086 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1090 * Is this in a namespace that allows actual pages?
1094 public function canExist() {
1095 return $this->mNamespace
>= NS_MAIN
;
1099 * Can this title be added to a user's watchlist?
1103 public function isWatchable() {
1104 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1108 * Returns true if this is a special page.
1112 public function isSpecialPage() {
1113 return $this->getNamespace() == NS_SPECIAL
;
1117 * Returns true if this title resolves to the named special page
1119 * @param string $name The special page name
1122 public function isSpecial( $name ) {
1123 if ( $this->isSpecialPage() ) {
1124 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1125 if ( $name == $thisName ) {
1133 * If the Title refers to a special page alias which is not the local default, resolve
1134 * the alias, and localise the name as necessary. Otherwise, return $this
1138 public function fixSpecialName() {
1139 if ( $this->isSpecialPage() ) {
1140 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1141 if ( $canonicalName ) {
1142 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1143 if ( $localName != $this->mDbkeyform
) {
1144 return self
::makeTitle( NS_SPECIAL
, $localName );
1152 * Returns true if the title is inside the specified namespace.
1154 * Please make use of this instead of comparing to getNamespace()
1155 * This function is much more resistant to changes we may make
1156 * to namespaces than code that makes direct comparisons.
1157 * @param int $ns The namespace
1161 public function inNamespace( $ns ) {
1162 return MWNamespace
::equals( $this->getNamespace(), $ns );
1166 * Returns true if the title is inside one of the specified namespaces.
1168 * @param int|int[] $namespaces,... The namespaces to check for
1172 public function inNamespaces( /* ... */ ) {
1173 $namespaces = func_get_args();
1174 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1175 $namespaces = $namespaces[0];
1178 foreach ( $namespaces as $ns ) {
1179 if ( $this->inNamespace( $ns ) ) {
1188 * Returns true if the title has the same subject namespace as the
1189 * namespace specified.
1190 * For example this method will take NS_USER and return true if namespace
1191 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1192 * as their subject namespace.
1194 * This is MUCH simpler than individually testing for equivalence
1195 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1200 public function hasSubjectNamespace( $ns ) {
1201 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1205 * Is this Title in a namespace which contains content?
1206 * In other words, is this a content page, for the purposes of calculating
1211 public function isContentPage() {
1212 return MWNamespace
::isContent( $this->getNamespace() );
1216 * Would anybody with sufficient privileges be able to move this page?
1217 * Some pages just aren't movable.
1221 public function isMovable() {
1222 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1223 // Interwiki title or immovable namespace. Hooks don't get to override here
1228 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1233 * Is this the mainpage?
1234 * @note Title::newFromText seems to be sufficiently optimized by the title
1235 * cache that we don't need to over-optimize by doing direct comparisons and
1236 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1237 * ends up reporting something differently than $title->isMainPage();
1242 public function isMainPage() {
1243 return $this->equals( self
::newMainPage() );
1247 * Is this a subpage?
1251 public function isSubpage() {
1252 return MWNamespace
::hasSubpages( $this->mNamespace
)
1253 ?
strpos( $this->getText(), '/' ) !== false
1258 * Is this a conversion table for the LanguageConverter?
1262 public function isConversionTable() {
1263 // @todo ConversionTable should become a separate content model.
1265 return $this->getNamespace() == NS_MEDIAWIKI
&&
1266 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1270 * Does that page contain wikitext, or it is JS, CSS or whatever?
1274 public function isWikitextPage() {
1275 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1279 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1280 * global UI. This is generally true for pages in the MediaWiki namespace having
1281 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1283 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1286 * Note that this method should not return true for pages that contain and show
1287 * "inactive" CSS, JSON, or JS.
1292 public function isSiteConfigPage() {
1294 $this->isSiteCssConfigPage()
1295 ||
$this->isSiteJsonConfigPage()
1296 ||
$this->isSiteJsConfigPage()
1302 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1304 public function isCssOrJsPage() {
1305 wfDeprecated( __METHOD__
, '1.31' );
1306 return ( NS_MEDIAWIKI
== $this->mNamespace
1307 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1308 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1312 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1317 public function isUserConfigPage() {
1319 $this->isUserCssConfigPage()
1320 ||
$this->isUserJsonConfigPage()
1321 ||
$this->isUserJsConfigPage()
1327 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1329 public function isCssJsSubpage() {
1330 wfDeprecated( __METHOD__
, '1.31' );
1331 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1332 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1333 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1337 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1339 * @return string Containing skin name from .css, .json, or .js subpage title
1342 public function getSkinFromConfigSubpage() {
1343 $subpage = explode( '/', $this->mTextform
);
1344 $subpage = $subpage[count( $subpage ) - 1];
1345 $lastdot = strrpos( $subpage, '.' );
1346 if ( $lastdot === false ) {
1347 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1349 return substr( $subpage, 0, $lastdot );
1353 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1354 * @return string Containing skin name from .css, .json, or .js subpage title
1356 public function getSkinFromCssJsSubpage() {
1357 wfDeprecated( __METHOD__
, '1.31' );
1358 return $this->getSkinFromConfigSubpage();
1362 * Is this a CSS "config" sub-page of a user page?
1367 public function isUserCssConfigPage() {
1369 NS_USER
== $this->mNamespace
1370 && $this->isSubpage()
1371 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1376 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1379 public function isCssSubpage() {
1380 wfDeprecated( __METHOD__
, '1.31' );
1381 return $this->isUserCssConfigPage();
1385 * Is this a JSON "config" sub-page of a user page?
1390 public function isUserJsonConfigPage() {
1392 NS_USER
== $this->mNamespace
1393 && $this->isSubpage()
1394 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1399 * Is this a JS "config" sub-page of a user page?
1404 public function isUserJsConfigPage() {
1406 NS_USER
== $this->mNamespace
1407 && $this->isSubpage()
1408 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1413 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1416 public function isJsSubpage() {
1417 wfDeprecated( __METHOD__
, '1.31' );
1418 return $this->isUserJsConfigPage();
1422 * Is this a sitewide CSS "config" page?
1427 public function isSiteCssConfigPage() {
1429 NS_MEDIAWIKI
== $this->mNamespace
1431 $this->hasContentModel( CONTENT_MODEL_CSS
)
1432 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1433 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1434 ||
substr( $this->getDBkey(), -4 ) === '.css'
1440 * Is this a sitewide JSON "config" page?
1445 public function isSiteJsonConfigPage() {
1447 NS_MEDIAWIKI
== $this->mNamespace
1449 $this->hasContentModel( CONTENT_MODEL_JSON
)
1450 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1451 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1452 ||
substr( $this->getDBkey(), -5 ) === '.json'
1458 * Is this a sitewide JS "config" page?
1463 public function isSiteJsConfigPage() {
1465 NS_MEDIAWIKI
== $this->mNamespace
1467 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1468 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1469 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1470 ||
substr( $this->getDBkey(), -3 ) === '.js'
1476 * Is this a talk page of some sort?
1480 public function isTalkPage() {
1481 return MWNamespace
::isTalk( $this->getNamespace() );
1485 * Get a Title object associated with the talk page of this article
1487 * @return Title The object for the talk page
1489 public function getTalkPage() {
1490 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1494 * Get a Title object associated with the talk page of this article,
1495 * if such a talk page can exist.
1499 * @return Title|null The object for the talk page,
1500 * or null if no associated talk page can exist, according to canHaveTalkPage().
1502 public function getTalkPageIfDefined() {
1503 if ( !$this->canHaveTalkPage() ) {
1507 return $this->getTalkPage();
1511 * Get a title object associated with the subject page of this
1514 * @return Title The object for the subject page
1516 public function getSubjectPage() {
1517 // Is this the same title?
1518 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1519 if ( $this->getNamespace() == $subjectNS ) {
1522 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1526 * Get the other title for this page, if this is a subject page
1527 * get the talk page, if it is a subject page get the talk page
1530 * @throws MWException If the page doesn't have an other page
1533 public function getOtherPage() {
1534 if ( $this->isSpecialPage() ) {
1535 throw new MWException( 'Special pages cannot have other pages' );
1537 if ( $this->isTalkPage() ) {
1538 return $this->getSubjectPage();
1540 if ( !$this->canHaveTalkPage() ) {
1541 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1543 return $this->getTalkPage();
1548 * Get the default namespace index, for when there is no namespace
1550 * @return int Default namespace index
1552 public function getDefaultNamespace() {
1553 return $this->mDefaultNamespace
;
1557 * Get the Title fragment (i.e.\ the bit after the #) in text form
1559 * Use Title::hasFragment to check for a fragment
1561 * @return string Title fragment
1563 public function getFragment() {
1564 return $this->mFragment
;
1568 * Check if a Title fragment is set
1573 public function hasFragment() {
1574 return $this->mFragment
!== '';
1578 * Get the fragment in URL form, including the "#" character if there is one
1580 * @return string Fragment in URL form
1582 public function getFragmentForURL() {
1583 if ( !$this->hasFragment() ) {
1585 } elseif ( $this->isExternal()
1586 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1588 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1590 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1594 * Set the fragment for this title. Removes the first character from the
1595 * specified fragment before setting, so it assumes you're passing it with
1598 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1599 * or Title::createFragmentTarget().
1600 * Still in active use privately.
1603 * @param string $fragment Text
1605 public function setFragment( $fragment ) {
1606 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1610 * Creates a new Title for a different fragment of the same page.
1613 * @param string $fragment
1616 public function createFragmentTarget( $fragment ) {
1617 return self
::makeTitle(
1618 $this->getNamespace(),
1621 $this->getInterwiki()
1626 * Prefix some arbitrary text with the namespace or interwiki prefix
1629 * @param string $name The text
1630 * @return string The prefixed text
1632 private function prefix( $name ) {
1634 if ( $this->isExternal() ) {
1635 $p = $this->mInterwiki
. ':';
1638 if ( 0 != $this->mNamespace
) {
1639 $nsText = $this->getNsText();
1641 if ( $nsText === false ) {
1642 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1643 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1644 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1647 $p .= $nsText . ':';
1653 * Get the prefixed database key form
1655 * @return string The prefixed title, with underscores and
1656 * any interwiki and namespace prefixes
1658 public function getPrefixedDBkey() {
1659 $s = $this->prefix( $this->mDbkeyform
);
1660 $s = strtr( $s, ' ', '_' );
1665 * Get the prefixed title with spaces.
1666 * This is the form usually used for display
1668 * @return string The prefixed title, with spaces
1670 public function getPrefixedText() {
1671 if ( $this->mPrefixedText
=== null ) {
1672 $s = $this->prefix( $this->mTextform
);
1673 $s = strtr( $s, '_', ' ' );
1674 $this->mPrefixedText
= $s;
1676 return $this->mPrefixedText
;
1680 * Return a string representation of this title
1682 * @return string Representation of this title
1684 public function __toString() {
1685 return $this->getPrefixedText();
1689 * Get the prefixed title with spaces, plus any fragment
1690 * (part beginning with '#')
1692 * @return string The prefixed title, with spaces and the fragment, including '#'
1694 public function getFullText() {
1695 $text = $this->getPrefixedText();
1696 if ( $this->hasFragment() ) {
1697 $text .= '#' . $this->getFragment();
1703 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1707 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1711 * @return string Root name
1714 public function getRootText() {
1715 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1716 return $this->getText();
1719 return strtok( $this->getText(), '/' );
1723 * Get the root page name title, i.e. the leftmost part before any slashes
1727 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1728 * # returns: Title{User:Foo}
1731 * @return Title Root title
1734 public function getRootTitle() {
1735 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1739 * Get the base page name without a namespace, i.e. the part before the subpage name
1743 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1744 * # returns: 'Foo/Bar'
1747 * @return string Base name
1749 public function getBaseText() {
1750 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1751 return $this->getText();
1754 $parts = explode( '/', $this->getText() );
1755 # Don't discard the real title if there's no subpage involved
1756 if ( count( $parts ) > 1 ) {
1757 unset( $parts[count( $parts ) - 1] );
1759 return implode( '/', $parts );
1763 * Get the base page name title, i.e. the part before the subpage name
1767 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1768 * # returns: Title{User:Foo/Bar}
1771 * @return Title Base title
1774 public function getBaseTitle() {
1775 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1779 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1783 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1787 * @return string Subpage name
1789 public function getSubpageText() {
1790 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1791 return $this->mTextform
;
1793 $parts = explode( '/', $this->mTextform
);
1794 return $parts[count( $parts ) - 1];
1798 * Get the title for a subpage of the current page
1802 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1803 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1806 * @param string $text The subpage name to add to the title
1807 * @return Title Subpage title
1810 public function getSubpage( $text ) {
1811 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1815 * Get a URL-encoded form of the subpage text
1817 * @return string URL-encoded subpage name
1819 public function getSubpageUrlForm() {
1820 $text = $this->getSubpageText();
1821 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1826 * Get a URL-encoded title (not an actual URL) including interwiki
1828 * @return string The URL-encoded form
1830 public function getPrefixedURL() {
1831 $s = $this->prefix( $this->mDbkeyform
);
1832 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1837 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1838 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1839 * second argument named variant. This was deprecated in favor
1840 * of passing an array of option with a "variant" key
1841 * Once $query2 is removed for good, this helper can be dropped
1842 * and the wfArrayToCgi moved to getLocalURL();
1844 * @since 1.19 (r105919)
1845 * @param array|string $query
1846 * @param string|string[]|bool $query2
1849 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1850 if ( $query2 !== false ) {
1851 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1852 "method called with a second parameter is deprecated. Add your " .
1853 "parameter to an array passed as the first parameter.", "1.19" );
1855 if ( is_array( $query ) ) {
1856 $query = wfArrayToCgi( $query );
1859 if ( is_string( $query2 ) ) {
1860 // $query2 is a string, we will consider this to be
1861 // a deprecated $variant argument and add it to the query
1862 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1864 $query2 = wfArrayToCgi( $query2 );
1866 // If we have $query content add a & to it first
1870 // Now append the queries together
1877 * Get a real URL referring to this title, with interwiki link and
1880 * @see self::getLocalURL for the arguments.
1882 * @param string|string[] $query
1883 * @param string|string[]|bool $query2
1884 * @param string|int|null $proto Protocol type to use in URL
1885 * @return string The URL
1887 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1888 $query = self
::fixUrlQueryArgs( $query, $query2 );
1890 # Hand off all the decisions on urls to getLocalURL
1891 $url = $this->getLocalURL( $query );
1893 # Expand the url to make it a full url. Note that getLocalURL has the
1894 # potential to output full urls for a variety of reasons, so we use
1895 # wfExpandUrl instead of simply prepending $wgServer
1896 $url = wfExpandUrl( $url, $proto );
1898 # Finally, add the fragment.
1899 $url .= $this->getFragmentForURL();
1900 // Avoid PHP 7.1 warning from passing $this by reference
1902 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1907 * Get a url appropriate for making redirects based on an untrusted url arg
1909 * This is basically the same as getFullUrl(), but in the case of external
1910 * interwikis, we send the user to a landing page, to prevent possible
1911 * phishing attacks and the like.
1913 * @note Uses current protocol by default, since technically relative urls
1914 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1915 * places where the url gets cached, as might pollute between
1916 * https and non-https users.
1917 * @see self::getLocalURL for the arguments.
1918 * @param array|string $query
1919 * @param string $proto Protocol type to use in URL
1920 * @return string A url suitable to use in an HTTP location header.
1922 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1924 if ( $this->isExternal() ) {
1925 $target = SpecialPage
::getTitleFor(
1927 $this->getPrefixedDBkey()
1930 return $target->getFullURL( $query, false, $proto );
1934 * Get a URL with no fragment or server name (relative URL) from a Title object.
1935 * If this page is generated with action=render, however,
1936 * $wgServer is prepended to make an absolute URL.
1938 * @see self::getFullURL to always get an absolute URL.
1939 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1940 * valid to link, locally, to the current Title.
1941 * @see self::newFromText to produce a Title object.
1943 * @param string|string[] $query An optional query string,
1944 * not used for interwiki links. Can be specified as an associative array as well,
1945 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1946 * Some query patterns will trigger various shorturl path replacements.
1947 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1948 * be an array. If a string is passed it will be interpreted as a deprecated
1949 * variant argument and urlencoded into a variant= argument.
1950 * This second query argument will be added to the $query
1951 * The second parameter is deprecated since 1.19. Pass it as a key,value
1952 * pair in the first parameter array instead.
1954 * @return string String of the URL.
1956 public function getLocalURL( $query = '', $query2 = false ) {
1957 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1959 $query = self
::fixUrlQueryArgs( $query, $query2 );
1961 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1963 $namespace = $this->getNsText();
1964 if ( $namespace != '' ) {
1965 # Can this actually happen? Interwikis shouldn't be parsed.
1966 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1969 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1970 $url = wfAppendQuery( $url, $query );
1972 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1973 if ( $query == '' ) {
1974 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1975 // Avoid PHP 7.1 warning from passing $this by reference
1977 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1979 global $wgVariantArticlePath, $wgActionPaths;
1983 if ( !empty( $wgActionPaths )
1984 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1986 $action = urldecode( $matches[2] );
1987 if ( isset( $wgActionPaths[$action] ) ) {
1988 $query = $matches[1];
1989 if ( isset( $matches[4] ) ) {
1990 $query .= $matches[4];
1992 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1993 if ( $query != '' ) {
1994 $url = wfAppendQuery( $url, $query );
2000 && $wgVariantArticlePath
2001 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2002 && $this->getPageLanguage()->equals(
2003 MediaWikiServices
::getInstance()->getContentLanguage() )
2004 && $this->getPageLanguage()->hasVariants()
2006 $variant = urldecode( $matches[1] );
2007 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2008 // Only do the variant replacement if the given variant is a valid
2009 // variant for the page's language.
2010 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2011 $url = str_replace( '$1', $dbkey, $url );
2015 if ( $url === false ) {
2016 if ( $query == '-' ) {
2019 $url = "{$wgScript}?title={$dbkey}&{$query}";
2022 // Avoid PHP 7.1 warning from passing $this by reference
2024 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2026 // @todo FIXME: This causes breakage in various places when we
2027 // actually expected a local URL and end up with dupe prefixes.
2028 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2029 $url = $wgServer . $url;
2032 // Avoid PHP 7.1 warning from passing $this by reference
2034 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2039 * Get a URL that's the simplest URL that will be valid to link, locally,
2040 * to the current Title. It includes the fragment, but does not include
2041 * the server unless action=render is used (or the link is external). If
2042 * there's a fragment but the prefixed text is empty, we just return a link
2045 * The result obviously should not be URL-escaped, but does need to be
2046 * HTML-escaped if it's being output in HTML.
2048 * @param string|string[] $query
2049 * @param bool $query2
2050 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2051 * or false (default) for no expansion
2052 * @see self::getLocalURL for the arguments.
2053 * @return string The URL
2055 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2056 if ( $this->isExternal() ||
$proto !== false ) {
2057 $ret = $this->getFullURL( $query, $query2, $proto );
2058 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2059 $ret = $this->getFragmentForURL();
2061 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2067 * Get the URL form for an internal link.
2068 * - Used in various CDN-related code, in case we have a different
2069 * internal hostname for the server from the exposed one.
2071 * This uses $wgInternalServer to qualify the path, or $wgServer
2072 * if $wgInternalServer is not set. If the server variable used is
2073 * protocol-relative, the URL will be expanded to http://
2075 * @see self::getLocalURL for the arguments.
2076 * @param string $query
2077 * @param string|bool $query2
2078 * @return string The URL
2080 public function getInternalURL( $query = '', $query2 = false ) {
2081 global $wgInternalServer, $wgServer;
2082 $query = self
::fixUrlQueryArgs( $query, $query2 );
2083 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2084 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2085 // Avoid PHP 7.1 warning from passing $this by reference
2087 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2092 * Get the URL for a canonical link, for use in things like IRC and
2093 * e-mail notifications. Uses $wgCanonicalServer and the
2094 * GetCanonicalURL hook.
2096 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2098 * @see self::getLocalURL for the arguments.
2099 * @param string $query
2100 * @param string|bool $query2
2101 * @return string The URL
2104 public function getCanonicalURL( $query = '', $query2 = false ) {
2105 $query = self
::fixUrlQueryArgs( $query, $query2 );
2106 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2107 // Avoid PHP 7.1 warning from passing $this by reference
2109 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2114 * Get the edit URL for this Title
2116 * @return string The URL, or a null string if this is an interwiki link
2118 public function getEditURL() {
2119 if ( $this->isExternal() ) {
2122 $s = $this->getLocalURL( 'action=edit' );
2128 * Can $user perform $action on this page?
2129 * This skips potentially expensive cascading permission checks
2130 * as well as avoids expensive error formatting
2132 * Suitable for use for nonessential UI controls in common cases, but
2133 * _not_ for functional access control.
2135 * May provide false positives, but should never provide a false negative.
2137 * @param string $action Action that permission needs to be checked for
2138 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2141 public function quickUserCan( $action, $user = null ) {
2142 return $this->userCan( $action, $user, false );
2146 * Can $user perform $action on this page?
2148 * @param string $action Action that permission needs to be checked for
2149 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2151 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2154 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2155 if ( !$user instanceof User
) {
2160 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2164 * Can $user perform $action on this page?
2166 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2168 * @param string $action Action that permission needs to be checked for
2169 * @param User $user User to check
2170 * @param string $rigor One of (quick,full,secure)
2171 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2172 * - full : does cheap and expensive checks possibly from a replica DB
2173 * - secure : does cheap and expensive checks, using the master as needed
2174 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2175 * whose corresponding errors may be ignored.
2176 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2178 public function getUserPermissionsErrors(
2179 $action, $user, $rigor = 'secure', $ignoreErrors = []
2181 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2183 // Remove the errors being ignored.
2184 foreach ( $errors as $index => $error ) {
2185 $errKey = is_array( $error ) ?
$error[0] : $error;
2187 if ( in_array( $errKey, $ignoreErrors ) ) {
2188 unset( $errors[$index] );
2190 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2191 unset( $errors[$index] );
2199 * Permissions checks that fail most often, and which are easiest to test.
2201 * @param string $action The action to check
2202 * @param User $user User to check
2203 * @param array $errors List of current errors
2204 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2205 * @param bool $short Short circuit on first error
2207 * @return array List of errors
2209 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2210 if ( !Hooks
::run( 'TitleQuickPermissions',
2211 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2216 if ( $action == 'create' ) {
2218 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2219 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2221 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2223 } elseif ( $action == 'move' ) {
2224 if ( !$user->isAllowed( 'move-rootuserpages' )
2225 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2226 // Show user page-specific message only if the user can move other pages
2227 $errors[] = [ 'cant-move-user-page' ];
2230 // Check if user is allowed to move files if it's a file
2231 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2232 $errors[] = [ 'movenotallowedfile' ];
2235 // Check if user is allowed to move category pages if it's a category page
2236 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2237 $errors[] = [ 'cant-move-category-page' ];
2240 if ( !$user->isAllowed( 'move' ) ) {
2241 // User can't move anything
2242 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2243 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2244 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2245 // custom message if logged-in users without any special rights can move
2246 $errors[] = [ 'movenologintext' ];
2248 $errors[] = [ 'movenotallowed' ];
2251 } elseif ( $action == 'move-target' ) {
2252 if ( !$user->isAllowed( 'move' ) ) {
2253 // User can't move anything
2254 $errors[] = [ 'movenotallowed' ];
2255 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2256 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2257 // Show user page-specific message only if the user can move other pages
2258 $errors[] = [ 'cant-move-to-user-page' ];
2259 } elseif ( !$user->isAllowed( 'move-categorypages' )
2260 && $this->mNamespace
== NS_CATEGORY
) {
2261 // Show category page-specific message only if the user can move other pages
2262 $errors[] = [ 'cant-move-to-category-page' ];
2264 } elseif ( !$user->isAllowed( $action ) ) {
2265 $errors[] = $this->missingPermissionError( $action, $short );
2272 * Add the resulting error code to the errors array
2274 * @param array $errors List of current errors
2275 * @param array $result Result of errors
2277 * @return array List of errors
2279 private function resultToError( $errors, $result ) {
2280 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2281 // A single array representing an error
2282 $errors[] = $result;
2283 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2284 // A nested array representing multiple errors
2285 $errors = array_merge( $errors, $result );
2286 } elseif ( $result !== '' && is_string( $result ) ) {
2287 // A string representing a message-id
2288 $errors[] = [ $result ];
2289 } elseif ( $result instanceof MessageSpecifier
) {
2290 // A message specifier representing an error
2291 $errors[] = [ $result ];
2292 } elseif ( $result === false ) {
2293 // a generic "We don't want them to do that"
2294 $errors[] = [ 'badaccess-group0' ];
2300 * Check various permission hooks
2302 * @param string $action The action to check
2303 * @param User $user User to check
2304 * @param array $errors List of current errors
2305 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2306 * @param bool $short Short circuit on first error
2308 * @return array List of errors
2310 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2311 // Use getUserPermissionsErrors instead
2313 // Avoid PHP 7.1 warning from passing $this by reference
2315 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2316 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2318 // Check getUserPermissionsErrors hook
2319 // Avoid PHP 7.1 warning from passing $this by reference
2321 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2322 $errors = $this->resultToError( $errors, $result );
2324 // Check getUserPermissionsErrorsExpensive hook
2327 && !( $short && count( $errors ) > 0 )
2328 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2330 $errors = $this->resultToError( $errors, $result );
2337 * Check permissions on special pages & namespaces
2339 * @param string $action The action to check
2340 * @param User $user User to check
2341 * @param array $errors List of current errors
2342 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2343 * @param bool $short Short circuit on first error
2345 * @return array List of errors
2347 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2348 # Only 'createaccount' can be performed on special pages,
2349 # which don't actually exist in the DB.
2350 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2351 $errors[] = [ 'ns-specialprotected' ];
2354 # Check $wgNamespaceProtection for restricted namespaces
2355 if ( $this->isNamespaceProtected( $user ) ) {
2356 $ns = $this->mNamespace
== NS_MAIN ?
2357 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2358 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2359 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2366 * Check sitewide CSS/JSON/JS permissions
2368 * @param string $action The action to check
2369 * @param User $user User to check
2370 * @param array $errors List of current errors
2371 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2372 * @param bool $short Short circuit on first error
2374 * @return array List of errors
2376 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2377 if ( $action != 'patrol' ) {
2379 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2380 // editinterface right. That's implemented as a restriction so no check needed here.
2381 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2382 $error = [ 'sitecssprotected', $action ];
2383 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2384 $error = [ 'sitejsonprotected', $action ];
2385 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2386 $error = [ 'sitejsprotected', $action ];
2390 if ( $user->isAllowed( 'editinterface' ) ) {
2391 // Most users / site admins will probably find out about the new, more restrictive
2392 // permissions by failing to edit something. Give them more info.
2393 // TODO remove this a few release cycles after 1.32
2394 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2404 * Check CSS/JSON/JS sub-page permissions
2406 * @param string $action The action to check
2407 * @param User $user User to check
2408 * @param array $errors List of current errors
2409 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2410 * @param bool $short Short circuit on first error
2412 * @return array List of errors
2414 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2415 # Protect css/json/js subpages of user pages
2416 # XXX: this might be better using restrictions
2418 if ( $action != 'patrol' ) {
2419 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2421 $this->isUserCssConfigPage()
2422 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2424 $errors[] = [ 'mycustomcssprotected', $action ];
2426 $this->isUserJsonConfigPage()
2427 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2429 $errors[] = [ 'mycustomjsonprotected', $action ];
2431 $this->isUserJsConfigPage()
2432 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2434 $errors[] = [ 'mycustomjsprotected', $action ];
2438 $this->isUserCssConfigPage()
2439 && !$user->isAllowed( 'editusercss' )
2441 $errors[] = [ 'customcssprotected', $action ];
2443 $this->isUserJsonConfigPage()
2444 && !$user->isAllowed( 'edituserjson' )
2446 $errors[] = [ 'customjsonprotected', $action ];
2448 $this->isUserJsConfigPage()
2449 && !$user->isAllowed( 'edituserjs' )
2451 $errors[] = [ 'customjsprotected', $action ];
2460 * Check against page_restrictions table requirements on this
2461 * page. The user must possess all required rights for this
2464 * @param string $action The action to check
2465 * @param User $user User to check
2466 * @param array $errors List of current errors
2467 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2468 * @param bool $short Short circuit on first error
2470 * @return array List of errors
2472 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2473 foreach ( $this->getRestrictions( $action ) as $right ) {
2474 // Backwards compatibility, rewrite sysop -> editprotected
2475 if ( $right == 'sysop' ) {
2476 $right = 'editprotected';
2478 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2479 if ( $right == 'autoconfirmed' ) {
2480 $right = 'editsemiprotected';
2482 if ( $right == '' ) {
2485 if ( !$user->isAllowed( $right ) ) {
2486 $errors[] = [ 'protectedpagetext', $right, $action ];
2487 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2488 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2496 * Check restrictions on cascading pages.
2498 * @param string $action The action to check
2499 * @param User $user User to check
2500 * @param array $errors List of current errors
2501 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2502 * @param bool $short Short circuit on first error
2504 * @return array List of errors
2506 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2507 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2508 # We /could/ use the protection level on the source page, but it's
2509 # fairly ugly as we have to establish a precedence hierarchy for pages
2510 # included by multiple cascade-protected pages. So just restrict
2511 # it to people with 'protect' permission, as they could remove the
2512 # protection anyway.
2513 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2514 # Cascading protection depends on more than this page...
2515 # Several cascading protected pages may include this page...
2516 # Check each cascading level
2517 # This is only for protection restrictions, not for all actions
2518 if ( isset( $restrictions[$action] ) ) {
2519 foreach ( $restrictions[$action] as $right ) {
2520 // Backwards compatibility, rewrite sysop -> editprotected
2521 if ( $right == 'sysop' ) {
2522 $right = 'editprotected';
2524 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2525 if ( $right == 'autoconfirmed' ) {
2526 $right = 'editsemiprotected';
2528 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2530 foreach ( $cascadingSources as $page ) {
2531 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2533 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2543 * Check action permissions not already checked in checkQuickPermissions
2545 * @param string $action The action to check
2546 * @param User $user User to check
2547 * @param array $errors List of current errors
2548 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2549 * @param bool $short Short circuit on first error
2551 * @return array List of errors
2553 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2554 global $wgDeleteRevisionsLimit, $wgLang;
2556 if ( $action == 'protect' ) {
2557 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2558 // If they can't edit, they shouldn't protect.
2559 $errors[] = [ 'protect-cantedit' ];
2561 } elseif ( $action == 'create' ) {
2562 $title_protection = $this->getTitleProtection();
2563 if ( $title_protection ) {
2564 if ( $title_protection['permission'] == ''
2565 ||
!$user->isAllowed( $title_protection['permission'] )
2569 User
::whoIs( $title_protection['user'] ),
2570 $title_protection['reason']
2574 } elseif ( $action == 'move' ) {
2575 // Check for immobile pages
2576 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2577 // Specific message for this case
2578 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2579 } elseif ( !$this->isMovable() ) {
2580 // Less specific message for rarer cases
2581 $errors[] = [ 'immobile-source-page' ];
2583 } elseif ( $action == 'move-target' ) {
2584 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2585 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2586 } elseif ( !$this->isMovable() ) {
2587 $errors[] = [ 'immobile-target-page' ];
2589 } elseif ( $action == 'delete' ) {
2590 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2591 if ( !$tempErrors ) {
2592 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2593 $user, $tempErrors, $rigor, true );
2595 if ( $tempErrors ) {
2596 // If protection keeps them from editing, they shouldn't be able to delete.
2597 $errors[] = [ 'deleteprotected' ];
2599 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2600 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2602 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2604 } elseif ( $action === 'undelete' ) {
2605 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2606 // Undeleting implies editing
2607 $errors[] = [ 'undelete-cantedit' ];
2609 if ( !$this->exists()
2610 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2612 // Undeleting where nothing currently exists implies creating
2613 $errors[] = [ 'undelete-cantcreate' ];
2620 * Check that the user isn't blocked from editing.
2622 * @param string $action The action to check
2623 * @param User $user User to check
2624 * @param array $errors List of current errors
2625 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2626 * @param bool $short Short circuit on first error
2628 * @return array List of errors
2630 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2631 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2632 // Account creation blocks handled at userlogin.
2633 // Unblocking handled in SpecialUnblock
2634 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2638 // Optimize for a very common case
2639 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2643 if ( $wgEmailConfirmToEdit
2644 && !$user->isEmailConfirmed()
2645 && $action === 'edit'
2647 $errors[] = [ 'confirmedittext' ];
2650 $useSlave = ( $rigor !== 'secure' );
2651 if ( ( $action == 'edit' ||
$action == 'create' )
2652 && !$user->isBlockedFrom( $this, $useSlave )
2654 // Don't block the user from editing their own talk page unless they've been
2655 // explicitly blocked from that too.
2656 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2657 // @todo FIXME: Pass the relevant context into this function.
2658 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2665 * Check that the user is allowed to read this page.
2667 * @param string $action The action to check
2668 * @param User $user User to check
2669 * @param array $errors List of current errors
2670 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2671 * @param bool $short Short circuit on first error
2673 * @return array List of errors
2675 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2676 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2678 $whitelisted = false;
2679 if ( User
::isEveryoneAllowed( 'read' ) ) {
2680 # Shortcut for public wikis, allows skipping quite a bit of code
2681 $whitelisted = true;
2682 } elseif ( $user->isAllowed( 'read' ) ) {
2683 # If the user is allowed to read pages, he is allowed to read all pages
2684 $whitelisted = true;
2685 } elseif ( $this->isSpecial( 'Userlogin' )
2686 ||
$this->isSpecial( 'PasswordReset' )
2687 ||
$this->isSpecial( 'Userlogout' )
2689 # Always grant access to the login page.
2690 # Even anons need to be able to log in.
2691 $whitelisted = true;
2692 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2693 # Time to check the whitelist
2694 # Only do these checks is there's something to check against
2695 $name = $this->getPrefixedText();
2696 $dbName = $this->getPrefixedDBkey();
2698 // Check for explicit whitelisting with and without underscores
2699 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2700 $whitelisted = true;
2701 } elseif ( $this->getNamespace() == NS_MAIN
) {
2702 # Old settings might have the title prefixed with
2703 # a colon for main-namespace pages
2704 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2705 $whitelisted = true;
2707 } elseif ( $this->isSpecialPage() ) {
2708 # If it's a special page, ditch the subpage bit and check again
2709 $name = $this->getDBkey();
2710 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2712 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2713 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2714 $whitelisted = true;
2720 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2721 $name = $this->getPrefixedText();
2722 // Check for regex whitelisting
2723 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2724 if ( preg_match( $listItem, $name ) ) {
2725 $whitelisted = true;
2731 if ( !$whitelisted ) {
2732 # If the title is not whitelisted, give extensions a chance to do so...
2733 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2734 if ( !$whitelisted ) {
2735 $errors[] = $this->missingPermissionError( $action, $short );
2743 * Get a description array when the user doesn't have the right to perform
2744 * $action (i.e. when User::isAllowed() returns false)
2746 * @param string $action The action to check
2747 * @param bool $short Short circuit on first error
2748 * @return array Array containing an error message key and any parameters
2750 private function missingPermissionError( $action, $short ) {
2751 // We avoid expensive display logic for quickUserCan's and such
2753 return [ 'badaccess-group0' ];
2756 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2760 * Can $user perform $action on this page? This is an internal function,
2761 * with multiple levels of checks depending on performance needs; see $rigor below.
2762 * It does not check wfReadOnly().
2764 * @param string $action Action that permission needs to be checked for
2765 * @param User $user User to check
2766 * @param string $rigor One of (quick,full,secure)
2767 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2768 * - full : does cheap and expensive checks possibly from a replica DB
2769 * - secure : does cheap and expensive checks, using the master as needed
2770 * @param bool $short Set this to true to stop after the first permission error.
2771 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2773 protected function getUserPermissionsErrorsInternal(
2774 $action, $user, $rigor = 'secure', $short = false
2776 if ( $rigor === true ) {
2777 $rigor = 'secure'; // b/c
2778 } elseif ( $rigor === false ) {
2779 $rigor = 'quick'; // b/c
2780 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2781 throw new Exception( "Invalid rigor parameter '$rigor'." );
2784 # Read has special handling
2785 if ( $action == 'read' ) {
2787 'checkPermissionHooks',
2788 'checkReadPermissions',
2789 'checkUserBlock', // for wgBlockDisablesLogin
2791 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2792 # or checkUserConfigPermissions here as it will lead to duplicate
2793 # error messages. This is okay to do since anywhere that checks for
2794 # create will also check for edit, and those checks are called for edit.
2795 } elseif ( $action == 'create' ) {
2797 'checkQuickPermissions',
2798 'checkPermissionHooks',
2799 'checkPageRestrictions',
2800 'checkCascadingSourcesRestrictions',
2801 'checkActionPermissions',
2806 'checkQuickPermissions',
2807 'checkPermissionHooks',
2808 'checkSpecialsAndNSPermissions',
2809 'checkSiteConfigPermissions',
2810 'checkUserConfigPermissions',
2811 'checkPageRestrictions',
2812 'checkCascadingSourcesRestrictions',
2813 'checkActionPermissions',
2819 while ( count( $checks ) > 0 &&
2820 !( $short && count( $errors ) > 0 ) ) {
2821 $method = array_shift( $checks );
2822 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2829 * Get a filtered list of all restriction types supported by this wiki.
2830 * @param bool $exists True to get all restriction types that apply to
2831 * titles that do exist, False for all restriction types that apply to
2832 * titles that do not exist
2835 public static function getFilteredRestrictionTypes( $exists = true ) {
2836 global $wgRestrictionTypes;
2837 $types = $wgRestrictionTypes;
2839 # Remove the create restriction for existing titles
2840 $types = array_diff( $types, [ 'create' ] );
2842 # Only the create and upload restrictions apply to non-existing titles
2843 $types = array_intersect( $types, [ 'create', 'upload' ] );
2849 * Returns restriction types for the current Title
2851 * @return array Applicable restriction types
2853 public function getRestrictionTypes() {
2854 if ( $this->isSpecialPage() ) {
2858 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2860 if ( $this->getNamespace() != NS_FILE
) {
2861 # Remove the upload restriction for non-file titles
2862 $types = array_diff( $types, [ 'upload' ] );
2865 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2867 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2868 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2874 * Is this title subject to title protection?
2875 * Title protection is the one applied against creation of such title.
2877 * @return array|bool An associative array representing any existent title
2878 * protection, or false if there's none.
2880 public function getTitleProtection() {
2881 $protection = $this->getTitleProtectionInternal();
2882 if ( $protection ) {
2883 if ( $protection['permission'] == 'sysop' ) {
2884 $protection['permission'] = 'editprotected'; // B/C
2886 if ( $protection['permission'] == 'autoconfirmed' ) {
2887 $protection['permission'] = 'editsemiprotected'; // B/C
2894 * Fetch title protection settings
2896 * To work correctly, $this->loadRestrictions() needs to have access to the
2897 * actual protections in the database without munging 'sysop' =>
2898 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2899 * callers probably want $this->getTitleProtection() instead.
2901 * @return array|bool
2903 protected function getTitleProtectionInternal() {
2904 // Can't protect pages in special namespaces
2905 if ( $this->getNamespace() < 0 ) {
2909 // Can't protect pages that exist.
2910 if ( $this->exists() ) {
2914 if ( $this->mTitleProtection
=== null ) {
2915 $dbr = wfGetDB( DB_REPLICA
);
2916 $commentStore = CommentStore
::getStore();
2917 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2918 $res = $dbr->select(
2919 [ 'protected_titles' ] +
$commentQuery['tables'],
2921 'user' => 'pt_user',
2922 'expiry' => 'pt_expiry',
2923 'permission' => 'pt_create_perm'
2924 ] +
$commentQuery['fields'],
2925 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2928 $commentQuery['joins']
2931 // fetchRow returns false if there are no rows.
2932 $row = $dbr->fetchRow( $res );
2934 $this->mTitleProtection
= [
2935 'user' => $row['user'],
2936 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2937 'permission' => $row['permission'],
2938 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2941 $this->mTitleProtection
= false;
2944 return $this->mTitleProtection
;
2948 * Remove any title protection due to page existing
2950 public function deleteTitleProtection() {
2951 $dbw = wfGetDB( DB_MASTER
);
2955 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2958 $this->mTitleProtection
= false;
2962 * Is this page "semi-protected" - the *only* protection levels are listed
2963 * in $wgSemiprotectedRestrictionLevels?
2965 * @param string $action Action to check (default: edit)
2968 public function isSemiProtected( $action = 'edit' ) {
2969 global $wgSemiprotectedRestrictionLevels;
2971 $restrictions = $this->getRestrictions( $action );
2972 $semi = $wgSemiprotectedRestrictionLevels;
2973 if ( !$restrictions ||
!$semi ) {
2974 // Not protected, or all protection is full protection
2978 // Remap autoconfirmed to editsemiprotected for BC
2979 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2980 $semi[$key] = 'editsemiprotected';
2982 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2983 $restrictions[$key] = 'editsemiprotected';
2986 return !array_diff( $restrictions, $semi );
2990 * Does the title correspond to a protected article?
2992 * @param string $action The action the page is protected from,
2993 * by default checks all actions.
2996 public function isProtected( $action = '' ) {
2997 global $wgRestrictionLevels;
2999 $restrictionTypes = $this->getRestrictionTypes();
3001 # Special pages have inherent protection
3002 if ( $this->isSpecialPage() ) {
3006 # Check regular protection levels
3007 foreach ( $restrictionTypes as $type ) {
3008 if ( $action == $type ||
$action == '' ) {
3009 $r = $this->getRestrictions( $type );
3010 foreach ( $wgRestrictionLevels as $level ) {
3011 if ( in_array( $level, $r ) && $level != '' ) {
3022 * Determines if $user is unable to edit this page because it has been protected
3023 * by $wgNamespaceProtection.
3025 * @param User $user User object to check permissions
3028 public function isNamespaceProtected( User
$user ) {
3029 global $wgNamespaceProtection;
3031 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3032 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3033 if ( $right != '' && !$user->isAllowed( $right ) ) {
3042 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3044 * @return bool If the page is subject to cascading restrictions.
3046 public function isCascadeProtected() {
3047 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3048 return ( $sources > 0 );
3052 * Determines whether cascading protection sources have already been loaded from
3055 * @param bool $getPages True to check if the pages are loaded, or false to check
3056 * if the status is loaded.
3057 * @return bool Whether or not the specified information has been loaded
3060 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3061 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3065 * Cascading protection: Get the source of any cascading restrictions on this page.
3067 * @param bool $getPages Whether or not to retrieve the actual pages
3068 * that the restrictions have come from and the actual restrictions
3070 * @return array Two elements: First is an array of Title objects of the
3071 * pages from which cascading restrictions have come, false for
3072 * none, or true if such restrictions exist but $getPages was not
3073 * set. Second is an array like that returned by
3074 * Title::getAllRestrictions(), or an empty array if $getPages is
3077 public function getCascadeProtectionSources( $getPages = true ) {
3078 $pagerestrictions = [];
3080 if ( $this->mCascadeSources
!== null && $getPages ) {
3081 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3082 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3083 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3086 $dbr = wfGetDB( DB_REPLICA
);
3088 if ( $this->getNamespace() == NS_FILE
) {
3089 $tables = [ 'imagelinks', 'page_restrictions' ];
3091 'il_to' => $this->getDBkey(),
3096 $tables = [ 'templatelinks', 'page_restrictions' ];
3098 'tl_namespace' => $this->getNamespace(),
3099 'tl_title' => $this->getDBkey(),
3106 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3107 'pr_expiry', 'pr_type', 'pr_level' ];
3108 $where_clauses[] = 'page_id=pr_page';
3111 $cols = [ 'pr_expiry' ];
3114 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3116 $sources = $getPages ?
[] : false;
3117 $now = wfTimestampNow();
3119 foreach ( $res as $row ) {
3120 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3121 if ( $expiry > $now ) {
3123 $page_id = $row->pr_page
;
3124 $page_ns = $row->page_namespace
;
3125 $page_title = $row->page_title
;
3126 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3127 # Add groups needed for each restriction type if its not already there
3128 # Make sure this restriction type still exists
3130 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3131 $pagerestrictions[$row->pr_type
] = [];
3135 isset( $pagerestrictions[$row->pr_type
] )
3136 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3138 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3147 $this->mCascadeSources
= $sources;
3148 $this->mCascadingRestrictions
= $pagerestrictions;
3150 $this->mHasCascadingRestrictions
= $sources;
3153 return [ $sources, $pagerestrictions ];
3157 * Accessor for mRestrictionsLoaded
3159 * @return bool Whether or not the page's restrictions have already been
3160 * loaded from the database
3163 public function areRestrictionsLoaded() {
3164 return $this->mRestrictionsLoaded
;
3168 * Accessor/initialisation for mRestrictions
3170 * @param string $action Action that permission needs to be checked for
3171 * @return array Restriction levels needed to take the action. All levels are
3172 * required. Note that restriction levels are normally user rights, but 'sysop'
3173 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3174 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3176 public function getRestrictions( $action ) {
3177 if ( !$this->mRestrictionsLoaded
) {
3178 $this->loadRestrictions();
3180 return $this->mRestrictions
[$action] ??
[];
3184 * Accessor/initialisation for mRestrictions
3186 * @return array Keys are actions, values are arrays as returned by
3187 * Title::getRestrictions()
3190 public function getAllRestrictions() {
3191 if ( !$this->mRestrictionsLoaded
) {
3192 $this->loadRestrictions();
3194 return $this->mRestrictions
;
3198 * Get the expiry time for the restriction against a given action
3200 * @param string $action
3201 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3202 * or not protected at all, or false if the action is not recognised.
3204 public function getRestrictionExpiry( $action ) {
3205 if ( !$this->mRestrictionsLoaded
) {
3206 $this->loadRestrictions();
3208 return $this->mRestrictionsExpiry
[$action] ??
false;
3212 * Returns cascading restrictions for the current article
3216 function areRestrictionsCascading() {
3217 if ( !$this->mRestrictionsLoaded
) {
3218 $this->loadRestrictions();
3221 return $this->mCascadeRestriction
;
3225 * Compiles list of active page restrictions from both page table (pre 1.10)
3226 * and page_restrictions table for this existing page.
3227 * Public for usage by LiquidThreads.
3229 * @param array $rows Array of db result objects
3230 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3231 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3232 * Edit and move sections are separated by a colon
3233 * Example: "edit=autoconfirmed,sysop:move=sysop"
3235 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3236 $dbr = wfGetDB( DB_REPLICA
);
3238 $restrictionTypes = $this->getRestrictionTypes();
3240 foreach ( $restrictionTypes as $type ) {
3241 $this->mRestrictions
[$type] = [];
3242 $this->mRestrictionsExpiry
[$type] = 'infinity';
3245 $this->mCascadeRestriction
= false;
3247 # Backwards-compatibility: also load the restrictions from the page record (old format).
3248 if ( $oldFashionedRestrictions !== null ) {
3249 $this->mOldRestrictions
= $oldFashionedRestrictions;
3252 if ( $this->mOldRestrictions
=== false ) {
3253 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3254 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3257 if ( $this->mOldRestrictions
!= '' ) {
3258 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3259 $temp = explode( '=', trim( $restrict ) );
3260 if ( count( $temp ) == 1 ) {
3261 // old old format should be treated as edit/move restriction
3262 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3263 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3265 $restriction = trim( $temp[1] );
3266 if ( $restriction != '' ) { // some old entries are empty
3267 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3273 if ( count( $rows ) ) {
3274 # Current system - load second to make them override.
3275 $now = wfTimestampNow();
3277 # Cycle through all the restrictions.
3278 foreach ( $rows as $row ) {
3279 // Don't take care of restrictions types that aren't allowed
3280 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3284 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3286 // Only apply the restrictions if they haven't expired!
3287 if ( !$expiry ||
$expiry > $now ) {
3288 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3289 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3291 $this->mCascadeRestriction |
= $row->pr_cascade
;
3296 $this->mRestrictionsLoaded
= true;
3300 * Load restrictions from the page_restrictions table
3302 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3303 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3304 * Edit and move sections are separated by a colon
3305 * Example: "edit=autoconfirmed,sysop:move=sysop"
3307 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3308 if ( $this->mRestrictionsLoaded
) {
3312 $id = $this->getArticleID();
3314 $cache = ObjectCache
::getMainWANInstance();
3315 $rows = $cache->getWithSetCallback(
3316 // Page protections always leave a new null revision
3317 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3319 function ( $curValue, &$ttl, array &$setOpts ) {
3320 $dbr = wfGetDB( DB_REPLICA
);
3322 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3324 return iterator_to_array(
3326 'page_restrictions',
3327 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3328 [ 'pr_page' => $this->getArticleID() ],
3335 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3337 $title_protection = $this->getTitleProtectionInternal();
3339 if ( $title_protection ) {
3340 $now = wfTimestampNow();
3341 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3343 if ( !$expiry ||
$expiry > $now ) {
3344 // Apply the restrictions
3345 $this->mRestrictionsExpiry
['create'] = $expiry;
3346 $this->mRestrictions
['create'] =
3347 explode( ',', trim( $title_protection['permission'] ) );
3348 } else { // Get rid of the old restrictions
3349 $this->mTitleProtection
= false;
3352 $this->mRestrictionsExpiry
['create'] = 'infinity';
3354 $this->mRestrictionsLoaded
= true;
3359 * Flush the protection cache in this object and force reload from the database.
3360 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3362 public function flushRestrictions() {
3363 $this->mRestrictionsLoaded
= false;
3364 $this->mTitleProtection
= null;
3368 * Purge expired restrictions from the page_restrictions table
3370 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3372 static function purgeExpiredRestrictions() {
3373 if ( wfReadOnly() ) {
3377 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3378 wfGetDB( DB_MASTER
),
3380 function ( IDatabase
$dbw, $fname ) {
3381 $config = MediaWikiServices
::getInstance()->getMainConfig();
3382 $ids = $dbw->selectFieldValues(
3383 'page_restrictions',
3385 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3387 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3390 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3395 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3396 wfGetDB( DB_MASTER
),
3398 function ( IDatabase
$dbw, $fname ) {
3401 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3409 * Does this have subpages? (Warning, usually requires an extra DB query.)
3413 public function hasSubpages() {
3414 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3419 # We dynamically add a member variable for the purpose of this method
3420 # alone to cache the result. There's no point in having it hanging
3421 # around uninitialized in every Title object; therefore we only add it
3422 # if needed and don't declare it statically.
3423 if ( $this->mHasSubpages
=== null ) {
3424 $this->mHasSubpages
= false;
3425 $subpages = $this->getSubpages( 1 );
3426 if ( $subpages instanceof TitleArray
) {
3427 $this->mHasSubpages
= (bool)$subpages->count();
3431 return $this->mHasSubpages
;
3435 * Get all subpages of this page.
3437 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3438 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3439 * doesn't allow subpages
3441 public function getSubpages( $limit = -1 ) {
3442 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3446 $dbr = wfGetDB( DB_REPLICA
);
3447 $conds['page_namespace'] = $this->getNamespace();
3448 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3450 if ( $limit > -1 ) {
3451 $options['LIMIT'] = $limit;
3453 return TitleArray
::newFromResult(
3454 $dbr->select( 'page',
3455 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3464 * Is there a version of this page in the deletion archive?
3466 * @return int The number of archived revisions
3468 public function isDeleted() {
3469 if ( $this->getNamespace() < 0 ) {
3472 $dbr = wfGetDB( DB_REPLICA
);
3474 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3475 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3478 if ( $this->getNamespace() == NS_FILE
) {
3479 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3480 [ 'fa_name' => $this->getDBkey() ],
3489 * Is there a version of this page in the deletion archive?
3493 public function isDeletedQuick() {
3494 if ( $this->getNamespace() < 0 ) {
3497 $dbr = wfGetDB( DB_REPLICA
);
3498 $deleted = (bool)$dbr->selectField( 'archive', '1',
3499 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3502 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3503 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3504 [ 'fa_name' => $this->getDBkey() ],
3512 * Get the article ID for this Title from the link cache,
3513 * adding it if necessary
3515 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3517 * @return int The ID
3519 public function getArticleID( $flags = 0 ) {
3520 if ( $this->getNamespace() < 0 ) {
3521 $this->mArticleID
= 0;
3522 return $this->mArticleID
;
3524 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3525 if ( $flags & self
::GAID_FOR_UPDATE
) {
3526 $oldUpdate = $linkCache->forUpdate( true );
3527 $linkCache->clearLink( $this );
3528 $this->mArticleID
= $linkCache->addLinkObj( $this );
3529 $linkCache->forUpdate( $oldUpdate );
3531 if ( -1 == $this->mArticleID
) {
3532 $this->mArticleID
= $linkCache->addLinkObj( $this );
3535 return $this->mArticleID
;
3539 * Is this an article that is a redirect page?
3540 * Uses link cache, adding it if necessary
3542 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3545 public function isRedirect( $flags = 0 ) {
3546 if ( !is_null( $this->mRedirect
) ) {
3547 return $this->mRedirect
;
3549 if ( !$this->getArticleID( $flags ) ) {
3550 $this->mRedirect
= false;
3551 return $this->mRedirect
;
3554 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3555 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3556 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3557 if ( $cached === null ) {
3558 # Trust LinkCache's state over our own
3559 # LinkCache is telling us that the page doesn't exist, despite there being cached
3560 # data relating to an existing page in $this->mArticleID. Updaters should clear
3561 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3562 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3563 # LinkCache to refresh its data from the master.
3564 $this->mRedirect
= false;
3565 return $this->mRedirect
;
3568 $this->mRedirect
= (bool)$cached;
3570 return $this->mRedirect
;
3574 * What is the length of this page?
3575 * Uses link cache, adding it if necessary
3577 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3580 public function getLength( $flags = 0 ) {
3581 if ( $this->mLength
!= -1 ) {
3582 return $this->mLength
;
3584 if ( !$this->getArticleID( $flags ) ) {
3586 return $this->mLength
;
3588 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3589 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3590 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3591 if ( $cached === null ) {
3592 # Trust LinkCache's state over our own, as for isRedirect()
3594 return $this->mLength
;
3597 $this->mLength
= intval( $cached );
3599 return $this->mLength
;
3603 * What is the page_latest field for this page?
3605 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3606 * @return int Int or 0 if the page doesn't exist
3608 public function getLatestRevID( $flags = 0 ) {
3609 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3610 return intval( $this->mLatestID
);
3612 if ( !$this->getArticleID( $flags ) ) {
3613 $this->mLatestID
= 0;
3614 return $this->mLatestID
;
3616 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3617 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3618 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3619 if ( $cached === null ) {
3620 # Trust LinkCache's state over our own, as for isRedirect()
3621 $this->mLatestID
= 0;
3622 return $this->mLatestID
;
3625 $this->mLatestID
= intval( $cached );
3627 return $this->mLatestID
;
3631 * This clears some fields in this object, and clears any associated
3632 * keys in the "bad links" section of the link cache.
3634 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3635 * loading of the new page_id. It's also called from
3636 * WikiPage::doDeleteArticleReal()
3638 * @param int $newid The new Article ID
3640 public function resetArticleID( $newid ) {
3641 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3642 $linkCache->clearLink( $this );
3644 if ( $newid === false ) {
3645 $this->mArticleID
= -1;
3647 $this->mArticleID
= intval( $newid );
3649 $this->mRestrictionsLoaded
= false;
3650 $this->mRestrictions
= [];
3651 $this->mOldRestrictions
= false;
3652 $this->mRedirect
= null;
3653 $this->mLength
= -1;
3654 $this->mLatestID
= false;
3655 $this->mContentModel
= false;
3656 $this->mEstimateRevisions
= null;
3657 $this->mPageLanguage
= false;
3658 $this->mDbPageLanguage
= false;
3659 $this->mIsBigDeletion
= null;
3662 public static function clearCaches() {
3663 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3664 $linkCache->clear();
3666 $titleCache = self
::getTitleCache();
3667 $titleCache->clear();
3671 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3673 * @param string $text Containing title to capitalize
3674 * @param int $ns Namespace index, defaults to NS_MAIN
3675 * @return string Containing capitalized title
3677 public static function capitalize( $text, $ns = NS_MAIN
) {
3678 if ( MWNamespace
::isCapitalized( $ns ) ) {
3679 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3686 * Secure and split - main initialisation function for this object
3688 * Assumes that mDbkeyform has been set, and is urldecoded
3689 * and uses underscores, but not otherwise munged. This function
3690 * removes illegal characters, splits off the interwiki and
3691 * namespace prefixes, sets the other forms, and canonicalizes
3694 * @throws MalformedTitleException On invalid titles
3695 * @return bool True on success
3697 private function secureAndSplit() {
3699 $this->mInterwiki
= '';
3700 $this->mFragment
= '';
3701 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3703 $dbkey = $this->mDbkeyform
;
3705 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3706 // the parsing code with Title, while avoiding massive refactoring.
3707 // @todo: get rid of secureAndSplit, refactor parsing code.
3708 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3709 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3710 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3711 // MalformedTitleException can be thrown here
3712 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3715 $this->setFragment( '#' . $parts['fragment'] );
3716 $this->mInterwiki
= $parts['interwiki'];
3717 $this->mLocalInterwiki
= $parts['local_interwiki'];
3718 $this->mNamespace
= $parts['namespace'];
3719 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3721 $this->mDbkeyform
= $parts['dbkey'];
3722 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3723 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3725 # We already know that some pages won't be in the database!
3726 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3727 $this->mArticleID
= 0;
3734 * Get an array of Title objects linking to this Title
3735 * Also stores the IDs in the link cache.
3737 * WARNING: do not use this function on arbitrary user-supplied titles!
3738 * On heavily-used templates it will max out the memory.
3740 * @param array $options May be FOR UPDATE
3741 * @param string $table Table name
3742 * @param string $prefix Fields prefix
3743 * @return Title[] Array of Title objects linking here
3745 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3746 if ( count( $options ) > 0 ) {
3747 $db = wfGetDB( DB_MASTER
);
3749 $db = wfGetDB( DB_REPLICA
);
3754 self
::getSelectFields(),
3756 "{$prefix}_from=page_id",
3757 "{$prefix}_namespace" => $this->getNamespace(),
3758 "{$prefix}_title" => $this->getDBkey() ],
3764 if ( $res->numRows() ) {
3765 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3766 foreach ( $res as $row ) {
3767 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3769 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3770 $retVal[] = $titleObj;
3778 * Get an array of Title objects using this Title as a template
3779 * Also stores the IDs in the link cache.
3781 * WARNING: do not use this function on arbitrary user-supplied titles!
3782 * On heavily-used templates it will max out the memory.
3784 * @param array $options Query option to Database::select()
3785 * @return Title[] Array of Title the Title objects linking here
3787 public function getTemplateLinksTo( $options = [] ) {
3788 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3792 * Get an array of Title objects linked from this Title
3793 * Also stores the IDs in the link cache.
3795 * WARNING: do not use this function on arbitrary user-supplied titles!
3796 * On heavily-used templates it will max out the memory.
3798 * @param array $options Query option to Database::select()
3799 * @param string $table Table name
3800 * @param string $prefix Fields prefix
3801 * @return array Array of Title objects linking here
3803 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3804 $id = $this->getArticleID();
3806 # If the page doesn't exist; there can't be any link from this page
3811 $db = wfGetDB( DB_REPLICA
);
3813 $blNamespace = "{$prefix}_namespace";
3814 $blTitle = "{$prefix}_title";
3816 $pageQuery = WikiPage
::getQueryInfo();
3818 [ $table, 'nestpage' => $pageQuery['tables'] ],
3820 [ $blNamespace, $blTitle ],
3821 $pageQuery['fields']
3823 [ "{$prefix}_from" => $id ],
3828 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3829 ] ] +
$pageQuery['joins']
3833 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3834 foreach ( $res as $row ) {
3835 if ( $row->page_id
) {
3836 $titleObj = self
::newFromRow( $row );
3838 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3839 $linkCache->addBadLinkObj( $titleObj );
3841 $retVal[] = $titleObj;
3848 * Get an array of Title objects used on this Title as a template
3849 * Also stores the IDs in the link cache.
3851 * WARNING: do not use this function on arbitrary user-supplied titles!
3852 * On heavily-used templates it will max out the memory.
3854 * @param array $options May be FOR UPDATE
3855 * @return Title[] Array of Title the Title objects used here
3857 public function getTemplateLinksFrom( $options = [] ) {
3858 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3862 * Get an array of Title objects referring to non-existent articles linked
3865 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3866 * should use redirect table in this case).
3867 * @return Title[] Array of Title the Title objects
3869 public function getBrokenLinksFrom() {
3870 if ( $this->getArticleID() == 0 ) {
3871 # All links from article ID 0 are false positives
3875 $dbr = wfGetDB( DB_REPLICA
);
3876 $res = $dbr->select(
3877 [ 'page', 'pagelinks' ],
3878 [ 'pl_namespace', 'pl_title' ],
3880 'pl_from' => $this->getArticleID(),
3881 'page_namespace IS NULL'
3887 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3893 foreach ( $res as $row ) {
3894 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3900 * Get a list of URLs to purge from the CDN cache when this
3903 * @return string[] Array of String the URLs
3905 public function getCdnUrls() {
3907 $this->getInternalURL(),
3908 $this->getInternalURL( 'action=history' )
3911 $pageLang = $this->getPageLanguage();
3912 if ( $pageLang->hasVariants() ) {
3913 $variants = $pageLang->getVariants();
3914 foreach ( $variants as $vCode ) {
3915 $urls[] = $this->getInternalURL( $vCode );
3919 // If we are looking at a css/js user subpage, purge the action=raw.
3920 if ( $this->isUserJsConfigPage() ) {
3921 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3922 } elseif ( $this->isUserJsonConfigPage() ) {
3923 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3924 } elseif ( $this->isUserCssConfigPage() ) {
3925 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3928 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3933 * @deprecated since 1.27 use getCdnUrls()
3935 public function getSquidURLs() {
3936 return $this->getCdnUrls();
3940 * Purge all applicable CDN URLs
3942 public function purgeSquid() {
3943 DeferredUpdates
::addUpdate(
3944 new CdnCacheUpdate( $this->getCdnUrls() ),
3945 DeferredUpdates
::PRESEND
3950 * Check whether a given move operation would be valid.
3951 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3953 * @deprecated since 1.25, use MovePage's methods instead
3954 * @param Title &$nt The new title
3955 * @param bool $auth Whether to check user permissions (uses $wgUser)
3956 * @param string $reason Is the log summary of the move, used for spam checking
3957 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3959 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3962 if ( !( $nt instanceof Title
) ) {
3963 // Normally we'd add this to $errors, but we'll get
3964 // lots of syntax errors if $nt is not an object
3965 return [ [ 'badtitletext' ] ];
3968 $mp = new MovePage( $this, $nt );
3969 $errors = $mp->isValidMove()->getErrorsArray();
3971 $errors = wfMergeErrorArrays(
3973 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3977 return $errors ?
: true;
3981 * Check if the requested move target is a valid file move target
3982 * @todo move this to MovePage
3983 * @param Title $nt Target title
3984 * @return array List of errors
3986 protected function validateFileMoveOperation( $nt ) {
3991 $destFile = wfLocalFile( $nt );
3992 $destFile->load( File
::READ_LATEST
);
3993 if ( !$wgUser->isAllowed( 'reupload-shared' )
3994 && !$destFile->exists() && wfFindFile( $nt )
3996 $errors[] = [ 'file-exists-sharedrepo' ];
4003 * Move a title to a new location
4005 * @deprecated since 1.25, use the MovePage class instead
4006 * @param Title &$nt The new title
4007 * @param bool $auth Indicates whether $wgUser's permissions
4009 * @param string $reason The reason for the move
4010 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4011 * Ignored if the user doesn't have the suppressredirect right.
4012 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4013 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4015 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4016 array $changeTags = []
4019 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4020 if ( is_array( $err ) ) {
4021 // Auto-block user's IP if the account was "hard" blocked
4022 $wgUser->spreadAnyEditBlock();
4025 // Check suppressredirect permission
4026 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4027 $createRedirect = true;
4030 $mp = new MovePage( $this, $nt );
4031 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4032 if ( $status->isOK() ) {
4035 return $status->getErrorsArray();
4040 * Move this page's subpages to be subpages of $nt
4042 * @param Title $nt Move target
4043 * @param bool $auth Whether $wgUser's permissions should be checked
4044 * @param string $reason The reason for the move
4045 * @param bool $createRedirect Whether to create redirects from the old subpages to
4046 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4047 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4048 * @return array Array with old page titles as keys, and strings (new page titles) or
4049 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4050 * getUserPermissionsErrors()-like error array with numeric indices if
4051 * no pages were moved
4053 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4054 array $changeTags = []
4056 global $wgMaximumMovedPages;
4057 // Check permissions
4058 if ( !$this->userCan( 'move-subpages' ) ) {
4060 [ 'cant-move-subpages' ],
4063 // Do the source and target namespaces support subpages?
4064 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4066 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
4069 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4071 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4075 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4078 foreach ( $subpages as $oldSubpage ) {
4080 if ( $count > $wgMaximumMovedPages ) {
4081 $retval[$oldSubpage->getPrefixedText()] = [
4082 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4087 // We don't know whether this function was called before
4088 // or after moving the root page, so check both
4090 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4091 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4093 // When moving a page to a subpage of itself,
4094 // don't move it twice
4097 $newPageName = preg_replace(
4098 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4099 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4100 $oldSubpage->getDBkey() );
4101 if ( $oldSubpage->isTalkPage() ) {
4102 $newNs = $nt->getTalkPage()->getNamespace();
4104 $newNs = $nt->getSubjectPage()->getNamespace();
4106 # T16385: we need makeTitleSafe because the new page names may
4107 # be longer than 255 characters.
4108 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4110 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4111 if ( $success === true ) {
4112 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4114 $retval[$oldSubpage->getPrefixedText()] = $success;
4121 * Checks if this page is just a one-rev redirect.
4122 * Adds lock, so don't use just for light purposes.
4126 public function isSingleRevRedirect() {
4127 global $wgContentHandlerUseDB;
4129 $dbw = wfGetDB( DB_MASTER
);
4132 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4133 if ( $wgContentHandlerUseDB ) {
4134 $fields[] = 'page_content_model';
4137 $row = $dbw->selectRow( 'page',
4143 # Cache some fields we may want
4144 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4145 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4146 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4147 $this->mContentModel
= $row && isset( $row->page_content_model
)
4148 ?
strval( $row->page_content_model
)
4151 if ( !$this->mRedirect
) {
4154 # Does the article have a history?
4155 $row = $dbw->selectField( [ 'page', 'revision' ],
4157 [ 'page_namespace' => $this->getNamespace(),
4158 'page_title' => $this->getDBkey(),
4160 'page_latest != rev_id'
4165 # Return true if there was no history
4166 return ( $row === false );
4170 * Checks if $this can be moved to a given Title
4171 * - Selects for update, so don't call it unless you mean business
4173 * @deprecated since 1.25, use MovePage's methods instead
4174 * @param Title $nt The new title to check
4177 public function isValidMoveTarget( $nt ) {
4178 # Is it an existing file?
4179 if ( $nt->getNamespace() == NS_FILE
) {
4180 $file = wfLocalFile( $nt );
4181 $file->load( File
::READ_LATEST
);
4182 if ( $file->exists() ) {
4183 wfDebug( __METHOD__
. ": file exists\n" );
4187 # Is it a redirect with no history?
4188 if ( !$nt->isSingleRevRedirect() ) {
4189 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4192 # Get the article text
4193 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4194 if ( !is_object( $rev ) ) {
4197 $content = $rev->getContent();
4198 # Does the redirect point to the source?
4199 # Or is it a broken self-redirect, usually caused by namespace collisions?
4200 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4202 if ( $redirTitle ) {
4203 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4204 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4205 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4211 # Fail safe (not a redirect after all. strange.)
4212 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4213 " is a redirect, but it doesn't contain a valid redirect.\n" );
4219 * Get categories to which this Title belongs and return an array of
4220 * categories' names.
4222 * @return array Array of parents in the form:
4223 * $parent => $currentarticle
4225 public function getParentCategories() {
4228 $titleKey = $this->getArticleID();
4230 if ( $titleKey === 0 ) {
4234 $dbr = wfGetDB( DB_REPLICA
);
4236 $res = $dbr->select(
4239 [ 'cl_from' => $titleKey ],
4243 if ( $res->numRows() > 0 ) {
4244 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4245 foreach ( $res as $row ) {
4246 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4247 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4248 $this->getFullText();
4255 * Get a tree of parent categories
4257 * @param array $children Array with the children in the keys, to check for circular refs
4258 * @return array Tree of parent categories
4260 public function getParentCategoryTree( $children = [] ) {
4262 $parents = $this->getParentCategories();
4265 foreach ( $parents as $parent => $current ) {
4266 if ( array_key_exists( $parent, $children ) ) {
4267 # Circular reference
4268 $stack[$parent] = [];
4270 $nt = self
::newFromText( $parent );
4272 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4282 * Get an associative array for selecting this title from
4285 * @return array Array suitable for the $where parameter of DB::select()
4287 public function pageCond() {
4288 if ( $this->mArticleID
> 0 ) {
4289 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4290 return [ 'page_id' => $this->mArticleID
];
4292 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4297 * Get next/previous revision ID relative to another revision ID
4298 * @param int $revId Revision ID. Get the revision that was before this one.
4299 * @param int $flags Title::GAID_FOR_UPDATE
4300 * @param string $dir 'next' or 'prev'
4301 * @return int|bool New revision ID, or false if none exists
4303 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4304 $revId = (int)$revId;
4305 if ( $dir === 'next' ) {
4308 } elseif ( $dir === 'prev' ) {
4312 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4315 if ( $flags & self
::GAID_FOR_UPDATE
) {
4316 $db = wfGetDB( DB_MASTER
);
4318 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4321 // Intentionally not caring if the specified revision belongs to this
4322 // page. We only care about the timestamp.
4323 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4324 if ( $ts === false ) {
4325 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4326 if ( $ts === false ) {
4327 // Or should this throw an InvalidArgumentException or something?
4331 $ts = $db->addQuotes( $ts );
4333 $revId = $db->selectField( 'revision', 'rev_id',
4335 'rev_page' => $this->getArticleID( $flags ),
4336 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4340 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4341 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4345 if ( $revId === false ) {
4348 return intval( $revId );
4353 * Get the revision ID of the previous revision
4355 * @param int $revId Revision ID. Get the revision that was before this one.
4356 * @param int $flags Title::GAID_FOR_UPDATE
4357 * @return int|bool Old revision ID, or false if none exists
4359 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4360 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4364 * Get the revision ID of the next revision
4366 * @param int $revId Revision ID. Get the revision that was after this one.
4367 * @param int $flags Title::GAID_FOR_UPDATE
4368 * @return int|bool Next revision ID, or false if none exists
4370 public function getNextRevisionID( $revId, $flags = 0 ) {
4371 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4375 * Get the first revision of the page
4377 * @param int $flags Title::GAID_FOR_UPDATE
4378 * @return Revision|null If page doesn't exist
4380 public function getFirstRevision( $flags = 0 ) {
4381 $pageId = $this->getArticleID( $flags );
4383 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4384 $revQuery = Revision
::getQueryInfo();
4385 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4386 [ 'rev_page' => $pageId ],
4389 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4390 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4395 return new Revision( $row );
4402 * Get the oldest revision timestamp of this page
4404 * @param int $flags Title::GAID_FOR_UPDATE
4405 * @return string MW timestamp
4407 public function getEarliestRevTime( $flags = 0 ) {
4408 $rev = $this->getFirstRevision( $flags );
4409 return $rev ?
$rev->getTimestamp() : null;
4413 * Check if this is a new page
4417 public function isNewPage() {
4418 $dbr = wfGetDB( DB_REPLICA
);
4419 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4423 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4427 public function isBigDeletion() {
4428 global $wgDeleteRevisionsLimit;
4430 if ( !$wgDeleteRevisionsLimit ) {
4434 if ( $this->mIsBigDeletion
=== null ) {
4435 $dbr = wfGetDB( DB_REPLICA
);
4437 $revCount = $dbr->selectRowCount(
4440 [ 'rev_page' => $this->getArticleID() ],
4442 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4445 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4448 return $this->mIsBigDeletion
;
4452 * Get the approximate revision count of this page.
4456 public function estimateRevisionCount() {
4457 if ( !$this->exists() ) {
4461 if ( $this->mEstimateRevisions
=== null ) {
4462 $dbr = wfGetDB( DB_REPLICA
);
4463 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4464 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4467 return $this->mEstimateRevisions
;
4471 * Get the number of revisions between the given revision.
4472 * Used for diffs and other things that really need it.
4474 * @param int|Revision $old Old revision or rev ID (first before range)
4475 * @param int|Revision $new New revision or rev ID (first after range)
4476 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4477 * @return int Number of revisions between these revisions.
4479 public function countRevisionsBetween( $old, $new, $max = null ) {
4480 if ( !( $old instanceof Revision
) ) {
4481 $old = Revision
::newFromTitle( $this, (int)$old );
4483 if ( !( $new instanceof Revision
) ) {
4484 $new = Revision
::newFromTitle( $this, (int)$new );
4486 if ( !$old ||
!$new ) {
4487 return 0; // nothing to compare
4489 $dbr = wfGetDB( DB_REPLICA
);
4491 'rev_page' => $this->getArticleID(),
4492 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4493 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4495 if ( $max !== null ) {
4496 return $dbr->selectRowCount( 'revision', '1',
4499 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4502 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4507 * Get the authors between the given revisions or revision IDs.
4508 * Used for diffs and other things that really need it.
4512 * @param int|Revision $old Old revision or rev ID (first before range by default)
4513 * @param int|Revision $new New revision or rev ID (first after range by default)
4514 * @param int $limit Maximum number of authors
4515 * @param string|array $options (Optional): Single option, or an array of options:
4516 * 'include_old' Include $old in the range; $new is excluded.
4517 * 'include_new' Include $new in the range; $old is excluded.
4518 * 'include_both' Include both $old and $new in the range.
4519 * Unknown option values are ignored.
4520 * @return array|null Names of revision authors in the range; null if not both revisions exist
4522 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4523 if ( !( $old instanceof Revision
) ) {
4524 $old = Revision
::newFromTitle( $this, (int)$old );
4526 if ( !( $new instanceof Revision
) ) {
4527 $new = Revision
::newFromTitle( $this, (int)$new );
4529 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4530 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4531 // in the sanity check below?
4532 if ( !$old ||
!$new ) {
4533 return null; // nothing to compare
4538 $options = (array)$options;
4539 if ( in_array( 'include_old', $options ) ) {
4542 if ( in_array( 'include_new', $options ) ) {
4545 if ( in_array( 'include_both', $options ) ) {
4549 // No DB query needed if $old and $new are the same or successive revisions:
4550 if ( $old->getId() === $new->getId() ) {
4551 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4553 [ $old->getUserText( Revision
::RAW
) ];
4554 } elseif ( $old->getId() === $new->getParentId() ) {
4555 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4556 $authors[] = $old->getUserText( Revision
::RAW
);
4557 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4558 $authors[] = $new->getUserText( Revision
::RAW
);
4560 } elseif ( $old_cmp === '>=' ) {
4561 $authors[] = $old->getUserText( Revision
::RAW
);
4562 } elseif ( $new_cmp === '<=' ) {
4563 $authors[] = $new->getUserText( Revision
::RAW
);
4567 $dbr = wfGetDB( DB_REPLICA
);
4568 $revQuery = Revision
::getQueryInfo();
4569 $authors = $dbr->selectFieldValues(
4570 $revQuery['tables'],
4571 $revQuery['fields']['rev_user_text'],
4573 'rev_page' => $this->getArticleID(),
4574 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4575 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4577 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4584 * Get the number of authors between the given revisions or revision IDs.
4585 * Used for diffs and other things that really need it.
4587 * @param int|Revision $old Old revision or rev ID (first before range by default)
4588 * @param int|Revision $new New revision or rev ID (first after range by default)
4589 * @param int $limit Maximum number of authors
4590 * @param string|array $options (Optional): Single option, or an array of options:
4591 * 'include_old' Include $old in the range; $new is excluded.
4592 * 'include_new' Include $new in the range; $old is excluded.
4593 * 'include_both' Include both $old and $new in the range.
4594 * Unknown option values are ignored.
4595 * @return int Number of revision authors in the range; zero if not both revisions exist
4597 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4598 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4599 return $authors ?
count( $authors ) : 0;
4603 * Compare with another title.
4605 * @param Title $title
4608 public function equals( Title
$title ) {
4609 // Note: === is necessary for proper matching of number-like titles.
4610 return $this->getInterwiki() === $title->getInterwiki()
4611 && $this->getNamespace() == $title->getNamespace()
4612 && $this->getDBkey() === $title->getDBkey();
4616 * Check if this title is a subpage of another title
4618 * @param Title $title
4621 public function isSubpageOf( Title
$title ) {
4622 return $this->getInterwiki() === $title->getInterwiki()
4623 && $this->getNamespace() == $title->getNamespace()
4624 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4628 * Check if page exists. For historical reasons, this function simply
4629 * checks for the existence of the title in the page table, and will
4630 * thus return false for interwiki links, special pages and the like.
4631 * If you want to know if a title can be meaningfully viewed, you should
4632 * probably call the isKnown() method instead.
4634 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4635 * from master/for update
4638 public function exists( $flags = 0 ) {
4639 $exists = $this->getArticleID( $flags ) != 0;
4640 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4645 * Should links to this title be shown as potentially viewable (i.e. as
4646 * "bluelinks"), even if there's no record by this title in the page
4649 * This function is semi-deprecated for public use, as well as somewhat
4650 * misleadingly named. You probably just want to call isKnown(), which
4651 * calls this function internally.
4653 * (ISSUE: Most of these checks are cheap, but the file existence check
4654 * can potentially be quite expensive. Including it here fixes a lot of
4655 * existing code, but we might want to add an optional parameter to skip
4656 * it and any other expensive checks.)
4660 public function isAlwaysKnown() {
4664 * Allows overriding default behavior for determining if a page exists.
4665 * If $isKnown is kept as null, regular checks happen. If it's
4666 * a boolean, this value is returned by the isKnown method.
4670 * @param Title $title
4671 * @param bool|null $isKnown
4673 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4675 if ( !is_null( $isKnown ) ) {
4679 if ( $this->isExternal() ) {
4680 return true; // any interwiki link might be viewable, for all we know
4683 switch ( $this->mNamespace
) {
4686 // file exists, possibly in a foreign repo
4687 return (bool)wfFindFile( $this );
4689 // valid special page
4690 return SpecialPageFactory
::exists( $this->getDBkey() );
4692 // selflink, possibly with fragment
4693 return $this->mDbkeyform
== '';
4695 // known system message
4696 return $this->hasSourceText() !== false;
4703 * Does this title refer to a page that can (or might) be meaningfully
4704 * viewed? In particular, this function may be used to determine if
4705 * links to the title should be rendered as "bluelinks" (as opposed to
4706 * "redlinks" to non-existent pages).
4707 * Adding something else to this function will cause inconsistency
4708 * since LinkHolderArray calls isAlwaysKnown() and does its own
4709 * page existence check.
4713 public function isKnown() {
4714 return $this->isAlwaysKnown() ||
$this->exists();
4718 * Does this page have source text?
4722 public function hasSourceText() {
4723 if ( $this->exists() ) {
4727 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4728 // If the page doesn't exist but is a known system message, default
4729 // message content will be displayed, same for language subpages-
4730 // Use always content language to avoid loading hundreds of languages
4731 // to get the link color.
4732 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4733 list( $name, ) = MessageCache
::singleton()->figureMessage(
4734 $contLang->lcfirst( $this->getText() )
4736 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4737 return $message->exists();
4744 * Get the default message text or false if the message doesn't exist
4746 * @return string|bool
4748 public function getDefaultMessageText() {
4749 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4753 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4754 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4756 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4758 if ( $message->exists() ) {
4759 return $message->plain();
4766 * Updates page_touched for this page; called from LinksUpdate.php
4768 * @param string|null $purgeTime [optional] TS_MW timestamp
4769 * @return bool True if the update succeeded
4771 public function invalidateCache( $purgeTime = null ) {
4772 if ( wfReadOnly() ) {
4774 } elseif ( $this->mArticleID
=== 0 ) {
4775 return true; // avoid gap locking if we know it's not there
4778 $dbw = wfGetDB( DB_MASTER
);
4779 $dbw->onTransactionPreCommitOrIdle(
4781 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4786 $conds = $this->pageCond();
4787 DeferredUpdates
::addUpdate(
4788 new AutoCommitUpdate(
4791 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4792 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4795 [ 'page_touched' => $dbTimestamp ],
4796 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4799 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4802 DeferredUpdates
::PRESEND
4809 * Update page_touched timestamps and send CDN purge messages for
4810 * pages linking to this title. May be sent to the job queue depending
4811 * on the number of links. Typically called on create and delete.
4813 public function touchLinks() {
4814 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4815 if ( $this->getNamespace() == NS_CATEGORY
) {
4816 DeferredUpdates
::addUpdate(
4817 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4823 * Get the last touched timestamp
4825 * @param IDatabase|null $db
4826 * @return string|false Last-touched timestamp
4828 public function getTouched( $db = null ) {
4829 if ( $db === null ) {
4830 $db = wfGetDB( DB_REPLICA
);
4832 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4837 * Get the timestamp when this page was updated since the user last saw it.
4839 * @param User|null $user
4840 * @return string|null
4842 public function getNotificationTimestamp( $user = null ) {
4845 // Assume current user if none given
4849 // Check cache first
4850 $uid = $user->getId();
4854 // avoid isset here, as it'll return false for null entries
4855 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4856 return $this->mNotificationTimestamp
[$uid];
4858 // Don't cache too much!
4859 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4860 $this->mNotificationTimestamp
= [];
4863 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4864 $watchedItem = $store->getWatchedItem( $user, $this );
4865 if ( $watchedItem ) {
4866 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4868 $this->mNotificationTimestamp
[$uid] = false;
4871 return $this->mNotificationTimestamp
[$uid];
4875 * Generate strings used for xml 'id' names in monobook tabs
4877 * @param string $prepend Defaults to 'nstab-'
4878 * @return string XML 'id' name
4880 public function getNamespaceKey( $prepend = 'nstab-' ) {
4881 // Gets the subject namespace of this title
4882 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
4883 // Prefer canonical namespace name for HTML IDs
4884 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4885 if ( $namespaceKey === false ) {
4886 // Fallback to localised text
4887 $namespaceKey = $this->getSubjectNsText();
4889 // Makes namespace key lowercase
4890 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4892 if ( $namespaceKey == '' ) {
4893 $namespaceKey = 'main';
4895 // Changes file to image for backwards compatibility
4896 if ( $namespaceKey == 'file' ) {
4897 $namespaceKey = 'image';
4899 return $prepend . $namespaceKey;
4903 * Get all extant redirects to this Title
4905 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4906 * @return Title[] Array of Title redirects to this title
4908 public function getRedirectsHere( $ns = null ) {
4911 $dbr = wfGetDB( DB_REPLICA
);
4913 'rd_namespace' => $this->getNamespace(),
4914 'rd_title' => $this->getDBkey(),
4917 if ( $this->isExternal() ) {
4918 $where['rd_interwiki'] = $this->getInterwiki();
4920 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4922 if ( !is_null( $ns ) ) {
4923 $where['page_namespace'] = $ns;
4926 $res = $dbr->select(
4927 [ 'redirect', 'page' ],
4928 [ 'page_namespace', 'page_title' ],
4933 foreach ( $res as $row ) {
4934 $redirs[] = self
::newFromRow( $row );
4940 * Check if this Title is a valid redirect target
4944 public function isValidRedirectTarget() {
4945 global $wgInvalidRedirectTargets;
4947 if ( $this->isSpecialPage() ) {
4948 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4949 if ( $this->isSpecial( 'Userlogout' ) ) {
4953 foreach ( $wgInvalidRedirectTargets as $target ) {
4954 if ( $this->isSpecial( $target ) ) {
4964 * Get a backlink cache object
4966 * @return BacklinkCache
4968 public function getBacklinkCache() {
4969 return BacklinkCache
::get( $this );
4973 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4977 public function canUseNoindex() {
4978 global $wgExemptFromUserRobotsControl;
4980 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4981 ? MWNamespace
::getContentNamespaces()
4982 : $wgExemptFromUserRobotsControl;
4984 return !in_array( $this->mNamespace
, $bannedNamespaces );
4988 * Returns the raw sort key to be used for categories, with the specified
4989 * prefix. This will be fed to Collation::getSortKey() to get a
4990 * binary sortkey that can be used for actual sorting.
4992 * @param string $prefix The prefix to be used, specified using
4993 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4997 public function getCategorySortkey( $prefix = '' ) {
4998 $unprefixed = $this->getText();
5000 // Anything that uses this hook should only depend
5001 // on the Title object passed in, and should probably
5002 // tell the users to run updateCollations.php --force
5003 // in order to re-sort existing category relations.
5004 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5005 if ( $prefix !== '' ) {
5006 # Separate with a line feed, so the unprefixed part is only used as
5007 # a tiebreaker when two pages have the exact same prefix.
5008 # In UCA, tab is the only character that can sort above LF
5009 # so we strip both of them from the original prefix.
5010 $prefix = strtr( $prefix, "\n\t", ' ' );
5011 return "$prefix\n$unprefixed";
5017 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5018 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5019 * the db, it will return NULL.
5021 * @return string|null|bool
5023 private function getDbPageLanguageCode() {
5024 global $wgPageLanguageUseDB;
5026 // check, if the page language could be saved in the database, and if so and
5027 // the value is not requested already, lookup the page language using LinkCache
5028 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5029 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5030 $linkCache->addLinkObj( $this );
5031 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5034 return $this->mDbPageLanguage
;
5038 * Get the language in which the content of this page is written in
5039 * wikitext. Defaults to content language, but in certain cases it can be
5040 * e.g. $wgLang (such as special pages, which are in the user language).
5045 public function getPageLanguage() {
5046 global $wgLang, $wgLanguageCode;
5047 if ( $this->isSpecialPage() ) {
5048 // special pages are in the user language
5052 // Checking if DB language is set
5053 $dbPageLanguage = $this->getDbPageLanguageCode();
5054 if ( $dbPageLanguage ) {
5055 return wfGetLangObj( $dbPageLanguage );
5058 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5059 // Note that this may depend on user settings, so the cache should
5060 // be only per-request.
5061 // NOTE: ContentHandler::getPageLanguage() may need to load the
5062 // content to determine the page language!
5063 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5065 $contentHandler = ContentHandler
::getForTitle( $this );
5066 $langObj = $contentHandler->getPageLanguage( $this );
5067 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5069 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5076 * Get the language in which the content of this page is written when
5077 * viewed by user. Defaults to content language, but in certain cases it can be
5078 * e.g. $wgLang (such as special pages, which are in the user language).
5083 public function getPageViewLanguage() {
5086 if ( $this->isSpecialPage() ) {
5087 // If the user chooses a variant, the content is actually
5088 // in a language whose code is the variant code.
5089 $variant = $wgLang->getPreferredVariant();
5090 if ( $wgLang->getCode() !== $variant ) {
5091 return Language
::factory( $variant );
5097 // Checking if DB language is set
5098 $dbPageLanguage = $this->getDbPageLanguageCode();
5099 if ( $dbPageLanguage ) {
5100 $pageLang = wfGetLangObj( $dbPageLanguage );
5101 $variant = $pageLang->getPreferredVariant();
5102 if ( $pageLang->getCode() !== $variant ) {
5103 $pageLang = Language
::factory( $variant );
5109 // @note Can't be cached persistently, depends on user settings.
5110 // @note ContentHandler::getPageViewLanguage() may need to load the
5111 // content to determine the page language!
5112 $contentHandler = ContentHandler
::getForTitle( $this );
5113 $pageLang = $contentHandler->getPageViewLanguage( $this );
5118 * Get a list of rendered edit notices for this page.
5120 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5121 * they will already be wrapped in paragraphs.
5124 * @param int $oldid Revision ID that's being edited
5127 public function getEditNotices( $oldid = 0 ) {
5130 // Optional notice for the entire namespace
5131 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5132 $msg = wfMessage( $editnotice_ns );
5133 if ( $msg->exists() ) {
5134 $html = $msg->parseAsBlock();
5135 // Edit notices may have complex logic, but output nothing (T91715)
5136 if ( trim( $html ) !== '' ) {
5137 $notices[$editnotice_ns] = Html
::rawElement(
5141 'mw-editnotice-namespace',
5142 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5149 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5150 // Optional notice for page itself and any parent page
5151 $parts = explode( '/', $this->getDBkey() );
5152 $editnotice_base = $editnotice_ns;
5153 while ( count( $parts ) > 0 ) {
5154 $editnotice_base .= '-' . array_shift( $parts );
5155 $msg = wfMessage( $editnotice_base );
5156 if ( $msg->exists() ) {
5157 $html = $msg->parseAsBlock();
5158 if ( trim( $html ) !== '' ) {
5159 $notices[$editnotice_base] = Html
::rawElement(
5163 'mw-editnotice-base',
5164 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5172 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5173 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
5174 $msg = wfMessage( $editnoticeText );
5175 if ( $msg->exists() ) {
5176 $html = $msg->parseAsBlock();
5177 if ( trim( $html ) !== '' ) {
5178 $notices[$editnoticeText] = Html
::rawElement(
5182 'mw-editnotice-page',
5183 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5191 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5198 public function __sleep() {
5206 'mDefaultNamespace',
5210 public function __wakeup() {
5211 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5212 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5213 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );