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 = [];
111 /** @var string|bool */
112 protected $mOldRestrictions = false;
114 /** @var bool Cascade restrictions on this page to included templates and images? */
115 public $mCascadeRestriction;
117 /** Caching the results of getCascadeProtectionSources */
118 public $mCascadingRestrictions;
120 /** @var array When do the restrictions on this page expire? */
121 protected $mRestrictionsExpiry = [];
123 /** @var bool Are cascading restrictions in effect on this page? */
124 protected $mHasCascadingRestrictions;
126 /** @var array Where are the cascading restrictions coming from on this page? */
127 public $mCascadeSources;
129 /** @var bool Boolean for initialisation on demand */
130 public $mRestrictionsLoaded = false;
132 /** @var string Text form including namespace/interwiki, initialised on demand */
133 protected $mPrefixedText = null;
135 /** @var mixed Cached value for getTitleProtection (create protection) */
136 public $mTitleProtection;
139 * @var int Namespace index when there is no namespace. Don't change the
140 * following default, NS_MAIN is hardcoded in several places. See T2696.
141 * Zero except in {{transclusion}} tags.
143 public $mDefaultNamespace = NS_MAIN
;
145 /** @var int The page length, 0 for special pages */
146 protected $mLength = -1;
148 /** @var null Is the article at this title a redirect? */
149 public $mRedirect = null;
151 /** @var array Associative array of user ID -> timestamp/false */
152 private $mNotificationTimestamp = [];
154 /** @var bool Whether a page has any subpages */
155 private $mHasSubpages;
157 /** @var bool The (string) language code of the page's language and content code. */
158 private $mPageLanguage = false;
160 /** @var string|bool|null The page language code from the database, null if not saved in
161 * the database or false if not loaded, yet. */
162 private $mDbPageLanguage = false;
164 /** @var TitleValue A corresponding TitleValue object */
165 private $mTitleValue = null;
167 /** @var bool Would deleting this page be a big deletion? */
168 private $mIsBigDeletion = null;
172 * B/C kludge: provide a TitleParser for use by Title.
173 * Ideally, Title would have no methods that need this.
174 * Avoid usage of this singleton by using TitleValue
175 * and the associated services when possible.
177 * @return TitleFormatter
179 private static function getTitleFormatter() {
180 return MediaWikiServices
::getInstance()->getTitleFormatter();
184 * B/C kludge: provide an InterwikiLookup for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
189 * @return InterwikiLookup
191 private static function getInterwikiLookup() {
192 return MediaWikiServices
::getInstance()->getInterwikiLookup();
198 function __construct() {
202 * Create a new Title from a prefixed DB key
204 * @param string $key The database key, which has underscores
205 * instead of spaces, possibly including namespace and
207 * @return Title|null Title, or null on an error
209 public static function newFromDBkey( $key ) {
211 $t->mDbkeyform
= $key;
214 $t->secureAndSplit();
216 } catch ( MalformedTitleException
$ex ) {
222 * Create a new Title from a TitleValue
224 * @param TitleValue $titleValue Assumed to be safe.
228 public static function newFromTitleValue( TitleValue
$titleValue ) {
229 return self
::newFromLinkTarget( $titleValue );
233 * Create a new Title from a LinkTarget
235 * @param LinkTarget $linkTarget Assumed to be safe.
239 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
240 if ( $linkTarget instanceof Title
) {
241 // Special case if it's already a Title object
244 return self
::makeTitle(
245 $linkTarget->getNamespace(),
246 $linkTarget->getText(),
247 $linkTarget->getFragment(),
248 $linkTarget->getInterwiki()
253 * Create a new Title from text, such as what one would find in a link. De-
254 * codes any HTML entities in the text.
256 * Title objects returned by this method are guaranteed to be valid, and
257 * thus return true from the isValid() method.
259 * @param string|int|null $text The link text; spaces, prefixes, and an
260 * initial ':' indicating the main namespace are accepted.
261 * @param int $defaultNamespace The namespace to use if none is specified
262 * by a prefix. If you want to force a specific namespace even if
263 * $text might begin with a namespace prefix, use makeTitle() or
265 * @throws InvalidArgumentException
266 * @return Title|null Title or null on an error.
268 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
269 // DWIM: Integers can be passed in here when page titles are used as array keys.
270 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
271 throw new InvalidArgumentException( '$text must be a string.' );
273 if ( $text === null ) {
278 return self
::newFromTextThrow( strval( $text ), $defaultNamespace );
279 } catch ( MalformedTitleException
$ex ) {
285 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
286 * rather than returning null.
288 * The exception subclasses encode detailed information about why the title is invalid.
290 * Title objects returned by this method are guaranteed to be valid, and
291 * thus return true from the isValid() method.
293 * @see Title::newFromText
296 * @param string $text Title text to check
297 * @param int $defaultNamespace
298 * @throws MalformedTitleException If the title is invalid
301 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
302 if ( is_object( $text ) ) {
303 throw new MWException( '$text must be a string, given an object' );
306 $titleCache = self
::getTitleCache();
308 // Wiki pages often contain multiple links to the same page.
309 // Title normalization and parsing can become expensive on pages with many
310 // links, so we can save a little time by caching them.
311 // In theory these are value objects and won't get changed...
312 if ( $defaultNamespace == NS_MAIN
) {
313 $t = $titleCache->get( $text );
319 // Convert things like é ā or 〗 into normalized (T16952) text
320 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
323 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
324 $t->mDefaultNamespace
= intval( $defaultNamespace );
326 $t->secureAndSplit();
327 if ( $defaultNamespace == NS_MAIN
) {
328 $titleCache->set( $text, $t );
334 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
336 * Example of wrong and broken code:
337 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
339 * Example of right code:
340 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
342 * Create a new Title from URL-encoded text. Ensures that
343 * the given title's length does not exceed the maximum.
345 * @param string $url The title, as might be taken from a URL
346 * @return Title|null The new object, or null on an error
348 public static function newFromURL( $url ) {
351 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
352 # but some URLs used it as a space replacement and they still come
353 # from some external search tools.
354 if ( strpos( self
::legalChars(), '+' ) === false ) {
355 $url = strtr( $url, '+', ' ' );
358 $t->mDbkeyform
= strtr( $url, ' ', '_' );
361 $t->secureAndSplit();
363 } catch ( MalformedTitleException
$ex ) {
369 * @return HashBagOStuff
371 private static function getTitleCache() {
372 if ( self
::$titleCache == null ) {
373 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
375 return self
::$titleCache;
379 * Returns a list of fields that are to be selected for initializing Title
380 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
381 * whether to include page_content_model.
385 protected static function getSelectFields() {
386 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
389 'page_namespace', 'page_title', 'page_id',
390 'page_len', 'page_is_redirect', 'page_latest',
393 if ( $wgContentHandlerUseDB ) {
394 $fields[] = 'page_content_model';
397 if ( $wgPageLanguageUseDB ) {
398 $fields[] = 'page_lang';
405 * Create a new Title from an article ID
407 * @param int $id The page_id corresponding to the Title to create
408 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
409 * @return Title|null The new object, or null on an error
411 public static function newFromID( $id, $flags = 0 ) {
412 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
413 $row = $db->selectRow(
415 self
::getSelectFields(),
416 [ 'page_id' => $id ],
419 if ( $row !== false ) {
420 $title = self
::newFromRow( $row );
428 * Make an array of titles from an array of IDs
430 * @param int[] $ids Array of IDs
431 * @return Title[] Array of Titles
433 public static function newFromIDs( $ids ) {
434 if ( !count( $ids ) ) {
437 $dbr = wfGetDB( DB_REPLICA
);
441 self
::getSelectFields(),
442 [ 'page_id' => $ids ],
447 foreach ( $res as $row ) {
448 $titles[] = self
::newFromRow( $row );
454 * Make a Title object from a DB row
456 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
457 * @return Title Corresponding Title
459 public static function newFromRow( $row ) {
460 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
461 $t->loadFromRow( $row );
466 * Load Title object fields from a DB row.
467 * If false is given, the title will be treated as non-existing.
469 * @param stdClass|bool $row Database row
471 public function loadFromRow( $row ) {
472 if ( $row ) { // page found
473 if ( isset( $row->page_id
) ) {
474 $this->mArticleID
= (int)$row->page_id
;
476 if ( isset( $row->page_len
) ) {
477 $this->mLength
= (int)$row->page_len
;
479 if ( isset( $row->page_is_redirect
) ) {
480 $this->mRedirect
= (bool)$row->page_is_redirect
;
482 if ( isset( $row->page_latest
) ) {
483 $this->mLatestID
= (int)$row->page_latest
;
485 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
486 $this->mContentModel
= strval( $row->page_content_model
);
487 } elseif ( !$this->mForcedContentModel
) {
488 $this->mContentModel
= false; # initialized lazily in getContentModel()
490 if ( isset( $row->page_lang
) ) {
491 $this->mDbPageLanguage
= (string)$row->page_lang
;
493 if ( isset( $row->page_restrictions
) ) {
494 $this->mOldRestrictions
= $row->page_restrictions
;
496 } else { // page not found
497 $this->mArticleID
= 0;
499 $this->mRedirect
= false;
500 $this->mLatestID
= 0;
501 if ( !$this->mForcedContentModel
) {
502 $this->mContentModel
= false; # initialized lazily in getContentModel()
508 * Create a new Title from a namespace index and a DB key.
510 * It's assumed that $ns and $title are safe, for instance when
511 * they came directly from the database or a special page name,
512 * not from user input.
514 * No validation is applied. For convenience, spaces are normalized
515 * to underscores, so that e.g. user_text fields can be used directly.
517 * @note This method may return Title objects that are "invalid"
518 * according to the isValid() method. This is usually caused by
519 * configuration changes: e.g. a namespace that was once defined is
520 * no longer configured, or a character that was once allowed in
521 * titles is now forbidden.
523 * @param int $ns The namespace of the article
524 * @param string $title The unprefixed database key form
525 * @param string $fragment The link fragment (after the "#")
526 * @param string $interwiki The interwiki prefix
527 * @return Title The new object
529 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
531 $t->mInterwiki
= $interwiki;
532 $t->mFragment
= $fragment;
533 $t->mNamespace
= $ns = intval( $ns );
534 $t->mDbkeyform
= strtr( $title, ' ', '_' );
535 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
536 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
537 $t->mTextform
= strtr( $title, '_', ' ' );
538 $t->mContentModel
= false; # initialized lazily in getContentModel()
543 * Create a new Title from a namespace index and a DB key.
544 * The parameters will be checked for validity, which is a bit slower
545 * than makeTitle() but safer for user-provided data.
547 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
548 * that is, they return true from the isValid() method. If no valid Title
549 * can be constructed from the input, this method returns null.
551 * @param int $ns The namespace of the article
552 * @param string $title Database key form
553 * @param string $fragment The link fragment (after the "#")
554 * @param string $interwiki Interwiki prefix
555 * @return Title|null The new object, or null on an error
557 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
558 // NOTE: ideally, this would just call makeTitle() and then isValid(),
559 // but presently, that means more overhead on a potential performance hotspot.
561 if ( !MWNamespace
::exists( $ns ) ) {
566 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
569 $t->secureAndSplit();
571 } catch ( MalformedTitleException
$ex ) {
577 * Create a new Title for the Main Page
579 * @return Title The new object
581 public static function newMainPage() {
582 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
583 // Don't give fatal errors if the message is broken
585 $title = self
::newFromText( 'Main Page' );
591 * Get the prefixed DB key associated with an ID
593 * @param int $id The page_id of the article
594 * @return Title|null An object representing the article, or null if no such article was found
596 public static function nameOf( $id ) {
597 $dbr = wfGetDB( DB_REPLICA
);
599 $s = $dbr->selectRow(
601 [ 'page_namespace', 'page_title' ],
602 [ 'page_id' => $id ],
605 if ( $s === false ) {
609 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
614 * Get a regex character class describing the legal characters in a link
616 * @return string The list of characters, not delimited
618 public static function legalChars() {
619 global $wgLegalTitleChars;
620 return $wgLegalTitleChars;
624 * Returns a simple regex that will match on characters and sequences invalid in titles.
625 * Note that this doesn't pick up many things that could be wrong with titles, but that
626 * replacing this regex with something valid will make many titles valid.
628 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
630 * @return string Regex string
632 static function getTitleInvalidRegex() {
633 wfDeprecated( __METHOD__
, '1.25' );
634 return MediaWikiTitleCodec
::getTitleInvalidRegex();
638 * Utility method for converting a character sequence from bytes to Unicode.
640 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
641 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
643 * @param string $byteClass
646 public static function convertByteClassToUnicodeClass( $byteClass ) {
647 $length = strlen( $byteClass );
649 $x0 = $x1 = $x2 = '';
651 $d0 = $d1 = $d2 = '';
652 // Decoded integer codepoints
653 $ord0 = $ord1 = $ord2 = 0;
655 $r0 = $r1 = $r2 = '';
659 $allowUnicode = false;
660 for ( $pos = 0; $pos < $length; $pos++
) {
661 // Shift the queues down
670 // Load the current input token and decoded values
671 $inChar = $byteClass[$pos];
672 if ( $inChar == '\\' ) {
673 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
674 $x0 = $inChar . $m[0];
675 $d0 = chr( hexdec( $m[1] ) );
676 $pos +
= strlen( $m[0] );
677 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
678 $x0 = $inChar . $m[0];
679 $d0 = chr( octdec( $m[0] ) );
680 $pos +
= strlen( $m[0] );
681 } elseif ( $pos +
1 >= $length ) {
684 $d0 = $byteClass[$pos +
1];
692 // Load the current re-encoded value
693 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
694 $r0 = sprintf( '\x%02x', $ord0 );
695 } elseif ( $ord0 >= 0x80 ) {
696 // Allow unicode if a single high-bit character appears
697 $r0 = sprintf( '\x%02x', $ord0 );
698 $allowUnicode = true;
699 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
705 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
707 if ( $ord2 > $ord0 ) {
709 } elseif ( $ord0 >= 0x80 ) {
711 $allowUnicode = true;
712 if ( $ord2 < 0x80 ) {
713 // Keep the non-unicode section of the range
720 // Reset state to the initial value
721 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
722 } elseif ( $ord2 < 0x80 ) {
727 if ( $ord1 < 0x80 ) {
730 if ( $ord0 < 0x80 ) {
733 if ( $allowUnicode ) {
734 $out .= '\u0080-\uFFFF';
740 * Make a prefixed DB key from a DB key and a namespace index
742 * @param int $ns Numerical representation of the namespace
743 * @param string $title The DB key form the title
744 * @param string $fragment The link fragment (after the "#")
745 * @param string $interwiki The interwiki prefix
746 * @param bool $canonicalNamespace If true, use the canonical name for
747 * $ns instead of the localized version.
748 * @return string The prefixed form of the title
750 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
751 $canonicalNamespace = false
755 if ( $canonicalNamespace ) {
756 $namespace = MWNamespace
::getCanonicalName( $ns );
758 $namespace = $wgContLang->getNsText( $ns );
760 $name = $namespace == '' ?
$title : "$namespace:$title";
761 if ( strval( $interwiki ) != '' ) {
762 $name = "$interwiki:$name";
764 if ( strval( $fragment ) != '' ) {
765 $name .= '#' . $fragment;
771 * Escape a text fragment, say from a link, for a URL
773 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
775 * @param string $fragment Containing a URL or link fragment (after the "#")
776 * @return string Escaped string
778 static function escapeFragmentForURL( $fragment ) {
779 wfDeprecated( __METHOD__
, '1.30' );
780 # Note that we don't urlencode the fragment. urlencoded Unicode
781 # fragments appear not to work in IE (at least up to 7) or in at least
782 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
783 # to care if they aren't encoded.
784 return Sanitizer
::escapeId( $fragment, 'noninitial' );
788 * Callback for usort() to do title sorts by (namespace, title)
790 * @param LinkTarget $a
791 * @param LinkTarget $b
793 * @return int Result of string comparison, or namespace comparison
795 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
796 if ( $a->getNamespace() == $b->getNamespace() ) {
797 return strcmp( $a->getText(), $b->getText() );
799 return $a->getNamespace() - $b->getNamespace();
804 * Returns true if the title is valid, false if it is invalid.
806 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
807 * Invalid titles may get returned from makeTitle(), and it may be useful to
808 * allow them to exist, e.g. in order to process log entries about pages in
809 * namespaces that belong to extensions that are no longer installed.
811 * @note This method is relatively expensive. When constructing Title
812 * objects that need to be valid, use an instantiator method that is guaranteed
813 * to return valid titles, such as makeTitleSafe() or newFromText().
817 public function isValid() {
818 $ns = $this->getNamespace();
820 if ( !MWNamespace
::exists( $ns ) ) {
825 $parser = MediaWikiServices
::getInstance()->getTitleParser();
826 $parser->parseTitle( $this->getDBkey(), $ns );
828 } catch ( MalformedTitleException
$ex ) {
834 * Determine whether the object refers to a page within
835 * this project (either this wiki or a wiki with a local
836 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
838 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
840 public function isLocal() {
841 if ( $this->isExternal() ) {
842 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
844 return $iw->isLocal();
851 * Is this Title interwiki?
855 public function isExternal() {
856 return $this->mInterwiki
!== '';
860 * Get the interwiki prefix
862 * Use Title::isExternal to check if a interwiki is set
864 * @return string Interwiki prefix
866 public function getInterwiki() {
867 return $this->mInterwiki
;
871 * Was this a local interwiki link?
875 public function wasLocalInterwiki() {
876 return $this->mLocalInterwiki
;
880 * Determine whether the object refers to a page within
881 * this project and is transcludable.
883 * @return bool True if this is transcludable
885 public function isTrans() {
886 if ( !$this->isExternal() ) {
890 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
894 * Returns the DB name of the distant wiki which owns the object.
896 * @return string|false The DB name
898 public function getTransWikiID() {
899 if ( !$this->isExternal() ) {
903 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
907 * Get a TitleValue object representing this Title.
909 * @note Not all valid Titles have a corresponding valid TitleValue
910 * (e.g. TitleValues cannot represent page-local links that have a
911 * fragment but no title text).
913 * @return TitleValue|null
915 public function getTitleValue() {
916 if ( $this->mTitleValue
=== null ) {
918 $this->mTitleValue
= new TitleValue(
919 $this->getNamespace(),
921 $this->getFragment(),
922 $this->getInterwiki()
924 } catch ( InvalidArgumentException
$ex ) {
925 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
926 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
930 return $this->mTitleValue
;
934 * Get the text form (spaces not underscores) of the main part
936 * @return string Main part of the title
938 public function getText() {
939 return $this->mTextform
;
943 * Get the URL-encoded form of the main part
945 * @return string Main part of the title, URL-encoded
947 public function getPartialURL() {
948 return $this->mUrlform
;
952 * Get the main part with underscores
954 * @return string Main part of the title, with underscores
956 public function getDBkey() {
957 return $this->mDbkeyform
;
961 * Get the DB key with the initial letter case as specified by the user
963 * @return string DB key
965 function getUserCaseDBKey() {
966 if ( !is_null( $this->mUserCaseDBKey
) ) {
967 return $this->mUserCaseDBKey
;
969 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
970 return $this->mDbkeyform
;
975 * Get the namespace index, i.e. one of the NS_xxxx constants.
977 * @return int Namespace index
979 public function getNamespace() {
980 return $this->mNamespace
;
984 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
986 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
987 * @return string Content model id
989 public function getContentModel( $flags = 0 ) {
990 if ( !$this->mForcedContentModel
991 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
992 && $this->getArticleID( $flags )
994 $linkCache = LinkCache
::singleton();
995 $linkCache->addLinkObj( $this ); # in case we already had an article ID
996 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
999 if ( !$this->mContentModel
) {
1000 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1003 return $this->mContentModel
;
1007 * Convenience method for checking a title's content model name
1009 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1010 * @return bool True if $this->getContentModel() == $id
1012 public function hasContentModel( $id ) {
1013 return $this->getContentModel() == $id;
1017 * Set a proposed content model for the page for permissions
1018 * checking. This does not actually change the content model
1021 * Additionally, you should make sure you've checked
1022 * ContentHandler::canBeUsedOn() first.
1025 * @param string $model CONTENT_MODEL_XXX constant
1027 public function setContentModel( $model ) {
1028 $this->mContentModel
= $model;
1029 $this->mForcedContentModel
= true;
1033 * Get the namespace text
1035 * @return string|false Namespace text
1037 public function getNsText() {
1038 if ( $this->isExternal() ) {
1039 // This probably shouldn't even happen,
1040 // but for interwiki transclusion it sometimes does.
1041 // Use the canonical namespaces if possible to try to
1042 // resolve a foreign namespace.
1043 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1044 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1049 $formatter = self
::getTitleFormatter();
1050 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1051 } catch ( InvalidArgumentException
$ex ) {
1052 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1058 * Get the namespace text of the subject (rather than talk) page
1060 * @return string Namespace text
1062 public function getSubjectNsText() {
1064 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1068 * Get the namespace text of the talk page
1070 * @return string Namespace text
1072 public function getTalkNsText() {
1074 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1078 * Can this title have a corresponding talk page?
1080 * @deprecated since 1.30, use canHaveTalkPage() instead.
1082 * @return bool True if this title either is a talk page or can have a talk page associated.
1084 public function canTalk() {
1085 return $this->canHaveTalkPage();
1089 * Can this title have a corresponding talk page?
1091 * @see MWNamespace::hasTalkNamespace
1094 * @return bool True if this title either is a talk page or can have a talk page associated.
1096 public function canHaveTalkPage() {
1097 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1101 * Is this in a namespace that allows actual pages?
1105 public function canExist() {
1106 return $this->mNamespace
>= NS_MAIN
;
1110 * Can this title be added to a user's watchlist?
1114 public function isWatchable() {
1115 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1119 * Returns true if this is a special page.
1123 public function isSpecialPage() {
1124 return $this->getNamespace() == NS_SPECIAL
;
1128 * Returns true if this title resolves to the named special page
1130 * @param string $name The special page name
1133 public function isSpecial( $name ) {
1134 if ( $this->isSpecialPage() ) {
1135 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1136 if ( $name == $thisName ) {
1144 * If the Title refers to a special page alias which is not the local default, resolve
1145 * the alias, and localise the name as necessary. Otherwise, return $this
1149 public function fixSpecialName() {
1150 if ( $this->isSpecialPage() ) {
1151 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1152 if ( $canonicalName ) {
1153 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1154 if ( $localName != $this->mDbkeyform
) {
1155 return self
::makeTitle( NS_SPECIAL
, $localName );
1163 * Returns true if the title is inside the specified namespace.
1165 * Please make use of this instead of comparing to getNamespace()
1166 * This function is much more resistant to changes we may make
1167 * to namespaces than code that makes direct comparisons.
1168 * @param int $ns The namespace
1172 public function inNamespace( $ns ) {
1173 return MWNamespace
::equals( $this->getNamespace(), $ns );
1177 * Returns true if the title is inside one of the specified namespaces.
1179 * @param int|int[] $namespaces,... The namespaces to check for
1183 public function inNamespaces( /* ... */ ) {
1184 $namespaces = func_get_args();
1185 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1186 $namespaces = $namespaces[0];
1189 foreach ( $namespaces as $ns ) {
1190 if ( $this->inNamespace( $ns ) ) {
1199 * Returns true if the title has the same subject namespace as the
1200 * namespace specified.
1201 * For example this method will take NS_USER and return true if namespace
1202 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1203 * as their subject namespace.
1205 * This is MUCH simpler than individually testing for equivalence
1206 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1211 public function hasSubjectNamespace( $ns ) {
1212 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1216 * Is this Title in a namespace which contains content?
1217 * In other words, is this a content page, for the purposes of calculating
1222 public function isContentPage() {
1223 return MWNamespace
::isContent( $this->getNamespace() );
1227 * Would anybody with sufficient privileges be able to move this page?
1228 * Some pages just aren't movable.
1232 public function isMovable() {
1233 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1234 // Interwiki title or immovable namespace. Hooks don't get to override here
1239 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1244 * Is this the mainpage?
1245 * @note Title::newFromText seems to be sufficiently optimized by the title
1246 * cache that we don't need to over-optimize by doing direct comparisons and
1247 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1248 * ends up reporting something differently than $title->isMainPage();
1253 public function isMainPage() {
1254 return $this->equals( self
::newMainPage() );
1258 * Is this a subpage?
1262 public function isSubpage() {
1263 return MWNamespace
::hasSubpages( $this->mNamespace
)
1264 ?
strpos( $this->getText(), '/' ) !== false
1269 * Is this a conversion table for the LanguageConverter?
1273 public function isConversionTable() {
1274 // @todo ConversionTable should become a separate content model.
1276 return $this->getNamespace() == NS_MEDIAWIKI
&&
1277 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1281 * Does that page contain wikitext, or it is JS, CSS or whatever?
1285 public function isWikitextPage() {
1286 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1290 * Could this page contain custom CSS or JavaScript for the global UI.
1291 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1292 * or CONTENT_MODEL_JAVASCRIPT.
1294 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1297 * Note that this method should not return true for pages that contain and
1298 * show "inactive" CSS or JS.
1301 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1303 public function isCssOrJsPage() {
1304 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1305 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1306 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1308 return $isCssOrJsPage;
1312 * Is this a .css or .js subpage of a user page?
1314 * @todo FIXME: Rename to isUserConfigPage()
1316 public function isCssJsSubpage() {
1317 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1318 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1319 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1323 * Trim down a .css or .js subpage title to get the corresponding skin name
1325 * @return string Containing skin name from .css or .js subpage title
1327 public function getSkinFromCssJsSubpage() {
1328 $subpage = explode( '/', $this->mTextform
);
1329 $subpage = $subpage[count( $subpage ) - 1];
1330 $lastdot = strrpos( $subpage, '.' );
1331 if ( $lastdot === false ) {
1332 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1334 return substr( $subpage, 0, $lastdot );
1338 * Is this a .css subpage of a user page?
1342 public function isCssSubpage() {
1343 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1344 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1348 * Is this a .js subpage of a user page?
1352 public function isJsSubpage() {
1353 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1354 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1358 * Is this a talk page of some sort?
1362 public function isTalkPage() {
1363 return MWNamespace
::isTalk( $this->getNamespace() );
1367 * Get a Title object associated with the talk page of this article
1369 * @return Title The object for the talk page
1371 public function getTalkPage() {
1372 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1376 * Get a Title object associated with the talk page of this article,
1377 * if such a talk page can exist.
1381 * @return Title|null The object for the talk page,
1382 * or null if no associated talk page can exist, according to canHaveTalkPage().
1384 public function getTalkPageIfDefined() {
1385 if ( !$this->canHaveTalkPage() ) {
1389 return $this->getTalkPage();
1393 * Get a title object associated with the subject page of this
1396 * @return Title The object for the subject page
1398 public function getSubjectPage() {
1399 // Is this the same title?
1400 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1401 if ( $this->getNamespace() == $subjectNS ) {
1404 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1408 * Get the other title for this page, if this is a subject page
1409 * get the talk page, if it is a subject page get the talk page
1412 * @throws MWException If the page doesn't have an other page
1415 public function getOtherPage() {
1416 if ( $this->isSpecialPage() ) {
1417 throw new MWException( 'Special pages cannot have other pages' );
1419 if ( $this->isTalkPage() ) {
1420 return $this->getSubjectPage();
1422 if ( !$this->canHaveTalkPage() ) {
1423 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1425 return $this->getTalkPage();
1430 * Get the default namespace index, for when there is no namespace
1432 * @return int Default namespace index
1434 public function getDefaultNamespace() {
1435 return $this->mDefaultNamespace
;
1439 * Get the Title fragment (i.e.\ the bit after the #) in text form
1441 * Use Title::hasFragment to check for a fragment
1443 * @return string Title fragment
1445 public function getFragment() {
1446 return $this->mFragment
;
1450 * Check if a Title fragment is set
1455 public function hasFragment() {
1456 return $this->mFragment
!== '';
1460 * Get the fragment in URL form, including the "#" character if there is one
1462 * @return string Fragment in URL form
1464 public function getFragmentForURL() {
1465 if ( !$this->hasFragment() ) {
1467 } elseif ( $this->isExternal()
1468 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1470 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1472 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1476 * Set the fragment for this title. Removes the first character from the
1477 * specified fragment before setting, so it assumes you're passing it with
1480 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1481 * or Title::createFragmentTarget().
1482 * Still in active use privately.
1485 * @param string $fragment Text
1487 public function setFragment( $fragment ) {
1488 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1492 * Creates a new Title for a different fragment of the same page.
1495 * @param string $fragment
1498 public function createFragmentTarget( $fragment ) {
1499 return self
::makeTitle(
1500 $this->getNamespace(),
1503 $this->getInterwiki()
1508 * Prefix some arbitrary text with the namespace or interwiki prefix
1511 * @param string $name The text
1512 * @return string The prefixed text
1514 private function prefix( $name ) {
1518 if ( $this->isExternal() ) {
1519 $p = $this->mInterwiki
. ':';
1522 if ( 0 != $this->mNamespace
) {
1523 $nsText = $this->getNsText();
1525 if ( $nsText === false ) {
1526 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1527 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1530 $p .= $nsText . ':';
1536 * Get the prefixed database key form
1538 * @return string The prefixed title, with underscores and
1539 * any interwiki and namespace prefixes
1541 public function getPrefixedDBkey() {
1542 $s = $this->prefix( $this->mDbkeyform
);
1543 $s = strtr( $s, ' ', '_' );
1548 * Get the prefixed title with spaces.
1549 * This is the form usually used for display
1551 * @return string The prefixed title, with spaces
1553 public function getPrefixedText() {
1554 if ( $this->mPrefixedText
=== null ) {
1555 $s = $this->prefix( $this->mTextform
);
1556 $s = strtr( $s, '_', ' ' );
1557 $this->mPrefixedText
= $s;
1559 return $this->mPrefixedText
;
1563 * Return a string representation of this title
1565 * @return string Representation of this title
1567 public function __toString() {
1568 return $this->getPrefixedText();
1572 * Get the prefixed title with spaces, plus any fragment
1573 * (part beginning with '#')
1575 * @return string The prefixed title, with spaces and the fragment, including '#'
1577 public function getFullText() {
1578 $text = $this->getPrefixedText();
1579 if ( $this->hasFragment() ) {
1580 $text .= '#' . $this->getFragment();
1586 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1590 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1594 * @return string Root name
1597 public function getRootText() {
1598 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1599 return $this->getText();
1602 return strtok( $this->getText(), '/' );
1606 * Get the root page name title, i.e. the leftmost part before any slashes
1610 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1611 * # returns: Title{User:Foo}
1614 * @return Title Root title
1617 public function getRootTitle() {
1618 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1622 * Get the base page name without a namespace, i.e. the part before the subpage name
1626 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1627 * # returns: 'Foo/Bar'
1630 * @return string Base name
1632 public function getBaseText() {
1633 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1634 return $this->getText();
1637 $parts = explode( '/', $this->getText() );
1638 # Don't discard the real title if there's no subpage involved
1639 if ( count( $parts ) > 1 ) {
1640 unset( $parts[count( $parts ) - 1] );
1642 return implode( '/', $parts );
1646 * Get the base page name title, i.e. the part before the subpage name
1650 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1651 * # returns: Title{User:Foo/Bar}
1654 * @return Title Base title
1657 public function getBaseTitle() {
1658 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1662 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1666 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1670 * @return string Subpage name
1672 public function getSubpageText() {
1673 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1674 return $this->mTextform
;
1676 $parts = explode( '/', $this->mTextform
);
1677 return $parts[count( $parts ) - 1];
1681 * Get the title for a subpage of the current page
1685 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1686 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1689 * @param string $text The subpage name to add to the title
1690 * @return Title Subpage title
1693 public function getSubpage( $text ) {
1694 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1698 * Get a URL-encoded form of the subpage text
1700 * @return string URL-encoded subpage name
1702 public function getSubpageUrlForm() {
1703 $text = $this->getSubpageText();
1704 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1709 * Get a URL-encoded title (not an actual URL) including interwiki
1711 * @return string The URL-encoded form
1713 public function getPrefixedURL() {
1714 $s = $this->prefix( $this->mDbkeyform
);
1715 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1720 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1721 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1722 * second argument named variant. This was deprecated in favor
1723 * of passing an array of option with a "variant" key
1724 * Once $query2 is removed for good, this helper can be dropped
1725 * and the wfArrayToCgi moved to getLocalURL();
1727 * @since 1.19 (r105919)
1728 * @param array|string $query
1729 * @param string|string[]|bool $query2
1732 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1733 if ( $query2 !== false ) {
1734 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1735 "method called with a second parameter is deprecated. Add your " .
1736 "parameter to an array passed as the first parameter.", "1.19" );
1738 if ( is_array( $query ) ) {
1739 $query = wfArrayToCgi( $query );
1742 if ( is_string( $query2 ) ) {
1743 // $query2 is a string, we will consider this to be
1744 // a deprecated $variant argument and add it to the query
1745 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1747 $query2 = wfArrayToCgi( $query2 );
1749 // If we have $query content add a & to it first
1753 // Now append the queries together
1760 * Get a real URL referring to this title, with interwiki link and
1763 * @see self::getLocalURL for the arguments.
1765 * @param string|string[] $query
1766 * @param string|string[]|bool $query2
1767 * @param string $proto Protocol type to use in URL
1768 * @return string The URL
1770 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1771 $query = self
::fixUrlQueryArgs( $query, $query2 );
1773 # Hand off all the decisions on urls to getLocalURL
1774 $url = $this->getLocalURL( $query );
1776 # Expand the url to make it a full url. Note that getLocalURL has the
1777 # potential to output full urls for a variety of reasons, so we use
1778 # wfExpandUrl instead of simply prepending $wgServer
1779 $url = wfExpandUrl( $url, $proto );
1781 # Finally, add the fragment.
1782 $url .= $this->getFragmentForURL();
1783 // Avoid PHP 7.1 warning from passing $this by reference
1785 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1790 * Get a url appropriate for making redirects based on an untrusted url arg
1792 * This is basically the same as getFullUrl(), but in the case of external
1793 * interwikis, we send the user to a landing page, to prevent possible
1794 * phishing attacks and the like.
1796 * @note Uses current protocol by default, since technically relative urls
1797 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1798 * places where the url gets cached, as might pollute between
1799 * https and non-https users.
1800 * @see self::getLocalURL for the arguments.
1801 * @param array|string $query
1802 * @param string $proto Protocol type to use in URL
1803 * @return string A url suitable to use in an HTTP location header.
1805 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1807 if ( $this->isExternal() ) {
1808 $target = SpecialPage
::getTitleFor(
1810 $this->getPrefixedDBKey()
1813 return $target->getFullUrl( $query, false, $proto );
1817 * Get a URL with no fragment or server name (relative URL) from a Title object.
1818 * If this page is generated with action=render, however,
1819 * $wgServer is prepended to make an absolute URL.
1821 * @see self::getFullURL to always get an absolute URL.
1822 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1823 * valid to link, locally, to the current Title.
1824 * @see self::newFromText to produce a Title object.
1826 * @param string|string[] $query An optional query string,
1827 * not used for interwiki links. Can be specified as an associative array as well,
1828 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1829 * Some query patterns will trigger various shorturl path replacements.
1830 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1831 * be an array. If a string is passed it will be interpreted as a deprecated
1832 * variant argument and urlencoded into a variant= argument.
1833 * This second query argument will be added to the $query
1834 * The second parameter is deprecated since 1.19. Pass it as a key,value
1835 * pair in the first parameter array instead.
1837 * @return string String of the URL.
1839 public function getLocalURL( $query = '', $query2 = false ) {
1840 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1842 $query = self
::fixUrlQueryArgs( $query, $query2 );
1844 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1846 $namespace = $this->getNsText();
1847 if ( $namespace != '' ) {
1848 # Can this actually happen? Interwikis shouldn't be parsed.
1849 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1852 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1853 $url = wfAppendQuery( $url, $query );
1855 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1856 if ( $query == '' ) {
1857 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1858 // Avoid PHP 7.1 warning from passing $this by reference
1860 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1862 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1866 if ( !empty( $wgActionPaths )
1867 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1869 $action = urldecode( $matches[2] );
1870 if ( isset( $wgActionPaths[$action] ) ) {
1871 $query = $matches[1];
1872 if ( isset( $matches[4] ) ) {
1873 $query .= $matches[4];
1875 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1876 if ( $query != '' ) {
1877 $url = wfAppendQuery( $url, $query );
1883 && $wgVariantArticlePath
1884 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1885 && $this->getPageLanguage()->equals( $wgContLang )
1886 && $this->getPageLanguage()->hasVariants()
1888 $variant = urldecode( $matches[1] );
1889 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1890 // Only do the variant replacement if the given variant is a valid
1891 // variant for the page's language.
1892 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1893 $url = str_replace( '$1', $dbkey, $url );
1897 if ( $url === false ) {
1898 if ( $query == '-' ) {
1901 $url = "{$wgScript}?title={$dbkey}&{$query}";
1904 // Avoid PHP 7.1 warning from passing $this by reference
1906 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1908 // @todo FIXME: This causes breakage in various places when we
1909 // actually expected a local URL and end up with dupe prefixes.
1910 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1911 $url = $wgServer . $url;
1914 // Avoid PHP 7.1 warning from passing $this by reference
1916 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1921 * Get a URL that's the simplest URL that will be valid to link, locally,
1922 * to the current Title. It includes the fragment, but does not include
1923 * the server unless action=render is used (or the link is external). If
1924 * there's a fragment but the prefixed text is empty, we just return a link
1927 * The result obviously should not be URL-escaped, but does need to be
1928 * HTML-escaped if it's being output in HTML.
1930 * @param string|string[] $query
1931 * @param bool $query2
1932 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1933 * or false (default) for no expansion
1934 * @see self::getLocalURL for the arguments.
1935 * @return string The URL
1937 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1938 if ( $this->isExternal() ||
$proto !== false ) {
1939 $ret = $this->getFullURL( $query, $query2, $proto );
1940 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1941 $ret = $this->getFragmentForURL();
1943 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1949 * Get the URL form for an internal link.
1950 * - Used in various CDN-related code, in case we have a different
1951 * internal hostname for the server from the exposed one.
1953 * This uses $wgInternalServer to qualify the path, or $wgServer
1954 * if $wgInternalServer is not set. If the server variable used is
1955 * protocol-relative, the URL will be expanded to http://
1957 * @see self::getLocalURL for the arguments.
1958 * @param string $query
1959 * @param string|bool $query2
1960 * @return string The URL
1962 public function getInternalURL( $query = '', $query2 = false ) {
1963 global $wgInternalServer, $wgServer;
1964 $query = self
::fixUrlQueryArgs( $query, $query2 );
1965 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1966 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1967 // Avoid PHP 7.1 warning from passing $this by reference
1969 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1974 * Get the URL for a canonical link, for use in things like IRC and
1975 * e-mail notifications. Uses $wgCanonicalServer and the
1976 * GetCanonicalURL hook.
1978 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1980 * @see self::getLocalURL for the arguments.
1981 * @param string $query
1982 * @param string|bool $query2
1983 * @return string The URL
1986 public function getCanonicalURL( $query = '', $query2 = false ) {
1987 $query = self
::fixUrlQueryArgs( $query, $query2 );
1988 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1989 // Avoid PHP 7.1 warning from passing $this by reference
1991 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1996 * Get the edit URL for this Title
1998 * @return string The URL, or a null string if this is an interwiki link
2000 public function getEditURL() {
2001 if ( $this->isExternal() ) {
2004 $s = $this->getLocalURL( 'action=edit' );
2010 * Can $user perform $action on this page?
2011 * This skips potentially expensive cascading permission checks
2012 * as well as avoids expensive error formatting
2014 * Suitable for use for nonessential UI controls in common cases, but
2015 * _not_ for functional access control.
2017 * May provide false positives, but should never provide a false negative.
2019 * @param string $action Action that permission needs to be checked for
2020 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
2023 public function quickUserCan( $action, $user = null ) {
2024 return $this->userCan( $action, $user, false );
2028 * Can $user perform $action on this page?
2030 * @param string $action Action that permission needs to be checked for
2031 * @param User $user User to check (since 1.19); $wgUser will be used if not
2033 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2036 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2037 if ( !$user instanceof User
) {
2042 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2046 * Can $user perform $action on this page?
2048 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2050 * @param string $action Action that permission needs to be checked for
2051 * @param User $user User to check
2052 * @param string $rigor One of (quick,full,secure)
2053 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2054 * - full : does cheap and expensive checks possibly from a replica DB
2055 * - secure : does cheap and expensive checks, using the master as needed
2056 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2057 * whose corresponding errors may be ignored.
2058 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2060 public function getUserPermissionsErrors(
2061 $action, $user, $rigor = 'secure', $ignoreErrors = []
2063 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2065 // Remove the errors being ignored.
2066 foreach ( $errors as $index => $error ) {
2067 $errKey = is_array( $error ) ?
$error[0] : $error;
2069 if ( in_array( $errKey, $ignoreErrors ) ) {
2070 unset( $errors[$index] );
2072 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2073 unset( $errors[$index] );
2081 * Permissions checks that fail most often, and which are easiest to test.
2083 * @param string $action The action to check
2084 * @param User $user User to check
2085 * @param array $errors List of current errors
2086 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2087 * @param bool $short Short circuit on first error
2089 * @return array List of errors
2091 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2092 if ( !Hooks
::run( 'TitleQuickPermissions',
2093 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2098 if ( $action == 'create' ) {
2100 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2101 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2103 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2105 } elseif ( $action == 'move' ) {
2106 if ( !$user->isAllowed( 'move-rootuserpages' )
2107 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2108 // Show user page-specific message only if the user can move other pages
2109 $errors[] = [ 'cant-move-user-page' ];
2112 // Check if user is allowed to move files if it's a file
2113 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2114 $errors[] = [ 'movenotallowedfile' ];
2117 // Check if user is allowed to move category pages if it's a category page
2118 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2119 $errors[] = [ 'cant-move-category-page' ];
2122 if ( !$user->isAllowed( 'move' ) ) {
2123 // User can't move anything
2124 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2125 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2126 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2127 // custom message if logged-in users without any special rights can move
2128 $errors[] = [ 'movenologintext' ];
2130 $errors[] = [ 'movenotallowed' ];
2133 } elseif ( $action == 'move-target' ) {
2134 if ( !$user->isAllowed( 'move' ) ) {
2135 // User can't move anything
2136 $errors[] = [ 'movenotallowed' ];
2137 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2138 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2139 // Show user page-specific message only if the user can move other pages
2140 $errors[] = [ 'cant-move-to-user-page' ];
2141 } elseif ( !$user->isAllowed( 'move-categorypages' )
2142 && $this->mNamespace
== NS_CATEGORY
) {
2143 // Show category page-specific message only if the user can move other pages
2144 $errors[] = [ 'cant-move-to-category-page' ];
2146 } elseif ( !$user->isAllowed( $action ) ) {
2147 $errors[] = $this->missingPermissionError( $action, $short );
2154 * Add the resulting error code to the errors array
2156 * @param array $errors List of current errors
2157 * @param array $result Result of errors
2159 * @return array List of errors
2161 private function resultToError( $errors, $result ) {
2162 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2163 // A single array representing an error
2164 $errors[] = $result;
2165 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2166 // A nested array representing multiple errors
2167 $errors = array_merge( $errors, $result );
2168 } elseif ( $result !== '' && is_string( $result ) ) {
2169 // A string representing a message-id
2170 $errors[] = [ $result ];
2171 } elseif ( $result instanceof MessageSpecifier
) {
2172 // A message specifier representing an error
2173 $errors[] = [ $result ];
2174 } elseif ( $result === false ) {
2175 // a generic "We don't want them to do that"
2176 $errors[] = [ 'badaccess-group0' ];
2182 * Check various permission hooks
2184 * @param string $action The action to check
2185 * @param User $user User to check
2186 * @param array $errors List of current errors
2187 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2188 * @param bool $short Short circuit on first error
2190 * @return array List of errors
2192 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2193 // Use getUserPermissionsErrors instead
2195 // Avoid PHP 7.1 warning from passing $this by reference
2197 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2198 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2200 // Check getUserPermissionsErrors hook
2201 // Avoid PHP 7.1 warning from passing $this by reference
2203 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2204 $errors = $this->resultToError( $errors, $result );
2206 // Check getUserPermissionsErrorsExpensive hook
2209 && !( $short && count( $errors ) > 0 )
2210 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2212 $errors = $this->resultToError( $errors, $result );
2219 * Check permissions on special pages & namespaces
2221 * @param string $action The action to check
2222 * @param User $user User to check
2223 * @param array $errors List of current errors
2224 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2225 * @param bool $short Short circuit on first error
2227 * @return array List of errors
2229 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2230 # Only 'createaccount' can be performed on special pages,
2231 # which don't actually exist in the DB.
2232 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2233 $errors[] = [ 'ns-specialprotected' ];
2236 # Check $wgNamespaceProtection for restricted namespaces
2237 if ( $this->isNamespaceProtected( $user ) ) {
2238 $ns = $this->mNamespace
== NS_MAIN ?
2239 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2240 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2241 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2248 * Check CSS/JS sub-page permissions
2250 * @param string $action The action to check
2251 * @param User $user User to check
2252 * @param array $errors List of current errors
2253 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2254 * @param bool $short Short circuit on first error
2256 * @return array List of errors
2258 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2259 # Protect css/js subpages of user pages
2260 # XXX: this might be better using restrictions
2261 if ( $action != 'patrol' ) {
2262 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2263 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2264 $errors[] = [ 'mycustomcssprotected', $action ];
2265 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2266 $errors[] = [ 'mycustomjsprotected', $action ];
2269 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2270 $errors[] = [ 'customcssprotected', $action ];
2271 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2272 $errors[] = [ 'customjsprotected', $action ];
2281 * Check against page_restrictions table requirements on this
2282 * page. The user must possess all required rights for this
2285 * @param string $action The action to check
2286 * @param User $user User to check
2287 * @param array $errors List of current errors
2288 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2289 * @param bool $short Short circuit on first error
2291 * @return array List of errors
2293 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2294 foreach ( $this->getRestrictions( $action ) as $right ) {
2295 // Backwards compatibility, rewrite sysop -> editprotected
2296 if ( $right == 'sysop' ) {
2297 $right = 'editprotected';
2299 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2300 if ( $right == 'autoconfirmed' ) {
2301 $right = 'editsemiprotected';
2303 if ( $right == '' ) {
2306 if ( !$user->isAllowed( $right ) ) {
2307 $errors[] = [ 'protectedpagetext', $right, $action ];
2308 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2309 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2317 * Check restrictions on cascading pages.
2319 * @param string $action The action to check
2320 * @param User $user User to check
2321 * @param array $errors List of current errors
2322 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2323 * @param bool $short Short circuit on first error
2325 * @return array List of errors
2327 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2328 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2329 # We /could/ use the protection level on the source page, but it's
2330 # fairly ugly as we have to establish a precedence hierarchy for pages
2331 # included by multiple cascade-protected pages. So just restrict
2332 # it to people with 'protect' permission, as they could remove the
2333 # protection anyway.
2334 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2335 # Cascading protection depends on more than this page...
2336 # Several cascading protected pages may include this page...
2337 # Check each cascading level
2338 # This is only for protection restrictions, not for all actions
2339 if ( isset( $restrictions[$action] ) ) {
2340 foreach ( $restrictions[$action] as $right ) {
2341 // Backwards compatibility, rewrite sysop -> editprotected
2342 if ( $right == 'sysop' ) {
2343 $right = 'editprotected';
2345 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2346 if ( $right == 'autoconfirmed' ) {
2347 $right = 'editsemiprotected';
2349 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2351 foreach ( $cascadingSources as $page ) {
2352 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2354 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2364 * Check action permissions not already checked in checkQuickPermissions
2366 * @param string $action The action to check
2367 * @param User $user User to check
2368 * @param array $errors List of current errors
2369 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2370 * @param bool $short Short circuit on first error
2372 * @return array List of errors
2374 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2375 global $wgDeleteRevisionsLimit, $wgLang;
2377 if ( $action == 'protect' ) {
2378 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2379 // If they can't edit, they shouldn't protect.
2380 $errors[] = [ 'protect-cantedit' ];
2382 } elseif ( $action == 'create' ) {
2383 $title_protection = $this->getTitleProtection();
2384 if ( $title_protection ) {
2385 if ( $title_protection['permission'] == ''
2386 ||
!$user->isAllowed( $title_protection['permission'] )
2390 User
::whoIs( $title_protection['user'] ),
2391 $title_protection['reason']
2395 } elseif ( $action == 'move' ) {
2396 // Check for immobile pages
2397 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2398 // Specific message for this case
2399 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2400 } elseif ( !$this->isMovable() ) {
2401 // Less specific message for rarer cases
2402 $errors[] = [ 'immobile-source-page' ];
2404 } elseif ( $action == 'move-target' ) {
2405 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2406 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2407 } elseif ( !$this->isMovable() ) {
2408 $errors[] = [ 'immobile-target-page' ];
2410 } elseif ( $action == 'delete' ) {
2411 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2412 if ( !$tempErrors ) {
2413 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2414 $user, $tempErrors, $rigor, true );
2416 if ( $tempErrors ) {
2417 // If protection keeps them from editing, they shouldn't be able to delete.
2418 $errors[] = [ 'deleteprotected' ];
2420 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2421 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2423 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2425 } elseif ( $action === 'undelete' ) {
2426 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2427 // Undeleting implies editing
2428 $errors[] = [ 'undelete-cantedit' ];
2430 if ( !$this->exists()
2431 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2433 // Undeleting where nothing currently exists implies creating
2434 $errors[] = [ 'undelete-cantcreate' ];
2441 * Check that the user isn't blocked from editing.
2443 * @param string $action The action to check
2444 * @param User $user User to check
2445 * @param array $errors List of current errors
2446 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2447 * @param bool $short Short circuit on first error
2449 * @return array List of errors
2451 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2452 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2453 // Account creation blocks handled at userlogin.
2454 // Unblocking handled in SpecialUnblock
2455 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2459 // Optimize for a very common case
2460 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2464 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2465 $errors[] = [ 'confirmedittext' ];
2468 $useSlave = ( $rigor !== 'secure' );
2469 if ( ( $action == 'edit' ||
$action == 'create' )
2470 && !$user->isBlockedFrom( $this, $useSlave )
2472 // Don't block the user from editing their own talk page unless they've been
2473 // explicitly blocked from that too.
2474 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2475 // @todo FIXME: Pass the relevant context into this function.
2476 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2483 * Check that the user is allowed to read this page.
2485 * @param string $action The action to check
2486 * @param User $user User to check
2487 * @param array $errors List of current errors
2488 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2489 * @param bool $short Short circuit on first error
2491 * @return array List of errors
2493 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2494 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2496 $whitelisted = false;
2497 if ( User
::isEveryoneAllowed( 'read' ) ) {
2498 # Shortcut for public wikis, allows skipping quite a bit of code
2499 $whitelisted = true;
2500 } elseif ( $user->isAllowed( 'read' ) ) {
2501 # If the user is allowed to read pages, he is allowed to read all pages
2502 $whitelisted = true;
2503 } elseif ( $this->isSpecial( 'Userlogin' )
2504 ||
$this->isSpecial( 'PasswordReset' )
2505 ||
$this->isSpecial( 'Userlogout' )
2507 # Always grant access to the login page.
2508 # Even anons need to be able to log in.
2509 $whitelisted = true;
2510 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2511 # Time to check the whitelist
2512 # Only do these checks is there's something to check against
2513 $name = $this->getPrefixedText();
2514 $dbName = $this->getPrefixedDBkey();
2516 // Check for explicit whitelisting with and without underscores
2517 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2518 $whitelisted = true;
2519 } elseif ( $this->getNamespace() == NS_MAIN
) {
2520 # Old settings might have the title prefixed with
2521 # a colon for main-namespace pages
2522 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2523 $whitelisted = true;
2525 } elseif ( $this->isSpecialPage() ) {
2526 # If it's a special page, ditch the subpage bit and check again
2527 $name = $this->getDBkey();
2528 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2530 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2531 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2532 $whitelisted = true;
2538 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2539 $name = $this->getPrefixedText();
2540 // Check for regex whitelisting
2541 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2542 if ( preg_match( $listItem, $name ) ) {
2543 $whitelisted = true;
2549 if ( !$whitelisted ) {
2550 # If the title is not whitelisted, give extensions a chance to do so...
2551 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2552 if ( !$whitelisted ) {
2553 $errors[] = $this->missingPermissionError( $action, $short );
2561 * Get a description array when the user doesn't have the right to perform
2562 * $action (i.e. when User::isAllowed() returns false)
2564 * @param string $action The action to check
2565 * @param bool $short Short circuit on first error
2566 * @return array Array containing an error message key and any parameters
2568 private function missingPermissionError( $action, $short ) {
2569 // We avoid expensive display logic for quickUserCan's and such
2571 return [ 'badaccess-group0' ];
2574 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2578 * Can $user perform $action on this page? This is an internal function,
2579 * with multiple levels of checks depending on performance needs; see $rigor below.
2580 * It does not check wfReadOnly().
2582 * @param string $action Action that permission needs to be checked for
2583 * @param User $user User to check
2584 * @param string $rigor One of (quick,full,secure)
2585 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2586 * - full : does cheap and expensive checks possibly from a replica DB
2587 * - secure : does cheap and expensive checks, using the master as needed
2588 * @param bool $short Set this to true to stop after the first permission error.
2589 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2591 protected function getUserPermissionsErrorsInternal(
2592 $action, $user, $rigor = 'secure', $short = false
2594 if ( $rigor === true ) {
2595 $rigor = 'secure'; // b/c
2596 } elseif ( $rigor === false ) {
2597 $rigor = 'quick'; // b/c
2598 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2599 throw new Exception( "Invalid rigor parameter '$rigor'." );
2602 # Read has special handling
2603 if ( $action == 'read' ) {
2605 'checkPermissionHooks',
2606 'checkReadPermissions',
2607 'checkUserBlock', // for wgBlockDisablesLogin
2609 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2610 # here as it will lead to duplicate error messages. This is okay to do
2611 # since anywhere that checks for create will also check for edit, and
2612 # those checks are called for edit.
2613 } elseif ( $action == 'create' ) {
2615 'checkQuickPermissions',
2616 'checkPermissionHooks',
2617 'checkPageRestrictions',
2618 'checkCascadingSourcesRestrictions',
2619 'checkActionPermissions',
2624 'checkQuickPermissions',
2625 'checkPermissionHooks',
2626 'checkSpecialsAndNSPermissions',
2627 'checkCSSandJSPermissions',
2628 'checkPageRestrictions',
2629 'checkCascadingSourcesRestrictions',
2630 'checkActionPermissions',
2636 while ( count( $checks ) > 0 &&
2637 !( $short && count( $errors ) > 0 ) ) {
2638 $method = array_shift( $checks );
2639 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2646 * Get a filtered list of all restriction types supported by this wiki.
2647 * @param bool $exists True to get all restriction types that apply to
2648 * titles that do exist, False for all restriction types that apply to
2649 * titles that do not exist
2652 public static function getFilteredRestrictionTypes( $exists = true ) {
2653 global $wgRestrictionTypes;
2654 $types = $wgRestrictionTypes;
2656 # Remove the create restriction for existing titles
2657 $types = array_diff( $types, [ 'create' ] );
2659 # Only the create and upload restrictions apply to non-existing titles
2660 $types = array_intersect( $types, [ 'create', 'upload' ] );
2666 * Returns restriction types for the current Title
2668 * @return array Applicable restriction types
2670 public function getRestrictionTypes() {
2671 if ( $this->isSpecialPage() ) {
2675 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2677 if ( $this->getNamespace() != NS_FILE
) {
2678 # Remove the upload restriction for non-file titles
2679 $types = array_diff( $types, [ 'upload' ] );
2682 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2684 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2685 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2691 * Is this title subject to title protection?
2692 * Title protection is the one applied against creation of such title.
2694 * @return array|bool An associative array representing any existent title
2695 * protection, or false if there's none.
2697 public function getTitleProtection() {
2698 $protection = $this->getTitleProtectionInternal();
2699 if ( $protection ) {
2700 if ( $protection['permission'] == 'sysop' ) {
2701 $protection['permission'] = 'editprotected'; // B/C
2703 if ( $protection['permission'] == 'autoconfirmed' ) {
2704 $protection['permission'] = 'editsemiprotected'; // B/C
2711 * Fetch title protection settings
2713 * To work correctly, $this->loadRestrictions() needs to have access to the
2714 * actual protections in the database without munging 'sysop' =>
2715 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2716 * callers probably want $this->getTitleProtection() instead.
2718 * @return array|bool
2720 protected function getTitleProtectionInternal() {
2721 // Can't protect pages in special namespaces
2722 if ( $this->getNamespace() < 0 ) {
2726 // Can't protect pages that exist.
2727 if ( $this->exists() ) {
2731 if ( $this->mTitleProtection
=== null ) {
2732 $dbr = wfGetDB( DB_REPLICA
);
2733 $commentStore = new CommentStore( 'pt_reason' );
2734 $commentQuery = $commentStore->getJoin();
2735 $res = $dbr->select(
2736 [ 'protected_titles' ] +
$commentQuery['tables'],
2738 'user' => 'pt_user',
2739 'expiry' => 'pt_expiry',
2740 'permission' => 'pt_create_perm'
2741 ] +
$commentQuery['fields'],
2742 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2745 $commentQuery['joins']
2748 // fetchRow returns false if there are no rows.
2749 $row = $dbr->fetchRow( $res );
2751 $this->mTitleProtection
= [
2752 'user' => $row['user'],
2753 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2754 'permission' => $row['permission'],
2755 'reason' => $commentStore->getComment( $row )->text
,
2758 $this->mTitleProtection
= false;
2761 return $this->mTitleProtection
;
2765 * Remove any title protection due to page existing
2767 public function deleteTitleProtection() {
2768 $dbw = wfGetDB( DB_MASTER
);
2772 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2775 $this->mTitleProtection
= false;
2779 * Is this page "semi-protected" - the *only* protection levels are listed
2780 * in $wgSemiprotectedRestrictionLevels?
2782 * @param string $action Action to check (default: edit)
2785 public function isSemiProtected( $action = 'edit' ) {
2786 global $wgSemiprotectedRestrictionLevels;
2788 $restrictions = $this->getRestrictions( $action );
2789 $semi = $wgSemiprotectedRestrictionLevels;
2790 if ( !$restrictions ||
!$semi ) {
2791 // Not protected, or all protection is full protection
2795 // Remap autoconfirmed to editsemiprotected for BC
2796 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2797 $semi[$key] = 'editsemiprotected';
2799 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2800 $restrictions[$key] = 'editsemiprotected';
2803 return !array_diff( $restrictions, $semi );
2807 * Does the title correspond to a protected article?
2809 * @param string $action The action the page is protected from,
2810 * by default checks all actions.
2813 public function isProtected( $action = '' ) {
2814 global $wgRestrictionLevels;
2816 $restrictionTypes = $this->getRestrictionTypes();
2818 # Special pages have inherent protection
2819 if ( $this->isSpecialPage() ) {
2823 # Check regular protection levels
2824 foreach ( $restrictionTypes as $type ) {
2825 if ( $action == $type ||
$action == '' ) {
2826 $r = $this->getRestrictions( $type );
2827 foreach ( $wgRestrictionLevels as $level ) {
2828 if ( in_array( $level, $r ) && $level != '' ) {
2839 * Determines if $user is unable to edit this page because it has been protected
2840 * by $wgNamespaceProtection.
2842 * @param User $user User object to check permissions
2845 public function isNamespaceProtected( User
$user ) {
2846 global $wgNamespaceProtection;
2848 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2849 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2850 if ( $right != '' && !$user->isAllowed( $right ) ) {
2859 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2861 * @return bool If the page is subject to cascading restrictions.
2863 public function isCascadeProtected() {
2864 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2865 return ( $sources > 0 );
2869 * Determines whether cascading protection sources have already been loaded from
2872 * @param bool $getPages True to check if the pages are loaded, or false to check
2873 * if the status is loaded.
2874 * @return bool Whether or not the specified information has been loaded
2877 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2878 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2882 * Cascading protection: Get the source of any cascading restrictions on this page.
2884 * @param bool $getPages Whether or not to retrieve the actual pages
2885 * that the restrictions have come from and the actual restrictions
2887 * @return array Two elements: First is an array of Title objects of the
2888 * pages from which cascading restrictions have come, false for
2889 * none, or true if such restrictions exist but $getPages was not
2890 * set. Second is an array like that returned by
2891 * Title::getAllRestrictions(), or an empty array if $getPages is
2894 public function getCascadeProtectionSources( $getPages = true ) {
2895 $pagerestrictions = [];
2897 if ( $this->mCascadeSources
!== null && $getPages ) {
2898 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2899 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2900 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2903 $dbr = wfGetDB( DB_REPLICA
);
2905 if ( $this->getNamespace() == NS_FILE
) {
2906 $tables = [ 'imagelinks', 'page_restrictions' ];
2908 'il_to' => $this->getDBkey(),
2913 $tables = [ 'templatelinks', 'page_restrictions' ];
2915 'tl_namespace' => $this->getNamespace(),
2916 'tl_title' => $this->getDBkey(),
2923 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2924 'pr_expiry', 'pr_type', 'pr_level' ];
2925 $where_clauses[] = 'page_id=pr_page';
2928 $cols = [ 'pr_expiry' ];
2931 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2933 $sources = $getPages ?
[] : false;
2934 $now = wfTimestampNow();
2936 foreach ( $res as $row ) {
2937 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2938 if ( $expiry > $now ) {
2940 $page_id = $row->pr_page
;
2941 $page_ns = $row->page_namespace
;
2942 $page_title = $row->page_title
;
2943 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2944 # Add groups needed for each restriction type if its not already there
2945 # Make sure this restriction type still exists
2947 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2948 $pagerestrictions[$row->pr_type
] = [];
2952 isset( $pagerestrictions[$row->pr_type
] )
2953 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2955 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2964 $this->mCascadeSources
= $sources;
2965 $this->mCascadingRestrictions
= $pagerestrictions;
2967 $this->mHasCascadingRestrictions
= $sources;
2970 return [ $sources, $pagerestrictions ];
2974 * Accessor for mRestrictionsLoaded
2976 * @return bool Whether or not the page's restrictions have already been
2977 * loaded from the database
2980 public function areRestrictionsLoaded() {
2981 return $this->mRestrictionsLoaded
;
2985 * Accessor/initialisation for mRestrictions
2987 * @param string $action Action that permission needs to be checked for
2988 * @return array Restriction levels needed to take the action. All levels are
2989 * required. Note that restriction levels are normally user rights, but 'sysop'
2990 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2991 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2993 public function getRestrictions( $action ) {
2994 if ( !$this->mRestrictionsLoaded
) {
2995 $this->loadRestrictions();
2997 return isset( $this->mRestrictions
[$action] )
2998 ?
$this->mRestrictions
[$action]
3003 * Accessor/initialisation for mRestrictions
3005 * @return array Keys are actions, values are arrays as returned by
3006 * Title::getRestrictions()
3009 public function getAllRestrictions() {
3010 if ( !$this->mRestrictionsLoaded
) {
3011 $this->loadRestrictions();
3013 return $this->mRestrictions
;
3017 * Get the expiry time for the restriction against a given action
3019 * @param string $action
3020 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3021 * or not protected at all, or false if the action is not recognised.
3023 public function getRestrictionExpiry( $action ) {
3024 if ( !$this->mRestrictionsLoaded
) {
3025 $this->loadRestrictions();
3027 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
3031 * Returns cascading restrictions for the current article
3035 function areRestrictionsCascading() {
3036 if ( !$this->mRestrictionsLoaded
) {
3037 $this->loadRestrictions();
3040 return $this->mCascadeRestriction
;
3044 * Compiles list of active page restrictions from both page table (pre 1.10)
3045 * and page_restrictions table for this existing page.
3046 * Public for usage by LiquidThreads.
3048 * @param array $rows Array of db result objects
3049 * @param string $oldFashionedRestrictions Comma-separated list of page
3050 * restrictions from page table (pre 1.10)
3052 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3053 $dbr = wfGetDB( DB_REPLICA
);
3055 $restrictionTypes = $this->getRestrictionTypes();
3057 foreach ( $restrictionTypes as $type ) {
3058 $this->mRestrictions
[$type] = [];
3059 $this->mRestrictionsExpiry
[$type] = 'infinity';
3062 $this->mCascadeRestriction
= false;
3064 # Backwards-compatibility: also load the restrictions from the page record (old format).
3065 if ( $oldFashionedRestrictions !== null ) {
3066 $this->mOldRestrictions
= $oldFashionedRestrictions;
3069 if ( $this->mOldRestrictions
=== false ) {
3070 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3071 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3074 if ( $this->mOldRestrictions
!= '' ) {
3075 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3076 $temp = explode( '=', trim( $restrict ) );
3077 if ( count( $temp ) == 1 ) {
3078 // old old format should be treated as edit/move restriction
3079 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3080 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3082 $restriction = trim( $temp[1] );
3083 if ( $restriction != '' ) { // some old entries are empty
3084 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3090 if ( count( $rows ) ) {
3091 # Current system - load second to make them override.
3092 $now = wfTimestampNow();
3094 # Cycle through all the restrictions.
3095 foreach ( $rows as $row ) {
3096 // Don't take care of restrictions types that aren't allowed
3097 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3101 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3103 // Only apply the restrictions if they haven't expired!
3104 if ( !$expiry ||
$expiry > $now ) {
3105 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3106 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3108 $this->mCascadeRestriction |
= $row->pr_cascade
;
3113 $this->mRestrictionsLoaded
= true;
3117 * Load restrictions from the page_restrictions table
3119 * @param string $oldFashionedRestrictions Comma-separated list of page
3120 * restrictions from page table (pre 1.10)
3122 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3123 if ( $this->mRestrictionsLoaded
) {
3127 $id = $this->getArticleID();
3129 $cache = ObjectCache
::getMainWANInstance();
3130 $rows = $cache->getWithSetCallback(
3131 // Page protections always leave a new null revision
3132 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3134 function ( $curValue, &$ttl, array &$setOpts ) {
3135 $dbr = wfGetDB( DB_REPLICA
);
3137 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3139 return iterator_to_array(
3141 'page_restrictions',
3142 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3143 [ 'pr_page' => $this->getArticleID() ],
3150 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3152 $title_protection = $this->getTitleProtectionInternal();
3154 if ( $title_protection ) {
3155 $now = wfTimestampNow();
3156 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3158 if ( !$expiry ||
$expiry > $now ) {
3159 // Apply the restrictions
3160 $this->mRestrictionsExpiry
['create'] = $expiry;
3161 $this->mRestrictions
['create'] =
3162 explode( ',', trim( $title_protection['permission'] ) );
3163 } else { // Get rid of the old restrictions
3164 $this->mTitleProtection
= false;
3167 $this->mRestrictionsExpiry
['create'] = 'infinity';
3169 $this->mRestrictionsLoaded
= true;
3174 * Flush the protection cache in this object and force reload from the database.
3175 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3177 public function flushRestrictions() {
3178 $this->mRestrictionsLoaded
= false;
3179 $this->mTitleProtection
= null;
3183 * Purge expired restrictions from the page_restrictions table
3185 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3187 static function purgeExpiredRestrictions() {
3188 if ( wfReadOnly() ) {
3192 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3193 wfGetDB( DB_MASTER
),
3195 function ( IDatabase
$dbw, $fname ) {
3196 $config = MediaWikiServices
::getInstance()->getMainConfig();
3197 $ids = $dbw->selectFieldValues(
3198 'page_restrictions',
3200 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3202 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3205 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3210 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3211 wfGetDB( DB_MASTER
),
3213 function ( IDatabase
$dbw, $fname ) {
3216 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3224 * Does this have subpages? (Warning, usually requires an extra DB query.)
3228 public function hasSubpages() {
3229 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3234 # We dynamically add a member variable for the purpose of this method
3235 # alone to cache the result. There's no point in having it hanging
3236 # around uninitialized in every Title object; therefore we only add it
3237 # if needed and don't declare it statically.
3238 if ( $this->mHasSubpages
=== null ) {
3239 $this->mHasSubpages
= false;
3240 $subpages = $this->getSubpages( 1 );
3241 if ( $subpages instanceof TitleArray
) {
3242 $this->mHasSubpages
= (bool)$subpages->count();
3246 return $this->mHasSubpages
;
3250 * Get all subpages of this page.
3252 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3253 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3254 * doesn't allow subpages
3256 public function getSubpages( $limit = -1 ) {
3257 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3261 $dbr = wfGetDB( DB_REPLICA
);
3262 $conds['page_namespace'] = $this->getNamespace();
3263 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3265 if ( $limit > -1 ) {
3266 $options['LIMIT'] = $limit;
3268 return TitleArray
::newFromResult(
3269 $dbr->select( 'page',
3270 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3279 * Is there a version of this page in the deletion archive?
3281 * @return int The number of archived revisions
3283 public function isDeleted() {
3284 if ( $this->getNamespace() < 0 ) {
3287 $dbr = wfGetDB( DB_REPLICA
);
3289 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3290 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3293 if ( $this->getNamespace() == NS_FILE
) {
3294 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3295 [ 'fa_name' => $this->getDBkey() ],
3304 * Is there a version of this page in the deletion archive?
3308 public function isDeletedQuick() {
3309 if ( $this->getNamespace() < 0 ) {
3312 $dbr = wfGetDB( DB_REPLICA
);
3313 $deleted = (bool)$dbr->selectField( 'archive', '1',
3314 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3317 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3318 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3319 [ 'fa_name' => $this->getDBkey() ],
3327 * Get the article ID for this Title from the link cache,
3328 * adding it if necessary
3330 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3332 * @return int The ID
3334 public function getArticleID( $flags = 0 ) {
3335 if ( $this->getNamespace() < 0 ) {
3336 $this->mArticleID
= 0;
3337 return $this->mArticleID
;
3339 $linkCache = LinkCache
::singleton();
3340 if ( $flags & self
::GAID_FOR_UPDATE
) {
3341 $oldUpdate = $linkCache->forUpdate( true );
3342 $linkCache->clearLink( $this );
3343 $this->mArticleID
= $linkCache->addLinkObj( $this );
3344 $linkCache->forUpdate( $oldUpdate );
3346 if ( -1 == $this->mArticleID
) {
3347 $this->mArticleID
= $linkCache->addLinkObj( $this );
3350 return $this->mArticleID
;
3354 * Is this an article that is a redirect page?
3355 * Uses link cache, adding it if necessary
3357 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3360 public function isRedirect( $flags = 0 ) {
3361 if ( !is_null( $this->mRedirect
) ) {
3362 return $this->mRedirect
;
3364 if ( !$this->getArticleID( $flags ) ) {
3365 $this->mRedirect
= false;
3366 return $this->mRedirect
;
3369 $linkCache = LinkCache
::singleton();
3370 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3371 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3372 if ( $cached === null ) {
3373 # Trust LinkCache's state over our own
3374 # LinkCache is telling us that the page doesn't exist, despite there being cached
3375 # data relating to an existing page in $this->mArticleID. Updaters should clear
3376 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3377 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3378 # LinkCache to refresh its data from the master.
3379 $this->mRedirect
= false;
3380 return $this->mRedirect
;
3383 $this->mRedirect
= (bool)$cached;
3385 return $this->mRedirect
;
3389 * What is the length of this page?
3390 * Uses link cache, adding it if necessary
3392 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3395 public function getLength( $flags = 0 ) {
3396 if ( $this->mLength
!= -1 ) {
3397 return $this->mLength
;
3399 if ( !$this->getArticleID( $flags ) ) {
3401 return $this->mLength
;
3403 $linkCache = LinkCache
::singleton();
3404 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3405 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3406 if ( $cached === null ) {
3407 # Trust LinkCache's state over our own, as for isRedirect()
3409 return $this->mLength
;
3412 $this->mLength
= intval( $cached );
3414 return $this->mLength
;
3418 * What is the page_latest field for this page?
3420 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3421 * @return int Int or 0 if the page doesn't exist
3423 public function getLatestRevID( $flags = 0 ) {
3424 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3425 return intval( $this->mLatestID
);
3427 if ( !$this->getArticleID( $flags ) ) {
3428 $this->mLatestID
= 0;
3429 return $this->mLatestID
;
3431 $linkCache = LinkCache
::singleton();
3432 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3433 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3434 if ( $cached === null ) {
3435 # Trust LinkCache's state over our own, as for isRedirect()
3436 $this->mLatestID
= 0;
3437 return $this->mLatestID
;
3440 $this->mLatestID
= intval( $cached );
3442 return $this->mLatestID
;
3446 * This clears some fields in this object, and clears any associated
3447 * keys in the "bad links" section of the link cache.
3449 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3450 * loading of the new page_id. It's also called from
3451 * WikiPage::doDeleteArticleReal()
3453 * @param int $newid The new Article ID
3455 public function resetArticleID( $newid ) {
3456 $linkCache = LinkCache
::singleton();
3457 $linkCache->clearLink( $this );
3459 if ( $newid === false ) {
3460 $this->mArticleID
= -1;
3462 $this->mArticleID
= intval( $newid );
3464 $this->mRestrictionsLoaded
= false;
3465 $this->mRestrictions
= [];
3466 $this->mOldRestrictions
= false;
3467 $this->mRedirect
= null;
3468 $this->mLength
= -1;
3469 $this->mLatestID
= false;
3470 $this->mContentModel
= false;
3471 $this->mEstimateRevisions
= null;
3472 $this->mPageLanguage
= false;
3473 $this->mDbPageLanguage
= false;
3474 $this->mIsBigDeletion
= null;
3477 public static function clearCaches() {
3478 $linkCache = LinkCache
::singleton();
3479 $linkCache->clear();
3481 $titleCache = self
::getTitleCache();
3482 $titleCache->clear();
3486 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3488 * @param string $text Containing title to capitalize
3489 * @param int $ns Namespace index, defaults to NS_MAIN
3490 * @return string Containing capitalized title
3492 public static function capitalize( $text, $ns = NS_MAIN
) {
3495 if ( MWNamespace
::isCapitalized( $ns ) ) {
3496 return $wgContLang->ucfirst( $text );
3503 * Secure and split - main initialisation function for this object
3505 * Assumes that mDbkeyform has been set, and is urldecoded
3506 * and uses underscores, but not otherwise munged. This function
3507 * removes illegal characters, splits off the interwiki and
3508 * namespace prefixes, sets the other forms, and canonicalizes
3511 * @throws MalformedTitleException On invalid titles
3512 * @return bool True on success
3514 private function secureAndSplit() {
3516 $this->mInterwiki
= '';
3517 $this->mFragment
= '';
3518 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3520 $dbkey = $this->mDbkeyform
;
3522 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3523 // the parsing code with Title, while avoiding massive refactoring.
3524 // @todo: get rid of secureAndSplit, refactor parsing code.
3525 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3526 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3527 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3528 // MalformedTitleException can be thrown here
3529 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3532 $this->setFragment( '#' . $parts['fragment'] );
3533 $this->mInterwiki
= $parts['interwiki'];
3534 $this->mLocalInterwiki
= $parts['local_interwiki'];
3535 $this->mNamespace
= $parts['namespace'];
3536 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3538 $this->mDbkeyform
= $parts['dbkey'];
3539 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3540 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3542 # We already know that some pages won't be in the database!
3543 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3544 $this->mArticleID
= 0;
3551 * Get an array of Title objects linking to this Title
3552 * Also stores the IDs in the link cache.
3554 * WARNING: do not use this function on arbitrary user-supplied titles!
3555 * On heavily-used templates it will max out the memory.
3557 * @param array $options May be FOR UPDATE
3558 * @param string $table Table name
3559 * @param string $prefix Fields prefix
3560 * @return Title[] Array of Title objects linking here
3562 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3563 if ( count( $options ) > 0 ) {
3564 $db = wfGetDB( DB_MASTER
);
3566 $db = wfGetDB( DB_REPLICA
);
3571 self
::getSelectFields(),
3573 "{$prefix}_from=page_id",
3574 "{$prefix}_namespace" => $this->getNamespace(),
3575 "{$prefix}_title" => $this->getDBkey() ],
3581 if ( $res->numRows() ) {
3582 $linkCache = LinkCache
::singleton();
3583 foreach ( $res as $row ) {
3584 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3586 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3587 $retVal[] = $titleObj;
3595 * Get an array of Title objects using this Title as a template
3596 * Also stores the IDs in the link cache.
3598 * WARNING: do not use this function on arbitrary user-supplied titles!
3599 * On heavily-used templates it will max out the memory.
3601 * @param array $options Query option to Database::select()
3602 * @return Title[] Array of Title the Title objects linking here
3604 public function getTemplateLinksTo( $options = [] ) {
3605 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3609 * Get an array of Title objects linked from this Title
3610 * Also stores the IDs in the link cache.
3612 * WARNING: do not use this function on arbitrary user-supplied titles!
3613 * On heavily-used templates it will max out the memory.
3615 * @param array $options Query option to Database::select()
3616 * @param string $table Table name
3617 * @param string $prefix Fields prefix
3618 * @return array Array of Title objects linking here
3620 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3621 $id = $this->getArticleID();
3623 # If the page doesn't exist; there can't be any link from this page
3628 $db = wfGetDB( DB_REPLICA
);
3630 $blNamespace = "{$prefix}_namespace";
3631 $blTitle = "{$prefix}_title";
3633 $pageQuery = WikiPage
::getQueryInfo();
3635 [ $table, 'nestpage' => $pageQuery['tables'] ],
3637 [ $blNamespace, $blTitle ],
3638 $pageQuery['fields']
3640 [ "{$prefix}_from" => $id ],
3645 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3646 ] ] +
$pageQuery['joins']
3650 $linkCache = LinkCache
::singleton();
3651 foreach ( $res as $row ) {
3652 if ( $row->page_id
) {
3653 $titleObj = self
::newFromRow( $row );
3655 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3656 $linkCache->addBadLinkObj( $titleObj );
3658 $retVal[] = $titleObj;
3665 * Get an array of Title objects used on this Title as a template
3666 * Also stores the IDs in the link cache.
3668 * WARNING: do not use this function on arbitrary user-supplied titles!
3669 * On heavily-used templates it will max out the memory.
3671 * @param array $options May be FOR UPDATE
3672 * @return Title[] Array of Title the Title objects used here
3674 public function getTemplateLinksFrom( $options = [] ) {
3675 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3679 * Get an array of Title objects referring to non-existent articles linked
3682 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3683 * should use redirect table in this case).
3684 * @return Title[] Array of Title the Title objects
3686 public function getBrokenLinksFrom() {
3687 if ( $this->getArticleID() == 0 ) {
3688 # All links from article ID 0 are false positives
3692 $dbr = wfGetDB( DB_REPLICA
);
3693 $res = $dbr->select(
3694 [ 'page', 'pagelinks' ],
3695 [ 'pl_namespace', 'pl_title' ],
3697 'pl_from' => $this->getArticleID(),
3698 'page_namespace IS NULL'
3704 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3710 foreach ( $res as $row ) {
3711 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3717 * Get a list of URLs to purge from the CDN cache when this
3720 * @return string[] Array of String the URLs
3722 public function getCdnUrls() {
3724 $this->getInternalURL(),
3725 $this->getInternalURL( 'action=history' )
3728 $pageLang = $this->getPageLanguage();
3729 if ( $pageLang->hasVariants() ) {
3730 $variants = $pageLang->getVariants();
3731 foreach ( $variants as $vCode ) {
3732 $urls[] = $this->getInternalURL( $vCode );
3736 // If we are looking at a css/js user subpage, purge the action=raw.
3737 if ( $this->isJsSubpage() ) {
3738 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3739 } elseif ( $this->isCssSubpage() ) {
3740 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3743 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3748 * @deprecated since 1.27 use getCdnUrls()
3750 public function getSquidURLs() {
3751 return $this->getCdnUrls();
3755 * Purge all applicable CDN URLs
3757 public function purgeSquid() {
3758 DeferredUpdates
::addUpdate(
3759 new CdnCacheUpdate( $this->getCdnUrls() ),
3760 DeferredUpdates
::PRESEND
3765 * Check whether a given move operation would be valid.
3766 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3768 * @deprecated since 1.25, use MovePage's methods instead
3769 * @param Title &$nt The new title
3770 * @param bool $auth Whether to check user permissions (uses $wgUser)
3771 * @param string $reason Is the log summary of the move, used for spam checking
3772 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3774 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3777 if ( !( $nt instanceof Title
) ) {
3778 // Normally we'd add this to $errors, but we'll get
3779 // lots of syntax errors if $nt is not an object
3780 return [ [ 'badtitletext' ] ];
3783 $mp = new MovePage( $this, $nt );
3784 $errors = $mp->isValidMove()->getErrorsArray();
3786 $errors = wfMergeErrorArrays(
3788 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3792 return $errors ?
: true;
3796 * Check if the requested move target is a valid file move target
3797 * @todo move this to MovePage
3798 * @param Title $nt Target title
3799 * @return array List of errors
3801 protected function validateFileMoveOperation( $nt ) {
3806 $destFile = wfLocalFile( $nt );
3807 $destFile->load( File
::READ_LATEST
);
3808 if ( !$wgUser->isAllowed( 'reupload-shared' )
3809 && !$destFile->exists() && wfFindFile( $nt )
3811 $errors[] = [ 'file-exists-sharedrepo' ];
3818 * Move a title to a new location
3820 * @deprecated since 1.25, use the MovePage class instead
3821 * @param Title &$nt The new title
3822 * @param bool $auth Indicates whether $wgUser's permissions
3824 * @param string $reason The reason for the move
3825 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3826 * Ignored if the user doesn't have the suppressredirect right.
3827 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3828 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3830 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3831 array $changeTags = []
3834 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3835 if ( is_array( $err ) ) {
3836 // Auto-block user's IP if the account was "hard" blocked
3837 $wgUser->spreadAnyEditBlock();
3840 // Check suppressredirect permission
3841 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3842 $createRedirect = true;
3845 $mp = new MovePage( $this, $nt );
3846 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3847 if ( $status->isOK() ) {
3850 return $status->getErrorsArray();
3855 * Move this page's subpages to be subpages of $nt
3857 * @param Title $nt Move target
3858 * @param bool $auth Whether $wgUser's permissions should be checked
3859 * @param string $reason The reason for the move
3860 * @param bool $createRedirect Whether to create redirects from the old subpages to
3861 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3862 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3863 * @return array Array with old page titles as keys, and strings (new page titles) or
3864 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3865 * getUserPermissionsErrors()-like error array with numeric indices if
3866 * no pages were moved
3868 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3869 array $changeTags = []
3871 global $wgMaximumMovedPages;
3872 // Check permissions
3873 if ( !$this->userCan( 'move-subpages' ) ) {
3875 [ 'cant-move-subpages' ],
3878 // Do the source and target namespaces support subpages?
3879 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3881 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3884 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3886 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3890 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3893 foreach ( $subpages as $oldSubpage ) {
3895 if ( $count > $wgMaximumMovedPages ) {
3896 $retval[$oldSubpage->getPrefixedText()] = [
3897 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3902 // We don't know whether this function was called before
3903 // or after moving the root page, so check both
3905 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3906 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3908 // When moving a page to a subpage of itself,
3909 // don't move it twice
3912 $newPageName = preg_replace(
3913 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3914 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3915 $oldSubpage->getDBkey() );
3916 if ( $oldSubpage->isTalkPage() ) {
3917 $newNs = $nt->getTalkPage()->getNamespace();
3919 $newNs = $nt->getSubjectPage()->getNamespace();
3921 # T16385: we need makeTitleSafe because the new page names may
3922 # be longer than 255 characters.
3923 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3925 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3926 if ( $success === true ) {
3927 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3929 $retval[$oldSubpage->getPrefixedText()] = $success;
3936 * Checks if this page is just a one-rev redirect.
3937 * Adds lock, so don't use just for light purposes.
3941 public function isSingleRevRedirect() {
3942 global $wgContentHandlerUseDB;
3944 $dbw = wfGetDB( DB_MASTER
);
3947 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3948 if ( $wgContentHandlerUseDB ) {
3949 $fields[] = 'page_content_model';
3952 $row = $dbw->selectRow( 'page',
3958 # Cache some fields we may want
3959 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3960 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3961 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3962 $this->mContentModel
= $row && isset( $row->page_content_model
)
3963 ?
strval( $row->page_content_model
)
3966 if ( !$this->mRedirect
) {
3969 # Does the article have a history?
3970 $row = $dbw->selectField( [ 'page', 'revision' ],
3972 [ 'page_namespace' => $this->getNamespace(),
3973 'page_title' => $this->getDBkey(),
3975 'page_latest != rev_id'
3980 # Return true if there was no history
3981 return ( $row === false );
3985 * Checks if $this can be moved to a given Title
3986 * - Selects for update, so don't call it unless you mean business
3988 * @deprecated since 1.25, use MovePage's methods instead
3989 * @param Title $nt The new title to check
3992 public function isValidMoveTarget( $nt ) {
3993 # Is it an existing file?
3994 if ( $nt->getNamespace() == NS_FILE
) {
3995 $file = wfLocalFile( $nt );
3996 $file->load( File
::READ_LATEST
);
3997 if ( $file->exists() ) {
3998 wfDebug( __METHOD__
. ": file exists\n" );
4002 # Is it a redirect with no history?
4003 if ( !$nt->isSingleRevRedirect() ) {
4004 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4007 # Get the article text
4008 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4009 if ( !is_object( $rev ) ) {
4012 $content = $rev->getContent();
4013 # Does the redirect point to the source?
4014 # Or is it a broken self-redirect, usually caused by namespace collisions?
4015 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4017 if ( $redirTitle ) {
4018 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4019 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4020 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4026 # Fail safe (not a redirect after all. strange.)
4027 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4028 " is a redirect, but it doesn't contain a valid redirect.\n" );
4034 * Get categories to which this Title belongs and return an array of
4035 * categories' names.
4037 * @return array Array of parents in the form:
4038 * $parent => $currentarticle
4040 public function getParentCategories() {
4045 $titleKey = $this->getArticleID();
4047 if ( $titleKey === 0 ) {
4051 $dbr = wfGetDB( DB_REPLICA
);
4053 $res = $dbr->select(
4056 [ 'cl_from' => $titleKey ],
4060 if ( $res->numRows() > 0 ) {
4061 foreach ( $res as $row ) {
4062 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4063 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4070 * Get a tree of parent categories
4072 * @param array $children Array with the children in the keys, to check for circular refs
4073 * @return array Tree of parent categories
4075 public function getParentCategoryTree( $children = [] ) {
4077 $parents = $this->getParentCategories();
4080 foreach ( $parents as $parent => $current ) {
4081 if ( array_key_exists( $parent, $children ) ) {
4082 # Circular reference
4083 $stack[$parent] = [];
4085 $nt = self
::newFromText( $parent );
4087 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4097 * Get an associative array for selecting this title from
4100 * @return array Array suitable for the $where parameter of DB::select()
4102 public function pageCond() {
4103 if ( $this->mArticleID
> 0 ) {
4104 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4105 return [ 'page_id' => $this->mArticleID
];
4107 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4112 * Get next/previous revision ID relative to another revision ID
4113 * @param int $revId Revision ID. Get the revision that was before this one.
4114 * @param int $flags Title::GAID_FOR_UPDATE
4115 * @param string $dir 'next' or 'prev'
4116 * @return int|bool New revision ID, or false if none exists
4118 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4119 $revId = (int)$revId;
4120 if ( $dir === 'next' ) {
4123 } elseif ( $dir === 'prev' ) {
4127 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4130 if ( $flags & self
::GAID_FOR_UPDATE
) {
4131 $db = wfGetDB( DB_MASTER
);
4133 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4136 // Intentionally not caring if the specified revision belongs to this
4137 // page. We only care about the timestamp.
4138 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4139 if ( $ts === false ) {
4140 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4141 if ( $ts === false ) {
4142 // Or should this throw an InvalidArgumentException or something?
4146 $ts = $db->addQuotes( $ts );
4148 $revId = $db->selectField( 'revision', 'rev_id',
4150 'rev_page' => $this->getArticleID( $flags ),
4151 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4155 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4156 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4160 if ( $revId === false ) {
4163 return intval( $revId );
4168 * Get the revision ID of the previous revision
4170 * @param int $revId Revision ID. Get the revision that was before this one.
4171 * @param int $flags Title::GAID_FOR_UPDATE
4172 * @return int|bool Old revision ID, or false if none exists
4174 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4175 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4179 * Get the revision ID of the next revision
4181 * @param int $revId Revision ID. Get the revision that was after this one.
4182 * @param int $flags Title::GAID_FOR_UPDATE
4183 * @return int|bool Next revision ID, or false if none exists
4185 public function getNextRevisionID( $revId, $flags = 0 ) {
4186 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4190 * Get the first revision of the page
4192 * @param int $flags Title::GAID_FOR_UPDATE
4193 * @return Revision|null If page doesn't exist
4195 public function getFirstRevision( $flags = 0 ) {
4196 $pageId = $this->getArticleID( $flags );
4198 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4199 $revQuery = Revision
::getQueryInfo();
4200 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4201 [ 'rev_page' => $pageId ],
4204 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4205 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4210 return new Revision( $row );
4217 * Get the oldest revision timestamp of this page
4219 * @param int $flags Title::GAID_FOR_UPDATE
4220 * @return string MW timestamp
4222 public function getEarliestRevTime( $flags = 0 ) {
4223 $rev = $this->getFirstRevision( $flags );
4224 return $rev ?
$rev->getTimestamp() : null;
4228 * Check if this is a new page
4232 public function isNewPage() {
4233 $dbr = wfGetDB( DB_REPLICA
);
4234 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4238 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4242 public function isBigDeletion() {
4243 global $wgDeleteRevisionsLimit;
4245 if ( !$wgDeleteRevisionsLimit ) {
4249 if ( $this->mIsBigDeletion
=== null ) {
4250 $dbr = wfGetDB( DB_REPLICA
);
4252 $revCount = $dbr->selectRowCount(
4255 [ 'rev_page' => $this->getArticleID() ],
4257 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4260 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4263 return $this->mIsBigDeletion
;
4267 * Get the approximate revision count of this page.
4271 public function estimateRevisionCount() {
4272 if ( !$this->exists() ) {
4276 if ( $this->mEstimateRevisions
=== null ) {
4277 $dbr = wfGetDB( DB_REPLICA
);
4278 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4279 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4282 return $this->mEstimateRevisions
;
4286 * Get the number of revisions between the given revision.
4287 * Used for diffs and other things that really need it.
4289 * @param int|Revision $old Old revision or rev ID (first before range)
4290 * @param int|Revision $new New revision or rev ID (first after range)
4291 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4292 * @return int Number of revisions between these revisions.
4294 public function countRevisionsBetween( $old, $new, $max = null ) {
4295 if ( !( $old instanceof Revision
) ) {
4296 $old = Revision
::newFromTitle( $this, (int)$old );
4298 if ( !( $new instanceof Revision
) ) {
4299 $new = Revision
::newFromTitle( $this, (int)$new );
4301 if ( !$old ||
!$new ) {
4302 return 0; // nothing to compare
4304 $dbr = wfGetDB( DB_REPLICA
);
4306 'rev_page' => $this->getArticleID(),
4307 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4308 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4310 if ( $max !== null ) {
4311 return $dbr->selectRowCount( 'revision', '1',
4314 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4317 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4322 * Get the authors between the given revisions or revision IDs.
4323 * Used for diffs and other things that really need it.
4327 * @param int|Revision $old Old revision or rev ID (first before range by default)
4328 * @param int|Revision $new New revision or rev ID (first after range by default)
4329 * @param int $limit Maximum number of authors
4330 * @param string|array $options (Optional): Single option, or an array of options:
4331 * 'include_old' Include $old in the range; $new is excluded.
4332 * 'include_new' Include $new in the range; $old is excluded.
4333 * 'include_both' Include both $old and $new in the range.
4334 * Unknown option values are ignored.
4335 * @return array|null Names of revision authors in the range; null if not both revisions exist
4337 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4338 if ( !( $old instanceof Revision
) ) {
4339 $old = Revision
::newFromTitle( $this, (int)$old );
4341 if ( !( $new instanceof Revision
) ) {
4342 $new = Revision
::newFromTitle( $this, (int)$new );
4344 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4345 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4346 // in the sanity check below?
4347 if ( !$old ||
!$new ) {
4348 return null; // nothing to compare
4353 $options = (array)$options;
4354 if ( in_array( 'include_old', $options ) ) {
4357 if ( in_array( 'include_new', $options ) ) {
4360 if ( in_array( 'include_both', $options ) ) {
4364 // No DB query needed if $old and $new are the same or successive revisions:
4365 if ( $old->getId() === $new->getId() ) {
4366 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4368 [ $old->getUserText( Revision
::RAW
) ];
4369 } elseif ( $old->getId() === $new->getParentId() ) {
4370 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4371 $authors[] = $old->getUserText( Revision
::RAW
);
4372 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4373 $authors[] = $new->getUserText( Revision
::RAW
);
4375 } elseif ( $old_cmp === '>=' ) {
4376 $authors[] = $old->getUserText( Revision
::RAW
);
4377 } elseif ( $new_cmp === '<=' ) {
4378 $authors[] = $new->getUserText( Revision
::RAW
);
4382 $dbr = wfGetDB( DB_REPLICA
);
4383 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4385 'rev_page' => $this->getArticleID(),
4386 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4387 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4389 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4391 foreach ( $res as $row ) {
4392 $authors[] = $row->rev_user_text
;
4398 * Get the number of authors between the given revisions or revision IDs.
4399 * 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 int Number of revision authors in the range; zero if not both revisions exist
4411 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4412 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4413 return $authors ?
count( $authors ) : 0;
4417 * Compare with another title.
4419 * @param Title $title
4422 public function equals( Title
$title ) {
4423 // Note: === is necessary for proper matching of number-like titles.
4424 return $this->getInterwiki() === $title->getInterwiki()
4425 && $this->getNamespace() == $title->getNamespace()
4426 && $this->getDBkey() === $title->getDBkey();
4430 * Check if this title is a subpage of another title
4432 * @param Title $title
4435 public function isSubpageOf( Title
$title ) {
4436 return $this->getInterwiki() === $title->getInterwiki()
4437 && $this->getNamespace() == $title->getNamespace()
4438 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4442 * Check if page exists. For historical reasons, this function simply
4443 * checks for the existence of the title in the page table, and will
4444 * thus return false for interwiki links, special pages and the like.
4445 * If you want to know if a title can be meaningfully viewed, you should
4446 * probably call the isKnown() method instead.
4448 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4449 * from master/for update
4452 public function exists( $flags = 0 ) {
4453 $exists = $this->getArticleID( $flags ) != 0;
4454 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4459 * Should links to this title be shown as potentially viewable (i.e. as
4460 * "bluelinks"), even if there's no record by this title in the page
4463 * This function is semi-deprecated for public use, as well as somewhat
4464 * misleadingly named. You probably just want to call isKnown(), which
4465 * calls this function internally.
4467 * (ISSUE: Most of these checks are cheap, but the file existence check
4468 * can potentially be quite expensive. Including it here fixes a lot of
4469 * existing code, but we might want to add an optional parameter to skip
4470 * it and any other expensive checks.)
4474 public function isAlwaysKnown() {
4478 * Allows overriding default behavior for determining if a page exists.
4479 * If $isKnown is kept as null, regular checks happen. If it's
4480 * a boolean, this value is returned by the isKnown method.
4484 * @param Title $title
4485 * @param bool|null $isKnown
4487 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4489 if ( !is_null( $isKnown ) ) {
4493 if ( $this->isExternal() ) {
4494 return true; // any interwiki link might be viewable, for all we know
4497 switch ( $this->mNamespace
) {
4500 // file exists, possibly in a foreign repo
4501 return (bool)wfFindFile( $this );
4503 // valid special page
4504 return SpecialPageFactory
::exists( $this->getDBkey() );
4506 // selflink, possibly with fragment
4507 return $this->mDbkeyform
== '';
4509 // known system message
4510 return $this->hasSourceText() !== false;
4517 * Does this title refer to a page that can (or might) be meaningfully
4518 * viewed? In particular, this function may be used to determine if
4519 * links to the title should be rendered as "bluelinks" (as opposed to
4520 * "redlinks" to non-existent pages).
4521 * Adding something else to this function will cause inconsistency
4522 * since LinkHolderArray calls isAlwaysKnown() and does its own
4523 * page existence check.
4527 public function isKnown() {
4528 return $this->isAlwaysKnown() ||
$this->exists();
4532 * Does this page have source text?
4536 public function hasSourceText() {
4537 if ( $this->exists() ) {
4541 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4542 // If the page doesn't exist but is a known system message, default
4543 // message content will be displayed, same for language subpages-
4544 // Use always content language to avoid loading hundreds of languages
4545 // to get the link color.
4547 list( $name, ) = MessageCache
::singleton()->figureMessage(
4548 $wgContLang->lcfirst( $this->getText() )
4550 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4551 return $message->exists();
4558 * Get the default message text or false if the message doesn't exist
4560 * @return string|bool
4562 public function getDefaultMessageText() {
4565 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4569 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4570 $wgContLang->lcfirst( $this->getText() )
4572 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4574 if ( $message->exists() ) {
4575 return $message->plain();
4582 * Updates page_touched for this page; called from LinksUpdate.php
4584 * @param string $purgeTime [optional] TS_MW timestamp
4585 * @return bool True if the update succeeded
4587 public function invalidateCache( $purgeTime = null ) {
4588 if ( wfReadOnly() ) {
4590 } elseif ( $this->mArticleID
=== 0 ) {
4591 return true; // avoid gap locking if we know it's not there
4594 $dbw = wfGetDB( DB_MASTER
);
4595 $dbw->onTransactionPreCommitOrIdle( function () {
4596 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4599 $conds = $this->pageCond();
4600 DeferredUpdates
::addUpdate(
4601 new AutoCommitUpdate(
4604 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4605 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4608 [ 'page_touched' => $dbTimestamp ],
4609 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4612 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4615 DeferredUpdates
::PRESEND
4622 * Update page_touched timestamps and send CDN purge messages for
4623 * pages linking to this title. May be sent to the job queue depending
4624 * on the number of links. Typically called on create and delete.
4626 public function touchLinks() {
4627 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4628 if ( $this->getNamespace() == NS_CATEGORY
) {
4629 DeferredUpdates
::addUpdate(
4630 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4636 * Get the last touched timestamp
4638 * @param IDatabase $db Optional db
4639 * @return string|false Last-touched timestamp
4641 public function getTouched( $db = null ) {
4642 if ( $db === null ) {
4643 $db = wfGetDB( DB_REPLICA
);
4645 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4650 * Get the timestamp when this page was updated since the user last saw it.
4653 * @return string|null
4655 public function getNotificationTimestamp( $user = null ) {
4658 // Assume current user if none given
4662 // Check cache first
4663 $uid = $user->getId();
4667 // avoid isset here, as it'll return false for null entries
4668 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4669 return $this->mNotificationTimestamp
[$uid];
4671 // Don't cache too much!
4672 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4673 $this->mNotificationTimestamp
= [];
4676 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4677 $watchedItem = $store->getWatchedItem( $user, $this );
4678 if ( $watchedItem ) {
4679 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4681 $this->mNotificationTimestamp
[$uid] = false;
4684 return $this->mNotificationTimestamp
[$uid];
4688 * Generate strings used for xml 'id' names in monobook tabs
4690 * @param string $prepend Defaults to 'nstab-'
4691 * @return string XML 'id' name
4693 public function getNamespaceKey( $prepend = 'nstab-' ) {
4695 // Gets the subject namespace if this title
4696 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4697 // Checks if canonical namespace name exists for namespace
4698 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4699 // Uses canonical namespace name
4700 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4702 // Uses text of namespace
4703 $namespaceKey = $this->getSubjectNsText();
4705 // Makes namespace key lowercase
4706 $namespaceKey = $wgContLang->lc( $namespaceKey );
4708 if ( $namespaceKey == '' ) {
4709 $namespaceKey = 'main';
4711 // Changes file to image for backwards compatibility
4712 if ( $namespaceKey == 'file' ) {
4713 $namespaceKey = 'image';
4715 return $prepend . $namespaceKey;
4719 * Get all extant redirects to this Title
4721 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4722 * @return Title[] Array of Title redirects to this title
4724 public function getRedirectsHere( $ns = null ) {
4727 $dbr = wfGetDB( DB_REPLICA
);
4729 'rd_namespace' => $this->getNamespace(),
4730 'rd_title' => $this->getDBkey(),
4733 if ( $this->isExternal() ) {
4734 $where['rd_interwiki'] = $this->getInterwiki();
4736 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4738 if ( !is_null( $ns ) ) {
4739 $where['page_namespace'] = $ns;
4742 $res = $dbr->select(
4743 [ 'redirect', 'page' ],
4744 [ 'page_namespace', 'page_title' ],
4749 foreach ( $res as $row ) {
4750 $redirs[] = self
::newFromRow( $row );
4756 * Check if this Title is a valid redirect target
4760 public function isValidRedirectTarget() {
4761 global $wgInvalidRedirectTargets;
4763 if ( $this->isSpecialPage() ) {
4764 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4765 if ( $this->isSpecial( 'Userlogout' ) ) {
4769 foreach ( $wgInvalidRedirectTargets as $target ) {
4770 if ( $this->isSpecial( $target ) ) {
4780 * Get a backlink cache object
4782 * @return BacklinkCache
4784 public function getBacklinkCache() {
4785 return BacklinkCache
::get( $this );
4789 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4793 public function canUseNoindex() {
4794 global $wgExemptFromUserRobotsControl;
4796 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4797 ? MWNamespace
::getContentNamespaces()
4798 : $wgExemptFromUserRobotsControl;
4800 return !in_array( $this->mNamespace
, $bannedNamespaces );
4804 * Returns the raw sort key to be used for categories, with the specified
4805 * prefix. This will be fed to Collation::getSortKey() to get a
4806 * binary sortkey that can be used for actual sorting.
4808 * @param string $prefix The prefix to be used, specified using
4809 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4813 public function getCategorySortkey( $prefix = '' ) {
4814 $unprefixed = $this->getText();
4816 // Anything that uses this hook should only depend
4817 // on the Title object passed in, and should probably
4818 // tell the users to run updateCollations.php --force
4819 // in order to re-sort existing category relations.
4820 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4821 if ( $prefix !== '' ) {
4822 # Separate with a line feed, so the unprefixed part is only used as
4823 # a tiebreaker when two pages have the exact same prefix.
4824 # In UCA, tab is the only character that can sort above LF
4825 # so we strip both of them from the original prefix.
4826 $prefix = strtr( $prefix, "\n\t", ' ' );
4827 return "$prefix\n$unprefixed";
4833 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4834 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4835 * the db, it will return NULL.
4837 * @return string|null|bool
4839 private function getDbPageLanguageCode() {
4840 global $wgPageLanguageUseDB;
4842 // check, if the page language could be saved in the database, and if so and
4843 // the value is not requested already, lookup the page language using LinkCache
4844 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4845 $linkCache = LinkCache
::singleton();
4846 $linkCache->addLinkObj( $this );
4847 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4850 return $this->mDbPageLanguage
;
4854 * Get the language in which the content of this page is written in
4855 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4856 * e.g. $wgLang (such as special pages, which are in the user language).
4861 public function getPageLanguage() {
4862 global $wgLang, $wgLanguageCode;
4863 if ( $this->isSpecialPage() ) {
4864 // special pages are in the user language
4868 // Checking if DB language is set
4869 $dbPageLanguage = $this->getDbPageLanguageCode();
4870 if ( $dbPageLanguage ) {
4871 return wfGetLangObj( $dbPageLanguage );
4874 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4875 // Note that this may depend on user settings, so the cache should
4876 // be only per-request.
4877 // NOTE: ContentHandler::getPageLanguage() may need to load the
4878 // content to determine the page language!
4879 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4881 $contentHandler = ContentHandler
::getForTitle( $this );
4882 $langObj = $contentHandler->getPageLanguage( $this );
4883 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4885 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4892 * Get the language in which the content of this page is written when
4893 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4894 * e.g. $wgLang (such as special pages, which are in the user language).
4899 public function getPageViewLanguage() {
4902 if ( $this->isSpecialPage() ) {
4903 // If the user chooses a variant, the content is actually
4904 // in a language whose code is the variant code.
4905 $variant = $wgLang->getPreferredVariant();
4906 if ( $wgLang->getCode() !== $variant ) {
4907 return Language
::factory( $variant );
4913 // Checking if DB language is set
4914 $dbPageLanguage = $this->getDbPageLanguageCode();
4915 if ( $dbPageLanguage ) {
4916 $pageLang = wfGetLangObj( $dbPageLanguage );
4917 $variant = $pageLang->getPreferredVariant();
4918 if ( $pageLang->getCode() !== $variant ) {
4919 $pageLang = Language
::factory( $variant );
4925 // @note Can't be cached persistently, depends on user settings.
4926 // @note ContentHandler::getPageViewLanguage() may need to load the
4927 // content to determine the page language!
4928 $contentHandler = ContentHandler
::getForTitle( $this );
4929 $pageLang = $contentHandler->getPageViewLanguage( $this );
4934 * Get a list of rendered edit notices for this page.
4936 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4937 * they will already be wrapped in paragraphs.
4940 * @param int $oldid Revision ID that's being edited
4943 public function getEditNotices( $oldid = 0 ) {
4946 // Optional notice for the entire namespace
4947 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4948 $msg = wfMessage( $editnotice_ns );
4949 if ( $msg->exists() ) {
4950 $html = $msg->parseAsBlock();
4951 // Edit notices may have complex logic, but output nothing (T91715)
4952 if ( trim( $html ) !== '' ) {
4953 $notices[$editnotice_ns] = Html
::rawElement(
4957 'mw-editnotice-namespace',
4958 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4965 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4966 // Optional notice for page itself and any parent page
4967 $parts = explode( '/', $this->getDBkey() );
4968 $editnotice_base = $editnotice_ns;
4969 while ( count( $parts ) > 0 ) {
4970 $editnotice_base .= '-' . array_shift( $parts );
4971 $msg = wfMessage( $editnotice_base );
4972 if ( $msg->exists() ) {
4973 $html = $msg->parseAsBlock();
4974 if ( trim( $html ) !== '' ) {
4975 $notices[$editnotice_base] = Html
::rawElement(
4979 'mw-editnotice-base',
4980 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4988 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4989 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4990 $msg = wfMessage( $editnoticeText );
4991 if ( $msg->exists() ) {
4992 $html = $msg->parseAsBlock();
4993 if ( trim( $html ) !== '' ) {
4994 $notices[$editnoticeText] = Html
::rawElement(
4998 'mw-editnotice-page',
4999 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5007 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5014 public function __sleep() {
5022 'mDefaultNamespace',
5026 public function __wakeup() {
5027 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5028 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5029 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );