3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
{
40 /** @var HashBagOStuff */
41 static private $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
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' );
311 $titleCache = self
::getTitleCache();
313 // Wiki pages often contain multiple links to the same page.
314 // Title normalization and parsing can become expensive on pages with many
315 // links, so we can save a little time by caching them.
316 // In theory these are value objects and won't get changed...
317 if ( $defaultNamespace == NS_MAIN
) {
318 $t = $titleCache->get( $text );
324 // Convert things like é ā or 〗 into normalized (T16952) text
325 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
328 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
329 $t->mDefaultNamespace
= intval( $defaultNamespace );
331 $t->secureAndSplit();
332 if ( $defaultNamespace == NS_MAIN
) {
333 $titleCache->set( $text, $t );
339 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
341 * Example of wrong and broken code:
342 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
344 * Example of right code:
345 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
347 * Create a new Title from URL-encoded text. Ensures that
348 * the given title's length does not exceed the maximum.
350 * @param string $url The title, as might be taken from a URL
351 * @return Title|null The new object, or null on an error
353 public static function newFromURL( $url ) {
356 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
357 # but some URLs used it as a space replacement and they still come
358 # from some external search tools.
359 if ( strpos( self
::legalChars(), '+' ) === false ) {
360 $url = strtr( $url, '+', ' ' );
363 $t->mDbkeyform
= strtr( $url, ' ', '_' );
366 $t->secureAndSplit();
368 } catch ( MalformedTitleException
$ex ) {
374 * @return HashBagOStuff
376 private static function getTitleCache() {
377 if ( self
::$titleCache == null ) {
378 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
380 return self
::$titleCache;
384 * Returns a list of fields that are to be selected for initializing Title
385 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
386 * whether to include page_content_model.
390 protected static function getSelectFields() {
391 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
394 'page_namespace', 'page_title', 'page_id',
395 'page_len', 'page_is_redirect', 'page_latest',
398 if ( $wgContentHandlerUseDB ) {
399 $fields[] = 'page_content_model';
402 if ( $wgPageLanguageUseDB ) {
403 $fields[] = 'page_lang';
410 * Create a new Title from an article ID
412 * @param int $id The page_id corresponding to the Title to create
413 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
414 * @return Title|null The new object, or null on an error
416 public static function newFromID( $id, $flags = 0 ) {
417 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
418 $row = $db->selectRow(
420 self
::getSelectFields(),
421 [ 'page_id' => $id ],
424 if ( $row !== false ) {
425 $title = self
::newFromRow( $row );
433 * Make an array of titles from an array of IDs
435 * @param int[] $ids Array of IDs
436 * @return Title[] Array of Titles
438 public static function newFromIDs( $ids ) {
439 if ( !count( $ids ) ) {
442 $dbr = wfGetDB( DB_REPLICA
);
446 self
::getSelectFields(),
447 [ 'page_id' => $ids ],
452 foreach ( $res as $row ) {
453 $titles[] = self
::newFromRow( $row );
459 * Make a Title object from a DB row
461 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
462 * @return Title Corresponding Title
464 public static function newFromRow( $row ) {
465 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
466 $t->loadFromRow( $row );
471 * Load Title object fields from a DB row.
472 * If false is given, the title will be treated as non-existing.
474 * @param stdClass|bool $row Database row
476 public function loadFromRow( $row ) {
477 if ( $row ) { // page found
478 if ( isset( $row->page_id
) ) {
479 $this->mArticleID
= (int)$row->page_id
;
481 if ( isset( $row->page_len
) ) {
482 $this->mLength
= (int)$row->page_len
;
484 if ( isset( $row->page_is_redirect
) ) {
485 $this->mRedirect
= (bool)$row->page_is_redirect
;
487 if ( isset( $row->page_latest
) ) {
488 $this->mLatestID
= (int)$row->page_latest
;
490 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
491 $this->mContentModel
= strval( $row->page_content_model
);
492 } elseif ( !$this->mForcedContentModel
) {
493 $this->mContentModel
= false; # initialized lazily in getContentModel()
495 if ( isset( $row->page_lang
) ) {
496 $this->mDbPageLanguage
= (string)$row->page_lang
;
498 if ( isset( $row->page_restrictions
) ) {
499 $this->mOldRestrictions
= $row->page_restrictions
;
501 } else { // page not found
502 $this->mArticleID
= 0;
504 $this->mRedirect
= false;
505 $this->mLatestID
= 0;
506 if ( !$this->mForcedContentModel
) {
507 $this->mContentModel
= false; # initialized lazily in getContentModel()
513 * Create a new Title from a namespace index and a DB key.
515 * It's assumed that $ns and $title are safe, for instance when
516 * they came directly from the database or a special page name,
517 * not from user input.
519 * No validation is applied. For convenience, spaces are normalized
520 * to underscores, so that e.g. user_text fields can be used directly.
522 * @note This method may return Title objects that are "invalid"
523 * according to the isValid() method. This is usually caused by
524 * configuration changes: e.g. a namespace that was once defined is
525 * no longer configured, or a character that was once allowed in
526 * titles is now forbidden.
528 * @param int $ns The namespace of the article
529 * @param string $title The unprefixed database key form
530 * @param string $fragment The link fragment (after the "#")
531 * @param string $interwiki The interwiki prefix
532 * @return Title The new object
534 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
536 $t->mInterwiki
= $interwiki;
537 $t->mFragment
= $fragment;
538 $t->mNamespace
= $ns = intval( $ns );
539 $t->mDbkeyform
= strtr( $title, ' ', '_' );
540 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
541 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
542 $t->mTextform
= strtr( $title, '_', ' ' );
543 $t->mContentModel
= false; # initialized lazily in getContentModel()
548 * Create a new Title from a namespace index and a DB key.
549 * The parameters will be checked for validity, which is a bit slower
550 * than makeTitle() but safer for user-provided data.
552 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
553 * that is, they return true from the isValid() method. If no valid Title
554 * can be constructed from the input, this method returns null.
556 * @param int $ns The namespace of the article
557 * @param string $title Database key form
558 * @param string $fragment The link fragment (after the "#")
559 * @param string $interwiki Interwiki prefix
560 * @return Title|null The new object, or null on an error
562 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
563 // NOTE: ideally, this would just call makeTitle() and then isValid(),
564 // but presently, that means more overhead on a potential performance hotspot.
566 if ( !MWNamespace
::exists( $ns ) ) {
571 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
574 $t->secureAndSplit();
576 } catch ( MalformedTitleException
$ex ) {
582 * Create a new Title for the Main Page
584 * @return Title The new object
586 public static function newMainPage() {
587 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
588 // Don't give fatal errors if the message is broken
590 $title = self
::newFromText( 'Main Page' );
596 * Get the prefixed DB key associated with an ID
598 * @param int $id The page_id of the article
599 * @return Title|null An object representing the article, or null if no such article was found
601 public static function nameOf( $id ) {
602 $dbr = wfGetDB( DB_REPLICA
);
604 $s = $dbr->selectRow(
606 [ 'page_namespace', 'page_title' ],
607 [ 'page_id' => $id ],
610 if ( $s === false ) {
614 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
619 * Get a regex character class describing the legal characters in a link
621 * @return string The list of characters, not delimited
623 public static function legalChars() {
624 global $wgLegalTitleChars;
625 return $wgLegalTitleChars;
629 * Utility method for converting a character sequence from bytes to Unicode.
631 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
632 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
634 * @param string $byteClass
637 public static function convertByteClassToUnicodeClass( $byteClass ) {
638 $length = strlen( $byteClass );
640 $x0 = $x1 = $x2 = '';
642 $d0 = $d1 = $d2 = '';
643 // Decoded integer codepoints
644 $ord0 = $ord1 = $ord2 = 0;
646 $r0 = $r1 = $r2 = '';
650 $allowUnicode = false;
651 for ( $pos = 0; $pos < $length; $pos++
) {
652 // Shift the queues down
661 // Load the current input token and decoded values
662 $inChar = $byteClass[$pos];
663 if ( $inChar == '\\' ) {
664 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
665 $x0 = $inChar . $m[0];
666 $d0 = chr( hexdec( $m[1] ) );
667 $pos +
= strlen( $m[0] );
668 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
669 $x0 = $inChar . $m[0];
670 $d0 = chr( octdec( $m[0] ) );
671 $pos +
= strlen( $m[0] );
672 } elseif ( $pos +
1 >= $length ) {
675 $d0 = $byteClass[$pos +
1];
683 // Load the current re-encoded value
684 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
685 $r0 = sprintf( '\x%02x', $ord0 );
686 } elseif ( $ord0 >= 0x80 ) {
687 // Allow unicode if a single high-bit character appears
688 $r0 = sprintf( '\x%02x', $ord0 );
689 $allowUnicode = true;
690 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
696 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
698 if ( $ord2 > $ord0 ) {
700 } elseif ( $ord0 >= 0x80 ) {
702 $allowUnicode = true;
703 if ( $ord2 < 0x80 ) {
704 // Keep the non-unicode section of the range
711 // Reset state to the initial value
712 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
713 } elseif ( $ord2 < 0x80 ) {
718 if ( $ord1 < 0x80 ) {
721 if ( $ord0 < 0x80 ) {
724 if ( $allowUnicode ) {
725 $out .= '\u0080-\uFFFF';
731 * Make a prefixed DB key from a DB key and a namespace index
733 * @param int $ns Numerical representation of the namespace
734 * @param string $title The DB key form the title
735 * @param string $fragment The link fragment (after the "#")
736 * @param string $interwiki The interwiki prefix
737 * @param bool $canonicalNamespace If true, use the canonical name for
738 * $ns instead of the localized version.
739 * @return string The prefixed form of the title
741 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
742 $canonicalNamespace = false
746 if ( $canonicalNamespace ) {
747 $namespace = MWNamespace
::getCanonicalName( $ns );
749 $namespace = $wgContLang->getNsText( $ns );
751 $name = $namespace == '' ?
$title : "$namespace:$title";
752 if ( strval( $interwiki ) != '' ) {
753 $name = "$interwiki:$name";
755 if ( strval( $fragment ) != '' ) {
756 $name .= '#' . $fragment;
762 * Escape a text fragment, say from a link, for a URL
764 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
766 * @param string $fragment Containing a URL or link fragment (after the "#")
767 * @return string Escaped string
769 static function escapeFragmentForURL( $fragment ) {
770 wfDeprecated( __METHOD__
, '1.30' );
771 # Note that we don't urlencode the fragment. urlencoded Unicode
772 # fragments appear not to work in IE (at least up to 7) or in at least
773 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
774 # to care if they aren't encoded.
775 return Sanitizer
::escapeId( $fragment, 'noninitial' );
779 * Callback for usort() to do title sorts by (namespace, title)
781 * @param LinkTarget $a
782 * @param LinkTarget $b
784 * @return int Result of string comparison, or namespace comparison
786 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
787 if ( $a->getNamespace() == $b->getNamespace() ) {
788 return strcmp( $a->getText(), $b->getText() );
790 return $a->getNamespace() - $b->getNamespace();
795 * Returns true if the title is valid, false if it is invalid.
797 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
798 * Invalid titles may get returned from makeTitle(), and it may be useful to
799 * allow them to exist, e.g. in order to process log entries about pages in
800 * namespaces that belong to extensions that are no longer installed.
802 * @note This method is relatively expensive. When constructing Title
803 * objects that need to be valid, use an instantiator method that is guaranteed
804 * to return valid titles, such as makeTitleSafe() or newFromText().
808 public function isValid() {
809 $ns = $this->getNamespace();
811 if ( !MWNamespace
::exists( $ns ) ) {
816 $parser = MediaWikiServices
::getInstance()->getTitleParser();
817 $parser->parseTitle( $this->getDBkey(), $ns );
819 } catch ( MalformedTitleException
$ex ) {
825 * Determine whether the object refers to a page within
826 * this project (either this wiki or a wiki with a local
827 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
829 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
831 public function isLocal() {
832 if ( $this->isExternal() ) {
833 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
835 return $iw->isLocal();
842 * Is this Title interwiki?
846 public function isExternal() {
847 return $this->mInterwiki
!== '';
851 * Get the interwiki prefix
853 * Use Title::isExternal to check if a interwiki is set
855 * @return string Interwiki prefix
857 public function getInterwiki() {
858 return $this->mInterwiki
;
862 * Was this a local interwiki link?
866 public function wasLocalInterwiki() {
867 return $this->mLocalInterwiki
;
871 * Determine whether the object refers to a page within
872 * this project and is transcludable.
874 * @return bool True if this is transcludable
876 public function isTrans() {
877 if ( !$this->isExternal() ) {
881 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
885 * Returns the DB name of the distant wiki which owns the object.
887 * @return string|false The DB name
889 public function getTransWikiID() {
890 if ( !$this->isExternal() ) {
894 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
898 * Get a TitleValue object representing this Title.
900 * @note Not all valid Titles have a corresponding valid TitleValue
901 * (e.g. TitleValues cannot represent page-local links that have a
902 * fragment but no title text).
904 * @return TitleValue|null
906 public function getTitleValue() {
907 if ( $this->mTitleValue
=== null ) {
909 $this->mTitleValue
= new TitleValue(
910 $this->getNamespace(),
912 $this->getFragment(),
913 $this->getInterwiki()
915 } catch ( InvalidArgumentException
$ex ) {
916 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
917 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
921 return $this->mTitleValue
;
925 * Get the text form (spaces not underscores) of the main part
927 * @return string Main part of the title
929 public function getText() {
930 return $this->mTextform
;
934 * Get the URL-encoded form of the main part
936 * @return string Main part of the title, URL-encoded
938 public function getPartialURL() {
939 return $this->mUrlform
;
943 * Get the main part with underscores
945 * @return string Main part of the title, with underscores
947 public function getDBkey() {
948 return $this->mDbkeyform
;
952 * Get the DB key with the initial letter case as specified by the user
954 * @return string DB key
956 function getUserCaseDBKey() {
957 if ( !is_null( $this->mUserCaseDBKey
) ) {
958 return $this->mUserCaseDBKey
;
960 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
961 return $this->mDbkeyform
;
966 * Get the namespace index, i.e. one of the NS_xxxx constants.
968 * @return int Namespace index
970 public function getNamespace() {
971 return $this->mNamespace
;
975 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
977 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
978 * @return string Content model id
980 public function getContentModel( $flags = 0 ) {
981 if ( !$this->mForcedContentModel
982 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
983 && $this->getArticleID( $flags )
985 $linkCache = LinkCache
::singleton();
986 $linkCache->addLinkObj( $this ); # in case we already had an article ID
987 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
990 if ( !$this->mContentModel
) {
991 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
994 return $this->mContentModel
;
998 * Convenience method for checking a title's content model name
1000 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1001 * @return bool True if $this->getContentModel() == $id
1003 public function hasContentModel( $id ) {
1004 return $this->getContentModel() == $id;
1008 * Set a proposed content model for the page for permissions
1009 * checking. This does not actually change the content model
1012 * Additionally, you should make sure you've checked
1013 * ContentHandler::canBeUsedOn() first.
1016 * @param string $model CONTENT_MODEL_XXX constant
1018 public function setContentModel( $model ) {
1019 $this->mContentModel
= $model;
1020 $this->mForcedContentModel
= true;
1024 * Get the namespace text
1026 * @return string|false Namespace text
1028 public function getNsText() {
1029 if ( $this->isExternal() ) {
1030 // This probably shouldn't even happen,
1031 // but for interwiki transclusion it sometimes does.
1032 // Use the canonical namespaces if possible to try to
1033 // resolve a foreign namespace.
1034 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1035 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1040 $formatter = self
::getTitleFormatter();
1041 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1042 } catch ( InvalidArgumentException
$ex ) {
1043 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1049 * Get the namespace text of the subject (rather than talk) page
1051 * @return string Namespace text
1053 public function getSubjectNsText() {
1055 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1059 * Get the namespace text of the talk page
1061 * @return string Namespace text
1063 public function getTalkNsText() {
1065 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1069 * Can this title have a corresponding talk page?
1071 * @deprecated since 1.30, use canHaveTalkPage() instead.
1073 * @return bool True if this title either is a talk page or can have a talk page associated.
1075 public function canTalk() {
1076 return $this->canHaveTalkPage();
1080 * Can this title have a corresponding talk page?
1082 * @see MWNamespace::hasTalkNamespace
1085 * @return bool True if this title either is a talk page or can have a talk page associated.
1087 public function canHaveTalkPage() {
1088 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1092 * Is this in a namespace that allows actual pages?
1096 public function canExist() {
1097 return $this->mNamespace
>= NS_MAIN
;
1101 * Can this title be added to a user's watchlist?
1105 public function isWatchable() {
1106 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1110 * Returns true if this is a special page.
1114 public function isSpecialPage() {
1115 return $this->getNamespace() == NS_SPECIAL
;
1119 * Returns true if this title resolves to the named special page
1121 * @param string $name The special page name
1124 public function isSpecial( $name ) {
1125 if ( $this->isSpecialPage() ) {
1126 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1127 if ( $name == $thisName ) {
1135 * If the Title refers to a special page alias which is not the local default, resolve
1136 * the alias, and localise the name as necessary. Otherwise, return $this
1140 public function fixSpecialName() {
1141 if ( $this->isSpecialPage() ) {
1142 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1143 if ( $canonicalName ) {
1144 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1145 if ( $localName != $this->mDbkeyform
) {
1146 return self
::makeTitle( NS_SPECIAL
, $localName );
1154 * Returns true if the title is inside the specified namespace.
1156 * Please make use of this instead of comparing to getNamespace()
1157 * This function is much more resistant to changes we may make
1158 * to namespaces than code that makes direct comparisons.
1159 * @param int $ns The namespace
1163 public function inNamespace( $ns ) {
1164 return MWNamespace
::equals( $this->getNamespace(), $ns );
1168 * Returns true if the title is inside one of the specified namespaces.
1170 * @param int|int[] $namespaces,... The namespaces to check for
1174 public function inNamespaces( /* ... */ ) {
1175 $namespaces = func_get_args();
1176 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1177 $namespaces = $namespaces[0];
1180 foreach ( $namespaces as $ns ) {
1181 if ( $this->inNamespace( $ns ) ) {
1190 * Returns true if the title has the same subject namespace as the
1191 * namespace specified.
1192 * For example this method will take NS_USER and return true if namespace
1193 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1194 * as their subject namespace.
1196 * This is MUCH simpler than individually testing for equivalence
1197 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1202 public function hasSubjectNamespace( $ns ) {
1203 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1207 * Is this Title in a namespace which contains content?
1208 * In other words, is this a content page, for the purposes of calculating
1213 public function isContentPage() {
1214 return MWNamespace
::isContent( $this->getNamespace() );
1218 * Would anybody with sufficient privileges be able to move this page?
1219 * Some pages just aren't movable.
1223 public function isMovable() {
1224 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1225 // Interwiki title or immovable namespace. Hooks don't get to override here
1230 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1235 * Is this the mainpage?
1236 * @note Title::newFromText seems to be sufficiently optimized by the title
1237 * cache that we don't need to over-optimize by doing direct comparisons and
1238 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1239 * ends up reporting something differently than $title->isMainPage();
1244 public function isMainPage() {
1245 return $this->equals( self
::newMainPage() );
1249 * Is this a subpage?
1253 public function isSubpage() {
1254 return MWNamespace
::hasSubpages( $this->mNamespace
)
1255 ?
strpos( $this->getText(), '/' ) !== false
1260 * Is this a conversion table for the LanguageConverter?
1264 public function isConversionTable() {
1265 // @todo ConversionTable should become a separate content model.
1267 return $this->getNamespace() == NS_MEDIAWIKI
&&
1268 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1272 * Does that page contain wikitext, or it is JS, CSS or whatever?
1276 public function isWikitextPage() {
1277 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1281 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1282 * global UI. This is generally true for pages in the MediaWiki namespace having
1283 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1285 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1288 * Note that this method should not return true for pages that contain and show
1289 * "inactive" CSS, JSON, or JS.
1294 public function isSiteConfigPage() {
1296 NS_MEDIAWIKI
== $this->mNamespace
1298 $this->hasContentModel( CONTENT_MODEL_CSS
)
1299 ||
$this->hasContentModel( CONTENT_MODEL_JSON
)
1300 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1307 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1309 public function isCssOrJsPage() {
1310 wfDeprecated( __METHOD__
, '1.31' );
1311 return ( NS_MEDIAWIKI
== $this->mNamespace
1312 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1313 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1317 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1322 public function isUserConfigPage() {
1324 NS_USER
== $this->mNamespace
1325 && $this->isSubpage()
1327 $this->hasContentModel( CONTENT_MODEL_CSS
)
1328 ||
$this->hasContentModel( CONTENT_MODEL_JSON
)
1329 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1336 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1338 public function isCssJsSubpage() {
1339 wfDeprecated( __METHOD__
, '1.31' );
1340 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1341 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1342 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1346 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1348 * @return string Containing skin name from .css, .json, or .js subpage title
1351 public function getSkinFromConfigSubpage() {
1352 $subpage = explode( '/', $this->mTextform
);
1353 $subpage = $subpage[count( $subpage ) - 1];
1354 $lastdot = strrpos( $subpage, '.' );
1355 if ( $lastdot === false ) {
1356 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1358 return substr( $subpage, 0, $lastdot );
1362 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1363 * @return string Containing skin name from .css, .json, or .js subpage title
1365 public function getSkinFromCssJsSubpage() {
1366 wfDeprecated( __METHOD__
, '1.31' );
1367 return $this->getSkinFromConfigSubpage();
1371 * Is this a CSS "config" sub-page of a user page?
1376 public function isUserCssConfigPage() {
1378 NS_USER
== $this->mNamespace
1379 && $this->isSubpage()
1380 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1385 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1388 public function isCssSubpage() {
1389 wfDeprecated( __METHOD__
, '1.31' );
1390 return $this->isUserCssConfigPage();
1394 * Is this a JSON "config" sub-page of a user page?
1399 public function isUserJsonConfigPage() {
1401 NS_USER
== $this->mNamespace
1402 && $this->isSubpage()
1403 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1408 * Is this a JS "config" sub-page of a user page?
1413 public function isUserJsConfigPage() {
1415 NS_USER
== $this->mNamespace
1416 && $this->isSubpage()
1417 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1422 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1425 public function isJsSubpage() {
1426 wfDeprecated( __METHOD__
, '1.31' );
1427 return $this->isUserJsConfigPage();
1431 * Is this a talk page of some sort?
1435 public function isTalkPage() {
1436 return MWNamespace
::isTalk( $this->getNamespace() );
1440 * Get a Title object associated with the talk page of this article
1442 * @return Title The object for the talk page
1444 public function getTalkPage() {
1445 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1449 * Get a Title object associated with the talk page of this article,
1450 * if such a talk page can exist.
1454 * @return Title|null The object for the talk page,
1455 * or null if no associated talk page can exist, according to canHaveTalkPage().
1457 public function getTalkPageIfDefined() {
1458 if ( !$this->canHaveTalkPage() ) {
1462 return $this->getTalkPage();
1466 * Get a title object associated with the subject page of this
1469 * @return Title The object for the subject page
1471 public function getSubjectPage() {
1472 // Is this the same title?
1473 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1474 if ( $this->getNamespace() == $subjectNS ) {
1477 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1481 * Get the other title for this page, if this is a subject page
1482 * get the talk page, if it is a subject page get the talk page
1485 * @throws MWException If the page doesn't have an other page
1488 public function getOtherPage() {
1489 if ( $this->isSpecialPage() ) {
1490 throw new MWException( 'Special pages cannot have other pages' );
1492 if ( $this->isTalkPage() ) {
1493 return $this->getSubjectPage();
1495 if ( !$this->canHaveTalkPage() ) {
1496 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1498 return $this->getTalkPage();
1503 * Get the default namespace index, for when there is no namespace
1505 * @return int Default namespace index
1507 public function getDefaultNamespace() {
1508 return $this->mDefaultNamespace
;
1512 * Get the Title fragment (i.e.\ the bit after the #) in text form
1514 * Use Title::hasFragment to check for a fragment
1516 * @return string Title fragment
1518 public function getFragment() {
1519 return $this->mFragment
;
1523 * Check if a Title fragment is set
1528 public function hasFragment() {
1529 return $this->mFragment
!== '';
1533 * Get the fragment in URL form, including the "#" character if there is one
1535 * @return string Fragment in URL form
1537 public function getFragmentForURL() {
1538 if ( !$this->hasFragment() ) {
1540 } elseif ( $this->isExternal()
1541 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1543 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1545 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1549 * Set the fragment for this title. Removes the first character from the
1550 * specified fragment before setting, so it assumes you're passing it with
1553 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1554 * or Title::createFragmentTarget().
1555 * Still in active use privately.
1558 * @param string $fragment Text
1560 public function setFragment( $fragment ) {
1561 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1565 * Creates a new Title for a different fragment of the same page.
1568 * @param string $fragment
1571 public function createFragmentTarget( $fragment ) {
1572 return self
::makeTitle(
1573 $this->getNamespace(),
1576 $this->getInterwiki()
1581 * Prefix some arbitrary text with the namespace or interwiki prefix
1584 * @param string $name The text
1585 * @return string The prefixed text
1587 private function prefix( $name ) {
1591 if ( $this->isExternal() ) {
1592 $p = $this->mInterwiki
. ':';
1595 if ( 0 != $this->mNamespace
) {
1596 $nsText = $this->getNsText();
1598 if ( $nsText === false ) {
1599 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1600 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1603 $p .= $nsText . ':';
1609 * Get the prefixed database key form
1611 * @return string The prefixed title, with underscores and
1612 * any interwiki and namespace prefixes
1614 public function getPrefixedDBkey() {
1615 $s = $this->prefix( $this->mDbkeyform
);
1616 $s = strtr( $s, ' ', '_' );
1621 * Get the prefixed title with spaces.
1622 * This is the form usually used for display
1624 * @return string The prefixed title, with spaces
1626 public function getPrefixedText() {
1627 if ( $this->mPrefixedText
=== null ) {
1628 $s = $this->prefix( $this->mTextform
);
1629 $s = strtr( $s, '_', ' ' );
1630 $this->mPrefixedText
= $s;
1632 return $this->mPrefixedText
;
1636 * Return a string representation of this title
1638 * @return string Representation of this title
1640 public function __toString() {
1641 return $this->getPrefixedText();
1645 * Get the prefixed title with spaces, plus any fragment
1646 * (part beginning with '#')
1648 * @return string The prefixed title, with spaces and the fragment, including '#'
1650 public function getFullText() {
1651 $text = $this->getPrefixedText();
1652 if ( $this->hasFragment() ) {
1653 $text .= '#' . $this->getFragment();
1659 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1663 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1667 * @return string Root name
1670 public function getRootText() {
1671 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1672 return $this->getText();
1675 return strtok( $this->getText(), '/' );
1679 * Get the root page name title, i.e. the leftmost part before any slashes
1683 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1684 * # returns: Title{User:Foo}
1687 * @return Title Root title
1690 public function getRootTitle() {
1691 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1695 * Get the base page name without a namespace, i.e. the part before the subpage name
1699 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1700 * # returns: 'Foo/Bar'
1703 * @return string Base name
1705 public function getBaseText() {
1706 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1707 return $this->getText();
1710 $parts = explode( '/', $this->getText() );
1711 # Don't discard the real title if there's no subpage involved
1712 if ( count( $parts ) > 1 ) {
1713 unset( $parts[count( $parts ) - 1] );
1715 return implode( '/', $parts );
1719 * Get the base page name title, i.e. the part before the subpage name
1723 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1724 * # returns: Title{User:Foo/Bar}
1727 * @return Title Base title
1730 public function getBaseTitle() {
1731 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1735 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1739 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1743 * @return string Subpage name
1745 public function getSubpageText() {
1746 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1747 return $this->mTextform
;
1749 $parts = explode( '/', $this->mTextform
);
1750 return $parts[count( $parts ) - 1];
1754 * Get the title for a subpage of the current page
1758 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1759 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1762 * @param string $text The subpage name to add to the title
1763 * @return Title Subpage title
1766 public function getSubpage( $text ) {
1767 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1771 * Get a URL-encoded form of the subpage text
1773 * @return string URL-encoded subpage name
1775 public function getSubpageUrlForm() {
1776 $text = $this->getSubpageText();
1777 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1782 * Get a URL-encoded title (not an actual URL) including interwiki
1784 * @return string The URL-encoded form
1786 public function getPrefixedURL() {
1787 $s = $this->prefix( $this->mDbkeyform
);
1788 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1793 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1794 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1795 * second argument named variant. This was deprecated in favor
1796 * of passing an array of option with a "variant" key
1797 * Once $query2 is removed for good, this helper can be dropped
1798 * and the wfArrayToCgi moved to getLocalURL();
1800 * @since 1.19 (r105919)
1801 * @param array|string $query
1802 * @param string|string[]|bool $query2
1805 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1806 if ( $query2 !== false ) {
1807 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1808 "method called with a second parameter is deprecated. Add your " .
1809 "parameter to an array passed as the first parameter.", "1.19" );
1811 if ( is_array( $query ) ) {
1812 $query = wfArrayToCgi( $query );
1815 if ( is_string( $query2 ) ) {
1816 // $query2 is a string, we will consider this to be
1817 // a deprecated $variant argument and add it to the query
1818 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1820 $query2 = wfArrayToCgi( $query2 );
1822 // If we have $query content add a & to it first
1826 // Now append the queries together
1833 * Get a real URL referring to this title, with interwiki link and
1836 * @see self::getLocalURL for the arguments.
1838 * @param string|string[] $query
1839 * @param string|string[]|bool $query2
1840 * @param string|int|null $proto Protocol type to use in URL
1841 * @return string The URL
1843 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1844 $query = self
::fixUrlQueryArgs( $query, $query2 );
1846 # Hand off all the decisions on urls to getLocalURL
1847 $url = $this->getLocalURL( $query );
1849 # Expand the url to make it a full url. Note that getLocalURL has the
1850 # potential to output full urls for a variety of reasons, so we use
1851 # wfExpandUrl instead of simply prepending $wgServer
1852 $url = wfExpandUrl( $url, $proto );
1854 # Finally, add the fragment.
1855 $url .= $this->getFragmentForURL();
1856 // Avoid PHP 7.1 warning from passing $this by reference
1858 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1863 * Get a url appropriate for making redirects based on an untrusted url arg
1865 * This is basically the same as getFullUrl(), but in the case of external
1866 * interwikis, we send the user to a landing page, to prevent possible
1867 * phishing attacks and the like.
1869 * @note Uses current protocol by default, since technically relative urls
1870 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1871 * places where the url gets cached, as might pollute between
1872 * https and non-https users.
1873 * @see self::getLocalURL for the arguments.
1874 * @param array|string $query
1875 * @param string $proto Protocol type to use in URL
1876 * @return string A url suitable to use in an HTTP location header.
1878 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1880 if ( $this->isExternal() ) {
1881 $target = SpecialPage
::getTitleFor(
1883 $this->getPrefixedDBkey()
1886 return $target->getFullURL( $query, false, $proto );
1890 * Get a URL with no fragment or server name (relative URL) from a Title object.
1891 * If this page is generated with action=render, however,
1892 * $wgServer is prepended to make an absolute URL.
1894 * @see self::getFullURL to always get an absolute URL.
1895 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1896 * valid to link, locally, to the current Title.
1897 * @see self::newFromText to produce a Title object.
1899 * @param string|string[] $query An optional query string,
1900 * not used for interwiki links. Can be specified as an associative array as well,
1901 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1902 * Some query patterns will trigger various shorturl path replacements.
1903 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1904 * be an array. If a string is passed it will be interpreted as a deprecated
1905 * variant argument and urlencoded into a variant= argument.
1906 * This second query argument will be added to the $query
1907 * The second parameter is deprecated since 1.19. Pass it as a key,value
1908 * pair in the first parameter array instead.
1910 * @return string String of the URL.
1912 public function getLocalURL( $query = '', $query2 = false ) {
1913 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1915 $query = self
::fixUrlQueryArgs( $query, $query2 );
1917 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1919 $namespace = $this->getNsText();
1920 if ( $namespace != '' ) {
1921 # Can this actually happen? Interwikis shouldn't be parsed.
1922 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1925 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1926 $url = wfAppendQuery( $url, $query );
1928 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1929 if ( $query == '' ) {
1930 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1931 // Avoid PHP 7.1 warning from passing $this by reference
1933 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1935 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1939 if ( !empty( $wgActionPaths )
1940 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1942 $action = urldecode( $matches[2] );
1943 if ( isset( $wgActionPaths[$action] ) ) {
1944 $query = $matches[1];
1945 if ( isset( $matches[4] ) ) {
1946 $query .= $matches[4];
1948 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1949 if ( $query != '' ) {
1950 $url = wfAppendQuery( $url, $query );
1956 && $wgVariantArticlePath
1957 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1958 && $this->getPageLanguage()->equals( $wgContLang )
1959 && $this->getPageLanguage()->hasVariants()
1961 $variant = urldecode( $matches[1] );
1962 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1963 // Only do the variant replacement if the given variant is a valid
1964 // variant for the page's language.
1965 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1966 $url = str_replace( '$1', $dbkey, $url );
1970 if ( $url === false ) {
1971 if ( $query == '-' ) {
1974 $url = "{$wgScript}?title={$dbkey}&{$query}";
1977 // Avoid PHP 7.1 warning from passing $this by reference
1979 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1981 // @todo FIXME: This causes breakage in various places when we
1982 // actually expected a local URL and end up with dupe prefixes.
1983 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1984 $url = $wgServer . $url;
1987 // Avoid PHP 7.1 warning from passing $this by reference
1989 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1994 * Get a URL that's the simplest URL that will be valid to link, locally,
1995 * to the current Title. It includes the fragment, but does not include
1996 * the server unless action=render is used (or the link is external). If
1997 * there's a fragment but the prefixed text is empty, we just return a link
2000 * The result obviously should not be URL-escaped, but does need to be
2001 * HTML-escaped if it's being output in HTML.
2003 * @param string|string[] $query
2004 * @param bool $query2
2005 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2006 * or false (default) for no expansion
2007 * @see self::getLocalURL for the arguments.
2008 * @return string The URL
2010 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2011 if ( $this->isExternal() ||
$proto !== false ) {
2012 $ret = $this->getFullURL( $query, $query2, $proto );
2013 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2014 $ret = $this->getFragmentForURL();
2016 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2022 * Get the URL form for an internal link.
2023 * - Used in various CDN-related code, in case we have a different
2024 * internal hostname for the server from the exposed one.
2026 * This uses $wgInternalServer to qualify the path, or $wgServer
2027 * if $wgInternalServer is not set. If the server variable used is
2028 * protocol-relative, the URL will be expanded to http://
2030 * @see self::getLocalURL for the arguments.
2031 * @param string $query
2032 * @param string|bool $query2
2033 * @return string The URL
2035 public function getInternalURL( $query = '', $query2 = false ) {
2036 global $wgInternalServer, $wgServer;
2037 $query = self
::fixUrlQueryArgs( $query, $query2 );
2038 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2039 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2040 // Avoid PHP 7.1 warning from passing $this by reference
2042 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2047 * Get the URL for a canonical link, for use in things like IRC and
2048 * e-mail notifications. Uses $wgCanonicalServer and the
2049 * GetCanonicalURL hook.
2051 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2053 * @see self::getLocalURL for the arguments.
2054 * @param string $query
2055 * @param string|bool $query2
2056 * @return string The URL
2059 public function getCanonicalURL( $query = '', $query2 = false ) {
2060 $query = self
::fixUrlQueryArgs( $query, $query2 );
2061 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2062 // Avoid PHP 7.1 warning from passing $this by reference
2064 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2069 * Get the edit URL for this Title
2071 * @return string The URL, or a null string if this is an interwiki link
2073 public function getEditURL() {
2074 if ( $this->isExternal() ) {
2077 $s = $this->getLocalURL( 'action=edit' );
2083 * Can $user perform $action on this page?
2084 * This skips potentially expensive cascading permission checks
2085 * as well as avoids expensive error formatting
2087 * Suitable for use for nonessential UI controls in common cases, but
2088 * _not_ for functional access control.
2090 * May provide false positives, but should never provide a false negative.
2092 * @param string $action Action that permission needs to be checked for
2093 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
2096 public function quickUserCan( $action, $user = null ) {
2097 return $this->userCan( $action, $user, false );
2101 * Can $user perform $action on this page?
2103 * @param string $action Action that permission needs to be checked for
2104 * @param User $user User to check (since 1.19); $wgUser will be used if not
2106 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2109 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2110 if ( !$user instanceof User
) {
2115 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2119 * Can $user perform $action on this page?
2121 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2123 * @param string $action Action that permission needs to be checked for
2124 * @param User $user User to check
2125 * @param string $rigor One of (quick,full,secure)
2126 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2127 * - full : does cheap and expensive checks possibly from a replica DB
2128 * - secure : does cheap and expensive checks, using the master as needed
2129 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2130 * whose corresponding errors may be ignored.
2131 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2133 public function getUserPermissionsErrors(
2134 $action, $user, $rigor = 'secure', $ignoreErrors = []
2136 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2138 // Remove the errors being ignored.
2139 foreach ( $errors as $index => $error ) {
2140 $errKey = is_array( $error ) ?
$error[0] : $error;
2142 if ( in_array( $errKey, $ignoreErrors ) ) {
2143 unset( $errors[$index] );
2145 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2146 unset( $errors[$index] );
2154 * Permissions checks that fail most often, and which are easiest to test.
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @param bool $short Short circuit on first error
2162 * @return array List of errors
2164 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2165 if ( !Hooks
::run( 'TitleQuickPermissions',
2166 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2171 if ( $action == 'create' ) {
2173 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2174 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2176 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2178 } elseif ( $action == 'move' ) {
2179 if ( !$user->isAllowed( 'move-rootuserpages' )
2180 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2181 // Show user page-specific message only if the user can move other pages
2182 $errors[] = [ 'cant-move-user-page' ];
2185 // Check if user is allowed to move files if it's a file
2186 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2187 $errors[] = [ 'movenotallowedfile' ];
2190 // Check if user is allowed to move category pages if it's a category page
2191 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2192 $errors[] = [ 'cant-move-category-page' ];
2195 if ( !$user->isAllowed( 'move' ) ) {
2196 // User can't move anything
2197 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2198 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2199 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2200 // custom message if logged-in users without any special rights can move
2201 $errors[] = [ 'movenologintext' ];
2203 $errors[] = [ 'movenotallowed' ];
2206 } elseif ( $action == 'move-target' ) {
2207 if ( !$user->isAllowed( 'move' ) ) {
2208 // User can't move anything
2209 $errors[] = [ 'movenotallowed' ];
2210 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2211 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2212 // Show user page-specific message only if the user can move other pages
2213 $errors[] = [ 'cant-move-to-user-page' ];
2214 } elseif ( !$user->isAllowed( 'move-categorypages' )
2215 && $this->mNamespace
== NS_CATEGORY
) {
2216 // Show category page-specific message only if the user can move other pages
2217 $errors[] = [ 'cant-move-to-category-page' ];
2219 } elseif ( !$user->isAllowed( $action ) ) {
2220 $errors[] = $this->missingPermissionError( $action, $short );
2227 * Add the resulting error code to the errors array
2229 * @param array $errors List of current errors
2230 * @param array $result Result of errors
2232 * @return array List of errors
2234 private function resultToError( $errors, $result ) {
2235 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2236 // A single array representing an error
2237 $errors[] = $result;
2238 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2239 // A nested array representing multiple errors
2240 $errors = array_merge( $errors, $result );
2241 } elseif ( $result !== '' && is_string( $result ) ) {
2242 // A string representing a message-id
2243 $errors[] = [ $result ];
2244 } elseif ( $result instanceof MessageSpecifier
) {
2245 // A message specifier representing an error
2246 $errors[] = [ $result ];
2247 } elseif ( $result === false ) {
2248 // a generic "We don't want them to do that"
2249 $errors[] = [ 'badaccess-group0' ];
2255 * Check various permission hooks
2257 * @param string $action The action to check
2258 * @param User $user User to check
2259 * @param array $errors List of current errors
2260 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2261 * @param bool $short Short circuit on first error
2263 * @return array List of errors
2265 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2266 // Use getUserPermissionsErrors instead
2268 // Avoid PHP 7.1 warning from passing $this by reference
2270 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2271 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2273 // Check getUserPermissionsErrors hook
2274 // Avoid PHP 7.1 warning from passing $this by reference
2276 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2277 $errors = $this->resultToError( $errors, $result );
2279 // Check getUserPermissionsErrorsExpensive hook
2282 && !( $short && count( $errors ) > 0 )
2283 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2285 $errors = $this->resultToError( $errors, $result );
2292 * Check permissions on special pages & namespaces
2294 * @param string $action The action to check
2295 * @param User $user User to check
2296 * @param array $errors List of current errors
2297 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2298 * @param bool $short Short circuit on first error
2300 * @return array List of errors
2302 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2303 # Only 'createaccount' can be performed on special pages,
2304 # which don't actually exist in the DB.
2305 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2306 $errors[] = [ 'ns-specialprotected' ];
2309 # Check $wgNamespaceProtection for restricted namespaces
2310 if ( $this->isNamespaceProtected( $user ) ) {
2311 $ns = $this->mNamespace
== NS_MAIN ?
2312 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2313 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2314 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2321 * Check CSS/JSON/JS sub-page permissions
2323 * @param string $action The action to check
2324 * @param User $user User to check
2325 * @param array $errors List of current errors
2326 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2327 * @param bool $short Short circuit on first error
2329 * @return array List of errors
2331 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2332 # Protect css/json/js subpages of user pages
2333 # XXX: this might be better using restrictions
2335 if ( $action != 'patrol' ) {
2336 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2338 $this->isUserCssConfigPage()
2339 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2341 $errors[] = [ 'mycustomcssprotected', $action ];
2343 $this->isUserJsonConfigPage()
2344 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2346 $errors[] = [ 'mycustomjsonprotected', $action ];
2348 $this->isUserJsConfigPage()
2349 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2351 $errors[] = [ 'mycustomjsprotected', $action ];
2355 $this->isUserCssConfigPage()
2356 && !$user->isAllowed( 'editusercss' )
2358 $errors[] = [ 'customcssprotected', $action ];
2360 $this->isUserJsonConfigPage()
2361 && !$user->isAllowed( 'edituserjson' )
2363 $errors[] = [ 'customjsonprotected', $action ];
2365 $this->isUserJsConfigPage()
2366 && !$user->isAllowed( 'edituserjs' )
2368 $errors[] = [ 'customjsprotected', $action ];
2377 * Check against page_restrictions table requirements on this
2378 * page. The user must possess all required rights for this
2381 * @param string $action The action to check
2382 * @param User $user User to check
2383 * @param array $errors List of current errors
2384 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2385 * @param bool $short Short circuit on first error
2387 * @return array List of errors
2389 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2390 foreach ( $this->getRestrictions( $action ) as $right ) {
2391 // Backwards compatibility, rewrite sysop -> editprotected
2392 if ( $right == 'sysop' ) {
2393 $right = 'editprotected';
2395 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2396 if ( $right == 'autoconfirmed' ) {
2397 $right = 'editsemiprotected';
2399 if ( $right == '' ) {
2402 if ( !$user->isAllowed( $right ) ) {
2403 $errors[] = [ 'protectedpagetext', $right, $action ];
2404 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2405 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2413 * Check restrictions on cascading pages.
2415 * @param string $action The action to check
2416 * @param User $user User to check
2417 * @param array $errors List of current errors
2418 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2419 * @param bool $short Short circuit on first error
2421 * @return array List of errors
2423 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2424 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2425 # We /could/ use the protection level on the source page, but it's
2426 # fairly ugly as we have to establish a precedence hierarchy for pages
2427 # included by multiple cascade-protected pages. So just restrict
2428 # it to people with 'protect' permission, as they could remove the
2429 # protection anyway.
2430 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2431 # Cascading protection depends on more than this page...
2432 # Several cascading protected pages may include this page...
2433 # Check each cascading level
2434 # This is only for protection restrictions, not for all actions
2435 if ( isset( $restrictions[$action] ) ) {
2436 foreach ( $restrictions[$action] as $right ) {
2437 // Backwards compatibility, rewrite sysop -> editprotected
2438 if ( $right == 'sysop' ) {
2439 $right = 'editprotected';
2441 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2442 if ( $right == 'autoconfirmed' ) {
2443 $right = 'editsemiprotected';
2445 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2447 foreach ( $cascadingSources as $page ) {
2448 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2450 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2460 * Check action permissions not already checked in checkQuickPermissions
2462 * @param string $action The action to check
2463 * @param User $user User to check
2464 * @param array $errors List of current errors
2465 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2466 * @param bool $short Short circuit on first error
2468 * @return array List of errors
2470 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2471 global $wgDeleteRevisionsLimit, $wgLang;
2473 if ( $action == 'protect' ) {
2474 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2475 // If they can't edit, they shouldn't protect.
2476 $errors[] = [ 'protect-cantedit' ];
2478 } elseif ( $action == 'create' ) {
2479 $title_protection = $this->getTitleProtection();
2480 if ( $title_protection ) {
2481 if ( $title_protection['permission'] == ''
2482 ||
!$user->isAllowed( $title_protection['permission'] )
2486 User
::whoIs( $title_protection['user'] ),
2487 $title_protection['reason']
2491 } elseif ( $action == 'move' ) {
2492 // Check for immobile pages
2493 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2494 // Specific message for this case
2495 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2496 } elseif ( !$this->isMovable() ) {
2497 // Less specific message for rarer cases
2498 $errors[] = [ 'immobile-source-page' ];
2500 } elseif ( $action == 'move-target' ) {
2501 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2502 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2503 } elseif ( !$this->isMovable() ) {
2504 $errors[] = [ 'immobile-target-page' ];
2506 } elseif ( $action == 'delete' ) {
2507 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2508 if ( !$tempErrors ) {
2509 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2510 $user, $tempErrors, $rigor, true );
2512 if ( $tempErrors ) {
2513 // If protection keeps them from editing, they shouldn't be able to delete.
2514 $errors[] = [ 'deleteprotected' ];
2516 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2517 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2519 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2521 } elseif ( $action === 'undelete' ) {
2522 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2523 // Undeleting implies editing
2524 $errors[] = [ 'undelete-cantedit' ];
2526 if ( !$this->exists()
2527 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2529 // Undeleting where nothing currently exists implies creating
2530 $errors[] = [ 'undelete-cantcreate' ];
2537 * Check that the user isn't blocked from editing.
2539 * @param string $action The action to check
2540 * @param User $user User to check
2541 * @param array $errors List of current errors
2542 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2543 * @param bool $short Short circuit on first error
2545 * @return array List of errors
2547 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2548 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2549 // Account creation blocks handled at userlogin.
2550 // Unblocking handled in SpecialUnblock
2551 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2555 // Optimize for a very common case
2556 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2560 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2561 $errors[] = [ 'confirmedittext' ];
2564 $useSlave = ( $rigor !== 'secure' );
2565 if ( ( $action == 'edit' ||
$action == 'create' )
2566 && !$user->isBlockedFrom( $this, $useSlave )
2568 // Don't block the user from editing their own talk page unless they've been
2569 // explicitly blocked from that too.
2570 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2571 // @todo FIXME: Pass the relevant context into this function.
2572 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2579 * Check that the user is allowed to read this page.
2581 * @param string $action The action to check
2582 * @param User $user User to check
2583 * @param array $errors List of current errors
2584 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2585 * @param bool $short Short circuit on first error
2587 * @return array List of errors
2589 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2590 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2592 $whitelisted = false;
2593 if ( User
::isEveryoneAllowed( 'read' ) ) {
2594 # Shortcut for public wikis, allows skipping quite a bit of code
2595 $whitelisted = true;
2596 } elseif ( $user->isAllowed( 'read' ) ) {
2597 # If the user is allowed to read pages, he is allowed to read all pages
2598 $whitelisted = true;
2599 } elseif ( $this->isSpecial( 'Userlogin' )
2600 ||
$this->isSpecial( 'PasswordReset' )
2601 ||
$this->isSpecial( 'Userlogout' )
2603 # Always grant access to the login page.
2604 # Even anons need to be able to log in.
2605 $whitelisted = true;
2606 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2607 # Time to check the whitelist
2608 # Only do these checks is there's something to check against
2609 $name = $this->getPrefixedText();
2610 $dbName = $this->getPrefixedDBkey();
2612 // Check for explicit whitelisting with and without underscores
2613 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2614 $whitelisted = true;
2615 } elseif ( $this->getNamespace() == NS_MAIN
) {
2616 # Old settings might have the title prefixed with
2617 # a colon for main-namespace pages
2618 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2619 $whitelisted = true;
2621 } elseif ( $this->isSpecialPage() ) {
2622 # If it's a special page, ditch the subpage bit and check again
2623 $name = $this->getDBkey();
2624 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2626 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2627 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2628 $whitelisted = true;
2634 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2635 $name = $this->getPrefixedText();
2636 // Check for regex whitelisting
2637 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2638 if ( preg_match( $listItem, $name ) ) {
2639 $whitelisted = true;
2645 if ( !$whitelisted ) {
2646 # If the title is not whitelisted, give extensions a chance to do so...
2647 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2648 if ( !$whitelisted ) {
2649 $errors[] = $this->missingPermissionError( $action, $short );
2657 * Get a description array when the user doesn't have the right to perform
2658 * $action (i.e. when User::isAllowed() returns false)
2660 * @param string $action The action to check
2661 * @param bool $short Short circuit on first error
2662 * @return array Array containing an error message key and any parameters
2664 private function missingPermissionError( $action, $short ) {
2665 // We avoid expensive display logic for quickUserCan's and such
2667 return [ 'badaccess-group0' ];
2670 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2674 * Can $user perform $action on this page? This is an internal function,
2675 * with multiple levels of checks depending on performance needs; see $rigor below.
2676 * It does not check wfReadOnly().
2678 * @param string $action Action that permission needs to be checked for
2679 * @param User $user User to check
2680 * @param string $rigor One of (quick,full,secure)
2681 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2682 * - full : does cheap and expensive checks possibly from a replica DB
2683 * - secure : does cheap and expensive checks, using the master as needed
2684 * @param bool $short Set this to true to stop after the first permission error.
2685 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2687 protected function getUserPermissionsErrorsInternal(
2688 $action, $user, $rigor = 'secure', $short = false
2690 if ( $rigor === true ) {
2691 $rigor = 'secure'; // b/c
2692 } elseif ( $rigor === false ) {
2693 $rigor = 'quick'; // b/c
2694 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2695 throw new Exception( "Invalid rigor parameter '$rigor'." );
2698 # Read has special handling
2699 if ( $action == 'read' ) {
2701 'checkPermissionHooks',
2702 'checkReadPermissions',
2703 'checkUserBlock', // for wgBlockDisablesLogin
2705 # Don't call checkSpecialsAndNSPermissions or checkUserConfigPermissions
2706 # here as it will lead to duplicate error messages. This is okay to do
2707 # since anywhere that checks for create will also check for edit, and
2708 # those checks are called for edit.
2709 } elseif ( $action == 'create' ) {
2711 'checkQuickPermissions',
2712 'checkPermissionHooks',
2713 'checkPageRestrictions',
2714 'checkCascadingSourcesRestrictions',
2715 'checkActionPermissions',
2720 'checkQuickPermissions',
2721 'checkPermissionHooks',
2722 'checkSpecialsAndNSPermissions',
2723 'checkUserConfigPermissions',
2724 'checkPageRestrictions',
2725 'checkCascadingSourcesRestrictions',
2726 'checkActionPermissions',
2732 while ( count( $checks ) > 0 &&
2733 !( $short && count( $errors ) > 0 ) ) {
2734 $method = array_shift( $checks );
2735 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2742 * Get a filtered list of all restriction types supported by this wiki.
2743 * @param bool $exists True to get all restriction types that apply to
2744 * titles that do exist, False for all restriction types that apply to
2745 * titles that do not exist
2748 public static function getFilteredRestrictionTypes( $exists = true ) {
2749 global $wgRestrictionTypes;
2750 $types = $wgRestrictionTypes;
2752 # Remove the create restriction for existing titles
2753 $types = array_diff( $types, [ 'create' ] );
2755 # Only the create and upload restrictions apply to non-existing titles
2756 $types = array_intersect( $types, [ 'create', 'upload' ] );
2762 * Returns restriction types for the current Title
2764 * @return array Applicable restriction types
2766 public function getRestrictionTypes() {
2767 if ( $this->isSpecialPage() ) {
2771 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2773 if ( $this->getNamespace() != NS_FILE
) {
2774 # Remove the upload restriction for non-file titles
2775 $types = array_diff( $types, [ 'upload' ] );
2778 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2780 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2781 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2787 * Is this title subject to title protection?
2788 * Title protection is the one applied against creation of such title.
2790 * @return array|bool An associative array representing any existent title
2791 * protection, or false if there's none.
2793 public function getTitleProtection() {
2794 $protection = $this->getTitleProtectionInternal();
2795 if ( $protection ) {
2796 if ( $protection['permission'] == 'sysop' ) {
2797 $protection['permission'] = 'editprotected'; // B/C
2799 if ( $protection['permission'] == 'autoconfirmed' ) {
2800 $protection['permission'] = 'editsemiprotected'; // B/C
2807 * Fetch title protection settings
2809 * To work correctly, $this->loadRestrictions() needs to have access to the
2810 * actual protections in the database without munging 'sysop' =>
2811 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2812 * callers probably want $this->getTitleProtection() instead.
2814 * @return array|bool
2816 protected function getTitleProtectionInternal() {
2817 // Can't protect pages in special namespaces
2818 if ( $this->getNamespace() < 0 ) {
2822 // Can't protect pages that exist.
2823 if ( $this->exists() ) {
2827 if ( $this->mTitleProtection
=== null ) {
2828 $dbr = wfGetDB( DB_REPLICA
);
2829 $commentStore = CommentStore
::getStore();
2830 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2831 $res = $dbr->select(
2832 [ 'protected_titles' ] +
$commentQuery['tables'],
2834 'user' => 'pt_user',
2835 'expiry' => 'pt_expiry',
2836 'permission' => 'pt_create_perm'
2837 ] +
$commentQuery['fields'],
2838 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2841 $commentQuery['joins']
2844 // fetchRow returns false if there are no rows.
2845 $row = $dbr->fetchRow( $res );
2847 $this->mTitleProtection
= [
2848 'user' => $row['user'],
2849 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2850 'permission' => $row['permission'],
2851 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2854 $this->mTitleProtection
= false;
2857 return $this->mTitleProtection
;
2861 * Remove any title protection due to page existing
2863 public function deleteTitleProtection() {
2864 $dbw = wfGetDB( DB_MASTER
);
2868 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2871 $this->mTitleProtection
= false;
2875 * Is this page "semi-protected" - the *only* protection levels are listed
2876 * in $wgSemiprotectedRestrictionLevels?
2878 * @param string $action Action to check (default: edit)
2881 public function isSemiProtected( $action = 'edit' ) {
2882 global $wgSemiprotectedRestrictionLevels;
2884 $restrictions = $this->getRestrictions( $action );
2885 $semi = $wgSemiprotectedRestrictionLevels;
2886 if ( !$restrictions ||
!$semi ) {
2887 // Not protected, or all protection is full protection
2891 // Remap autoconfirmed to editsemiprotected for BC
2892 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2893 $semi[$key] = 'editsemiprotected';
2895 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2896 $restrictions[$key] = 'editsemiprotected';
2899 return !array_diff( $restrictions, $semi );
2903 * Does the title correspond to a protected article?
2905 * @param string $action The action the page is protected from,
2906 * by default checks all actions.
2909 public function isProtected( $action = '' ) {
2910 global $wgRestrictionLevels;
2912 $restrictionTypes = $this->getRestrictionTypes();
2914 # Special pages have inherent protection
2915 if ( $this->isSpecialPage() ) {
2919 # Check regular protection levels
2920 foreach ( $restrictionTypes as $type ) {
2921 if ( $action == $type ||
$action == '' ) {
2922 $r = $this->getRestrictions( $type );
2923 foreach ( $wgRestrictionLevels as $level ) {
2924 if ( in_array( $level, $r ) && $level != '' ) {
2935 * Determines if $user is unable to edit this page because it has been protected
2936 * by $wgNamespaceProtection.
2938 * @param User $user User object to check permissions
2941 public function isNamespaceProtected( User
$user ) {
2942 global $wgNamespaceProtection;
2944 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2945 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2946 if ( $right != '' && !$user->isAllowed( $right ) ) {
2955 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2957 * @return bool If the page is subject to cascading restrictions.
2959 public function isCascadeProtected() {
2960 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2961 return ( $sources > 0 );
2965 * Determines whether cascading protection sources have already been loaded from
2968 * @param bool $getPages True to check if the pages are loaded, or false to check
2969 * if the status is loaded.
2970 * @return bool Whether or not the specified information has been loaded
2973 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2974 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2978 * Cascading protection: Get the source of any cascading restrictions on this page.
2980 * @param bool $getPages Whether or not to retrieve the actual pages
2981 * that the restrictions have come from and the actual restrictions
2983 * @return array Two elements: First is an array of Title objects of the
2984 * pages from which cascading restrictions have come, false for
2985 * none, or true if such restrictions exist but $getPages was not
2986 * set. Second is an array like that returned by
2987 * Title::getAllRestrictions(), or an empty array if $getPages is
2990 public function getCascadeProtectionSources( $getPages = true ) {
2991 $pagerestrictions = [];
2993 if ( $this->mCascadeSources
!== null && $getPages ) {
2994 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2995 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2996 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2999 $dbr = wfGetDB( DB_REPLICA
);
3001 if ( $this->getNamespace() == NS_FILE
) {
3002 $tables = [ 'imagelinks', 'page_restrictions' ];
3004 'il_to' => $this->getDBkey(),
3009 $tables = [ 'templatelinks', 'page_restrictions' ];
3011 'tl_namespace' => $this->getNamespace(),
3012 'tl_title' => $this->getDBkey(),
3019 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3020 'pr_expiry', 'pr_type', 'pr_level' ];
3021 $where_clauses[] = 'page_id=pr_page';
3024 $cols = [ 'pr_expiry' ];
3027 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3029 $sources = $getPages ?
[] : false;
3030 $now = wfTimestampNow();
3032 foreach ( $res as $row ) {
3033 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3034 if ( $expiry > $now ) {
3036 $page_id = $row->pr_page
;
3037 $page_ns = $row->page_namespace
;
3038 $page_title = $row->page_title
;
3039 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3040 # Add groups needed for each restriction type if its not already there
3041 # Make sure this restriction type still exists
3043 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3044 $pagerestrictions[$row->pr_type
] = [];
3048 isset( $pagerestrictions[$row->pr_type
] )
3049 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3051 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3060 $this->mCascadeSources
= $sources;
3061 $this->mCascadingRestrictions
= $pagerestrictions;
3063 $this->mHasCascadingRestrictions
= $sources;
3066 return [ $sources, $pagerestrictions ];
3070 * Accessor for mRestrictionsLoaded
3072 * @return bool Whether or not the page's restrictions have already been
3073 * loaded from the database
3076 public function areRestrictionsLoaded() {
3077 return $this->mRestrictionsLoaded
;
3081 * Accessor/initialisation for mRestrictions
3083 * @param string $action Action that permission needs to be checked for
3084 * @return array Restriction levels needed to take the action. All levels are
3085 * required. Note that restriction levels are normally user rights, but 'sysop'
3086 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3087 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3089 public function getRestrictions( $action ) {
3090 if ( !$this->mRestrictionsLoaded
) {
3091 $this->loadRestrictions();
3093 return isset( $this->mRestrictions
[$action] )
3094 ?
$this->mRestrictions
[$action]
3099 * Accessor/initialisation for mRestrictions
3101 * @return array Keys are actions, values are arrays as returned by
3102 * Title::getRestrictions()
3105 public function getAllRestrictions() {
3106 if ( !$this->mRestrictionsLoaded
) {
3107 $this->loadRestrictions();
3109 return $this->mRestrictions
;
3113 * Get the expiry time for the restriction against a given action
3115 * @param string $action
3116 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3117 * or not protected at all, or false if the action is not recognised.
3119 public function getRestrictionExpiry( $action ) {
3120 if ( !$this->mRestrictionsLoaded
) {
3121 $this->loadRestrictions();
3123 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
3127 * Returns cascading restrictions for the current article
3131 function areRestrictionsCascading() {
3132 if ( !$this->mRestrictionsLoaded
) {
3133 $this->loadRestrictions();
3136 return $this->mCascadeRestriction
;
3140 * Compiles list of active page restrictions from both page table (pre 1.10)
3141 * and page_restrictions table for this existing page.
3142 * Public for usage by LiquidThreads.
3144 * @param array $rows Array of db result objects
3145 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3146 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3147 * Edit and move sections are separated by a colon
3148 * Example: "edit=autoconfirmed,sysop:move=sysop"
3150 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3151 $dbr = wfGetDB( DB_REPLICA
);
3153 $restrictionTypes = $this->getRestrictionTypes();
3155 foreach ( $restrictionTypes as $type ) {
3156 $this->mRestrictions
[$type] = [];
3157 $this->mRestrictionsExpiry
[$type] = 'infinity';
3160 $this->mCascadeRestriction
= false;
3162 # Backwards-compatibility: also load the restrictions from the page record (old format).
3163 if ( $oldFashionedRestrictions !== null ) {
3164 $this->mOldRestrictions
= $oldFashionedRestrictions;
3167 if ( $this->mOldRestrictions
=== false ) {
3168 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3169 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3172 if ( $this->mOldRestrictions
!= '' ) {
3173 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3174 $temp = explode( '=', trim( $restrict ) );
3175 if ( count( $temp ) == 1 ) {
3176 // old old format should be treated as edit/move restriction
3177 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3178 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3180 $restriction = trim( $temp[1] );
3181 if ( $restriction != '' ) { // some old entries are empty
3182 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3188 if ( count( $rows ) ) {
3189 # Current system - load second to make them override.
3190 $now = wfTimestampNow();
3192 # Cycle through all the restrictions.
3193 foreach ( $rows as $row ) {
3194 // Don't take care of restrictions types that aren't allowed
3195 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3199 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3201 // Only apply the restrictions if they haven't expired!
3202 if ( !$expiry ||
$expiry > $now ) {
3203 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3204 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3206 $this->mCascadeRestriction |
= $row->pr_cascade
;
3211 $this->mRestrictionsLoaded
= true;
3215 * Load restrictions from the page_restrictions table
3217 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3218 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3219 * Edit and move sections are separated by a colon
3220 * Example: "edit=autoconfirmed,sysop:move=sysop"
3222 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3223 if ( $this->mRestrictionsLoaded
) {
3227 $id = $this->getArticleID();
3229 $cache = ObjectCache
::getMainWANInstance();
3230 $rows = $cache->getWithSetCallback(
3231 // Page protections always leave a new null revision
3232 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3234 function ( $curValue, &$ttl, array &$setOpts ) {
3235 $dbr = wfGetDB( DB_REPLICA
);
3237 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3239 return iterator_to_array(
3241 'page_restrictions',
3242 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3243 [ 'pr_page' => $this->getArticleID() ],
3250 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3252 $title_protection = $this->getTitleProtectionInternal();
3254 if ( $title_protection ) {
3255 $now = wfTimestampNow();
3256 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3258 if ( !$expiry ||
$expiry > $now ) {
3259 // Apply the restrictions
3260 $this->mRestrictionsExpiry
['create'] = $expiry;
3261 $this->mRestrictions
['create'] =
3262 explode( ',', trim( $title_protection['permission'] ) );
3263 } else { // Get rid of the old restrictions
3264 $this->mTitleProtection
= false;
3267 $this->mRestrictionsExpiry
['create'] = 'infinity';
3269 $this->mRestrictionsLoaded
= true;
3274 * Flush the protection cache in this object and force reload from the database.
3275 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3277 public function flushRestrictions() {
3278 $this->mRestrictionsLoaded
= false;
3279 $this->mTitleProtection
= null;
3283 * Purge expired restrictions from the page_restrictions table
3285 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3287 static function purgeExpiredRestrictions() {
3288 if ( wfReadOnly() ) {
3292 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3293 wfGetDB( DB_MASTER
),
3295 function ( IDatabase
$dbw, $fname ) {
3296 $config = MediaWikiServices
::getInstance()->getMainConfig();
3297 $ids = $dbw->selectFieldValues(
3298 'page_restrictions',
3300 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3302 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3305 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3310 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3311 wfGetDB( DB_MASTER
),
3313 function ( IDatabase
$dbw, $fname ) {
3316 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3324 * Does this have subpages? (Warning, usually requires an extra DB query.)
3328 public function hasSubpages() {
3329 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3334 # We dynamically add a member variable for the purpose of this method
3335 # alone to cache the result. There's no point in having it hanging
3336 # around uninitialized in every Title object; therefore we only add it
3337 # if needed and don't declare it statically.
3338 if ( $this->mHasSubpages
=== null ) {
3339 $this->mHasSubpages
= false;
3340 $subpages = $this->getSubpages( 1 );
3341 if ( $subpages instanceof TitleArray
) {
3342 $this->mHasSubpages
= (bool)$subpages->count();
3346 return $this->mHasSubpages
;
3350 * Get all subpages of this page.
3352 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3353 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3354 * doesn't allow subpages
3356 public function getSubpages( $limit = -1 ) {
3357 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3361 $dbr = wfGetDB( DB_REPLICA
);
3362 $conds['page_namespace'] = $this->getNamespace();
3363 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3365 if ( $limit > -1 ) {
3366 $options['LIMIT'] = $limit;
3368 return TitleArray
::newFromResult(
3369 $dbr->select( 'page',
3370 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3379 * Is there a version of this page in the deletion archive?
3381 * @return int The number of archived revisions
3383 public function isDeleted() {
3384 if ( $this->getNamespace() < 0 ) {
3387 $dbr = wfGetDB( DB_REPLICA
);
3389 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3390 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3393 if ( $this->getNamespace() == NS_FILE
) {
3394 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3395 [ 'fa_name' => $this->getDBkey() ],
3404 * Is there a version of this page in the deletion archive?
3408 public function isDeletedQuick() {
3409 if ( $this->getNamespace() < 0 ) {
3412 $dbr = wfGetDB( DB_REPLICA
);
3413 $deleted = (bool)$dbr->selectField( 'archive', '1',
3414 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3417 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3418 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3419 [ 'fa_name' => $this->getDBkey() ],
3427 * Get the article ID for this Title from the link cache,
3428 * adding it if necessary
3430 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3432 * @return int The ID
3434 public function getArticleID( $flags = 0 ) {
3435 if ( $this->getNamespace() < 0 ) {
3436 $this->mArticleID
= 0;
3437 return $this->mArticleID
;
3439 $linkCache = LinkCache
::singleton();
3440 if ( $flags & self
::GAID_FOR_UPDATE
) {
3441 $oldUpdate = $linkCache->forUpdate( true );
3442 $linkCache->clearLink( $this );
3443 $this->mArticleID
= $linkCache->addLinkObj( $this );
3444 $linkCache->forUpdate( $oldUpdate );
3446 if ( -1 == $this->mArticleID
) {
3447 $this->mArticleID
= $linkCache->addLinkObj( $this );
3450 return $this->mArticleID
;
3454 * Is this an article that is a redirect page?
3455 * Uses link cache, adding it if necessary
3457 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3460 public function isRedirect( $flags = 0 ) {
3461 if ( !is_null( $this->mRedirect
) ) {
3462 return $this->mRedirect
;
3464 if ( !$this->getArticleID( $flags ) ) {
3465 $this->mRedirect
= false;
3466 return $this->mRedirect
;
3469 $linkCache = LinkCache
::singleton();
3470 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3471 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3472 if ( $cached === null ) {
3473 # Trust LinkCache's state over our own
3474 # LinkCache is telling us that the page doesn't exist, despite there being cached
3475 # data relating to an existing page in $this->mArticleID. Updaters should clear
3476 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3477 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3478 # LinkCache to refresh its data from the master.
3479 $this->mRedirect
= false;
3480 return $this->mRedirect
;
3483 $this->mRedirect
= (bool)$cached;
3485 return $this->mRedirect
;
3489 * What is the length of this page?
3490 * Uses link cache, adding it if necessary
3492 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3495 public function getLength( $flags = 0 ) {
3496 if ( $this->mLength
!= -1 ) {
3497 return $this->mLength
;
3499 if ( !$this->getArticleID( $flags ) ) {
3501 return $this->mLength
;
3503 $linkCache = LinkCache
::singleton();
3504 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3505 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3506 if ( $cached === null ) {
3507 # Trust LinkCache's state over our own, as for isRedirect()
3509 return $this->mLength
;
3512 $this->mLength
= intval( $cached );
3514 return $this->mLength
;
3518 * What is the page_latest field for this page?
3520 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3521 * @return int Int or 0 if the page doesn't exist
3523 public function getLatestRevID( $flags = 0 ) {
3524 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3525 return intval( $this->mLatestID
);
3527 if ( !$this->getArticleID( $flags ) ) {
3528 $this->mLatestID
= 0;
3529 return $this->mLatestID
;
3531 $linkCache = LinkCache
::singleton();
3532 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3533 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3534 if ( $cached === null ) {
3535 # Trust LinkCache's state over our own, as for isRedirect()
3536 $this->mLatestID
= 0;
3537 return $this->mLatestID
;
3540 $this->mLatestID
= intval( $cached );
3542 return $this->mLatestID
;
3546 * This clears some fields in this object, and clears any associated
3547 * keys in the "bad links" section of the link cache.
3549 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3550 * loading of the new page_id. It's also called from
3551 * WikiPage::doDeleteArticleReal()
3553 * @param int $newid The new Article ID
3555 public function resetArticleID( $newid ) {
3556 $linkCache = LinkCache
::singleton();
3557 $linkCache->clearLink( $this );
3559 if ( $newid === false ) {
3560 $this->mArticleID
= -1;
3562 $this->mArticleID
= intval( $newid );
3564 $this->mRestrictionsLoaded
= false;
3565 $this->mRestrictions
= [];
3566 $this->mOldRestrictions
= false;
3567 $this->mRedirect
= null;
3568 $this->mLength
= -1;
3569 $this->mLatestID
= false;
3570 $this->mContentModel
= false;
3571 $this->mEstimateRevisions
= null;
3572 $this->mPageLanguage
= false;
3573 $this->mDbPageLanguage
= false;
3574 $this->mIsBigDeletion
= null;
3577 public static function clearCaches() {
3578 $linkCache = LinkCache
::singleton();
3579 $linkCache->clear();
3581 $titleCache = self
::getTitleCache();
3582 $titleCache->clear();
3586 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3588 * @param string $text Containing title to capitalize
3589 * @param int $ns Namespace index, defaults to NS_MAIN
3590 * @return string Containing capitalized title
3592 public static function capitalize( $text, $ns = NS_MAIN
) {
3595 if ( MWNamespace
::isCapitalized( $ns ) ) {
3596 return $wgContLang->ucfirst( $text );
3603 * Secure and split - main initialisation function for this object
3605 * Assumes that mDbkeyform has been set, and is urldecoded
3606 * and uses underscores, but not otherwise munged. This function
3607 * removes illegal characters, splits off the interwiki and
3608 * namespace prefixes, sets the other forms, and canonicalizes
3611 * @throws MalformedTitleException On invalid titles
3612 * @return bool True on success
3614 private function secureAndSplit() {
3616 $this->mInterwiki
= '';
3617 $this->mFragment
= '';
3618 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3620 $dbkey = $this->mDbkeyform
;
3622 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3623 // the parsing code with Title, while avoiding massive refactoring.
3624 // @todo: get rid of secureAndSplit, refactor parsing code.
3625 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3626 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3627 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3628 // MalformedTitleException can be thrown here
3629 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3632 $this->setFragment( '#' . $parts['fragment'] );
3633 $this->mInterwiki
= $parts['interwiki'];
3634 $this->mLocalInterwiki
= $parts['local_interwiki'];
3635 $this->mNamespace
= $parts['namespace'];
3636 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3638 $this->mDbkeyform
= $parts['dbkey'];
3639 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3640 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3642 # We already know that some pages won't be in the database!
3643 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3644 $this->mArticleID
= 0;
3651 * Get an array of Title objects linking to this Title
3652 * Also stores the IDs in the link cache.
3654 * WARNING: do not use this function on arbitrary user-supplied titles!
3655 * On heavily-used templates it will max out the memory.
3657 * @param array $options May be FOR UPDATE
3658 * @param string $table Table name
3659 * @param string $prefix Fields prefix
3660 * @return Title[] Array of Title objects linking here
3662 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3663 if ( count( $options ) > 0 ) {
3664 $db = wfGetDB( DB_MASTER
);
3666 $db = wfGetDB( DB_REPLICA
);
3671 self
::getSelectFields(),
3673 "{$prefix}_from=page_id",
3674 "{$prefix}_namespace" => $this->getNamespace(),
3675 "{$prefix}_title" => $this->getDBkey() ],
3681 if ( $res->numRows() ) {
3682 $linkCache = LinkCache
::singleton();
3683 foreach ( $res as $row ) {
3684 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3686 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3687 $retVal[] = $titleObj;
3695 * Get an array of Title objects using this Title as a template
3696 * Also stores the IDs in the link cache.
3698 * WARNING: do not use this function on arbitrary user-supplied titles!
3699 * On heavily-used templates it will max out the memory.
3701 * @param array $options Query option to Database::select()
3702 * @return Title[] Array of Title the Title objects linking here
3704 public function getTemplateLinksTo( $options = [] ) {
3705 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3709 * Get an array of Title objects linked from this Title
3710 * Also stores the IDs in the link cache.
3712 * WARNING: do not use this function on arbitrary user-supplied titles!
3713 * On heavily-used templates it will max out the memory.
3715 * @param array $options Query option to Database::select()
3716 * @param string $table Table name
3717 * @param string $prefix Fields prefix
3718 * @return array Array of Title objects linking here
3720 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3721 $id = $this->getArticleID();
3723 # If the page doesn't exist; there can't be any link from this page
3728 $db = wfGetDB( DB_REPLICA
);
3730 $blNamespace = "{$prefix}_namespace";
3731 $blTitle = "{$prefix}_title";
3733 $pageQuery = WikiPage
::getQueryInfo();
3735 [ $table, 'nestpage' => $pageQuery['tables'] ],
3737 [ $blNamespace, $blTitle ],
3738 $pageQuery['fields']
3740 [ "{$prefix}_from" => $id ],
3745 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3746 ] ] +
$pageQuery['joins']
3750 $linkCache = LinkCache
::singleton();
3751 foreach ( $res as $row ) {
3752 if ( $row->page_id
) {
3753 $titleObj = self
::newFromRow( $row );
3755 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3756 $linkCache->addBadLinkObj( $titleObj );
3758 $retVal[] = $titleObj;
3765 * Get an array of Title objects used on this Title as a template
3766 * Also stores the IDs in the link cache.
3768 * WARNING: do not use this function on arbitrary user-supplied titles!
3769 * On heavily-used templates it will max out the memory.
3771 * @param array $options May be FOR UPDATE
3772 * @return Title[] Array of Title the Title objects used here
3774 public function getTemplateLinksFrom( $options = [] ) {
3775 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3779 * Get an array of Title objects referring to non-existent articles linked
3782 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3783 * should use redirect table in this case).
3784 * @return Title[] Array of Title the Title objects
3786 public function getBrokenLinksFrom() {
3787 if ( $this->getArticleID() == 0 ) {
3788 # All links from article ID 0 are false positives
3792 $dbr = wfGetDB( DB_REPLICA
);
3793 $res = $dbr->select(
3794 [ 'page', 'pagelinks' ],
3795 [ 'pl_namespace', 'pl_title' ],
3797 'pl_from' => $this->getArticleID(),
3798 'page_namespace IS NULL'
3804 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3810 foreach ( $res as $row ) {
3811 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3817 * Get a list of URLs to purge from the CDN cache when this
3820 * @return string[] Array of String the URLs
3822 public function getCdnUrls() {
3824 $this->getInternalURL(),
3825 $this->getInternalURL( 'action=history' )
3828 $pageLang = $this->getPageLanguage();
3829 if ( $pageLang->hasVariants() ) {
3830 $variants = $pageLang->getVariants();
3831 foreach ( $variants as $vCode ) {
3832 $urls[] = $this->getInternalURL( $vCode );
3836 // If we are looking at a css/js user subpage, purge the action=raw.
3837 if ( $this->isUserJsConfigPage() ) {
3838 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3839 } elseif ( $this->isUserJsonConfigPage() ) {
3840 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3841 } elseif ( $this->isUserCssConfigPage() ) {
3842 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3845 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3850 * @deprecated since 1.27 use getCdnUrls()
3852 public function getSquidURLs() {
3853 return $this->getCdnUrls();
3857 * Purge all applicable CDN URLs
3859 public function purgeSquid() {
3860 DeferredUpdates
::addUpdate(
3861 new CdnCacheUpdate( $this->getCdnUrls() ),
3862 DeferredUpdates
::PRESEND
3867 * Check whether a given move operation would be valid.
3868 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3870 * @deprecated since 1.25, use MovePage's methods instead
3871 * @param Title &$nt The new title
3872 * @param bool $auth Whether to check user permissions (uses $wgUser)
3873 * @param string $reason Is the log summary of the move, used for spam checking
3874 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3876 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3879 if ( !( $nt instanceof Title
) ) {
3880 // Normally we'd add this to $errors, but we'll get
3881 // lots of syntax errors if $nt is not an object
3882 return [ [ 'badtitletext' ] ];
3885 $mp = new MovePage( $this, $nt );
3886 $errors = $mp->isValidMove()->getErrorsArray();
3888 $errors = wfMergeErrorArrays(
3890 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3894 return $errors ?
: true;
3898 * Check if the requested move target is a valid file move target
3899 * @todo move this to MovePage
3900 * @param Title $nt Target title
3901 * @return array List of errors
3903 protected function validateFileMoveOperation( $nt ) {
3908 $destFile = wfLocalFile( $nt );
3909 $destFile->load( File
::READ_LATEST
);
3910 if ( !$wgUser->isAllowed( 'reupload-shared' )
3911 && !$destFile->exists() && wfFindFile( $nt )
3913 $errors[] = [ 'file-exists-sharedrepo' ];
3920 * Move a title to a new location
3922 * @deprecated since 1.25, use the MovePage class instead
3923 * @param Title &$nt The new title
3924 * @param bool $auth Indicates whether $wgUser's permissions
3926 * @param string $reason The reason for the move
3927 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3928 * Ignored if the user doesn't have the suppressredirect right.
3929 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3930 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3932 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3933 array $changeTags = []
3936 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3937 if ( is_array( $err ) ) {
3938 // Auto-block user's IP if the account was "hard" blocked
3939 $wgUser->spreadAnyEditBlock();
3942 // Check suppressredirect permission
3943 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3944 $createRedirect = true;
3947 $mp = new MovePage( $this, $nt );
3948 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3949 if ( $status->isOK() ) {
3952 return $status->getErrorsArray();
3957 * Move this page's subpages to be subpages of $nt
3959 * @param Title $nt Move target
3960 * @param bool $auth Whether $wgUser's permissions should be checked
3961 * @param string $reason The reason for the move
3962 * @param bool $createRedirect Whether to create redirects from the old subpages to
3963 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3964 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3965 * @return array Array with old page titles as keys, and strings (new page titles) or
3966 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3967 * getUserPermissionsErrors()-like error array with numeric indices if
3968 * no pages were moved
3970 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3971 array $changeTags = []
3973 global $wgMaximumMovedPages;
3974 // Check permissions
3975 if ( !$this->userCan( 'move-subpages' ) ) {
3977 [ 'cant-move-subpages' ],
3980 // Do the source and target namespaces support subpages?
3981 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3983 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3986 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3988 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3992 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3995 foreach ( $subpages as $oldSubpage ) {
3997 if ( $count > $wgMaximumMovedPages ) {
3998 $retval[$oldSubpage->getPrefixedText()] = [
3999 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4004 // We don't know whether this function was called before
4005 // or after moving the root page, so check both
4007 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4008 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4010 // When moving a page to a subpage of itself,
4011 // don't move it twice
4014 $newPageName = preg_replace(
4015 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4016 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4017 $oldSubpage->getDBkey() );
4018 if ( $oldSubpage->isTalkPage() ) {
4019 $newNs = $nt->getTalkPage()->getNamespace();
4021 $newNs = $nt->getSubjectPage()->getNamespace();
4023 # T16385: we need makeTitleSafe because the new page names may
4024 # be longer than 255 characters.
4025 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4027 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4028 if ( $success === true ) {
4029 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4031 $retval[$oldSubpage->getPrefixedText()] = $success;
4038 * Checks if this page is just a one-rev redirect.
4039 * Adds lock, so don't use just for light purposes.
4043 public function isSingleRevRedirect() {
4044 global $wgContentHandlerUseDB;
4046 $dbw = wfGetDB( DB_MASTER
);
4049 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4050 if ( $wgContentHandlerUseDB ) {
4051 $fields[] = 'page_content_model';
4054 $row = $dbw->selectRow( 'page',
4060 # Cache some fields we may want
4061 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4062 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4063 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4064 $this->mContentModel
= $row && isset( $row->page_content_model
)
4065 ?
strval( $row->page_content_model
)
4068 if ( !$this->mRedirect
) {
4071 # Does the article have a history?
4072 $row = $dbw->selectField( [ 'page', 'revision' ],
4074 [ 'page_namespace' => $this->getNamespace(),
4075 'page_title' => $this->getDBkey(),
4077 'page_latest != rev_id'
4082 # Return true if there was no history
4083 return ( $row === false );
4087 * Checks if $this can be moved to a given Title
4088 * - Selects for update, so don't call it unless you mean business
4090 * @deprecated since 1.25, use MovePage's methods instead
4091 * @param Title $nt The new title to check
4094 public function isValidMoveTarget( $nt ) {
4095 # Is it an existing file?
4096 if ( $nt->getNamespace() == NS_FILE
) {
4097 $file = wfLocalFile( $nt );
4098 $file->load( File
::READ_LATEST
);
4099 if ( $file->exists() ) {
4100 wfDebug( __METHOD__
. ": file exists\n" );
4104 # Is it a redirect with no history?
4105 if ( !$nt->isSingleRevRedirect() ) {
4106 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4109 # Get the article text
4110 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4111 if ( !is_object( $rev ) ) {
4114 $content = $rev->getContent();
4115 # Does the redirect point to the source?
4116 # Or is it a broken self-redirect, usually caused by namespace collisions?
4117 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4119 if ( $redirTitle ) {
4120 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4121 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4122 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4128 # Fail safe (not a redirect after all. strange.)
4129 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4130 " is a redirect, but it doesn't contain a valid redirect.\n" );
4136 * Get categories to which this Title belongs and return an array of
4137 * categories' names.
4139 * @return array Array of parents in the form:
4140 * $parent => $currentarticle
4142 public function getParentCategories() {
4147 $titleKey = $this->getArticleID();
4149 if ( $titleKey === 0 ) {
4153 $dbr = wfGetDB( DB_REPLICA
);
4155 $res = $dbr->select(
4158 [ 'cl_from' => $titleKey ],
4162 if ( $res->numRows() > 0 ) {
4163 foreach ( $res as $row ) {
4164 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4165 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4172 * Get a tree of parent categories
4174 * @param array $children Array with the children in the keys, to check for circular refs
4175 * @return array Tree of parent categories
4177 public function getParentCategoryTree( $children = [] ) {
4179 $parents = $this->getParentCategories();
4182 foreach ( $parents as $parent => $current ) {
4183 if ( array_key_exists( $parent, $children ) ) {
4184 # Circular reference
4185 $stack[$parent] = [];
4187 $nt = self
::newFromText( $parent );
4189 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4199 * Get an associative array for selecting this title from
4202 * @return array Array suitable for the $where parameter of DB::select()
4204 public function pageCond() {
4205 if ( $this->mArticleID
> 0 ) {
4206 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4207 return [ 'page_id' => $this->mArticleID
];
4209 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4214 * Get next/previous revision ID relative to another revision ID
4215 * @param int $revId Revision ID. Get the revision that was before this one.
4216 * @param int $flags Title::GAID_FOR_UPDATE
4217 * @param string $dir 'next' or 'prev'
4218 * @return int|bool New revision ID, or false if none exists
4220 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4221 $revId = (int)$revId;
4222 if ( $dir === 'next' ) {
4225 } elseif ( $dir === 'prev' ) {
4229 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4232 if ( $flags & self
::GAID_FOR_UPDATE
) {
4233 $db = wfGetDB( DB_MASTER
);
4235 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4238 // Intentionally not caring if the specified revision belongs to this
4239 // page. We only care about the timestamp.
4240 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4241 if ( $ts === false ) {
4242 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4243 if ( $ts === false ) {
4244 // Or should this throw an InvalidArgumentException or something?
4248 $ts = $db->addQuotes( $ts );
4250 $revId = $db->selectField( 'revision', 'rev_id',
4252 'rev_page' => $this->getArticleID( $flags ),
4253 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4257 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4258 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4262 if ( $revId === false ) {
4265 return intval( $revId );
4270 * Get the revision ID of the previous revision
4272 * @param int $revId Revision ID. Get the revision that was before this one.
4273 * @param int $flags Title::GAID_FOR_UPDATE
4274 * @return int|bool Old revision ID, or false if none exists
4276 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4277 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4281 * Get the revision ID of the next revision
4283 * @param int $revId Revision ID. Get the revision that was after this one.
4284 * @param int $flags Title::GAID_FOR_UPDATE
4285 * @return int|bool Next revision ID, or false if none exists
4287 public function getNextRevisionID( $revId, $flags = 0 ) {
4288 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4292 * Get the first revision of the page
4294 * @param int $flags Title::GAID_FOR_UPDATE
4295 * @return Revision|null If page doesn't exist
4297 public function getFirstRevision( $flags = 0 ) {
4298 $pageId = $this->getArticleID( $flags );
4300 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4301 $revQuery = Revision
::getQueryInfo();
4302 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4303 [ 'rev_page' => $pageId ],
4306 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4307 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4312 return new Revision( $row );
4319 * Get the oldest revision timestamp of this page
4321 * @param int $flags Title::GAID_FOR_UPDATE
4322 * @return string MW timestamp
4324 public function getEarliestRevTime( $flags = 0 ) {
4325 $rev = $this->getFirstRevision( $flags );
4326 return $rev ?
$rev->getTimestamp() : null;
4330 * Check if this is a new page
4334 public function isNewPage() {
4335 $dbr = wfGetDB( DB_REPLICA
);
4336 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4340 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4344 public function isBigDeletion() {
4345 global $wgDeleteRevisionsLimit;
4347 if ( !$wgDeleteRevisionsLimit ) {
4351 if ( $this->mIsBigDeletion
=== null ) {
4352 $dbr = wfGetDB( DB_REPLICA
);
4354 $revCount = $dbr->selectRowCount(
4357 [ 'rev_page' => $this->getArticleID() ],
4359 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4362 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4365 return $this->mIsBigDeletion
;
4369 * Get the approximate revision count of this page.
4373 public function estimateRevisionCount() {
4374 if ( !$this->exists() ) {
4378 if ( $this->mEstimateRevisions
=== null ) {
4379 $dbr = wfGetDB( DB_REPLICA
);
4380 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4381 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4384 return $this->mEstimateRevisions
;
4388 * Get the number of revisions between the given revision.
4389 * Used for diffs and other things that really need it.
4391 * @param int|Revision $old Old revision or rev ID (first before range)
4392 * @param int|Revision $new New revision or rev ID (first after range)
4393 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4394 * @return int Number of revisions between these revisions.
4396 public function countRevisionsBetween( $old, $new, $max = null ) {
4397 if ( !( $old instanceof Revision
) ) {
4398 $old = Revision
::newFromTitle( $this, (int)$old );
4400 if ( !( $new instanceof Revision
) ) {
4401 $new = Revision
::newFromTitle( $this, (int)$new );
4403 if ( !$old ||
!$new ) {
4404 return 0; // nothing to compare
4406 $dbr = wfGetDB( DB_REPLICA
);
4408 'rev_page' => $this->getArticleID(),
4409 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4410 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4412 if ( $max !== null ) {
4413 return $dbr->selectRowCount( 'revision', '1',
4416 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4419 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4424 * Get the authors between the given revisions or revision IDs.
4425 * Used for diffs and other things that really need it.
4429 * @param int|Revision $old Old revision or rev ID (first before range by default)
4430 * @param int|Revision $new New revision or rev ID (first after range by default)
4431 * @param int $limit Maximum number of authors
4432 * @param string|array $options (Optional): Single option, or an array of options:
4433 * 'include_old' Include $old in the range; $new is excluded.
4434 * 'include_new' Include $new in the range; $old is excluded.
4435 * 'include_both' Include both $old and $new in the range.
4436 * Unknown option values are ignored.
4437 * @return array|null Names of revision authors in the range; null if not both revisions exist
4439 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4440 if ( !( $old instanceof Revision
) ) {
4441 $old = Revision
::newFromTitle( $this, (int)$old );
4443 if ( !( $new instanceof Revision
) ) {
4444 $new = Revision
::newFromTitle( $this, (int)$new );
4446 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4447 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4448 // in the sanity check below?
4449 if ( !$old ||
!$new ) {
4450 return null; // nothing to compare
4455 $options = (array)$options;
4456 if ( in_array( 'include_old', $options ) ) {
4459 if ( in_array( 'include_new', $options ) ) {
4462 if ( in_array( 'include_both', $options ) ) {
4466 // No DB query needed if $old and $new are the same or successive revisions:
4467 if ( $old->getId() === $new->getId() ) {
4468 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4470 [ $old->getUserText( Revision
::RAW
) ];
4471 } elseif ( $old->getId() === $new->getParentId() ) {
4472 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4473 $authors[] = $old->getUserText( Revision
::RAW
);
4474 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4475 $authors[] = $new->getUserText( Revision
::RAW
);
4477 } elseif ( $old_cmp === '>=' ) {
4478 $authors[] = $old->getUserText( Revision
::RAW
);
4479 } elseif ( $new_cmp === '<=' ) {
4480 $authors[] = $new->getUserText( Revision
::RAW
);
4484 $dbr = wfGetDB( DB_REPLICA
);
4485 $revQuery = Revision
::getQueryInfo();
4486 $authors = $dbr->selectFieldValues(
4487 $revQuery['tables'],
4488 $revQuery['fields']['rev_user_text'],
4490 'rev_page' => $this->getArticleID(),
4491 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4492 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4494 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4501 * Get the number of authors between the given revisions or revision IDs.
4502 * Used for diffs and other things that really need it.
4504 * @param int|Revision $old Old revision or rev ID (first before range by default)
4505 * @param int|Revision $new New revision or rev ID (first after range by default)
4506 * @param int $limit Maximum number of authors
4507 * @param string|array $options (Optional): Single option, or an array of options:
4508 * 'include_old' Include $old in the range; $new is excluded.
4509 * 'include_new' Include $new in the range; $old is excluded.
4510 * 'include_both' Include both $old and $new in the range.
4511 * Unknown option values are ignored.
4512 * @return int Number of revision authors in the range; zero if not both revisions exist
4514 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4515 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4516 return $authors ?
count( $authors ) : 0;
4520 * Compare with another title.
4522 * @param Title $title
4525 public function equals( Title
$title ) {
4526 // Note: === is necessary for proper matching of number-like titles.
4527 return $this->getInterwiki() === $title->getInterwiki()
4528 && $this->getNamespace() == $title->getNamespace()
4529 && $this->getDBkey() === $title->getDBkey();
4533 * Check if this title is a subpage of another title
4535 * @param Title $title
4538 public function isSubpageOf( Title
$title ) {
4539 return $this->getInterwiki() === $title->getInterwiki()
4540 && $this->getNamespace() == $title->getNamespace()
4541 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4545 * Check if page exists. For historical reasons, this function simply
4546 * checks for the existence of the title in the page table, and will
4547 * thus return false for interwiki links, special pages and the like.
4548 * If you want to know if a title can be meaningfully viewed, you should
4549 * probably call the isKnown() method instead.
4551 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4552 * from master/for update
4555 public function exists( $flags = 0 ) {
4556 $exists = $this->getArticleID( $flags ) != 0;
4557 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4562 * Should links to this title be shown as potentially viewable (i.e. as
4563 * "bluelinks"), even if there's no record by this title in the page
4566 * This function is semi-deprecated for public use, as well as somewhat
4567 * misleadingly named. You probably just want to call isKnown(), which
4568 * calls this function internally.
4570 * (ISSUE: Most of these checks are cheap, but the file existence check
4571 * can potentially be quite expensive. Including it here fixes a lot of
4572 * existing code, but we might want to add an optional parameter to skip
4573 * it and any other expensive checks.)
4577 public function isAlwaysKnown() {
4581 * Allows overriding default behavior for determining if a page exists.
4582 * If $isKnown is kept as null, regular checks happen. If it's
4583 * a boolean, this value is returned by the isKnown method.
4587 * @param Title $title
4588 * @param bool|null $isKnown
4590 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4592 if ( !is_null( $isKnown ) ) {
4596 if ( $this->isExternal() ) {
4597 return true; // any interwiki link might be viewable, for all we know
4600 switch ( $this->mNamespace
) {
4603 // file exists, possibly in a foreign repo
4604 return (bool)wfFindFile( $this );
4606 // valid special page
4607 return SpecialPageFactory
::exists( $this->getDBkey() );
4609 // selflink, possibly with fragment
4610 return $this->mDbkeyform
== '';
4612 // known system message
4613 return $this->hasSourceText() !== false;
4620 * Does this title refer to a page that can (or might) be meaningfully
4621 * viewed? In particular, this function may be used to determine if
4622 * links to the title should be rendered as "bluelinks" (as opposed to
4623 * "redlinks" to non-existent pages).
4624 * Adding something else to this function will cause inconsistency
4625 * since LinkHolderArray calls isAlwaysKnown() and does its own
4626 * page existence check.
4630 public function isKnown() {
4631 return $this->isAlwaysKnown() ||
$this->exists();
4635 * Does this page have source text?
4639 public function hasSourceText() {
4640 if ( $this->exists() ) {
4644 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4645 // If the page doesn't exist but is a known system message, default
4646 // message content will be displayed, same for language subpages-
4647 // Use always content language to avoid loading hundreds of languages
4648 // to get the link color.
4650 list( $name, ) = MessageCache
::singleton()->figureMessage(
4651 $wgContLang->lcfirst( $this->getText() )
4653 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4654 return $message->exists();
4661 * Get the default message text or false if the message doesn't exist
4663 * @return string|bool
4665 public function getDefaultMessageText() {
4668 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4672 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4673 $wgContLang->lcfirst( $this->getText() )
4675 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4677 if ( $message->exists() ) {
4678 return $message->plain();
4685 * Updates page_touched for this page; called from LinksUpdate.php
4687 * @param string $purgeTime [optional] TS_MW timestamp
4688 * @return bool True if the update succeeded
4690 public function invalidateCache( $purgeTime = null ) {
4691 if ( wfReadOnly() ) {
4693 } elseif ( $this->mArticleID
=== 0 ) {
4694 return true; // avoid gap locking if we know it's not there
4697 $dbw = wfGetDB( DB_MASTER
);
4698 $dbw->onTransactionPreCommitOrIdle( function () {
4699 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4702 $conds = $this->pageCond();
4703 DeferredUpdates
::addUpdate(
4704 new AutoCommitUpdate(
4707 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4708 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4711 [ 'page_touched' => $dbTimestamp ],
4712 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4715 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4718 DeferredUpdates
::PRESEND
4725 * Update page_touched timestamps and send CDN purge messages for
4726 * pages linking to this title. May be sent to the job queue depending
4727 * on the number of links. Typically called on create and delete.
4729 public function touchLinks() {
4730 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4731 if ( $this->getNamespace() == NS_CATEGORY
) {
4732 DeferredUpdates
::addUpdate(
4733 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4739 * Get the last touched timestamp
4741 * @param IDatabase|null $db
4742 * @return string|false Last-touched timestamp
4744 public function getTouched( $db = null ) {
4745 if ( $db === null ) {
4746 $db = wfGetDB( DB_REPLICA
);
4748 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4753 * Get the timestamp when this page was updated since the user last saw it.
4756 * @return string|null
4758 public function getNotificationTimestamp( $user = null ) {
4761 // Assume current user if none given
4765 // Check cache first
4766 $uid = $user->getId();
4770 // avoid isset here, as it'll return false for null entries
4771 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4772 return $this->mNotificationTimestamp
[$uid];
4774 // Don't cache too much!
4775 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4776 $this->mNotificationTimestamp
= [];
4779 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4780 $watchedItem = $store->getWatchedItem( $user, $this );
4781 if ( $watchedItem ) {
4782 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4784 $this->mNotificationTimestamp
[$uid] = false;
4787 return $this->mNotificationTimestamp
[$uid];
4791 * Generate strings used for xml 'id' names in monobook tabs
4793 * @param string $prepend Defaults to 'nstab-'
4794 * @return string XML 'id' name
4796 public function getNamespaceKey( $prepend = 'nstab-' ) {
4798 // Gets the subject namespace if this title
4799 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4800 // Checks if canonical namespace name exists for namespace
4801 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4802 // Uses canonical namespace name
4803 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4805 // Uses text of namespace
4806 $namespaceKey = $this->getSubjectNsText();
4808 // Makes namespace key lowercase
4809 $namespaceKey = $wgContLang->lc( $namespaceKey );
4811 if ( $namespaceKey == '' ) {
4812 $namespaceKey = 'main';
4814 // Changes file to image for backwards compatibility
4815 if ( $namespaceKey == 'file' ) {
4816 $namespaceKey = 'image';
4818 return $prepend . $namespaceKey;
4822 * Get all extant redirects to this Title
4824 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4825 * @return Title[] Array of Title redirects to this title
4827 public function getRedirectsHere( $ns = null ) {
4830 $dbr = wfGetDB( DB_REPLICA
);
4832 'rd_namespace' => $this->getNamespace(),
4833 'rd_title' => $this->getDBkey(),
4836 if ( $this->isExternal() ) {
4837 $where['rd_interwiki'] = $this->getInterwiki();
4839 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4841 if ( !is_null( $ns ) ) {
4842 $where['page_namespace'] = $ns;
4845 $res = $dbr->select(
4846 [ 'redirect', 'page' ],
4847 [ 'page_namespace', 'page_title' ],
4852 foreach ( $res as $row ) {
4853 $redirs[] = self
::newFromRow( $row );
4859 * Check if this Title is a valid redirect target
4863 public function isValidRedirectTarget() {
4864 global $wgInvalidRedirectTargets;
4866 if ( $this->isSpecialPage() ) {
4867 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4868 if ( $this->isSpecial( 'Userlogout' ) ) {
4872 foreach ( $wgInvalidRedirectTargets as $target ) {
4873 if ( $this->isSpecial( $target ) ) {
4883 * Get a backlink cache object
4885 * @return BacklinkCache
4887 public function getBacklinkCache() {
4888 return BacklinkCache
::get( $this );
4892 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4896 public function canUseNoindex() {
4897 global $wgExemptFromUserRobotsControl;
4899 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4900 ? MWNamespace
::getContentNamespaces()
4901 : $wgExemptFromUserRobotsControl;
4903 return !in_array( $this->mNamespace
, $bannedNamespaces );
4907 * Returns the raw sort key to be used for categories, with the specified
4908 * prefix. This will be fed to Collation::getSortKey() to get a
4909 * binary sortkey that can be used for actual sorting.
4911 * @param string $prefix The prefix to be used, specified using
4912 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4916 public function getCategorySortkey( $prefix = '' ) {
4917 $unprefixed = $this->getText();
4919 // Anything that uses this hook should only depend
4920 // on the Title object passed in, and should probably
4921 // tell the users to run updateCollations.php --force
4922 // in order to re-sort existing category relations.
4923 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4924 if ( $prefix !== '' ) {
4925 # Separate with a line feed, so the unprefixed part is only used as
4926 # a tiebreaker when two pages have the exact same prefix.
4927 # In UCA, tab is the only character that can sort above LF
4928 # so we strip both of them from the original prefix.
4929 $prefix = strtr( $prefix, "\n\t", ' ' );
4930 return "$prefix\n$unprefixed";
4936 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4937 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4938 * the db, it will return NULL.
4940 * @return string|null|bool
4942 private function getDbPageLanguageCode() {
4943 global $wgPageLanguageUseDB;
4945 // check, if the page language could be saved in the database, and if so and
4946 // the value is not requested already, lookup the page language using LinkCache
4947 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4948 $linkCache = LinkCache
::singleton();
4949 $linkCache->addLinkObj( $this );
4950 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4953 return $this->mDbPageLanguage
;
4957 * Get the language in which the content of this page is written in
4958 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4959 * e.g. $wgLang (such as special pages, which are in the user language).
4964 public function getPageLanguage() {
4965 global $wgLang, $wgLanguageCode;
4966 if ( $this->isSpecialPage() ) {
4967 // special pages are in the user language
4971 // Checking if DB language is set
4972 $dbPageLanguage = $this->getDbPageLanguageCode();
4973 if ( $dbPageLanguage ) {
4974 return wfGetLangObj( $dbPageLanguage );
4977 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4978 // Note that this may depend on user settings, so the cache should
4979 // be only per-request.
4980 // NOTE: ContentHandler::getPageLanguage() may need to load the
4981 // content to determine the page language!
4982 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4984 $contentHandler = ContentHandler
::getForTitle( $this );
4985 $langObj = $contentHandler->getPageLanguage( $this );
4986 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4988 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4995 * Get the language in which the content of this page is written when
4996 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4997 * e.g. $wgLang (such as special pages, which are in the user language).
5002 public function getPageViewLanguage() {
5005 if ( $this->isSpecialPage() ) {
5006 // If the user chooses a variant, the content is actually
5007 // in a language whose code is the variant code.
5008 $variant = $wgLang->getPreferredVariant();
5009 if ( $wgLang->getCode() !== $variant ) {
5010 return Language
::factory( $variant );
5016 // Checking if DB language is set
5017 $dbPageLanguage = $this->getDbPageLanguageCode();
5018 if ( $dbPageLanguage ) {
5019 $pageLang = wfGetLangObj( $dbPageLanguage );
5020 $variant = $pageLang->getPreferredVariant();
5021 if ( $pageLang->getCode() !== $variant ) {
5022 $pageLang = Language
::factory( $variant );
5028 // @note Can't be cached persistently, depends on user settings.
5029 // @note ContentHandler::getPageViewLanguage() may need to load the
5030 // content to determine the page language!
5031 $contentHandler = ContentHandler
::getForTitle( $this );
5032 $pageLang = $contentHandler->getPageViewLanguage( $this );
5037 * Get a list of rendered edit notices for this page.
5039 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5040 * they will already be wrapped in paragraphs.
5043 * @param int $oldid Revision ID that's being edited
5046 public function getEditNotices( $oldid = 0 ) {
5049 // Optional notice for the entire namespace
5050 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5051 $msg = wfMessage( $editnotice_ns );
5052 if ( $msg->exists() ) {
5053 $html = $msg->parseAsBlock();
5054 // Edit notices may have complex logic, but output nothing (T91715)
5055 if ( trim( $html ) !== '' ) {
5056 $notices[$editnotice_ns] = Html
::rawElement(
5060 'mw-editnotice-namespace',
5061 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5068 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5069 // Optional notice for page itself and any parent page
5070 $parts = explode( '/', $this->getDBkey() );
5071 $editnotice_base = $editnotice_ns;
5072 while ( count( $parts ) > 0 ) {
5073 $editnotice_base .= '-' . array_shift( $parts );
5074 $msg = wfMessage( $editnotice_base );
5075 if ( $msg->exists() ) {
5076 $html = $msg->parseAsBlock();
5077 if ( trim( $html ) !== '' ) {
5078 $notices[$editnotice_base] = Html
::rawElement(
5082 'mw-editnotice-base',
5083 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5091 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5092 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
5093 $msg = wfMessage( $editnoticeText );
5094 if ( $msg->exists() ) {
5095 $html = $msg->parseAsBlock();
5096 if ( trim( $html ) !== '' ) {
5097 $notices[$editnoticeText] = Html
::rawElement(
5101 'mw-editnotice-page',
5102 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5110 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5117 public function __sleep() {
5125 'mDefaultNamespace',
5129 public function __wakeup() {
5130 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5131 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5132 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );