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 page contain custom CSS or JavaScript for the global UI.
1282 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1283 * or CONTENT_MODEL_JAVASCRIPT.
1285 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1288 * Note that this method should not return true for pages that contain and
1289 * show "inactive" CSS or JS.
1294 public function isSiteConfigPage() {
1296 NS_MEDIAWIKI
== $this->mNamespace
1298 $this->hasContentModel( CONTENT_MODEL_CSS
)
1299 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1306 * @deprecated Since 1.31; use ::isSiteConfigPage() instead
1308 public function isCssOrJsPage() {
1309 wfDeprecated( __METHOD__
, '1.31' );
1310 return ( NS_MEDIAWIKI
== $this->mNamespace
1311 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1312 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1316 * Is this a "config" (.css or .js) sub-page of a user page?
1321 public function isUserConfigPage() {
1323 NS_USER
== $this->mNamespace
1324 && $this->isSubpage()
1326 $this->hasContentModel( CONTENT_MODEL_CSS
)
1327 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1334 * @deprecated Since 1.31; use ::isUserConfigPage() instead
1336 public function isCssJsSubpage() {
1337 wfDeprecated( __METHOD__
, '1.31' );
1338 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1339 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1340 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1344 * Trim down a .css or .js subpage title to get the corresponding skin name
1346 * @return string Containing skin name from .css or .js subpage title
1349 public function getSkinFromConfigSubpage() {
1350 $subpage = explode( '/', $this->mTextform
);
1351 $subpage = $subpage[count( $subpage ) - 1];
1352 $lastdot = strrpos( $subpage, '.' );
1353 if ( $lastdot === false ) {
1354 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1356 return substr( $subpage, 0, $lastdot );
1360 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1361 * @return string Containing skin name from .css or .js subpage title
1363 public function getSkinFromCssJsSubpage() {
1364 wfDeprecated( __METHOD__
, '1.31' );
1365 return $this->getSkinFromConfigSubpage();
1369 * Is this a CSS "config" sub-page of a user page?
1374 public function isUserCssConfigPage() {
1376 NS_USER
== $this->mNamespace
1377 && $this->isSubpage()
1378 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1383 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1386 public function isCssSubpage() {
1387 wfDeprecated( __METHOD__
, '1.31' );
1388 return $this->isUserCssConfigPage();
1392 * Is this a .js subpage of a user page?
1397 public function isUserJsConfigPage() {
1399 NS_USER
== $this->mNamespace
1400 && $this->isSubpage()
1401 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1406 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1409 public function isJsSubpage() {
1410 wfDeprecated( __METHOD__
, '1.31' );
1411 return $this->isUserJsConfigPage();
1415 * Is this a talk page of some sort?
1419 public function isTalkPage() {
1420 return MWNamespace
::isTalk( $this->getNamespace() );
1424 * Get a Title object associated with the talk page of this article
1426 * @return Title The object for the talk page
1428 public function getTalkPage() {
1429 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1433 * Get a Title object associated with the talk page of this article,
1434 * if such a talk page can exist.
1438 * @return Title|null The object for the talk page,
1439 * or null if no associated talk page can exist, according to canHaveTalkPage().
1441 public function getTalkPageIfDefined() {
1442 if ( !$this->canHaveTalkPage() ) {
1446 return $this->getTalkPage();
1450 * Get a title object associated with the subject page of this
1453 * @return Title The object for the subject page
1455 public function getSubjectPage() {
1456 // Is this the same title?
1457 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1458 if ( $this->getNamespace() == $subjectNS ) {
1461 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1465 * Get the other title for this page, if this is a subject page
1466 * get the talk page, if it is a subject page get the talk page
1469 * @throws MWException If the page doesn't have an other page
1472 public function getOtherPage() {
1473 if ( $this->isSpecialPage() ) {
1474 throw new MWException( 'Special pages cannot have other pages' );
1476 if ( $this->isTalkPage() ) {
1477 return $this->getSubjectPage();
1479 if ( !$this->canHaveTalkPage() ) {
1480 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1482 return $this->getTalkPage();
1487 * Get the default namespace index, for when there is no namespace
1489 * @return int Default namespace index
1491 public function getDefaultNamespace() {
1492 return $this->mDefaultNamespace
;
1496 * Get the Title fragment (i.e.\ the bit after the #) in text form
1498 * Use Title::hasFragment to check for a fragment
1500 * @return string Title fragment
1502 public function getFragment() {
1503 return $this->mFragment
;
1507 * Check if a Title fragment is set
1512 public function hasFragment() {
1513 return $this->mFragment
!== '';
1517 * Get the fragment in URL form, including the "#" character if there is one
1519 * @return string Fragment in URL form
1521 public function getFragmentForURL() {
1522 if ( !$this->hasFragment() ) {
1524 } elseif ( $this->isExternal()
1525 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1527 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1529 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1533 * Set the fragment for this title. Removes the first character from the
1534 * specified fragment before setting, so it assumes you're passing it with
1537 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1538 * or Title::createFragmentTarget().
1539 * Still in active use privately.
1542 * @param string $fragment Text
1544 public function setFragment( $fragment ) {
1545 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1549 * Creates a new Title for a different fragment of the same page.
1552 * @param string $fragment
1555 public function createFragmentTarget( $fragment ) {
1556 return self
::makeTitle(
1557 $this->getNamespace(),
1560 $this->getInterwiki()
1565 * Prefix some arbitrary text with the namespace or interwiki prefix
1568 * @param string $name The text
1569 * @return string The prefixed text
1571 private function prefix( $name ) {
1575 if ( $this->isExternal() ) {
1576 $p = $this->mInterwiki
. ':';
1579 if ( 0 != $this->mNamespace
) {
1580 $nsText = $this->getNsText();
1582 if ( $nsText === false ) {
1583 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1584 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1587 $p .= $nsText . ':';
1593 * Get the prefixed database key form
1595 * @return string The prefixed title, with underscores and
1596 * any interwiki and namespace prefixes
1598 public function getPrefixedDBkey() {
1599 $s = $this->prefix( $this->mDbkeyform
);
1600 $s = strtr( $s, ' ', '_' );
1605 * Get the prefixed title with spaces.
1606 * This is the form usually used for display
1608 * @return string The prefixed title, with spaces
1610 public function getPrefixedText() {
1611 if ( $this->mPrefixedText
=== null ) {
1612 $s = $this->prefix( $this->mTextform
);
1613 $s = strtr( $s, '_', ' ' );
1614 $this->mPrefixedText
= $s;
1616 return $this->mPrefixedText
;
1620 * Return a string representation of this title
1622 * @return string Representation of this title
1624 public function __toString() {
1625 return $this->getPrefixedText();
1629 * Get the prefixed title with spaces, plus any fragment
1630 * (part beginning with '#')
1632 * @return string The prefixed title, with spaces and the fragment, including '#'
1634 public function getFullText() {
1635 $text = $this->getPrefixedText();
1636 if ( $this->hasFragment() ) {
1637 $text .= '#' . $this->getFragment();
1643 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1647 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1651 * @return string Root name
1654 public function getRootText() {
1655 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1656 return $this->getText();
1659 return strtok( $this->getText(), '/' );
1663 * Get the root page name title, i.e. the leftmost part before any slashes
1667 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1668 * # returns: Title{User:Foo}
1671 * @return Title Root title
1674 public function getRootTitle() {
1675 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1679 * Get the base page name without a namespace, i.e. the part before the subpage name
1683 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1684 * # returns: 'Foo/Bar'
1687 * @return string Base name
1689 public function getBaseText() {
1690 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1691 return $this->getText();
1694 $parts = explode( '/', $this->getText() );
1695 # Don't discard the real title if there's no subpage involved
1696 if ( count( $parts ) > 1 ) {
1697 unset( $parts[count( $parts ) - 1] );
1699 return implode( '/', $parts );
1703 * Get the base page name title, i.e. the part before the subpage name
1707 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1708 * # returns: Title{User:Foo/Bar}
1711 * @return Title Base title
1714 public function getBaseTitle() {
1715 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1719 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1723 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1727 * @return string Subpage name
1729 public function getSubpageText() {
1730 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1731 return $this->mTextform
;
1733 $parts = explode( '/', $this->mTextform
);
1734 return $parts[count( $parts ) - 1];
1738 * Get the title for a subpage of the current page
1742 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1743 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1746 * @param string $text The subpage name to add to the title
1747 * @return Title Subpage title
1750 public function getSubpage( $text ) {
1751 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1755 * Get a URL-encoded form of the subpage text
1757 * @return string URL-encoded subpage name
1759 public function getSubpageUrlForm() {
1760 $text = $this->getSubpageText();
1761 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1766 * Get a URL-encoded title (not an actual URL) including interwiki
1768 * @return string The URL-encoded form
1770 public function getPrefixedURL() {
1771 $s = $this->prefix( $this->mDbkeyform
);
1772 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1777 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1778 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1779 * second argument named variant. This was deprecated in favor
1780 * of passing an array of option with a "variant" key
1781 * Once $query2 is removed for good, this helper can be dropped
1782 * and the wfArrayToCgi moved to getLocalURL();
1784 * @since 1.19 (r105919)
1785 * @param array|string $query
1786 * @param string|string[]|bool $query2
1789 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1790 if ( $query2 !== false ) {
1791 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1792 "method called with a second parameter is deprecated. Add your " .
1793 "parameter to an array passed as the first parameter.", "1.19" );
1795 if ( is_array( $query ) ) {
1796 $query = wfArrayToCgi( $query );
1799 if ( is_string( $query2 ) ) {
1800 // $query2 is a string, we will consider this to be
1801 // a deprecated $variant argument and add it to the query
1802 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1804 $query2 = wfArrayToCgi( $query2 );
1806 // If we have $query content add a & to it first
1810 // Now append the queries together
1817 * Get a real URL referring to this title, with interwiki link and
1820 * @see self::getLocalURL for the arguments.
1822 * @param string|string[] $query
1823 * @param string|string[]|bool $query2
1824 * @param string|int|null $proto Protocol type to use in URL
1825 * @return string The URL
1827 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1828 $query = self
::fixUrlQueryArgs( $query, $query2 );
1830 # Hand off all the decisions on urls to getLocalURL
1831 $url = $this->getLocalURL( $query );
1833 # Expand the url to make it a full url. Note that getLocalURL has the
1834 # potential to output full urls for a variety of reasons, so we use
1835 # wfExpandUrl instead of simply prepending $wgServer
1836 $url = wfExpandUrl( $url, $proto );
1838 # Finally, add the fragment.
1839 $url .= $this->getFragmentForURL();
1840 // Avoid PHP 7.1 warning from passing $this by reference
1842 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1847 * Get a url appropriate for making redirects based on an untrusted url arg
1849 * This is basically the same as getFullUrl(), but in the case of external
1850 * interwikis, we send the user to a landing page, to prevent possible
1851 * phishing attacks and the like.
1853 * @note Uses current protocol by default, since technically relative urls
1854 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1855 * places where the url gets cached, as might pollute between
1856 * https and non-https users.
1857 * @see self::getLocalURL for the arguments.
1858 * @param array|string $query
1859 * @param string $proto Protocol type to use in URL
1860 * @return string A url suitable to use in an HTTP location header.
1862 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1864 if ( $this->isExternal() ) {
1865 $target = SpecialPage
::getTitleFor(
1867 $this->getPrefixedDBkey()
1870 return $target->getFullURL( $query, false, $proto );
1874 * Get a URL with no fragment or server name (relative URL) from a Title object.
1875 * If this page is generated with action=render, however,
1876 * $wgServer is prepended to make an absolute URL.
1878 * @see self::getFullURL to always get an absolute URL.
1879 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1880 * valid to link, locally, to the current Title.
1881 * @see self::newFromText to produce a Title object.
1883 * @param string|string[] $query An optional query string,
1884 * not used for interwiki links. Can be specified as an associative array as well,
1885 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1886 * Some query patterns will trigger various shorturl path replacements.
1887 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1888 * be an array. If a string is passed it will be interpreted as a deprecated
1889 * variant argument and urlencoded into a variant= argument.
1890 * This second query argument will be added to the $query
1891 * The second parameter is deprecated since 1.19. Pass it as a key,value
1892 * pair in the first parameter array instead.
1894 * @return string String of the URL.
1896 public function getLocalURL( $query = '', $query2 = false ) {
1897 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1899 $query = self
::fixUrlQueryArgs( $query, $query2 );
1901 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1903 $namespace = $this->getNsText();
1904 if ( $namespace != '' ) {
1905 # Can this actually happen? Interwikis shouldn't be parsed.
1906 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1909 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1910 $url = wfAppendQuery( $url, $query );
1912 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1913 if ( $query == '' ) {
1914 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1915 // Avoid PHP 7.1 warning from passing $this by reference
1917 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1919 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1923 if ( !empty( $wgActionPaths )
1924 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1926 $action = urldecode( $matches[2] );
1927 if ( isset( $wgActionPaths[$action] ) ) {
1928 $query = $matches[1];
1929 if ( isset( $matches[4] ) ) {
1930 $query .= $matches[4];
1932 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1933 if ( $query != '' ) {
1934 $url = wfAppendQuery( $url, $query );
1940 && $wgVariantArticlePath
1941 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1942 && $this->getPageLanguage()->equals( $wgContLang )
1943 && $this->getPageLanguage()->hasVariants()
1945 $variant = urldecode( $matches[1] );
1946 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1947 // Only do the variant replacement if the given variant is a valid
1948 // variant for the page's language.
1949 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1950 $url = str_replace( '$1', $dbkey, $url );
1954 if ( $url === false ) {
1955 if ( $query == '-' ) {
1958 $url = "{$wgScript}?title={$dbkey}&{$query}";
1961 // Avoid PHP 7.1 warning from passing $this by reference
1963 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1965 // @todo FIXME: This causes breakage in various places when we
1966 // actually expected a local URL and end up with dupe prefixes.
1967 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1968 $url = $wgServer . $url;
1971 // Avoid PHP 7.1 warning from passing $this by reference
1973 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1978 * Get a URL that's the simplest URL that will be valid to link, locally,
1979 * to the current Title. It includes the fragment, but does not include
1980 * the server unless action=render is used (or the link is external). If
1981 * there's a fragment but the prefixed text is empty, we just return a link
1984 * The result obviously should not be URL-escaped, but does need to be
1985 * HTML-escaped if it's being output in HTML.
1987 * @param string|string[] $query
1988 * @param bool $query2
1989 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1990 * or false (default) for no expansion
1991 * @see self::getLocalURL for the arguments.
1992 * @return string The URL
1994 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1995 if ( $this->isExternal() ||
$proto !== false ) {
1996 $ret = $this->getFullURL( $query, $query2, $proto );
1997 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1998 $ret = $this->getFragmentForURL();
2000 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2006 * Get the URL form for an internal link.
2007 * - Used in various CDN-related code, in case we have a different
2008 * internal hostname for the server from the exposed one.
2010 * This uses $wgInternalServer to qualify the path, or $wgServer
2011 * if $wgInternalServer is not set. If the server variable used is
2012 * protocol-relative, the URL will be expanded to http://
2014 * @see self::getLocalURL for the arguments.
2015 * @param string $query
2016 * @param string|bool $query2
2017 * @return string The URL
2019 public function getInternalURL( $query = '', $query2 = false ) {
2020 global $wgInternalServer, $wgServer;
2021 $query = self
::fixUrlQueryArgs( $query, $query2 );
2022 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2023 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2024 // Avoid PHP 7.1 warning from passing $this by reference
2026 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2031 * Get the URL for a canonical link, for use in things like IRC and
2032 * e-mail notifications. Uses $wgCanonicalServer and the
2033 * GetCanonicalURL hook.
2035 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2037 * @see self::getLocalURL for the arguments.
2038 * @param string $query
2039 * @param string|bool $query2
2040 * @return string The URL
2043 public function getCanonicalURL( $query = '', $query2 = false ) {
2044 $query = self
::fixUrlQueryArgs( $query, $query2 );
2045 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2046 // Avoid PHP 7.1 warning from passing $this by reference
2048 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2053 * Get the edit URL for this Title
2055 * @return string The URL, or a null string if this is an interwiki link
2057 public function getEditURL() {
2058 if ( $this->isExternal() ) {
2061 $s = $this->getLocalURL( 'action=edit' );
2067 * Can $user perform $action on this page?
2068 * This skips potentially expensive cascading permission checks
2069 * as well as avoids expensive error formatting
2071 * Suitable for use for nonessential UI controls in common cases, but
2072 * _not_ for functional access control.
2074 * May provide false positives, but should never provide a false negative.
2076 * @param string $action Action that permission needs to be checked for
2077 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
2080 public function quickUserCan( $action, $user = null ) {
2081 return $this->userCan( $action, $user, false );
2085 * Can $user perform $action on this page?
2087 * @param string $action Action that permission needs to be checked for
2088 * @param User $user User to check (since 1.19); $wgUser will be used if not
2090 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2093 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2094 if ( !$user instanceof User
) {
2099 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2103 * Can $user perform $action on this page?
2105 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2107 * @param string $action Action that permission needs to be checked for
2108 * @param User $user User to check
2109 * @param string $rigor One of (quick,full,secure)
2110 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2111 * - full : does cheap and expensive checks possibly from a replica DB
2112 * - secure : does cheap and expensive checks, using the master as needed
2113 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2114 * whose corresponding errors may be ignored.
2115 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2117 public function getUserPermissionsErrors(
2118 $action, $user, $rigor = 'secure', $ignoreErrors = []
2120 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2122 // Remove the errors being ignored.
2123 foreach ( $errors as $index => $error ) {
2124 $errKey = is_array( $error ) ?
$error[0] : $error;
2126 if ( in_array( $errKey, $ignoreErrors ) ) {
2127 unset( $errors[$index] );
2129 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2130 unset( $errors[$index] );
2138 * Permissions checks that fail most often, and which are easiest to test.
2140 * @param string $action The action to check
2141 * @param User $user User to check
2142 * @param array $errors List of current errors
2143 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2144 * @param bool $short Short circuit on first error
2146 * @return array List of errors
2148 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2149 if ( !Hooks
::run( 'TitleQuickPermissions',
2150 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2155 if ( $action == 'create' ) {
2157 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2158 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2160 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2162 } elseif ( $action == 'move' ) {
2163 if ( !$user->isAllowed( 'move-rootuserpages' )
2164 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2165 // Show user page-specific message only if the user can move other pages
2166 $errors[] = [ 'cant-move-user-page' ];
2169 // Check if user is allowed to move files if it's a file
2170 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2171 $errors[] = [ 'movenotallowedfile' ];
2174 // Check if user is allowed to move category pages if it's a category page
2175 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2176 $errors[] = [ 'cant-move-category-page' ];
2179 if ( !$user->isAllowed( 'move' ) ) {
2180 // User can't move anything
2181 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2182 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2183 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2184 // custom message if logged-in users without any special rights can move
2185 $errors[] = [ 'movenologintext' ];
2187 $errors[] = [ 'movenotallowed' ];
2190 } elseif ( $action == 'move-target' ) {
2191 if ( !$user->isAllowed( 'move' ) ) {
2192 // User can't move anything
2193 $errors[] = [ 'movenotallowed' ];
2194 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2195 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2196 // Show user page-specific message only if the user can move other pages
2197 $errors[] = [ 'cant-move-to-user-page' ];
2198 } elseif ( !$user->isAllowed( 'move-categorypages' )
2199 && $this->mNamespace
== NS_CATEGORY
) {
2200 // Show category page-specific message only if the user can move other pages
2201 $errors[] = [ 'cant-move-to-category-page' ];
2203 } elseif ( !$user->isAllowed( $action ) ) {
2204 $errors[] = $this->missingPermissionError( $action, $short );
2211 * Add the resulting error code to the errors array
2213 * @param array $errors List of current errors
2214 * @param array $result Result of errors
2216 * @return array List of errors
2218 private function resultToError( $errors, $result ) {
2219 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2220 // A single array representing an error
2221 $errors[] = $result;
2222 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2223 // A nested array representing multiple errors
2224 $errors = array_merge( $errors, $result );
2225 } elseif ( $result !== '' && is_string( $result ) ) {
2226 // A string representing a message-id
2227 $errors[] = [ $result ];
2228 } elseif ( $result instanceof MessageSpecifier
) {
2229 // A message specifier representing an error
2230 $errors[] = [ $result ];
2231 } elseif ( $result === false ) {
2232 // a generic "We don't want them to do that"
2233 $errors[] = [ 'badaccess-group0' ];
2239 * Check various permission hooks
2241 * @param string $action The action to check
2242 * @param User $user User to check
2243 * @param array $errors List of current errors
2244 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2245 * @param bool $short Short circuit on first error
2247 * @return array List of errors
2249 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2250 // Use getUserPermissionsErrors instead
2252 // Avoid PHP 7.1 warning from passing $this by reference
2254 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2255 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2257 // Check getUserPermissionsErrors hook
2258 // Avoid PHP 7.1 warning from passing $this by reference
2260 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2261 $errors = $this->resultToError( $errors, $result );
2263 // Check getUserPermissionsErrorsExpensive hook
2266 && !( $short && count( $errors ) > 0 )
2267 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2269 $errors = $this->resultToError( $errors, $result );
2276 * Check permissions on special pages & namespaces
2278 * @param string $action The action to check
2279 * @param User $user User to check
2280 * @param array $errors List of current errors
2281 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2282 * @param bool $short Short circuit on first error
2284 * @return array List of errors
2286 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2287 # Only 'createaccount' can be performed on special pages,
2288 # which don't actually exist in the DB.
2289 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2290 $errors[] = [ 'ns-specialprotected' ];
2293 # Check $wgNamespaceProtection for restricted namespaces
2294 if ( $this->isNamespaceProtected( $user ) ) {
2295 $ns = $this->mNamespace
== NS_MAIN ?
2296 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2297 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2298 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2305 * Check CSS/JS sub-page permissions
2307 * @param string $action The action to check
2308 * @param User $user User to check
2309 * @param array $errors List of current errors
2310 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2311 * @param bool $short Short circuit on first error
2313 * @return array List of errors
2315 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2316 # Protect css/js subpages of user pages
2317 # XXX: this might be better using restrictions
2319 if ( $action != 'patrol' ) {
2320 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2322 $this->isUserCssConfigPage()
2323 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2325 $errors[] = [ 'mycustomcssprotected', $action ];
2327 $this->isUserJsConfigPage()
2328 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2330 $errors[] = [ 'mycustomjsprotected', $action ];
2334 $this->isUserCssConfigPage()
2335 && !$user->isAllowed( 'editusercss' )
2337 $errors[] = [ 'customcssprotected', $action ];
2339 $this->isUserJsConfigPage()
2340 && !$user->isAllowed( 'edituserjs' )
2342 $errors[] = [ 'customjsprotected', $action ];
2351 * Check against page_restrictions table requirements on this
2352 * page. The user must possess all required rights for this
2355 * @param string $action The action to check
2356 * @param User $user User to check
2357 * @param array $errors List of current errors
2358 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2359 * @param bool $short Short circuit on first error
2361 * @return array List of errors
2363 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2364 foreach ( $this->getRestrictions( $action ) as $right ) {
2365 // Backwards compatibility, rewrite sysop -> editprotected
2366 if ( $right == 'sysop' ) {
2367 $right = 'editprotected';
2369 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2370 if ( $right == 'autoconfirmed' ) {
2371 $right = 'editsemiprotected';
2373 if ( $right == '' ) {
2376 if ( !$user->isAllowed( $right ) ) {
2377 $errors[] = [ 'protectedpagetext', $right, $action ];
2378 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2379 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2387 * Check restrictions on cascading pages.
2389 * @param string $action The action to check
2390 * @param User $user User to check
2391 * @param array $errors List of current errors
2392 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2393 * @param bool $short Short circuit on first error
2395 * @return array List of errors
2397 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2398 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2399 # We /could/ use the protection level on the source page, but it's
2400 # fairly ugly as we have to establish a precedence hierarchy for pages
2401 # included by multiple cascade-protected pages. So just restrict
2402 # it to people with 'protect' permission, as they could remove the
2403 # protection anyway.
2404 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2405 # Cascading protection depends on more than this page...
2406 # Several cascading protected pages may include this page...
2407 # Check each cascading level
2408 # This is only for protection restrictions, not for all actions
2409 if ( isset( $restrictions[$action] ) ) {
2410 foreach ( $restrictions[$action] as $right ) {
2411 // Backwards compatibility, rewrite sysop -> editprotected
2412 if ( $right == 'sysop' ) {
2413 $right = 'editprotected';
2415 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2416 if ( $right == 'autoconfirmed' ) {
2417 $right = 'editsemiprotected';
2419 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2421 foreach ( $cascadingSources as $page ) {
2422 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2424 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2434 * Check action permissions not already checked in checkQuickPermissions
2436 * @param string $action The action to check
2437 * @param User $user User to check
2438 * @param array $errors List of current errors
2439 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2440 * @param bool $short Short circuit on first error
2442 * @return array List of errors
2444 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2445 global $wgDeleteRevisionsLimit, $wgLang;
2447 if ( $action == 'protect' ) {
2448 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2449 // If they can't edit, they shouldn't protect.
2450 $errors[] = [ 'protect-cantedit' ];
2452 } elseif ( $action == 'create' ) {
2453 $title_protection = $this->getTitleProtection();
2454 if ( $title_protection ) {
2455 if ( $title_protection['permission'] == ''
2456 ||
!$user->isAllowed( $title_protection['permission'] )
2460 User
::whoIs( $title_protection['user'] ),
2461 $title_protection['reason']
2465 } elseif ( $action == 'move' ) {
2466 // Check for immobile pages
2467 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2468 // Specific message for this case
2469 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2470 } elseif ( !$this->isMovable() ) {
2471 // Less specific message for rarer cases
2472 $errors[] = [ 'immobile-source-page' ];
2474 } elseif ( $action == 'move-target' ) {
2475 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2476 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2477 } elseif ( !$this->isMovable() ) {
2478 $errors[] = [ 'immobile-target-page' ];
2480 } elseif ( $action == 'delete' ) {
2481 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2482 if ( !$tempErrors ) {
2483 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2484 $user, $tempErrors, $rigor, true );
2486 if ( $tempErrors ) {
2487 // If protection keeps them from editing, they shouldn't be able to delete.
2488 $errors[] = [ 'deleteprotected' ];
2490 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2491 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2493 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2495 } elseif ( $action === 'undelete' ) {
2496 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2497 // Undeleting implies editing
2498 $errors[] = [ 'undelete-cantedit' ];
2500 if ( !$this->exists()
2501 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2503 // Undeleting where nothing currently exists implies creating
2504 $errors[] = [ 'undelete-cantcreate' ];
2511 * Check that the user isn't blocked from editing.
2513 * @param string $action The action to check
2514 * @param User $user User to check
2515 * @param array $errors List of current errors
2516 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2517 * @param bool $short Short circuit on first error
2519 * @return array List of errors
2521 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2522 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2523 // Account creation blocks handled at userlogin.
2524 // Unblocking handled in SpecialUnblock
2525 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2529 // Optimize for a very common case
2530 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2534 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2535 $errors[] = [ 'confirmedittext' ];
2538 $useSlave = ( $rigor !== 'secure' );
2539 if ( ( $action == 'edit' ||
$action == 'create' )
2540 && !$user->isBlockedFrom( $this, $useSlave )
2542 // Don't block the user from editing their own talk page unless they've been
2543 // explicitly blocked from that too.
2544 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2545 // @todo FIXME: Pass the relevant context into this function.
2546 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2553 * Check that the user is allowed to read this page.
2555 * @param string $action The action to check
2556 * @param User $user User to check
2557 * @param array $errors List of current errors
2558 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2559 * @param bool $short Short circuit on first error
2561 * @return array List of errors
2563 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2564 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2566 $whitelisted = false;
2567 if ( User
::isEveryoneAllowed( 'read' ) ) {
2568 # Shortcut for public wikis, allows skipping quite a bit of code
2569 $whitelisted = true;
2570 } elseif ( $user->isAllowed( 'read' ) ) {
2571 # If the user is allowed to read pages, he is allowed to read all pages
2572 $whitelisted = true;
2573 } elseif ( $this->isSpecial( 'Userlogin' )
2574 ||
$this->isSpecial( 'PasswordReset' )
2575 ||
$this->isSpecial( 'Userlogout' )
2577 # Always grant access to the login page.
2578 # Even anons need to be able to log in.
2579 $whitelisted = true;
2580 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2581 # Time to check the whitelist
2582 # Only do these checks is there's something to check against
2583 $name = $this->getPrefixedText();
2584 $dbName = $this->getPrefixedDBkey();
2586 // Check for explicit whitelisting with and without underscores
2587 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2588 $whitelisted = true;
2589 } elseif ( $this->getNamespace() == NS_MAIN
) {
2590 # Old settings might have the title prefixed with
2591 # a colon for main-namespace pages
2592 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2593 $whitelisted = true;
2595 } elseif ( $this->isSpecialPage() ) {
2596 # If it's a special page, ditch the subpage bit and check again
2597 $name = $this->getDBkey();
2598 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2600 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2601 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2602 $whitelisted = true;
2608 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2609 $name = $this->getPrefixedText();
2610 // Check for regex whitelisting
2611 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2612 if ( preg_match( $listItem, $name ) ) {
2613 $whitelisted = true;
2619 if ( !$whitelisted ) {
2620 # If the title is not whitelisted, give extensions a chance to do so...
2621 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2622 if ( !$whitelisted ) {
2623 $errors[] = $this->missingPermissionError( $action, $short );
2631 * Get a description array when the user doesn't have the right to perform
2632 * $action (i.e. when User::isAllowed() returns false)
2634 * @param string $action The action to check
2635 * @param bool $short Short circuit on first error
2636 * @return array Array containing an error message key and any parameters
2638 private function missingPermissionError( $action, $short ) {
2639 // We avoid expensive display logic for quickUserCan's and such
2641 return [ 'badaccess-group0' ];
2644 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2648 * Can $user perform $action on this page? This is an internal function,
2649 * with multiple levels of checks depending on performance needs; see $rigor below.
2650 * It does not check wfReadOnly().
2652 * @param string $action Action that permission needs to be checked for
2653 * @param User $user User to check
2654 * @param string $rigor One of (quick,full,secure)
2655 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2656 * - full : does cheap and expensive checks possibly from a replica DB
2657 * - secure : does cheap and expensive checks, using the master as needed
2658 * @param bool $short Set this to true to stop after the first permission error.
2659 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2661 protected function getUserPermissionsErrorsInternal(
2662 $action, $user, $rigor = 'secure', $short = false
2664 if ( $rigor === true ) {
2665 $rigor = 'secure'; // b/c
2666 } elseif ( $rigor === false ) {
2667 $rigor = 'quick'; // b/c
2668 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2669 throw new Exception( "Invalid rigor parameter '$rigor'." );
2672 # Read has special handling
2673 if ( $action == 'read' ) {
2675 'checkPermissionHooks',
2676 'checkReadPermissions',
2677 'checkUserBlock', // for wgBlockDisablesLogin
2679 # Don't call checkSpecialsAndNSPermissions or checkUserConfigPermissions
2680 # here as it will lead to duplicate error messages. This is okay to do
2681 # since anywhere that checks for create will also check for edit, and
2682 # those checks are called for edit.
2683 } elseif ( $action == 'create' ) {
2685 'checkQuickPermissions',
2686 'checkPermissionHooks',
2687 'checkPageRestrictions',
2688 'checkCascadingSourcesRestrictions',
2689 'checkActionPermissions',
2694 'checkQuickPermissions',
2695 'checkPermissionHooks',
2696 'checkSpecialsAndNSPermissions',
2697 'checkUserConfigPermissions',
2698 'checkPageRestrictions',
2699 'checkCascadingSourcesRestrictions',
2700 'checkActionPermissions',
2706 while ( count( $checks ) > 0 &&
2707 !( $short && count( $errors ) > 0 ) ) {
2708 $method = array_shift( $checks );
2709 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2716 * Get a filtered list of all restriction types supported by this wiki.
2717 * @param bool $exists True to get all restriction types that apply to
2718 * titles that do exist, False for all restriction types that apply to
2719 * titles that do not exist
2722 public static function getFilteredRestrictionTypes( $exists = true ) {
2723 global $wgRestrictionTypes;
2724 $types = $wgRestrictionTypes;
2726 # Remove the create restriction for existing titles
2727 $types = array_diff( $types, [ 'create' ] );
2729 # Only the create and upload restrictions apply to non-existing titles
2730 $types = array_intersect( $types, [ 'create', 'upload' ] );
2736 * Returns restriction types for the current Title
2738 * @return array Applicable restriction types
2740 public function getRestrictionTypes() {
2741 if ( $this->isSpecialPage() ) {
2745 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2747 if ( $this->getNamespace() != NS_FILE
) {
2748 # Remove the upload restriction for non-file titles
2749 $types = array_diff( $types, [ 'upload' ] );
2752 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2754 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2755 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2761 * Is this title subject to title protection?
2762 * Title protection is the one applied against creation of such title.
2764 * @return array|bool An associative array representing any existent title
2765 * protection, or false if there's none.
2767 public function getTitleProtection() {
2768 $protection = $this->getTitleProtectionInternal();
2769 if ( $protection ) {
2770 if ( $protection['permission'] == 'sysop' ) {
2771 $protection['permission'] = 'editprotected'; // B/C
2773 if ( $protection['permission'] == 'autoconfirmed' ) {
2774 $protection['permission'] = 'editsemiprotected'; // B/C
2781 * Fetch title protection settings
2783 * To work correctly, $this->loadRestrictions() needs to have access to the
2784 * actual protections in the database without munging 'sysop' =>
2785 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2786 * callers probably want $this->getTitleProtection() instead.
2788 * @return array|bool
2790 protected function getTitleProtectionInternal() {
2791 // Can't protect pages in special namespaces
2792 if ( $this->getNamespace() < 0 ) {
2796 // Can't protect pages that exist.
2797 if ( $this->exists() ) {
2801 if ( $this->mTitleProtection
=== null ) {
2802 $dbr = wfGetDB( DB_REPLICA
);
2803 $commentStore = CommentStore
::getStore();
2804 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2805 $res = $dbr->select(
2806 [ 'protected_titles' ] +
$commentQuery['tables'],
2808 'user' => 'pt_user',
2809 'expiry' => 'pt_expiry',
2810 'permission' => 'pt_create_perm'
2811 ] +
$commentQuery['fields'],
2812 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2815 $commentQuery['joins']
2818 // fetchRow returns false if there are no rows.
2819 $row = $dbr->fetchRow( $res );
2821 $this->mTitleProtection
= [
2822 'user' => $row['user'],
2823 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2824 'permission' => $row['permission'],
2825 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2828 $this->mTitleProtection
= false;
2831 return $this->mTitleProtection
;
2835 * Remove any title protection due to page existing
2837 public function deleteTitleProtection() {
2838 $dbw = wfGetDB( DB_MASTER
);
2842 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2845 $this->mTitleProtection
= false;
2849 * Is this page "semi-protected" - the *only* protection levels are listed
2850 * in $wgSemiprotectedRestrictionLevels?
2852 * @param string $action Action to check (default: edit)
2855 public function isSemiProtected( $action = 'edit' ) {
2856 global $wgSemiprotectedRestrictionLevels;
2858 $restrictions = $this->getRestrictions( $action );
2859 $semi = $wgSemiprotectedRestrictionLevels;
2860 if ( !$restrictions ||
!$semi ) {
2861 // Not protected, or all protection is full protection
2865 // Remap autoconfirmed to editsemiprotected for BC
2866 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2867 $semi[$key] = 'editsemiprotected';
2869 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2870 $restrictions[$key] = 'editsemiprotected';
2873 return !array_diff( $restrictions, $semi );
2877 * Does the title correspond to a protected article?
2879 * @param string $action The action the page is protected from,
2880 * by default checks all actions.
2883 public function isProtected( $action = '' ) {
2884 global $wgRestrictionLevels;
2886 $restrictionTypes = $this->getRestrictionTypes();
2888 # Special pages have inherent protection
2889 if ( $this->isSpecialPage() ) {
2893 # Check regular protection levels
2894 foreach ( $restrictionTypes as $type ) {
2895 if ( $action == $type ||
$action == '' ) {
2896 $r = $this->getRestrictions( $type );
2897 foreach ( $wgRestrictionLevels as $level ) {
2898 if ( in_array( $level, $r ) && $level != '' ) {
2909 * Determines if $user is unable to edit this page because it has been protected
2910 * by $wgNamespaceProtection.
2912 * @param User $user User object to check permissions
2915 public function isNamespaceProtected( User
$user ) {
2916 global $wgNamespaceProtection;
2918 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2919 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2920 if ( $right != '' && !$user->isAllowed( $right ) ) {
2929 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2931 * @return bool If the page is subject to cascading restrictions.
2933 public function isCascadeProtected() {
2934 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2935 return ( $sources > 0 );
2939 * Determines whether cascading protection sources have already been loaded from
2942 * @param bool $getPages True to check if the pages are loaded, or false to check
2943 * if the status is loaded.
2944 * @return bool Whether or not the specified information has been loaded
2947 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2948 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2952 * Cascading protection: Get the source of any cascading restrictions on this page.
2954 * @param bool $getPages Whether or not to retrieve the actual pages
2955 * that the restrictions have come from and the actual restrictions
2957 * @return array Two elements: First is an array of Title objects of the
2958 * pages from which cascading restrictions have come, false for
2959 * none, or true if such restrictions exist but $getPages was not
2960 * set. Second is an array like that returned by
2961 * Title::getAllRestrictions(), or an empty array if $getPages is
2964 public function getCascadeProtectionSources( $getPages = true ) {
2965 $pagerestrictions = [];
2967 if ( $this->mCascadeSources
!== null && $getPages ) {
2968 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2969 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2970 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2973 $dbr = wfGetDB( DB_REPLICA
);
2975 if ( $this->getNamespace() == NS_FILE
) {
2976 $tables = [ 'imagelinks', 'page_restrictions' ];
2978 'il_to' => $this->getDBkey(),
2983 $tables = [ 'templatelinks', 'page_restrictions' ];
2985 'tl_namespace' => $this->getNamespace(),
2986 'tl_title' => $this->getDBkey(),
2993 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2994 'pr_expiry', 'pr_type', 'pr_level' ];
2995 $where_clauses[] = 'page_id=pr_page';
2998 $cols = [ 'pr_expiry' ];
3001 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3003 $sources = $getPages ?
[] : false;
3004 $now = wfTimestampNow();
3006 foreach ( $res as $row ) {
3007 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3008 if ( $expiry > $now ) {
3010 $page_id = $row->pr_page
;
3011 $page_ns = $row->page_namespace
;
3012 $page_title = $row->page_title
;
3013 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3014 # Add groups needed for each restriction type if its not already there
3015 # Make sure this restriction type still exists
3017 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3018 $pagerestrictions[$row->pr_type
] = [];
3022 isset( $pagerestrictions[$row->pr_type
] )
3023 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3025 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3034 $this->mCascadeSources
= $sources;
3035 $this->mCascadingRestrictions
= $pagerestrictions;
3037 $this->mHasCascadingRestrictions
= $sources;
3040 return [ $sources, $pagerestrictions ];
3044 * Accessor for mRestrictionsLoaded
3046 * @return bool Whether or not the page's restrictions have already been
3047 * loaded from the database
3050 public function areRestrictionsLoaded() {
3051 return $this->mRestrictionsLoaded
;
3055 * Accessor/initialisation for mRestrictions
3057 * @param string $action Action that permission needs to be checked for
3058 * @return array Restriction levels needed to take the action. All levels are
3059 * required. Note that restriction levels are normally user rights, but 'sysop'
3060 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3061 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3063 public function getRestrictions( $action ) {
3064 if ( !$this->mRestrictionsLoaded
) {
3065 $this->loadRestrictions();
3067 return isset( $this->mRestrictions
[$action] )
3068 ?
$this->mRestrictions
[$action]
3073 * Accessor/initialisation for mRestrictions
3075 * @return array Keys are actions, values are arrays as returned by
3076 * Title::getRestrictions()
3079 public function getAllRestrictions() {
3080 if ( !$this->mRestrictionsLoaded
) {
3081 $this->loadRestrictions();
3083 return $this->mRestrictions
;
3087 * Get the expiry time for the restriction against a given action
3089 * @param string $action
3090 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3091 * or not protected at all, or false if the action is not recognised.
3093 public function getRestrictionExpiry( $action ) {
3094 if ( !$this->mRestrictionsLoaded
) {
3095 $this->loadRestrictions();
3097 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
3101 * Returns cascading restrictions for the current article
3105 function areRestrictionsCascading() {
3106 if ( !$this->mRestrictionsLoaded
) {
3107 $this->loadRestrictions();
3110 return $this->mCascadeRestriction
;
3114 * Compiles list of active page restrictions from both page table (pre 1.10)
3115 * and page_restrictions table for this existing page.
3116 * Public for usage by LiquidThreads.
3118 * @param array $rows Array of db result objects
3119 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3120 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3121 * Edit and move sections are separated by a colon
3122 * Example: "edit=autoconfirmed,sysop:move=sysop"
3124 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3125 $dbr = wfGetDB( DB_REPLICA
);
3127 $restrictionTypes = $this->getRestrictionTypes();
3129 foreach ( $restrictionTypes as $type ) {
3130 $this->mRestrictions
[$type] = [];
3131 $this->mRestrictionsExpiry
[$type] = 'infinity';
3134 $this->mCascadeRestriction
= false;
3136 # Backwards-compatibility: also load the restrictions from the page record (old format).
3137 if ( $oldFashionedRestrictions !== null ) {
3138 $this->mOldRestrictions
= $oldFashionedRestrictions;
3141 if ( $this->mOldRestrictions
=== false ) {
3142 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3143 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3146 if ( $this->mOldRestrictions
!= '' ) {
3147 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3148 $temp = explode( '=', trim( $restrict ) );
3149 if ( count( $temp ) == 1 ) {
3150 // old old format should be treated as edit/move restriction
3151 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3152 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3154 $restriction = trim( $temp[1] );
3155 if ( $restriction != '' ) { // some old entries are empty
3156 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3162 if ( count( $rows ) ) {
3163 # Current system - load second to make them override.
3164 $now = wfTimestampNow();
3166 # Cycle through all the restrictions.
3167 foreach ( $rows as $row ) {
3168 // Don't take care of restrictions types that aren't allowed
3169 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3173 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3175 // Only apply the restrictions if they haven't expired!
3176 if ( !$expiry ||
$expiry > $now ) {
3177 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3178 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3180 $this->mCascadeRestriction |
= $row->pr_cascade
;
3185 $this->mRestrictionsLoaded
= true;
3189 * Load restrictions from the page_restrictions table
3191 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3192 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3193 * Edit and move sections are separated by a colon
3194 * Example: "edit=autoconfirmed,sysop:move=sysop"
3196 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3197 if ( $this->mRestrictionsLoaded
) {
3201 $id = $this->getArticleID();
3203 $cache = ObjectCache
::getMainWANInstance();
3204 $rows = $cache->getWithSetCallback(
3205 // Page protections always leave a new null revision
3206 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3208 function ( $curValue, &$ttl, array &$setOpts ) {
3209 $dbr = wfGetDB( DB_REPLICA
);
3211 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3213 return iterator_to_array(
3215 'page_restrictions',
3216 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3217 [ 'pr_page' => $this->getArticleID() ],
3224 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3226 $title_protection = $this->getTitleProtectionInternal();
3228 if ( $title_protection ) {
3229 $now = wfTimestampNow();
3230 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3232 if ( !$expiry ||
$expiry > $now ) {
3233 // Apply the restrictions
3234 $this->mRestrictionsExpiry
['create'] = $expiry;
3235 $this->mRestrictions
['create'] =
3236 explode( ',', trim( $title_protection['permission'] ) );
3237 } else { // Get rid of the old restrictions
3238 $this->mTitleProtection
= false;
3241 $this->mRestrictionsExpiry
['create'] = 'infinity';
3243 $this->mRestrictionsLoaded
= true;
3248 * Flush the protection cache in this object and force reload from the database.
3249 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3251 public function flushRestrictions() {
3252 $this->mRestrictionsLoaded
= false;
3253 $this->mTitleProtection
= null;
3257 * Purge expired restrictions from the page_restrictions table
3259 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3261 static function purgeExpiredRestrictions() {
3262 if ( wfReadOnly() ) {
3266 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3267 wfGetDB( DB_MASTER
),
3269 function ( IDatabase
$dbw, $fname ) {
3270 $config = MediaWikiServices
::getInstance()->getMainConfig();
3271 $ids = $dbw->selectFieldValues(
3272 'page_restrictions',
3274 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3276 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3279 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3284 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3285 wfGetDB( DB_MASTER
),
3287 function ( IDatabase
$dbw, $fname ) {
3290 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3298 * Does this have subpages? (Warning, usually requires an extra DB query.)
3302 public function hasSubpages() {
3303 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3308 # We dynamically add a member variable for the purpose of this method
3309 # alone to cache the result. There's no point in having it hanging
3310 # around uninitialized in every Title object; therefore we only add it
3311 # if needed and don't declare it statically.
3312 if ( $this->mHasSubpages
=== null ) {
3313 $this->mHasSubpages
= false;
3314 $subpages = $this->getSubpages( 1 );
3315 if ( $subpages instanceof TitleArray
) {
3316 $this->mHasSubpages
= (bool)$subpages->count();
3320 return $this->mHasSubpages
;
3324 * Get all subpages of this page.
3326 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3327 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3328 * doesn't allow subpages
3330 public function getSubpages( $limit = -1 ) {
3331 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3335 $dbr = wfGetDB( DB_REPLICA
);
3336 $conds['page_namespace'] = $this->getNamespace();
3337 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3339 if ( $limit > -1 ) {
3340 $options['LIMIT'] = $limit;
3342 return TitleArray
::newFromResult(
3343 $dbr->select( 'page',
3344 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3353 * Is there a version of this page in the deletion archive?
3355 * @return int The number of archived revisions
3357 public function isDeleted() {
3358 if ( $this->getNamespace() < 0 ) {
3361 $dbr = wfGetDB( DB_REPLICA
);
3363 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3364 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3367 if ( $this->getNamespace() == NS_FILE
) {
3368 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3369 [ 'fa_name' => $this->getDBkey() ],
3378 * Is there a version of this page in the deletion archive?
3382 public function isDeletedQuick() {
3383 if ( $this->getNamespace() < 0 ) {
3386 $dbr = wfGetDB( DB_REPLICA
);
3387 $deleted = (bool)$dbr->selectField( 'archive', '1',
3388 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3391 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3392 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3393 [ 'fa_name' => $this->getDBkey() ],
3401 * Get the article ID for this Title from the link cache,
3402 * adding it if necessary
3404 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3406 * @return int The ID
3408 public function getArticleID( $flags = 0 ) {
3409 if ( $this->getNamespace() < 0 ) {
3410 $this->mArticleID
= 0;
3411 return $this->mArticleID
;
3413 $linkCache = LinkCache
::singleton();
3414 if ( $flags & self
::GAID_FOR_UPDATE
) {
3415 $oldUpdate = $linkCache->forUpdate( true );
3416 $linkCache->clearLink( $this );
3417 $this->mArticleID
= $linkCache->addLinkObj( $this );
3418 $linkCache->forUpdate( $oldUpdate );
3420 if ( -1 == $this->mArticleID
) {
3421 $this->mArticleID
= $linkCache->addLinkObj( $this );
3424 return $this->mArticleID
;
3428 * Is this an article that is a redirect page?
3429 * Uses link cache, adding it if necessary
3431 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3434 public function isRedirect( $flags = 0 ) {
3435 if ( !is_null( $this->mRedirect
) ) {
3436 return $this->mRedirect
;
3438 if ( !$this->getArticleID( $flags ) ) {
3439 $this->mRedirect
= false;
3440 return $this->mRedirect
;
3443 $linkCache = LinkCache
::singleton();
3444 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3445 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3446 if ( $cached === null ) {
3447 # Trust LinkCache's state over our own
3448 # LinkCache is telling us that the page doesn't exist, despite there being cached
3449 # data relating to an existing page in $this->mArticleID. Updaters should clear
3450 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3451 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3452 # LinkCache to refresh its data from the master.
3453 $this->mRedirect
= false;
3454 return $this->mRedirect
;
3457 $this->mRedirect
= (bool)$cached;
3459 return $this->mRedirect
;
3463 * What is the length of this page?
3464 * Uses link cache, adding it if necessary
3466 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3469 public function getLength( $flags = 0 ) {
3470 if ( $this->mLength
!= -1 ) {
3471 return $this->mLength
;
3473 if ( !$this->getArticleID( $flags ) ) {
3475 return $this->mLength
;
3477 $linkCache = LinkCache
::singleton();
3478 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3479 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3480 if ( $cached === null ) {
3481 # Trust LinkCache's state over our own, as for isRedirect()
3483 return $this->mLength
;
3486 $this->mLength
= intval( $cached );
3488 return $this->mLength
;
3492 * What is the page_latest field for this page?
3494 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3495 * @return int Int or 0 if the page doesn't exist
3497 public function getLatestRevID( $flags = 0 ) {
3498 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3499 return intval( $this->mLatestID
);
3501 if ( !$this->getArticleID( $flags ) ) {
3502 $this->mLatestID
= 0;
3503 return $this->mLatestID
;
3505 $linkCache = LinkCache
::singleton();
3506 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3507 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3508 if ( $cached === null ) {
3509 # Trust LinkCache's state over our own, as for isRedirect()
3510 $this->mLatestID
= 0;
3511 return $this->mLatestID
;
3514 $this->mLatestID
= intval( $cached );
3516 return $this->mLatestID
;
3520 * This clears some fields in this object, and clears any associated
3521 * keys in the "bad links" section of the link cache.
3523 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3524 * loading of the new page_id. It's also called from
3525 * WikiPage::doDeleteArticleReal()
3527 * @param int $newid The new Article ID
3529 public function resetArticleID( $newid ) {
3530 $linkCache = LinkCache
::singleton();
3531 $linkCache->clearLink( $this );
3533 if ( $newid === false ) {
3534 $this->mArticleID
= -1;
3536 $this->mArticleID
= intval( $newid );
3538 $this->mRestrictionsLoaded
= false;
3539 $this->mRestrictions
= [];
3540 $this->mOldRestrictions
= false;
3541 $this->mRedirect
= null;
3542 $this->mLength
= -1;
3543 $this->mLatestID
= false;
3544 $this->mContentModel
= false;
3545 $this->mEstimateRevisions
= null;
3546 $this->mPageLanguage
= false;
3547 $this->mDbPageLanguage
= false;
3548 $this->mIsBigDeletion
= null;
3551 public static function clearCaches() {
3552 $linkCache = LinkCache
::singleton();
3553 $linkCache->clear();
3555 $titleCache = self
::getTitleCache();
3556 $titleCache->clear();
3560 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3562 * @param string $text Containing title to capitalize
3563 * @param int $ns Namespace index, defaults to NS_MAIN
3564 * @return string Containing capitalized title
3566 public static function capitalize( $text, $ns = NS_MAIN
) {
3569 if ( MWNamespace
::isCapitalized( $ns ) ) {
3570 return $wgContLang->ucfirst( $text );
3577 * Secure and split - main initialisation function for this object
3579 * Assumes that mDbkeyform has been set, and is urldecoded
3580 * and uses underscores, but not otherwise munged. This function
3581 * removes illegal characters, splits off the interwiki and
3582 * namespace prefixes, sets the other forms, and canonicalizes
3585 * @throws MalformedTitleException On invalid titles
3586 * @return bool True on success
3588 private function secureAndSplit() {
3590 $this->mInterwiki
= '';
3591 $this->mFragment
= '';
3592 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3594 $dbkey = $this->mDbkeyform
;
3596 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3597 // the parsing code with Title, while avoiding massive refactoring.
3598 // @todo: get rid of secureAndSplit, refactor parsing code.
3599 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3600 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3601 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3602 // MalformedTitleException can be thrown here
3603 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3606 $this->setFragment( '#' . $parts['fragment'] );
3607 $this->mInterwiki
= $parts['interwiki'];
3608 $this->mLocalInterwiki
= $parts['local_interwiki'];
3609 $this->mNamespace
= $parts['namespace'];
3610 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3612 $this->mDbkeyform
= $parts['dbkey'];
3613 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3614 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3616 # We already know that some pages won't be in the database!
3617 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3618 $this->mArticleID
= 0;
3625 * Get an array of Title objects linking to this Title
3626 * Also stores the IDs in the link cache.
3628 * WARNING: do not use this function on arbitrary user-supplied titles!
3629 * On heavily-used templates it will max out the memory.
3631 * @param array $options May be FOR UPDATE
3632 * @param string $table Table name
3633 * @param string $prefix Fields prefix
3634 * @return Title[] Array of Title objects linking here
3636 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3637 if ( count( $options ) > 0 ) {
3638 $db = wfGetDB( DB_MASTER
);
3640 $db = wfGetDB( DB_REPLICA
);
3645 self
::getSelectFields(),
3647 "{$prefix}_from=page_id",
3648 "{$prefix}_namespace" => $this->getNamespace(),
3649 "{$prefix}_title" => $this->getDBkey() ],
3655 if ( $res->numRows() ) {
3656 $linkCache = LinkCache
::singleton();
3657 foreach ( $res as $row ) {
3658 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3660 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3661 $retVal[] = $titleObj;
3669 * Get an array of Title objects using this Title as a template
3670 * Also stores the IDs in the link cache.
3672 * WARNING: do not use this function on arbitrary user-supplied titles!
3673 * On heavily-used templates it will max out the memory.
3675 * @param array $options Query option to Database::select()
3676 * @return Title[] Array of Title the Title objects linking here
3678 public function getTemplateLinksTo( $options = [] ) {
3679 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3683 * Get an array of Title objects linked from this Title
3684 * Also stores the IDs in the link cache.
3686 * WARNING: do not use this function on arbitrary user-supplied titles!
3687 * On heavily-used templates it will max out the memory.
3689 * @param array $options Query option to Database::select()
3690 * @param string $table Table name
3691 * @param string $prefix Fields prefix
3692 * @return array Array of Title objects linking here
3694 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3695 $id = $this->getArticleID();
3697 # If the page doesn't exist; there can't be any link from this page
3702 $db = wfGetDB( DB_REPLICA
);
3704 $blNamespace = "{$prefix}_namespace";
3705 $blTitle = "{$prefix}_title";
3707 $pageQuery = WikiPage
::getQueryInfo();
3709 [ $table, 'nestpage' => $pageQuery['tables'] ],
3711 [ $blNamespace, $blTitle ],
3712 $pageQuery['fields']
3714 [ "{$prefix}_from" => $id ],
3719 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3720 ] ] +
$pageQuery['joins']
3724 $linkCache = LinkCache
::singleton();
3725 foreach ( $res as $row ) {
3726 if ( $row->page_id
) {
3727 $titleObj = self
::newFromRow( $row );
3729 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3730 $linkCache->addBadLinkObj( $titleObj );
3732 $retVal[] = $titleObj;
3739 * Get an array of Title objects used on this Title as a template
3740 * Also stores the IDs in the link cache.
3742 * WARNING: do not use this function on arbitrary user-supplied titles!
3743 * On heavily-used templates it will max out the memory.
3745 * @param array $options May be FOR UPDATE
3746 * @return Title[] Array of Title the Title objects used here
3748 public function getTemplateLinksFrom( $options = [] ) {
3749 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3753 * Get an array of Title objects referring to non-existent articles linked
3756 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3757 * should use redirect table in this case).
3758 * @return Title[] Array of Title the Title objects
3760 public function getBrokenLinksFrom() {
3761 if ( $this->getArticleID() == 0 ) {
3762 # All links from article ID 0 are false positives
3766 $dbr = wfGetDB( DB_REPLICA
);
3767 $res = $dbr->select(
3768 [ 'page', 'pagelinks' ],
3769 [ 'pl_namespace', 'pl_title' ],
3771 'pl_from' => $this->getArticleID(),
3772 'page_namespace IS NULL'
3778 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3784 foreach ( $res as $row ) {
3785 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3791 * Get a list of URLs to purge from the CDN cache when this
3794 * @return string[] Array of String the URLs
3796 public function getCdnUrls() {
3798 $this->getInternalURL(),
3799 $this->getInternalURL( 'action=history' )
3802 $pageLang = $this->getPageLanguage();
3803 if ( $pageLang->hasVariants() ) {
3804 $variants = $pageLang->getVariants();
3805 foreach ( $variants as $vCode ) {
3806 $urls[] = $this->getInternalURL( $vCode );
3810 // If we are looking at a css/js user subpage, purge the action=raw.
3811 if ( $this->isUserJsConfigPage() ) {
3812 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3813 } elseif ( $this->isUserCssConfigPage() ) {
3814 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3817 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3822 * @deprecated since 1.27 use getCdnUrls()
3824 public function getSquidURLs() {
3825 return $this->getCdnUrls();
3829 * Purge all applicable CDN URLs
3831 public function purgeSquid() {
3832 DeferredUpdates
::addUpdate(
3833 new CdnCacheUpdate( $this->getCdnUrls() ),
3834 DeferredUpdates
::PRESEND
3839 * Check whether a given move operation would be valid.
3840 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3842 * @deprecated since 1.25, use MovePage's methods instead
3843 * @param Title &$nt The new title
3844 * @param bool $auth Whether to check user permissions (uses $wgUser)
3845 * @param string $reason Is the log summary of the move, used for spam checking
3846 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3848 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3851 if ( !( $nt instanceof Title
) ) {
3852 // Normally we'd add this to $errors, but we'll get
3853 // lots of syntax errors if $nt is not an object
3854 return [ [ 'badtitletext' ] ];
3857 $mp = new MovePage( $this, $nt );
3858 $errors = $mp->isValidMove()->getErrorsArray();
3860 $errors = wfMergeErrorArrays(
3862 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3866 return $errors ?
: true;
3870 * Check if the requested move target is a valid file move target
3871 * @todo move this to MovePage
3872 * @param Title $nt Target title
3873 * @return array List of errors
3875 protected function validateFileMoveOperation( $nt ) {
3880 $destFile = wfLocalFile( $nt );
3881 $destFile->load( File
::READ_LATEST
);
3882 if ( !$wgUser->isAllowed( 'reupload-shared' )
3883 && !$destFile->exists() && wfFindFile( $nt )
3885 $errors[] = [ 'file-exists-sharedrepo' ];
3892 * Move a title to a new location
3894 * @deprecated since 1.25, use the MovePage class instead
3895 * @param Title &$nt The new title
3896 * @param bool $auth Indicates whether $wgUser's permissions
3898 * @param string $reason The reason for the move
3899 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3900 * Ignored if the user doesn't have the suppressredirect right.
3901 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3902 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3904 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3905 array $changeTags = []
3908 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3909 if ( is_array( $err ) ) {
3910 // Auto-block user's IP if the account was "hard" blocked
3911 $wgUser->spreadAnyEditBlock();
3914 // Check suppressredirect permission
3915 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3916 $createRedirect = true;
3919 $mp = new MovePage( $this, $nt );
3920 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3921 if ( $status->isOK() ) {
3924 return $status->getErrorsArray();
3929 * Move this page's subpages to be subpages of $nt
3931 * @param Title $nt Move target
3932 * @param bool $auth Whether $wgUser's permissions should be checked
3933 * @param string $reason The reason for the move
3934 * @param bool $createRedirect Whether to create redirects from the old subpages to
3935 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3936 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3937 * @return array Array with old page titles as keys, and strings (new page titles) or
3938 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3939 * getUserPermissionsErrors()-like error array with numeric indices if
3940 * no pages were moved
3942 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3943 array $changeTags = []
3945 global $wgMaximumMovedPages;
3946 // Check permissions
3947 if ( !$this->userCan( 'move-subpages' ) ) {
3949 [ 'cant-move-subpages' ],
3952 // Do the source and target namespaces support subpages?
3953 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3955 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3958 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3960 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3964 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3967 foreach ( $subpages as $oldSubpage ) {
3969 if ( $count > $wgMaximumMovedPages ) {
3970 $retval[$oldSubpage->getPrefixedText()] = [
3971 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3976 // We don't know whether this function was called before
3977 // or after moving the root page, so check both
3979 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3980 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3982 // When moving a page to a subpage of itself,
3983 // don't move it twice
3986 $newPageName = preg_replace(
3987 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3988 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3989 $oldSubpage->getDBkey() );
3990 if ( $oldSubpage->isTalkPage() ) {
3991 $newNs = $nt->getTalkPage()->getNamespace();
3993 $newNs = $nt->getSubjectPage()->getNamespace();
3995 # T16385: we need makeTitleSafe because the new page names may
3996 # be longer than 255 characters.
3997 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3999 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4000 if ( $success === true ) {
4001 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4003 $retval[$oldSubpage->getPrefixedText()] = $success;
4010 * Checks if this page is just a one-rev redirect.
4011 * Adds lock, so don't use just for light purposes.
4015 public function isSingleRevRedirect() {
4016 global $wgContentHandlerUseDB;
4018 $dbw = wfGetDB( DB_MASTER
);
4021 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4022 if ( $wgContentHandlerUseDB ) {
4023 $fields[] = 'page_content_model';
4026 $row = $dbw->selectRow( 'page',
4032 # Cache some fields we may want
4033 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4034 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4035 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4036 $this->mContentModel
= $row && isset( $row->page_content_model
)
4037 ?
strval( $row->page_content_model
)
4040 if ( !$this->mRedirect
) {
4043 # Does the article have a history?
4044 $row = $dbw->selectField( [ 'page', 'revision' ],
4046 [ 'page_namespace' => $this->getNamespace(),
4047 'page_title' => $this->getDBkey(),
4049 'page_latest != rev_id'
4054 # Return true if there was no history
4055 return ( $row === false );
4059 * Checks if $this can be moved to a given Title
4060 * - Selects for update, so don't call it unless you mean business
4062 * @deprecated since 1.25, use MovePage's methods instead
4063 * @param Title $nt The new title to check
4066 public function isValidMoveTarget( $nt ) {
4067 # Is it an existing file?
4068 if ( $nt->getNamespace() == NS_FILE
) {
4069 $file = wfLocalFile( $nt );
4070 $file->load( File
::READ_LATEST
);
4071 if ( $file->exists() ) {
4072 wfDebug( __METHOD__
. ": file exists\n" );
4076 # Is it a redirect with no history?
4077 if ( !$nt->isSingleRevRedirect() ) {
4078 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4081 # Get the article text
4082 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4083 if ( !is_object( $rev ) ) {
4086 $content = $rev->getContent();
4087 # Does the redirect point to the source?
4088 # Or is it a broken self-redirect, usually caused by namespace collisions?
4089 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4091 if ( $redirTitle ) {
4092 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4093 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4094 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4100 # Fail safe (not a redirect after all. strange.)
4101 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4102 " is a redirect, but it doesn't contain a valid redirect.\n" );
4108 * Get categories to which this Title belongs and return an array of
4109 * categories' names.
4111 * @return array Array of parents in the form:
4112 * $parent => $currentarticle
4114 public function getParentCategories() {
4119 $titleKey = $this->getArticleID();
4121 if ( $titleKey === 0 ) {
4125 $dbr = wfGetDB( DB_REPLICA
);
4127 $res = $dbr->select(
4130 [ 'cl_from' => $titleKey ],
4134 if ( $res->numRows() > 0 ) {
4135 foreach ( $res as $row ) {
4136 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4137 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4144 * Get a tree of parent categories
4146 * @param array $children Array with the children in the keys, to check for circular refs
4147 * @return array Tree of parent categories
4149 public function getParentCategoryTree( $children = [] ) {
4151 $parents = $this->getParentCategories();
4154 foreach ( $parents as $parent => $current ) {
4155 if ( array_key_exists( $parent, $children ) ) {
4156 # Circular reference
4157 $stack[$parent] = [];
4159 $nt = self
::newFromText( $parent );
4161 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4171 * Get an associative array for selecting this title from
4174 * @return array Array suitable for the $where parameter of DB::select()
4176 public function pageCond() {
4177 if ( $this->mArticleID
> 0 ) {
4178 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4179 return [ 'page_id' => $this->mArticleID
];
4181 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4186 * Get next/previous revision ID relative to another revision ID
4187 * @param int $revId Revision ID. Get the revision that was before this one.
4188 * @param int $flags Title::GAID_FOR_UPDATE
4189 * @param string $dir 'next' or 'prev'
4190 * @return int|bool New revision ID, or false if none exists
4192 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4193 $revId = (int)$revId;
4194 if ( $dir === 'next' ) {
4197 } elseif ( $dir === 'prev' ) {
4201 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4204 if ( $flags & self
::GAID_FOR_UPDATE
) {
4205 $db = wfGetDB( DB_MASTER
);
4207 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4210 // Intentionally not caring if the specified revision belongs to this
4211 // page. We only care about the timestamp.
4212 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4213 if ( $ts === false ) {
4214 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4215 if ( $ts === false ) {
4216 // Or should this throw an InvalidArgumentException or something?
4220 $ts = $db->addQuotes( $ts );
4222 $revId = $db->selectField( 'revision', 'rev_id',
4224 'rev_page' => $this->getArticleID( $flags ),
4225 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4229 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4230 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4234 if ( $revId === false ) {
4237 return intval( $revId );
4242 * Get the revision ID of the previous revision
4244 * @param int $revId Revision ID. Get the revision that was before this one.
4245 * @param int $flags Title::GAID_FOR_UPDATE
4246 * @return int|bool Old revision ID, or false if none exists
4248 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4249 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4253 * Get the revision ID of the next revision
4255 * @param int $revId Revision ID. Get the revision that was after this one.
4256 * @param int $flags Title::GAID_FOR_UPDATE
4257 * @return int|bool Next revision ID, or false if none exists
4259 public function getNextRevisionID( $revId, $flags = 0 ) {
4260 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4264 * Get the first revision of the page
4266 * @param int $flags Title::GAID_FOR_UPDATE
4267 * @return Revision|null If page doesn't exist
4269 public function getFirstRevision( $flags = 0 ) {
4270 $pageId = $this->getArticleID( $flags );
4272 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4273 $revQuery = Revision
::getQueryInfo();
4274 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4275 [ 'rev_page' => $pageId ],
4278 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4279 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4284 return new Revision( $row );
4291 * Get the oldest revision timestamp of this page
4293 * @param int $flags Title::GAID_FOR_UPDATE
4294 * @return string MW timestamp
4296 public function getEarliestRevTime( $flags = 0 ) {
4297 $rev = $this->getFirstRevision( $flags );
4298 return $rev ?
$rev->getTimestamp() : null;
4302 * Check if this is a new page
4306 public function isNewPage() {
4307 $dbr = wfGetDB( DB_REPLICA
);
4308 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4312 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4316 public function isBigDeletion() {
4317 global $wgDeleteRevisionsLimit;
4319 if ( !$wgDeleteRevisionsLimit ) {
4323 if ( $this->mIsBigDeletion
=== null ) {
4324 $dbr = wfGetDB( DB_REPLICA
);
4326 $revCount = $dbr->selectRowCount(
4329 [ 'rev_page' => $this->getArticleID() ],
4331 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4334 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4337 return $this->mIsBigDeletion
;
4341 * Get the approximate revision count of this page.
4345 public function estimateRevisionCount() {
4346 if ( !$this->exists() ) {
4350 if ( $this->mEstimateRevisions
=== null ) {
4351 $dbr = wfGetDB( DB_REPLICA
);
4352 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4353 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4356 return $this->mEstimateRevisions
;
4360 * Get the number of revisions between the given revision.
4361 * Used for diffs and other things that really need it.
4363 * @param int|Revision $old Old revision or rev ID (first before range)
4364 * @param int|Revision $new New revision or rev ID (first after range)
4365 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4366 * @return int Number of revisions between these revisions.
4368 public function countRevisionsBetween( $old, $new, $max = null ) {
4369 if ( !( $old instanceof Revision
) ) {
4370 $old = Revision
::newFromTitle( $this, (int)$old );
4372 if ( !( $new instanceof Revision
) ) {
4373 $new = Revision
::newFromTitle( $this, (int)$new );
4375 if ( !$old ||
!$new ) {
4376 return 0; // nothing to compare
4378 $dbr = wfGetDB( DB_REPLICA
);
4380 'rev_page' => $this->getArticleID(),
4381 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4382 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4384 if ( $max !== null ) {
4385 return $dbr->selectRowCount( 'revision', '1',
4388 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4391 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4396 * Get the authors between the given revisions or revision IDs.
4397 * Used for diffs and other things that really need it.
4401 * @param int|Revision $old Old revision or rev ID (first before range by default)
4402 * @param int|Revision $new New revision or rev ID (first after range by default)
4403 * @param int $limit Maximum number of authors
4404 * @param string|array $options (Optional): Single option, or an array of options:
4405 * 'include_old' Include $old in the range; $new is excluded.
4406 * 'include_new' Include $new in the range; $old is excluded.
4407 * 'include_both' Include both $old and $new in the range.
4408 * Unknown option values are ignored.
4409 * @return array|null Names of revision authors in the range; null if not both revisions exist
4411 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4412 if ( !( $old instanceof Revision
) ) {
4413 $old = Revision
::newFromTitle( $this, (int)$old );
4415 if ( !( $new instanceof Revision
) ) {
4416 $new = Revision
::newFromTitle( $this, (int)$new );
4418 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4419 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4420 // in the sanity check below?
4421 if ( !$old ||
!$new ) {
4422 return null; // nothing to compare
4427 $options = (array)$options;
4428 if ( in_array( 'include_old', $options ) ) {
4431 if ( in_array( 'include_new', $options ) ) {
4434 if ( in_array( 'include_both', $options ) ) {
4438 // No DB query needed if $old and $new are the same or successive revisions:
4439 if ( $old->getId() === $new->getId() ) {
4440 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4442 [ $old->getUserText( Revision
::RAW
) ];
4443 } elseif ( $old->getId() === $new->getParentId() ) {
4444 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4445 $authors[] = $old->getUserText( Revision
::RAW
);
4446 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4447 $authors[] = $new->getUserText( Revision
::RAW
);
4449 } elseif ( $old_cmp === '>=' ) {
4450 $authors[] = $old->getUserText( Revision
::RAW
);
4451 } elseif ( $new_cmp === '<=' ) {
4452 $authors[] = $new->getUserText( Revision
::RAW
);
4456 $dbr = wfGetDB( DB_REPLICA
);
4457 $revQuery = Revision
::getQueryInfo();
4458 $authors = $dbr->selectFieldValues(
4459 $revQuery['tables'],
4460 $revQuery['fields']['rev_user_text'],
4462 'rev_page' => $this->getArticleID(),
4463 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4464 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4466 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4473 * Get the number of authors between the given revisions or revision IDs.
4474 * Used for diffs and other things that really need it.
4476 * @param int|Revision $old Old revision or rev ID (first before range by default)
4477 * @param int|Revision $new New revision or rev ID (first after range by default)
4478 * @param int $limit Maximum number of authors
4479 * @param string|array $options (Optional): Single option, or an array of options:
4480 * 'include_old' Include $old in the range; $new is excluded.
4481 * 'include_new' Include $new in the range; $old is excluded.
4482 * 'include_both' Include both $old and $new in the range.
4483 * Unknown option values are ignored.
4484 * @return int Number of revision authors in the range; zero if not both revisions exist
4486 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4487 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4488 return $authors ?
count( $authors ) : 0;
4492 * Compare with another title.
4494 * @param Title $title
4497 public function equals( Title
$title ) {
4498 // Note: === is necessary for proper matching of number-like titles.
4499 return $this->getInterwiki() === $title->getInterwiki()
4500 && $this->getNamespace() == $title->getNamespace()
4501 && $this->getDBkey() === $title->getDBkey();
4505 * Check if this title is a subpage of another title
4507 * @param Title $title
4510 public function isSubpageOf( Title
$title ) {
4511 return $this->getInterwiki() === $title->getInterwiki()
4512 && $this->getNamespace() == $title->getNamespace()
4513 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4517 * Check if page exists. For historical reasons, this function simply
4518 * checks for the existence of the title in the page table, and will
4519 * thus return false for interwiki links, special pages and the like.
4520 * If you want to know if a title can be meaningfully viewed, you should
4521 * probably call the isKnown() method instead.
4523 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4524 * from master/for update
4527 public function exists( $flags = 0 ) {
4528 $exists = $this->getArticleID( $flags ) != 0;
4529 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4534 * Should links to this title be shown as potentially viewable (i.e. as
4535 * "bluelinks"), even if there's no record by this title in the page
4538 * This function is semi-deprecated for public use, as well as somewhat
4539 * misleadingly named. You probably just want to call isKnown(), which
4540 * calls this function internally.
4542 * (ISSUE: Most of these checks are cheap, but the file existence check
4543 * can potentially be quite expensive. Including it here fixes a lot of
4544 * existing code, but we might want to add an optional parameter to skip
4545 * it and any other expensive checks.)
4549 public function isAlwaysKnown() {
4553 * Allows overriding default behavior for determining if a page exists.
4554 * If $isKnown is kept as null, regular checks happen. If it's
4555 * a boolean, this value is returned by the isKnown method.
4559 * @param Title $title
4560 * @param bool|null $isKnown
4562 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4564 if ( !is_null( $isKnown ) ) {
4568 if ( $this->isExternal() ) {
4569 return true; // any interwiki link might be viewable, for all we know
4572 switch ( $this->mNamespace
) {
4575 // file exists, possibly in a foreign repo
4576 return (bool)wfFindFile( $this );
4578 // valid special page
4579 return SpecialPageFactory
::exists( $this->getDBkey() );
4581 // selflink, possibly with fragment
4582 return $this->mDbkeyform
== '';
4584 // known system message
4585 return $this->hasSourceText() !== false;
4592 * Does this title refer to a page that can (or might) be meaningfully
4593 * viewed? In particular, this function may be used to determine if
4594 * links to the title should be rendered as "bluelinks" (as opposed to
4595 * "redlinks" to non-existent pages).
4596 * Adding something else to this function will cause inconsistency
4597 * since LinkHolderArray calls isAlwaysKnown() and does its own
4598 * page existence check.
4602 public function isKnown() {
4603 return $this->isAlwaysKnown() ||
$this->exists();
4607 * Does this page have source text?
4611 public function hasSourceText() {
4612 if ( $this->exists() ) {
4616 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4617 // If the page doesn't exist but is a known system message, default
4618 // message content will be displayed, same for language subpages-
4619 // Use always content language to avoid loading hundreds of languages
4620 // to get the link color.
4622 list( $name, ) = MessageCache
::singleton()->figureMessage(
4623 $wgContLang->lcfirst( $this->getText() )
4625 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4626 return $message->exists();
4633 * Get the default message text or false if the message doesn't exist
4635 * @return string|bool
4637 public function getDefaultMessageText() {
4640 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4644 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4645 $wgContLang->lcfirst( $this->getText() )
4647 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4649 if ( $message->exists() ) {
4650 return $message->plain();
4657 * Updates page_touched for this page; called from LinksUpdate.php
4659 * @param string $purgeTime [optional] TS_MW timestamp
4660 * @return bool True if the update succeeded
4662 public function invalidateCache( $purgeTime = null ) {
4663 if ( wfReadOnly() ) {
4665 } elseif ( $this->mArticleID
=== 0 ) {
4666 return true; // avoid gap locking if we know it's not there
4669 $dbw = wfGetDB( DB_MASTER
);
4670 $dbw->onTransactionPreCommitOrIdle( function () {
4671 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4674 $conds = $this->pageCond();
4675 DeferredUpdates
::addUpdate(
4676 new AutoCommitUpdate(
4679 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4680 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4683 [ 'page_touched' => $dbTimestamp ],
4684 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4687 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4690 DeferredUpdates
::PRESEND
4697 * Update page_touched timestamps and send CDN purge messages for
4698 * pages linking to this title. May be sent to the job queue depending
4699 * on the number of links. Typically called on create and delete.
4701 public function touchLinks() {
4702 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4703 if ( $this->getNamespace() == NS_CATEGORY
) {
4704 DeferredUpdates
::addUpdate(
4705 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4711 * Get the last touched timestamp
4713 * @param IDatabase|null $db
4714 * @return string|false Last-touched timestamp
4716 public function getTouched( $db = null ) {
4717 if ( $db === null ) {
4718 $db = wfGetDB( DB_REPLICA
);
4720 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4725 * Get the timestamp when this page was updated since the user last saw it.
4728 * @return string|null
4730 public function getNotificationTimestamp( $user = null ) {
4733 // Assume current user if none given
4737 // Check cache first
4738 $uid = $user->getId();
4742 // avoid isset here, as it'll return false for null entries
4743 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4744 return $this->mNotificationTimestamp
[$uid];
4746 // Don't cache too much!
4747 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4748 $this->mNotificationTimestamp
= [];
4751 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4752 $watchedItem = $store->getWatchedItem( $user, $this );
4753 if ( $watchedItem ) {
4754 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4756 $this->mNotificationTimestamp
[$uid] = false;
4759 return $this->mNotificationTimestamp
[$uid];
4763 * Generate strings used for xml 'id' names in monobook tabs
4765 * @param string $prepend Defaults to 'nstab-'
4766 * @return string XML 'id' name
4768 public function getNamespaceKey( $prepend = 'nstab-' ) {
4770 // Gets the subject namespace if this title
4771 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4772 // Checks if canonical namespace name exists for namespace
4773 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4774 // Uses canonical namespace name
4775 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4777 // Uses text of namespace
4778 $namespaceKey = $this->getSubjectNsText();
4780 // Makes namespace key lowercase
4781 $namespaceKey = $wgContLang->lc( $namespaceKey );
4783 if ( $namespaceKey == '' ) {
4784 $namespaceKey = 'main';
4786 // Changes file to image for backwards compatibility
4787 if ( $namespaceKey == 'file' ) {
4788 $namespaceKey = 'image';
4790 return $prepend . $namespaceKey;
4794 * Get all extant redirects to this Title
4796 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4797 * @return Title[] Array of Title redirects to this title
4799 public function getRedirectsHere( $ns = null ) {
4802 $dbr = wfGetDB( DB_REPLICA
);
4804 'rd_namespace' => $this->getNamespace(),
4805 'rd_title' => $this->getDBkey(),
4808 if ( $this->isExternal() ) {
4809 $where['rd_interwiki'] = $this->getInterwiki();
4811 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4813 if ( !is_null( $ns ) ) {
4814 $where['page_namespace'] = $ns;
4817 $res = $dbr->select(
4818 [ 'redirect', 'page' ],
4819 [ 'page_namespace', 'page_title' ],
4824 foreach ( $res as $row ) {
4825 $redirs[] = self
::newFromRow( $row );
4831 * Check if this Title is a valid redirect target
4835 public function isValidRedirectTarget() {
4836 global $wgInvalidRedirectTargets;
4838 if ( $this->isSpecialPage() ) {
4839 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4840 if ( $this->isSpecial( 'Userlogout' ) ) {
4844 foreach ( $wgInvalidRedirectTargets as $target ) {
4845 if ( $this->isSpecial( $target ) ) {
4855 * Get a backlink cache object
4857 * @return BacklinkCache
4859 public function getBacklinkCache() {
4860 return BacklinkCache
::get( $this );
4864 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4868 public function canUseNoindex() {
4869 global $wgExemptFromUserRobotsControl;
4871 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4872 ? MWNamespace
::getContentNamespaces()
4873 : $wgExemptFromUserRobotsControl;
4875 return !in_array( $this->mNamespace
, $bannedNamespaces );
4879 * Returns the raw sort key to be used for categories, with the specified
4880 * prefix. This will be fed to Collation::getSortKey() to get a
4881 * binary sortkey that can be used for actual sorting.
4883 * @param string $prefix The prefix to be used, specified using
4884 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4888 public function getCategorySortkey( $prefix = '' ) {
4889 $unprefixed = $this->getText();
4891 // Anything that uses this hook should only depend
4892 // on the Title object passed in, and should probably
4893 // tell the users to run updateCollations.php --force
4894 // in order to re-sort existing category relations.
4895 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4896 if ( $prefix !== '' ) {
4897 # Separate with a line feed, so the unprefixed part is only used as
4898 # a tiebreaker when two pages have the exact same prefix.
4899 # In UCA, tab is the only character that can sort above LF
4900 # so we strip both of them from the original prefix.
4901 $prefix = strtr( $prefix, "\n\t", ' ' );
4902 return "$prefix\n$unprefixed";
4908 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4909 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4910 * the db, it will return NULL.
4912 * @return string|null|bool
4914 private function getDbPageLanguageCode() {
4915 global $wgPageLanguageUseDB;
4917 // check, if the page language could be saved in the database, and if so and
4918 // the value is not requested already, lookup the page language using LinkCache
4919 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4920 $linkCache = LinkCache
::singleton();
4921 $linkCache->addLinkObj( $this );
4922 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4925 return $this->mDbPageLanguage
;
4929 * Get the language in which the content of this page is written in
4930 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4931 * e.g. $wgLang (such as special pages, which are in the user language).
4936 public function getPageLanguage() {
4937 global $wgLang, $wgLanguageCode;
4938 if ( $this->isSpecialPage() ) {
4939 // special pages are in the user language
4943 // Checking if DB language is set
4944 $dbPageLanguage = $this->getDbPageLanguageCode();
4945 if ( $dbPageLanguage ) {
4946 return wfGetLangObj( $dbPageLanguage );
4949 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4950 // Note that this may depend on user settings, so the cache should
4951 // be only per-request.
4952 // NOTE: ContentHandler::getPageLanguage() may need to load the
4953 // content to determine the page language!
4954 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4956 $contentHandler = ContentHandler
::getForTitle( $this );
4957 $langObj = $contentHandler->getPageLanguage( $this );
4958 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4960 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4967 * Get the language in which the content of this page is written when
4968 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4969 * e.g. $wgLang (such as special pages, which are in the user language).
4974 public function getPageViewLanguage() {
4977 if ( $this->isSpecialPage() ) {
4978 // If the user chooses a variant, the content is actually
4979 // in a language whose code is the variant code.
4980 $variant = $wgLang->getPreferredVariant();
4981 if ( $wgLang->getCode() !== $variant ) {
4982 return Language
::factory( $variant );
4988 // Checking if DB language is set
4989 $dbPageLanguage = $this->getDbPageLanguageCode();
4990 if ( $dbPageLanguage ) {
4991 $pageLang = wfGetLangObj( $dbPageLanguage );
4992 $variant = $pageLang->getPreferredVariant();
4993 if ( $pageLang->getCode() !== $variant ) {
4994 $pageLang = Language
::factory( $variant );
5000 // @note Can't be cached persistently, depends on user settings.
5001 // @note ContentHandler::getPageViewLanguage() may need to load the
5002 // content to determine the page language!
5003 $contentHandler = ContentHandler
::getForTitle( $this );
5004 $pageLang = $contentHandler->getPageViewLanguage( $this );
5009 * Get a list of rendered edit notices for this page.
5011 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5012 * they will already be wrapped in paragraphs.
5015 * @param int $oldid Revision ID that's being edited
5018 public function getEditNotices( $oldid = 0 ) {
5021 // Optional notice for the entire namespace
5022 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5023 $msg = wfMessage( $editnotice_ns );
5024 if ( $msg->exists() ) {
5025 $html = $msg->parseAsBlock();
5026 // Edit notices may have complex logic, but output nothing (T91715)
5027 if ( trim( $html ) !== '' ) {
5028 $notices[$editnotice_ns] = Html
::rawElement(
5032 'mw-editnotice-namespace',
5033 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5040 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5041 // Optional notice for page itself and any parent page
5042 $parts = explode( '/', $this->getDBkey() );
5043 $editnotice_base = $editnotice_ns;
5044 while ( count( $parts ) > 0 ) {
5045 $editnotice_base .= '-' . array_shift( $parts );
5046 $msg = wfMessage( $editnotice_base );
5047 if ( $msg->exists() ) {
5048 $html = $msg->parseAsBlock();
5049 if ( trim( $html ) !== '' ) {
5050 $notices[$editnotice_base] = Html
::rawElement(
5054 'mw-editnotice-base',
5055 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5063 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5064 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
5065 $msg = wfMessage( $editnoticeText );
5066 if ( $msg->exists() ) {
5067 $html = $msg->parseAsBlock();
5068 if ( trim( $html ) !== '' ) {
5069 $notices[$editnoticeText] = Html
::rawElement(
5073 'mw-editnotice-page',
5074 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5082 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5089 public function __sleep() {
5097 'mDefaultNamespace',
5101 public function __wakeup() {
5102 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5103 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5104 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );